text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import { expect } from "chai";
import { mount, ReactWrapper } from "enzyme";
import * as React from "react";
import * as sinon from "sinon";
import * as Classes from "../../src/common/classes";
import * as Errors from "../../src/common/errors";
import { Grid } from "../../src/common/grid";
import { ITableQuadrantProps, QuadrantType, TableQuadrant } from "../../src/quadrants/tableQuadrant";
/**
* <TableQuadrant> is responsible for showing a single table "instance" of both
* header and body cells.
*/
describe("TableQuadrant", () => {
const NUM_ROWS = 5;
const NUM_COLUMNS = 3;
const ROW_HEIGHT = 10;
const COLUMN_WIDTH = 100;
const ROW_HEIGHTS = Array(NUM_ROWS).fill(ROW_HEIGHT);
const COLUMN_WIDTHS = Array(NUM_COLUMNS).fill(COLUMN_WIDTH);
let grid: Grid;
const bodyRenderer = sinon.spy();
beforeEach(() => {
grid = new Grid(ROW_HEIGHTS, COLUMN_WIDTHS);
});
afterEach(() => {
bodyRenderer.resetHistory();
});
describe("Event callbacks", () => {
it("adds onScroll to the TABLE_QUADRANT_SCROLL_CONTAINER", () => {
const onScroll = sinon.spy();
const component = mountTableQuadrant({ onScroll });
component.find(`.${Classes.TABLE_QUADRANT_SCROLL_CONTAINER}`).simulate("scroll");
expect(onScroll.called).to.be.true;
});
it("adds onWheel to the TABLE_QUADRANT_SCROLL_CONTAINER", () => {
const onWheel = sinon.spy();
const component = mountTableQuadrant({ onWheel });
component.find(`.${Classes.TABLE_QUADRANT_SCROLL_CONTAINER}`).simulate("wheel");
expect(onWheel.called).to.be.true;
});
it("prints a console warning if onScroll is provided when quadrantType != MAIN", () => {
const consoleWarn = sinon.stub(console, "warn");
mountTableQuadrant({ onScroll: sinon.spy(), quadrantType: QuadrantType.LEFT });
expect(consoleWarn.calledOnce);
expect(consoleWarn.firstCall.args[0]).to.equal(Errors.QUADRANT_ON_SCROLL_UNNECESSARILY_DEFINED);
consoleWarn.restore();
});
});
describe("refs", () => {
it("bodyRef returns TABLE_QUADRANT_BODY_CONTAINER element", () => {
runTest("bodyRef", Classes.TABLE_QUADRANT_BODY_CONTAINER);
});
it("quadrantRef returns top-level TABLE_QUADRANT element", () => {
runTest("quadrantRef", Classes.TABLE_QUADRANT);
});
it("scrollContainerRef returns TABLE_QUADRANT_SCROLL_CONTAINER element", () => {
runTest("scrollContainerRef", Classes.TABLE_QUADRANT_SCROLL_CONTAINER);
});
function runTest(propKey: "bodyRef" | "quadrantRef" | "scrollContainerRef", expectedClassName: string) {
const refHandler = sinon.spy();
mountTableQuadrant({ [propKey]: refHandler });
expect(refHandler.calledOnce).to.be.true;
const ref = refHandler.firstCall.args[0] as HTMLElement;
expect(ref.classList.contains(expectedClassName)).to.be.true;
}
});
describe("style", () => {
it("applies custom props.style to the top-level element", () => {
// need to use `rgb()` syntax, because colors are expressed that way
// in rendered style object
const style = { background: "rgb(1, 2, 3)", color: "rgb(4, 5, 6)" };
const component = mountTableQuadrant({ style });
const renderedStyle = (component.getDOMNode() as HTMLElement).style;
expect(renderedStyle.background).to.deep.equal(style.background);
expect(renderedStyle.color).to.deep.equal(style.color);
});
});
/**
* <TableQuadrant> knows which portions of the body should be rendered based on the quadrantType,
* and it passes those opinions to the bodyRenderer() callback via flags.
*/
describe("bodyRenderer", () => {
it("invokes with proper params for QuarantType.MAIN", () => {
runTest(QuadrantType.MAIN, [QuadrantType.MAIN, false, false]);
});
it("invokes with proper params for QuarantType.TOP", () => {
runTest(QuadrantType.TOP, [QuadrantType.TOP, true, false]);
});
it("invokes with proper params for QuarantType.LEFT", () => {
runTest(QuadrantType.LEFT, [QuadrantType.LEFT, false, true]);
});
it("invokes with proper params for QuarantType.TOP_LEFT", () => {
runTest(QuadrantType.TOP_LEFT, [QuadrantType.TOP_LEFT, true, true]);
});
it("invokes with no params when quarantType not provided", () => {
runTest(undefined, []);
});
function runTest(quadrantType: QuadrantType, expectedArgs: any[]) {
mountTableQuadrant({ quadrantType });
expect(bodyRenderer.calledOnce).to.be.true;
expect(bodyRenderer.firstCall.args).to.deep.equal(expectedArgs);
}
});
describe("Render logic", () => {
describe("Menu", () => {
const MENU_CLASS = "foo";
it("renders menu if menuRenderer provided", () => {
const menuRenderer = sinon.stub().returns(<div className={MENU_CLASS} />);
const component = mountTableQuadrant({ menuRenderer });
expect(menuRenderer.called).to.be.true;
expect(component.find(`.${Classes.TABLE_TOP_CONTAINER} > .${MENU_CLASS}`).length).to.equal(1);
});
it("does not render menu if menuRenderer not provided", () => {
const component = mountTableQuadrant();
expect(component.find(`.${Classes.TABLE_TOP_CONTAINER}`).children().length).to.equal(0);
});
it("does not render menu if enableRowHeader=false", () => {
const menuRenderer = sinon.stub().returns(<div className={MENU_CLASS} />);
const component = mountTableQuadrant({ enableRowHeader: false, menuRenderer });
expect(menuRenderer.called).to.be.false;
expect(component.find(`.${Classes.TABLE_TOP_CONTAINER}`).children().length).to.equal(0);
});
});
describe("Row header", () => {
const ROW_HEADER_CLASS = "foo";
it("renders row header if rowHeaderCellRenderer provided", () => {
const rowHeaderCellRenderer = sinon.stub().returns(<div className={ROW_HEADER_CLASS} />);
const component = mountTableQuadrant({ rowHeaderCellRenderer });
expect(rowHeaderCellRenderer.called).to.be.true;
expect(component.find(`.${Classes.TABLE_BOTTOM_CONTAINER} > .${ROW_HEADER_CLASS}`).length).to.equal(1);
});
it("does not render row header if rowHeaderCellRenderer not provided", () => {
const component = mountTableQuadrant();
// just the body should exist
expect(component.find(`.${Classes.TABLE_BOTTOM_CONTAINER}`).children().length).to.equal(1);
});
it("does not render row header if enableRowHeader=false", () => {
const rowHeaderCellRenderer = sinon.stub().returns(<div className={ROW_HEADER_CLASS} />);
const component = mountTableQuadrant({
enableRowHeader: false,
rowHeaderCellRenderer,
});
expect(rowHeaderCellRenderer.called).to.be.false;
expect(component.find(`.${Classes.TABLE_BOTTOM_CONTAINER}`).children().length).to.equal(1);
});
});
describe("Column header", () => {
const COLUMN_HEADER_CLASS = "foo";
it("renders column header if columnHeaderCellRenderer provided", () => {
const columnHeaderCellRenderer = sinon.stub().returns(<div className={COLUMN_HEADER_CLASS} />);
const component = mountTableQuadrant({ columnHeaderCellRenderer });
expect(columnHeaderCellRenderer.called).to.be.true;
expect(component.find(`.${Classes.TABLE_TOP_CONTAINER} > .${COLUMN_HEADER_CLASS}`).length).to.equal(1);
});
it("does not render column header if columnHeaderCellRenderer not provided", () => {
const component = mountTableQuadrant();
expect(component.find(`.${Classes.TABLE_TOP_CONTAINER}`).children().length).to.equal(0);
});
it("still renders column header if enableRowHeader=false", () => {
const columnHeaderCellRenderer = sinon.stub().returns(<div className={COLUMN_HEADER_CLASS} />);
const component = mountTableQuadrant({
columnHeaderCellRenderer,
enableRowHeader: false,
});
expect(columnHeaderCellRenderer.called).to.be.true;
expect(component.find(`.${Classes.TABLE_TOP_CONTAINER} > .${COLUMN_HEADER_CLASS}`).length).to.equal(1);
});
});
});
describe("CSS classes", () => {
it("renders outermost element with TABLE_QUADRANT_MAIN class if quadrantType=MAIN", () => {
runTest(QuadrantType.MAIN, Classes.TABLE_QUADRANT_MAIN);
});
it("renders outermost element with TABLE_QUADRANT_TOP class if quadrantType=TOP", () => {
runTest(QuadrantType.TOP, Classes.TABLE_QUADRANT_TOP);
});
it("renders outermost element with TABLE_QUADRANT_LEFT class if quadrantType=LEFT", () => {
runTest(QuadrantType.LEFT, Classes.TABLE_QUADRANT_LEFT);
});
it("renders outermost element with TABLE_QUADRANT_TOP_LEFT class if quadrantType=TOP_LEFT", () => {
runTest(QuadrantType.TOP_LEFT, Classes.TABLE_QUADRANT_TOP_LEFT);
});
it("renders outermost element with no custom class if quadrantTypeย not provided", () => {
const component = mountTableQuadrant();
const element = getDomNode(component);
expect(element.classList.toString()).to.equal(Classes.TABLE_QUADRANT);
});
it("applies custom props.className to outermost element", () => {
const CUSTOM_CLASS = "foo";
const component = mountTableQuadrant({ className: CUSTOM_CLASS });
const element = getDomNode(component);
expect(element.classList.contains(CUSTOM_CLASS)).to.be.true;
});
function runTest(quadrantType: QuadrantType, expectedCssClass: string) {
const component = mountTableQuadrant({ quadrantType });
const element = getDomNode(component);
expect(element.classList.contains(expectedCssClass)).to.be.true;
}
});
function getDomNode(component: ReactWrapper<any, any>) {
return component.getDOMNode() as HTMLElement;
}
function mountTableQuadrant(props: Partial<ITableQuadrantProps> = {}) {
return mount(<TableQuadrant grid={grid} bodyRenderer={bodyRenderer} {...props} />);
}
}); | the_stack |
import { IKeyboardEvent, IKeyboardResult, KeyboardResultType } from 'common/Types';
import { C0 } from 'common/data/EscapeSequences';
// reg + shift key mappings for digits and special chars
const KEYCODE_KEY_MAPPINGS: { [key: number]: [string, string]} = {
// digits 0-9
48: ['0', ')'],
49: ['1', '!'],
50: ['2', '@'],
51: ['3', '#'],
52: ['4', '$'],
53: ['5', '%'],
54: ['6', '^'],
55: ['7', '&'],
56: ['8', '*'],
57: ['9', '('],
// special chars
186: [';', ':'],
187: ['=', '+'],
188: [',', '<'],
189: ['-', '_'],
190: ['.', '>'],
191: ['/', '?'],
192: ['`', '~'],
219: ['[', '{'],
220: ['\\', '|'],
221: [']', '}'],
222: ['\'', '"']
};
export function evaluateKeyboardEvent(
ev: IKeyboardEvent,
applicationCursorMode: boolean,
isMac: boolean,
macOptionIsMeta: boolean
): IKeyboardResult {
const result: IKeyboardResult = {
type: KeyboardResultType.SEND_KEY,
// Whether to cancel event propagation (NOTE: this may not be needed since the event is
// canceled at the end of keyDown
cancel: false,
// The new key even to emit
key: undefined
};
const modifiers = (ev.shiftKey ? 1 : 0) | (ev.altKey ? 2 : 0) | (ev.ctrlKey ? 4 : 0) | (ev.metaKey ? 8 : 0);
switch (ev.keyCode) {
case 0:
if (ev.key === 'UIKeyInputUpArrow') {
if (applicationCursorMode) {
result.key = C0.ESC + 'OA';
} else {
result.key = C0.ESC + '[A';
}
}
else if (ev.key === 'UIKeyInputLeftArrow') {
if (applicationCursorMode) {
result.key = C0.ESC + 'OD';
} else {
result.key = C0.ESC + '[D';
}
}
else if (ev.key === 'UIKeyInputRightArrow') {
if (applicationCursorMode) {
result.key = C0.ESC + 'OC';
} else {
result.key = C0.ESC + '[C';
}
}
else if (ev.key === 'UIKeyInputDownArrow') {
if (applicationCursorMode) {
result.key = C0.ESC + 'OB';
} else {
result.key = C0.ESC + '[B';
}
}
break;
case 8:
// backspace
if (ev.shiftKey) {
result.key = C0.BS; // ^H
break;
} else if (ev.altKey) {
result.key = C0.ESC + C0.DEL; // \e ^?
break;
}
result.key = C0.DEL; // ^?
break;
case 9:
// tab
if (ev.shiftKey) {
result.key = C0.ESC + '[Z';
break;
}
result.key = C0.HT;
result.cancel = true;
break;
case 13:
// return/enter
result.key = ev.altKey ? C0.ESC + C0.CR : C0.CR;
result.cancel = true;
break;
case 27:
// escape
result.key = C0.ESC;
if (ev.altKey) {
result.key = C0.ESC + C0.ESC;
}
result.cancel = true;
break;
case 37:
// left-arrow
if (ev.metaKey) {
break;
}
if (modifiers) {
result.key = C0.ESC + '[1;' + (modifiers + 1) + 'D';
// HACK: Make Alt + left-arrow behave like Ctrl + left-arrow: move one word backwards
// http://unix.stackexchange.com/a/108106
// macOS uses different escape sequences than linux
if (result.key === C0.ESC + '[1;3D') {
result.key = C0.ESC + (isMac ? 'b' : '[1;5D');
}
} else if (applicationCursorMode) {
result.key = C0.ESC + 'OD';
} else {
result.key = C0.ESC + '[D';
}
break;
case 39:
// right-arrow
if (ev.metaKey) {
break;
}
if (modifiers) {
result.key = C0.ESC + '[1;' + (modifiers + 1) + 'C';
// HACK: Make Alt + right-arrow behave like Ctrl + right-arrow: move one word forward
// http://unix.stackexchange.com/a/108106
// macOS uses different escape sequences than linux
if (result.key === C0.ESC + '[1;3C') {
result.key = C0.ESC + (isMac ? 'f' : '[1;5C');
}
} else if (applicationCursorMode) {
result.key = C0.ESC + 'OC';
} else {
result.key = C0.ESC + '[C';
}
break;
case 38:
// up-arrow
if (ev.metaKey) {
break;
}
if (modifiers) {
result.key = C0.ESC + '[1;' + (modifiers + 1) + 'A';
// HACK: Make Alt + up-arrow behave like Ctrl + up-arrow
// http://unix.stackexchange.com/a/108106
// macOS uses different escape sequences than linux
if (!isMac && result.key === C0.ESC + '[1;3A') {
result.key = C0.ESC + '[1;5A';
}
} else if (applicationCursorMode) {
result.key = C0.ESC + 'OA';
} else {
result.key = C0.ESC + '[A';
}
break;
case 40:
// down-arrow
if (ev.metaKey) {
break;
}
if (modifiers) {
result.key = C0.ESC + '[1;' + (modifiers + 1) + 'B';
// HACK: Make Alt + down-arrow behave like Ctrl + down-arrow
// http://unix.stackexchange.com/a/108106
// macOS uses different escape sequences than linux
if (!isMac && result.key === C0.ESC + '[1;3B') {
result.key = C0.ESC + '[1;5B';
}
} else if (applicationCursorMode) {
result.key = C0.ESC + 'OB';
} else {
result.key = C0.ESC + '[B';
}
break;
case 45:
// insert
if (!ev.shiftKey && !ev.ctrlKey) {
// <Ctrl> or <Shift> + <Insert> are used to
// copy-paste on some systems.
result.key = C0.ESC + '[2~';
}
break;
case 46:
// delete
if (modifiers) {
result.key = C0.ESC + '[3;' + (modifiers + 1) + '~';
} else {
result.key = C0.ESC + '[3~';
}
break;
case 36:
// home
if (modifiers) {
result.key = C0.ESC + '[1;' + (modifiers + 1) + 'H';
} else if (applicationCursorMode) {
result.key = C0.ESC + 'OH';
} else {
result.key = C0.ESC + '[H';
}
break;
case 35:
// end
if (modifiers) {
result.key = C0.ESC + '[1;' + (modifiers + 1) + 'F';
} else if (applicationCursorMode) {
result.key = C0.ESC + 'OF';
} else {
result.key = C0.ESC + '[F';
}
break;
case 33:
// page up
if (ev.shiftKey) {
result.type = KeyboardResultType.PAGE_UP;
} else {
result.key = C0.ESC + '[5~';
}
break;
case 34:
// page down
if (ev.shiftKey) {
result.type = KeyboardResultType.PAGE_DOWN;
} else {
result.key = C0.ESC + '[6~';
}
break;
case 112:
// F1-F12
if (modifiers) {
result.key = C0.ESC + '[1;' + (modifiers + 1) + 'P';
} else {
result.key = C0.ESC + 'OP';
}
break;
case 113:
if (modifiers) {
result.key = C0.ESC + '[1;' + (modifiers + 1) + 'Q';
} else {
result.key = C0.ESC + 'OQ';
}
break;
case 114:
if (modifiers) {
result.key = C0.ESC + '[1;' + (modifiers + 1) + 'R';
} else {
result.key = C0.ESC + 'OR';
}
break;
case 115:
if (modifiers) {
result.key = C0.ESC + '[1;' + (modifiers + 1) + 'S';
} else {
result.key = C0.ESC + 'OS';
}
break;
case 116:
if (modifiers) {
result.key = C0.ESC + '[15;' + (modifiers + 1) + '~';
} else {
result.key = C0.ESC + '[15~';
}
break;
case 117:
if (modifiers) {
result.key = C0.ESC + '[17;' + (modifiers + 1) + '~';
} else {
result.key = C0.ESC + '[17~';
}
break;
case 118:
if (modifiers) {
result.key = C0.ESC + '[18;' + (modifiers + 1) + '~';
} else {
result.key = C0.ESC + '[18~';
}
break;
case 119:
if (modifiers) {
result.key = C0.ESC + '[19;' + (modifiers + 1) + '~';
} else {
result.key = C0.ESC + '[19~';
}
break;
case 120:
if (modifiers) {
result.key = C0.ESC + '[20;' + (modifiers + 1) + '~';
} else {
result.key = C0.ESC + '[20~';
}
break;
case 121:
if (modifiers) {
result.key = C0.ESC + '[21;' + (modifiers + 1) + '~';
} else {
result.key = C0.ESC + '[21~';
}
break;
case 122:
if (modifiers) {
result.key = C0.ESC + '[23;' + (modifiers + 1) + '~';
} else {
result.key = C0.ESC + '[23~';
}
break;
case 123:
if (modifiers) {
result.key = C0.ESC + '[24;' + (modifiers + 1) + '~';
} else {
result.key = C0.ESC + '[24~';
}
break;
default:
// a-z and space
if (ev.ctrlKey && !ev.shiftKey && !ev.altKey && !ev.metaKey) {
if (ev.keyCode >= 65 && ev.keyCode <= 90) {
result.key = String.fromCharCode(ev.keyCode - 64);
} else if (ev.keyCode === 32) {
result.key = C0.NUL;
} else if (ev.keyCode >= 51 && ev.keyCode <= 55) {
// escape, file sep, group sep, record sep, unit sep
result.key = String.fromCharCode(ev.keyCode - 51 + 27);
} else if (ev.keyCode === 56) {
result.key = C0.DEL;
} else if (ev.keyCode === 219) {
result.key = C0.ESC;
} else if (ev.keyCode === 220) {
result.key = C0.FS;
} else if (ev.keyCode === 221) {
result.key = C0.GS;
}
} else if ((!isMac || macOptionIsMeta) && ev.altKey && !ev.metaKey) {
// On macOS this is a third level shift when !macOptionIsMeta. Use <Esc> instead.
const keyMapping = KEYCODE_KEY_MAPPINGS[ev.keyCode];
const key = keyMapping && keyMapping[!ev.shiftKey ? 0 : 1];
if (key) {
result.key = C0.ESC + key;
} else if (ev.keyCode >= 65 && ev.keyCode <= 90) {
const keyCode = ev.ctrlKey ? ev.keyCode - 64 : ev.keyCode + 32;
result.key = C0.ESC + String.fromCharCode(keyCode);
}
} else if (isMac && !ev.altKey && !ev.ctrlKey && !ev.shiftKey && ev.metaKey) {
if (ev.keyCode === 65) { // cmd + a
result.type = KeyboardResultType.SELECT_ALL;
}
} else if (ev.key && !ev.ctrlKey && !ev.altKey && !ev.metaKey && ev.keyCode >= 48 && ev.key.length === 1) {
// Include only keys that that result in a _single_ character; don't include num lock, volume up, etc.
result.key = ev.key;
} else if (ev.key && ev.ctrlKey) {
if (ev.key === '_') { // ^_
result.key = C0.US;
}
}
break;
}
return result;
} | the_stack |
import { AudioConfig } from '@/game/config/audio-config';
import { LogHandler } from '@/game/utilities/log-handler';
import { BinaryReader } from '../file/binary-reader';
import { AdlibCommandCallback } from './sound-image-player';
/*eslint no-constant-condition: ["error", { "checkLoops": false }]*/
enum SoundImagChannelState {
NONE,
SOUND,
MUSIC,
}
/** interpreter for a channel of a song from a sound image file
* by calling 'read' its state is changes by processing commands
* and as result OPL3 command are returned */
export class SoundImageChannels {
public waitTime = 0;
public waitSum = 0;
public programPointer = 0;
public channelPosition = 0;
public di00h = 0;
public di02h = 0;
public di04h = 0;
public di05hL = 0;
public di05hH = 0;
public di07h = 0;
public di08hL = 0;
public di08hH = 0;
public di0Fh = 0;
public di12h = 0;
public di13h = 0;
public unused = 0;
/** only play if this is true */
public playingState: SoundImagChannelState = SoundImagChannelState.NONE;
/** some constants */
public soundImageVersion = 0;
public instrumentPos = 0;
private reader: BinaryReader;
private log: LogHandler = new LogHandler('SoundImageChannels');
private fileConfig: AudioConfig
constructor(reader: BinaryReader,
audioConfig: AudioConfig) {
this.fileConfig = audioConfig;
this.reader = new BinaryReader(reader);
}
/** read the channel data and write it to the callback */
public read(commandCallback: AdlibCommandCallback) {
if (this.playingState == SoundImagChannelState.NONE) {
return;
}
this.waitTime--;
const saveChannelPosition = this.channelPosition;
if (this.waitTime <= 0) {
if (this.soundImageVersion == 1) {
this.readBarVersion1(commandCallback);
} else {
this.readBarVersion2(commandCallback);
}
return;
}
if (this.di13h != 0) {
this.di00h = this.di00h + this.di13h;
this.setFrequency(commandCallback);
}
if (this.reader.readByte(saveChannelPosition) != 0x82) {
if (this.reader.readByte(this.di02h + 0xE) == this.waitTime) {
commandCallback(this.di08hL, this.di08hH);
this.di13h = 0
}
}
}
private readBarVersion1(commandCallback: AdlibCommandCallback) {
let cmdPos = this.channelPosition;
while (true) {
const cmd = this.reader.readByte(cmdPos);
cmdPos++;
if ((cmd & 0x80) == 0) {
this.setFrequencyHigh(commandCallback, cmd);
this.channelPosition = cmdPos;
return;
} else if ((cmd >= 0xE0)) {
this.waitSum = (cmd - 0xDF);
} else if ((cmd >= 0xC0)) {
this.setEnvelope(commandCallback, cmd - 0xC0);
} else if ((cmd <= 0xB0)) {
cmdPos = this.part3(commandCallback, cmd, cmdPos);
if (cmdPos < 0) return;
} else {
this.setLevel(commandCallback, cmdPos);
cmdPos++;
}
}
}
private readBarVersion2(commandCallback: AdlibCommandCallback) {
let cmdPos: number = this.channelPosition;
while (true) {
const cmd = this.reader.readByte(cmdPos)
cmdPos++;
if ((cmd & 0x80) == 0) {
this.setFrequencyHigh(commandCallback, cmd);
this.channelPosition = cmdPos;
return;
} else if ((cmd >= 0xE0)) {
this.waitSum = (cmd - 0xDF);
} else if ((cmd <= 0xA0)) {
cmdPos = this.part3(commandCallback, cmd, cmdPos);
if (cmdPos < 0) return;
} else {
this.setEnvelope(commandCallback, cmd - 0xA0);
}
}
}
private setFrequencyHigh(commandCallback: AdlibCommandCallback, cmd: number) {
this.di00h = cmd;
commandCallback(this.di08hL, this.di08hH);
this.setFrequency(commandCallback);
this.waitTime = this.waitSum;
}
private setFrequency(commandCallback: AdlibCommandCallback) {
const mainPos = ((this.di00h + this.di12h) & 0xFF) + 4;
let octave = this.reader.readByte(mainPos + this.fileConfig.octavesOffset)
const frequenciesCount = this.reader.readByte(mainPos + this.fileConfig.frequenciesCountOffset)
let frequency = this.reader.readWordBE(this.fileConfig.frequenciesOffset + frequenciesCount * 32)
if ((frequency & 0x8000) == 0) {
octave--;
}
if ((octave & 0x80) > 0) {
octave++;
frequency = frequency << 1; // * 2
}
/// write low part of frequency
commandCallback(this.di07h + 0xA0, frequency & 0xFF);
/// 0x3 : mask F-Number most sig.
this.di08hH = ((frequency >> 8) & 0x3) | ((octave << 2) & 0xFF);
this.di08hL = this.di07h + 0xB0;
/// write high part of frequency
/// 0x20 = set Key On
commandCallback(this.di08hL, this.di08hH | 0x20);
}
private setEnvelope(commandCallback: AdlibCommandCallback, cmd: number) {
this.di04h = cmd;
let pos = this.instrumentPos;
if (this.playingState == SoundImagChannelState.SOUND) {
pos = this.fileConfig.soundDataOffset;
}
pos = pos + ((cmd - 1) << 4);
/// Attack Rate / Decay Rate
let value = this.reader.readByte(pos + 0);
commandCallback(this.di05hL + 0x60, value);
value = this.reader.readByte(pos + 1);
commandCallback(this.di05hH + 0x60, value);
/// Sustain Level / Release Rate
value = this.reader.readByte(pos + 2);
commandCallback(this.di05hL + 0x80, value);
value = this.reader.readByte(pos + 3);
commandCallback(this.di05hH + 0x80, value);
/// Waveform Select
value = this.reader.readByte(pos + 6);
commandCallback(this.di05hL + 0xE0, value);
value = this.reader.readByte(pos + 7);
commandCallback(this.di05hH + 0xE0, value);
/// 0xC0 -'
value = this.reader.readByte(pos + 9);
commandCallback(this.di07h + 0xC0, value);
/// 0x20 -'
value = this.reader.readByte(pos + 4);
commandCallback(this.di05hL + 0x20, value);
value = this.reader.readByte(pos + 5);
commandCallback(this.di05hH + 0x20, value);
/// other
this.di12h = this.reader.readByte(pos + 8);
this.di0Fh = this.reader.readByte(pos + 11);
this.di02h = pos;
this.setLevel(commandCallback, pos + 10);
}
private part3(commandCallback: AdlibCommandCallback, cmd: number, cmdPos: number): number {
switch (cmd & 0xF) {
case 0:
{
let tmpPos = this.programPointer;
const cx = this.reader.readWordBE(tmpPos);
tmpPos += 2;
if (cx == 0) {
tmpPos = this.reader.readWordBE(tmpPos) + this.fileConfig.instructionsOffset;
cmdPos = this.reader.readWordBE(tmpPos) + this.fileConfig.instructionsOffset;
tmpPos += 2;
} else {
cmdPos = cx + this.fileConfig.instructionsOffset;
}
this.programPointer = tmpPos;
this.channelPosition = cmdPos;
break;
}
case 1:
/// Set frequency
commandCallback(this.di08hL, this.di08hH);
this.di13h = 0;
this.channelPosition = cmdPos;
this.waitTime = this.waitSum;
return -1;
case 2:
this.channelPosition = cmdPos;
this.waitTime = this.waitSum
return -1;
case 3:
this.log.log('not implemented - end of song');
// Todo:
///-- reset all chanels ----
/*
for (let i:number = 0; i< this.channelCount; i++) {
commandCallback(this.di08h_l, this.di08h_h);
this.playingState = AdliChannelsPlayingType.NONE;
}
*/
return -1;
case 4:
this.di12h = this.reader.readByte(cmdPos);
cmdPos++;
break;
case 5:
commandCallback(this.di08hL, this.di08hH);
this.playingState = SoundImagChannelState.NONE;
return -1;
case 6:
this.di13h = 1;
break;
case 7:
this.di13h = 0xFF;
break;
case 8:
this.setLevel(commandCallback, cmdPos);
cmdPos++;
break;
default:
this.log.log('unknown command in part3');
}
return cmdPos;
}
private setLevel(commandCallback: AdlibCommandCallback, cmdPos: number) {
let pos = this.reader.readByte(cmdPos);
let ah = this.reader.readByte((pos & 0x7F) + this.fileConfig.dataOffset);
let al = this.reader.readByte(this.di02h + 0xC);
al = (al << 2) & 0xC0;
ah = ah | al;
commandCallback(this.di05hL + 0x40, ah);
pos = this.di0Fh + this.reader.readByte(this.di02h + 0xA) & 0x7F;
ah = this.reader.readByte(pos + this.fileConfig.dataOffset);
al = this.reader.readByte(this.di02h + 0xC);
al = (al >> 2) & 0xC0;
al = al & 0xC0;
ah = ah | al;
commandCallback(this.di05hH + 0x40, ah);
}
/** init this channel for music */
public initMusic() {
this.channelPosition = this.reader.readWordBE(this.programPointer) + this.fileConfig.instructionsOffset;
/// move the programm pointer
this.programPointer += 2;
this.playingState = SoundImagChannelState.MUSIC;
}
/** init this channel for sound */
public initSound() {
this.playingState = SoundImagChannelState.SOUND;
}
/** read the adlib config for this channel from the giffen offset */
public initChannel(offset: number, index: number) {
offset = offset + index * 20; /// 20: sizeof(Channel-Init-Data)
this.reader.setOffset(offset);
/// read Cahnnel-Init-Data
this.di00h = this.reader.readByte();
this.waitTime = this.reader.readByte();
this.di02h = this.reader.readWordBE();
this.di04h = this.reader.readByte();
this.di05hL = this.reader.readByte();
this.di05hH = this.reader.readByte();
this.di07h = this.reader.readByte();
this.di08hH = this.reader.readByte();
this.di08hL = this.reader.readByte();
this.programPointer = this.reader.readWordBE();
this.channelPosition = this.reader.readWordBE();
this.unused = this.reader.readByte();
this.di0Fh = this.reader.readByte();
this.playingState = this.intToPlayingState(this.reader.readByte());
this.waitSum = this.reader.readByte();
this.di12h = this.reader.readByte();
this.di13h = this.reader.readByte();
}
/** convert a number to a playState */
private intToPlayingState(stateVal: number): SoundImagChannelState {
switch (stateVal) {
case 1:
return SoundImagChannelState.MUSIC;
case 2:
return SoundImagChannelState.SOUND;
default:
return SoundImagChannelState.NONE;
}
}
} | the_stack |
import { DOCUMENT, DatePipe, DecimalPipe, getLocaleNumberFormat, NumberFormatStyle, CurrencyPipe, PercentPipe } from '@angular/common';
import {
AfterContentInit,
AfterViewInit,
ChangeDetectorRef,
ComponentFactoryResolver,
ContentChildren,
ContentChild,
ElementRef,
EventEmitter,
HostBinding,
Inject,
Input,
IterableChangeRecord,
IterableDiffers,
NgZone,
OnDestroy,
OnInit,
Output,
QueryList,
TemplateRef,
ViewChild,
ViewChildren,
ViewContainerRef,
InjectionToken,
Optional,
DoCheck,
Directive,
LOCALE_ID,
HostListener
} from '@angular/core';
import { resizeObservable } from '../core/utils';
import 'igniteui-trial-watermark';
import { Subject, pipe, fromEvent, animationFrameScheduler, merge } from 'rxjs';
import { takeUntil, first, filter, throttleTime, map, shareReplay, takeWhile } from 'rxjs/operators';
import { cloneArray, mergeObjects, compareMaps, resolveNestedPath, isObject, PlatformUtil } from '../core/utils';
import { GridColumnDataType } from '../data-operations/data-util';
import { FilteringLogic, IFilteringExpression } from '../data-operations/filtering-expression.interface';
import { IGroupByRecord } from '../data-operations/groupby-record.interface';
import { ISortingExpression, SortingDirection } from '../data-operations/sorting-expression.interface';
import { IgxGridForOfDirective } from '../directives/for-of/for_of.directive';
import { IgxTextHighlightDirective } from '../directives/text-highlight/text-highlight.directive';
import {
AbsoluteScrollStrategy,
HorizontalAlignment,
VerticalAlignment,
IgxOverlayService,
OverlaySettings,
PositionSettings,
ConnectedPositioningStrategy,
ContainerPositionStrategy,
StateUpdateEvent,
TransactionEventOrigin,
Action,
} from '../services/public_api';
import { GridBaseAPIService } from './api.service';
import { ISummaryExpression } from './summaries/grid-summary';
import { RowEditPositionStrategy, IPinningConfig } from './grid.common';
import { IgxGridToolbarComponent } from './toolbar/grid-toolbar.component';
import { IgxRowDirective } from './row.directive';
import { IgxOverlayOutletDirective, IgxToggleDirective } from '../directives/toggle/toggle.directive';
import {
FilteringExpressionsTree, IFilteringExpressionsTree, FilteringExpressionsTreeType
} from '../data-operations/filtering-expressions-tree';
import { IFilteringOperation } from '../data-operations/filtering-condition';
import { Transaction, TransactionType, TransactionService, State } from '../services/public_api';
import {
IgxRowAddTextDirective,
IgxRowEditTemplateDirective,
IgxRowEditTabStopDirective,
IgxRowEditTextDirective,
IgxRowEditActionsDirective
} from './grid.rowEdit.directive';
import { IgxGridNavigationService, IActiveNode } from './grid-navigation.service';
import { IDisplayDensityOptions, DisplayDensityToken, DisplayDensityBase, DisplayDensity } from '../core/displayDensity';
import { IgxFilteringService } from './filtering/grid-filtering.service';
import { IgxGridFilteringCellComponent } from './filtering/base/grid-filtering-cell.component';
import { WatchChanges } from './watch-changes';
import { IgxGridHeaderGroupComponent } from './headers/grid-header-group.component';
import { IGridResourceStrings } from '../core/i18n/grid-resources';
import { CurrentResourceStrings } from '../core/i18n/resources';
import { IgxGridSummaryService } from './summaries/grid-summary.service';
import { IgxSummaryRowComponent } from './summaries/summary-row.component';
import {
IgxGridSelectionService,
GridSelectionRange
} from './selection/selection.service';
import { IgxEditRow, IgxCell, IgxAddRow } from './common/crud.service';
import { ICachedViewLoadedEventArgs, IgxTemplateOutletDirective } from '../directives/template-outlet/template_outlet.directive';
import { IgxExcelStyleLoadingValuesTemplateDirective } from './filtering/excel-style/excel-style-search.component';
import { IgxGridColumnResizerComponent } from './resizing/resizer.component';
import { CharSeparatedValueData } from '../services/csv/char-separated-value-data';
import { IgxColumnResizingService } from './resizing/resizing.service';
import { IFilteringStrategy } from '../data-operations/filtering-strategy';
import {
IgxRowExpandedIndicatorDirective, IgxRowCollapsedIndicatorDirective,
IgxHeaderExpandIndicatorDirective, IgxHeaderCollapseIndicatorDirective, IgxExcelStyleHeaderIconDirective
} from './grid/grid.directives';
import {
GridKeydownTargetType,
GridSelectionMode,
GridSummaryPosition,
GridSummaryCalculationMode,
FilterMode,
ColumnPinningPosition,
RowPinningPosition,
GridPagingMode
} from './common/enums';
import {
IGridCellEventArgs,
IRowSelectionEventArgs,
IPinColumnEventArgs,
IGridEditEventArgs,
IRowDataEventArgs,
IColumnResizeEventArgs,
IColumnMovingStartEventArgs,
IColumnMovingEventArgs,
IColumnMovingEndEventArgs,
IGridKeydownEventArgs,
IRowDragStartEventArgs,
IRowDragEndEventArgs,
IGridClipboardEvent,
IGridToolbarExportEventArgs,
ISearchInfo,
ICellPosition,
IRowToggleEventArgs,
IColumnSelectionEventArgs,
IPinRowEventArgs,
IGridScrollEventArgs,
IGridEditDoneEventArgs,
IActiveNodeChangeEventArgs,
ISortingEventArgs,
IFilteringEventArgs,
IColumnVisibilityChangedEventArgs,
IColumnVisibilityChangingEventArgs,
IPinColumnCancellableEventArgs
} from './common/events';
import { IgxAdvancedFilteringDialogComponent } from './filtering/advanced-filtering/advanced-filtering-dialog.component';
import { GridType } from './common/grid.interface';
import { DropPosition } from './moving/moving.service';
import { IgxHeadSelectorDirective, IgxRowSelectorDirective } from './selection/row-selectors';
import { IgxColumnComponent } from './columns/column.component';
import { IgxColumnGroupComponent } from './columns/column-group.component';
import { IGridSortingStrategy } from '../data-operations/sorting-strategy';
import { IgxRowDragGhostDirective, IgxDragIndicatorIconDirective } from './row-drag.directive';
import { IgxGridExcelStyleFilteringComponent } from './filtering/excel-style/grid.excel-style-filtering.component';
import { IgxSnackbarComponent } from '../snackbar/snackbar.component';
import { v4 as uuidv4 } from 'uuid';
import { IgxActionStripComponent } from '../action-strip/action-strip.component';
import { DeprecateMethod, DeprecateProperty } from '../core/deprecateDecorators';
import { RowType } from './common/row.interface';
import { IgxGridRowComponent } from './grid/grid-row.component';
import { IPageEventArgs } from '../paginator/paginator-interfaces';
import { IgxPaginatorComponent } from '../paginator/paginator.component';
import { IgxGridHeaderRowComponent } from './headers/grid-header-row.component';
import { IgxGridGroupByAreaComponent } from './grouping/grid-group-by-area.component';
import { IgxFlatTransactionFactory, TRANSACTION_TYPE } from '../services/transaction/transaction-factory.service';
let FAKE_ROW_ID = -1;
const DEFAULT_ITEMS_PER_PAGE = 15;
const MINIMUM_COLUMN_WIDTH = 136;
const FILTER_ROW_HEIGHT = 50;
// By default row editing overlay outlet is inside grid body so that overlay is hidden below grid header when scrolling.
// In cases when grid has 1-2 rows there isn't enough space in grid body and row editing overlay should be shown above header.
// Default row editing overlay height is higher then row height that is why the case is valid also for row with 2 rows.
// More accurate calculation is not possible, cause row editing overlay is still not shown and we don't know its height,
// but in the same time we need to set row editing overlay outlet before opening the overlay itself.
const MIN_ROW_EDITING_COUNT_THRESHOLD = 2;
export const IgxGridTransaction = new InjectionToken<string>('IgxGridTransaction');
@Directive()
export abstract class IgxGridBaseDirective extends DisplayDensityBase implements GridType,
OnInit, DoCheck, OnDestroy, AfterContentInit, AfterViewInit {
/**
* Gets/Sets the display time for the row adding snackbar notification.
*
* @remarks
* By default it is 6000ms.
*/
@Input()
public snackbarDisplayTime = 6000;
/**
* Gets/Sets whether to autogenerate the columns.
*
* @remarks
* The default value is false. When set to true, it will override all columns declared through code or in markup.
* @example
* ```html
* <igx-grid [data]="Data" [autoGenerate]="true"></igx-grid>
* ```
*/
@Input()
public autoGenerate = false;
/**
* Gets/Sets a custom template when empty.
*
* @example
* ```html
* <igx-grid [id]="'igx-grid-1'" [data]="Data" [emptyGridTemplate]="myTemplate" [autoGenerate]="true"></igx-grid>
* ```
*/
@Input()
public emptyGridTemplate: TemplateRef<any>;
/**
* Gets/Sets a custom template for adding row UI when grid is empty.
*
* @example
* ```html
* <igx-grid [id]="'igx-grid-1'" [data]="Data" [addRowEmptyTemplate]="myTemplate" [autoGenerate]="true"></igx-grid>
* ```
*/
@Input()
public addRowEmptyTemplate: TemplateRef<any>;
/**
* Gets/Sets a custom template when loading.
*
* @example
* ```html
* <igx-grid [id]="'igx-grid-1'" [data]="Data" [loadingGridTemplate]="myTemplate" [autoGenerate]="true"></igx-grid>
* ```
*/
@Input()
public loadingGridTemplate: TemplateRef<any>;
/**
* Controls the copy behavior of the grid.
*/
@Input()
public clipboardOptions = {
/**
* Enables/disables the copy behavior
*/
enabled: true,
/**
* Include the columns headers in the clipboard output.
*/
copyHeaders: true,
/**
* Apply the columns formatters (if any) on the data in the clipboard output.
*/
copyFormatters: true,
/**
* The separator used for formatting the copy output. Defaults to `\t`.
*/
separator: '\t'
};
/**
* Emitted after filtering is performed.
*
* @remarks
* Returns the filtering expressions tree of the column for which filtering was performed.
* @example
* ```html
* <igx-grid #grid [data]="localData" [height]="'305px'" [autoGenerate]="true"
* (filteringExpressionsTreeChange)="filteringExprTreeChange($event)"></igx-grid>
* ```
*/
@Output()
public filteringExpressionsTreeChange = new EventEmitter<IFilteringExpressionsTree>();
/**
* Emitted after advanced filtering is performed.
*
* @remarks
* Returns the advanced filtering expressions tree.
* @example
* ```html
* <igx-grid #grid [data]="localData" [height]="'305px'" [autoGenerate]="true"
* (advancedFilteringExpressionsTreeChange)="advancedFilteringExprTreeChange($event)"></igx-grid>
* ```
*/
@Output()
public advancedFilteringExpressionsTreeChange = new EventEmitter<IFilteringExpressionsTree>();
/**
* Emitted when grid is scrolled horizontally/vertically.
*
* @example
* ```html
* <igx-grid #grid [data]="localData" [height]="'305px'" [autoGenerate]="true"
* (gridScroll)="onScroll($event)"></igx-grid>
* ```
*/
@Output()
public gridScroll = new EventEmitter<IGridScrollEventArgs>();
/**
* Emitted after the current page is changed.
*
* @deprecated in version 12.1.0
* @example
* ```html
* <igx-grid (pageChange)="onPageChange($event)"></igx-grid>
* ```
* ```typescript
* public onPageChange(page: number) {
* this.currentPage = page;
* }
* ```
*/
@DeprecateProperty('`pageChange` is deprecated. Use the corresponding output exposed by the `igx-paginator` component instead.')
@Output()
public pageChange = new EventEmitter<number>();
/**
* Emitted when `perPage` property value of the grid is changed.
*
* @deprecated in version 12.1.0
* @example
* ```html
* <igx-grid #grid (perPageChange)="onPerPageChange($event)" [autoGenerate]="true"></igx-grid>
* ```
* ```typescript
* public onPerPageChange(perPage: number) {
* this.perPage = perPage;
* }
* ```
*/
@DeprecateProperty('`perPageChange` is deprecated. Use the corresponding output exposed by the `igx-paginator` component instead.')
@Output()
public perPageChange = new EventEmitter<number>();
/**
* @hidden
* @internal
*/
@Input()
public class = '';
/**
* Gets/Sets the styling classes applied to all even `IgxGridRowComponent`s in the grid.
*
* @example
* ```html
* <igx-grid #grid [data]="Data" [evenRowCSS]="'igx-grid--my-even-class'" [autoGenerate]="true"></igx-grid>
* ```
*/
@DeprecateProperty('`evenRowCSS` is deprecated. We suggest using `rowClasses` property instead.')
@Input()
public evenRowCSS = 'igx-grid__tr--even';
/**
* Gets/Sets the styling classes applied to all odd `IgxGridRowComponent`s in the grid.
*
* @example
* ```html
* <igx-grid #grid [data]="Data" [evenRowCSS]="'igx-grid--my-odd-class'" [autoGenerate]="true"></igx-grid>
* ```
*/
@DeprecateProperty('`oddRowCSS` is deprecated. We suggest using `rowClasses` property instead.')
@Input()
public oddRowCSS = 'igx-grid__tr--odd';
/**
* Sets a conditional class selector to the grid's row element.
* Accepts an object literal, containing key-value pairs,
* where the key is the name of the CSS class and the value is
* either a callback function that returns a boolean, or boolean, like so:
* ```typescript
* callback = (row: RowType) => { return row.selected > 6; }
* rowClasses = { 'className' : this.callback };
* ```
* ```html
* <igx-grid #grid [data]="Data" [rowClasses] = "rowClasses" [autoGenerate]="true"></igx-grid>
* ```
*
* @memberof IgxColumnComponent
*/
@Input()
public rowClasses: any;
/**
* Sets conditional style properties on the grid row element.
* It accepts an object literal where the keys are
* the style properties and the value is an expression to be evaluated.
* ```typescript
* styles = {
* background: 'yellow',
* color: (row: RowType) => row.selected : 'red': 'white'
* }
* ```
* ```html
* <igx-grid #grid [data]="Data" [rowStyles]="styles" [autoGenerate]="true"></igx-grid>
* ```
*
* @memberof IgxColumnComponent
*/
@Input()
public rowStyles = null;
/**
* Gets/Sets the primary key.
*
* @example
* ```html
* <igx-grid #grid [data]="localData" [primaryKey]="'ProductID'" [autoGenerate]="true"></igx-grid>
* ```
*/
@WatchChanges()
@Input()
public primaryKey;
/**
* Gets/Sets a unique values strategy used by the Excel Style Filtering
*
* @remarks
* Provides a callback for loading unique column values on demand.
* If this property is provided, the unique values it generates will be used by the Excel Style Filtering.
* @example
* ```html
* <igx-grid [data]="localData" [filterMode]="'excelStyleFilter'" [uniqueColumnValuesStrategy]="columnValuesStrategy"></igx-grid>
* ```
*/
@Input()
public uniqueColumnValuesStrategy: (column: IgxColumnComponent,
filteringExpressionsTree: IFilteringExpressionsTree,
done: (values: any[]) => void) => void;
/**
* @hidden @internal
*/
@ContentChildren(IgxGridExcelStyleFilteringComponent, { read: IgxGridExcelStyleFilteringComponent, descendants: false })
public excelStyleFilteringComponents: QueryList<IgxGridExcelStyleFilteringComponent>;
public get headerGroups() {
return this.theadRow.groups;
}
/**
* Emitted when a cell is clicked.
*
* @remarks
* Returns the `IgxGridCell`.
* @example
* ```html
* <igx-grid #grid (cellClick)="cellClick($event)" [data]="localData" [height]="'305px'" [autoGenerate]="true"></igx-grid>
* ```
*/
@Output()
public cellClick = new EventEmitter<IGridCellEventArgs>();
/**
* Emitted when a cell is selected.
*
* @remarks
* Returns the `IgxGridCell`.
* @example
* ```html
* <igx-grid #grid (selected)="onCellSelect($event)" [data]="localData" [height]="'305px'" [autoGenerate]="true"></igx-grid>
* ```
*/
@Output()
public selected = new EventEmitter<IGridCellEventArgs>();
/**
* Emitted when `IgxGridRowComponent` is selected.
*
* @example
* ```html
* <igx-grid #grid (rowSelected)="onCellClickChange($event)" [data]="localData" [autoGenerate]="true"></igx-grid>
* ```
*/
@Output()
public rowSelected = new EventEmitter<IRowSelectionEventArgs>();
/**
* Emitted when `IgxColumnComponent` is selected.
*
* @example
* ```html
* <igx-grid #grid (columnSelected)="columnSelected($event)" [data]="localData" [autoGenerate]="true"></igx-grid>
* ```
*/
@Output()
public columnSelected = new EventEmitter<IColumnSelectionEventArgs>();
/**
* Emitted before `IgxColumnComponent` is pinned.
*
* @remarks
* The index at which to insert the column may be changed through the `insertAtIndex` property.
* @example
* ```typescript
* public columnPinning(event) {
* if (event.column.field === "Name") {
* event.insertAtIndex = 0;
* }
* }
* ```
*/
@Output()
public columnPin = new EventEmitter<IPinColumnCancellableEventArgs>();
/**
* Emitted after `IgxColumnComponent` is pinned.
*
* @remarks
* The index that the column is inserted at may be changed through the `insertAtIndex` property.
* @example
* ```typescript
* public columnPinning(event) {
* if (event.column.field === "Name") {
* event.insertAtIndex = 0;
* }
* }
* ```
*/
@Output()
public columnPinned = new EventEmitter<IPinColumnEventArgs>();
/**
* Emitted when cell enters edit mode.
*
* @remarks
* This event is cancelable.
* @example
* ```html
* <igx-grid #grid3 (cellEditEnter)="editStart($event)" [data]="data" [primaryKey]="'ProductID'">
* </igx-grid>
* ```
*/
@Output()
public cellEditEnter = new EventEmitter<IGridEditEventArgs>();
/**
* Emitted when cell exits edit mode.
*
* @example
* ```html
* <igx-grid #grid3 (cellEditExit)="editExit($event)" [data]="data" [primaryKey]="'ProductID'">
* </igx-grid>
* ```
*/
@Output()
public cellEditExit = new EventEmitter<IGridEditDoneEventArgs>();
/**
* Emitted when cell has been edited.
*
* @remarks
* Event is fired after editing is completed, when the cell is exiting edit mode.
* This event is cancelable.
* @example
* ```html
* <igx-grid #grid3 (cellEdit)="editDone($event)" [data]="data" [primaryKey]="'ProductID'">
* </igx-grid>
* ```
*/
@Output()
public cellEdit = new EventEmitter<IGridEditEventArgs>();
/**
* Emitted after cell has been edited and editing has been committed.
*
* @example
* ```html
* <igx-grid #grid3 (cellEditDone)="editDone($event)" [data]="data" [primaryKey]="'ProductID'">
* </igx-grid>
* ```
*/
@Output()
public cellEditDone = new EventEmitter<IGridEditDoneEventArgs>();
/**
* Emitted when a row enters edit mode.
*
* @remarks
* Emitted when [rowEditable]="true".
* This event is cancelable.
* @example
* ```html
* <igx-grid #grid3 (rowEditEnter)="editStart($event)" [primaryKey]="'ProductID'" [rowEditable]="true">
* </igx-grid>
* ```
*/
@Output()
public rowEditEnter = new EventEmitter<IGridEditEventArgs>();
/**
* Emitted when exiting edit mode for a row.
*
* @remarks
* Emitted when [rowEditable]="true" & `endEdit(true)` is called.
* Emitted when changing rows during edit mode, selecting an un-editable cell in the edited row,
* performing paging operation, column resizing, pinning, moving or hitting `Done`
* button inside of the rowEditingOverlay, or hitting the `Enter` key while editing a cell.
* This event is cancelable.
* @example
* ```html
* <igx-grid #grid3 (rowEdit)="editDone($event)" [data]="data" [primaryKey]="'ProductID'" [rowEditable]="true">
* </igx-grid>
* ```
*/
@Output()
public rowEdit = new EventEmitter<IGridEditEventArgs>();
/**
* Emitted after exiting edit mode for a row and editing has been committed.
*
* @remarks
* Emitted when [rowEditable]="true" & `endEdit(true)` is called.
* Emitted when changing rows during edit mode, selecting an un-editable cell in the edited row,
* performing paging operation, column resizing, pinning, moving or hitting `Done`
* button inside of the rowEditingOverlay, or hitting the `Enter` key while editing a cell.
* @example
* ```html
* <igx-grid #grid3 (rowEditDone)="editDone($event)" [data]="data" [primaryKey]="'ProductID'" [rowEditable]="true">
* </igx-grid>
* ```
*/
@Output()
public rowEditDone = new EventEmitter<IGridEditDoneEventArgs>();
/**
* Emitted when row editing is canceled.
*
* @remarks
* Emits when [rowEditable]="true" & `endEdit(false)` is called.
* Emitted when changing hitting `Esc` key during cell editing and when click on the `Cancel` button
* in the row editing overlay.
* @example
* ```html
* <igx-grid #grid3 (rowEditExit)="editExit($event)" [data]="data" [primaryKey]="'ProductID'" [rowEditable]="true">
* </igx-grid>
* ```
*/
@Output()
public rowEditExit = new EventEmitter<IGridEditDoneEventArgs>();
/**
* Emitted when a column is initialized.
*
* @remarks
* Returns the column object.
* @example
* ```html
* <igx-grid #grid [data]="localData" (columnInit)="initColumns($event)" [autoGenerate]="true"></igx-grid>
* ```
*/
@Output()
public columnInit = new EventEmitter<IgxColumnComponent>();
/**
* Emitted before sorting expressions are applied.
*
* @remarks
* Returns an `ISortingEventArgs` object. `sortingExpressions` key holds the sorting expressions.
* @example
* ```html
* <igx-grid #grid [data]="localData" [autoGenerate]="true" (sorting)="sorting($event)"></igx-grid>
* ```
*/
@Output()
public sorting = new EventEmitter<ISortingEventArgs>();
/**
* Emitted after sorting is completed.
*
* @remarks
* Returns the sorting expression.
* @example
* ```html
* <igx-grid #grid [data]="localData" [autoGenerate]="true" (sortingDone)="sortingDone($event)"></igx-grid>
* ```
*/
@Output()
public sortingDone = new EventEmitter<ISortingExpression | Array<ISortingExpression>>();
/**
* Emitted before filtering expressions are applied.
*
* @remarks
* Returns an `IFilteringEventArgs` object. `filteringExpressions` key holds the filtering expressions for the column.
* @example
* ```html
* <igx-grid #grid [data]="localData" [height]="'305px'" [autoGenerate]="true" (filtering)="filtering($event)"></igx-grid>
* ```
*/
@Output()
public filtering = new EventEmitter<IFilteringEventArgs>();
/**
* Emitted after filtering is performed through the UI.
*
* @remarks
* Returns the filtering expressions tree of the column for which filtering was performed.
* @example
* ```html
* <igx-grid #grid [data]="localData" [height]="'305px'" [autoGenerate]="true" (filteringDone)="filteringDone($event)"></igx-grid>
* ```
*/
@Output()
public filteringDone = new EventEmitter<IFilteringExpressionsTree>();
/**
* Emitted after paging is performed.
*
* @deprecated in version 12.1.x
* @remarks
* Returns an object consisting of the previous and next pages.
* @example
* ```html
* <igx-grid #grid [data]="localData" [height]="'305px'" [autoGenerate]="true" (pagingDone)="pagingDone($event)"></igx-grid>
* ```
*/
@DeprecateProperty('`pagingDone` is deprecated. Use the corresponding output exposed by the `igx-paginator` component instead.')
@Output()
public pagingDone = new EventEmitter<IPageEventArgs>();
/**
* Emitted when a row is added.
*
* @remarks
* Returns the data for the new `IgxGridRowComponent` object.
* @example
* ```html
* <igx-grid #grid [data]="localData" (rowAdded)="rowAdded($event)" [height]="'305px'" [autoGenerate]="true"></igx-grid>
* ```
*/
@Output()
public rowAdded = new EventEmitter<IRowDataEventArgs>();
/**
* Emitted when a row is deleted.
*
* @remarks
* Returns an `IRowDataEventArgs` object.
* @example
* ```html
* <igx-grid #grid [data]="localData" (rowDeleted)="rowDeleted($event)" [height]="'305px'" [autoGenerate]="true"></igx-grid>
* ```
*/
@Output()
public rowDeleted = new EventEmitter<IRowDataEventArgs>();
/**
* Emmited when deleting a row.
*
* @remarks
* This event is cancelable.
* Returns an `IGridEditEventArgs` object.
* @example
* ```html
* <igx-grid #grid [data]="localData" (rowDelete)="rowDelete($event)" [height]="'305px'" [autoGenerate]="true"></igx-grid>
* ```
*/
@Output()
public rowDelete = new EventEmitter<IGridEditEventArgs>();
/**
* Emmited just before the newly added row is commited.
*
* @remarks
* This event is cancelable.
* Returns an `IGridEditEventArgs` object.
* @example
* ```html
* <igx-grid #grid [data]="localData" (rowAdd)="rowAdd($event)" [height]="'305px'" [autoGenerate]="true"></igx-grid>
* ```
*/
@Output()
public rowAdd = new EventEmitter<IGridEditEventArgs>();
/**
* Emitted after column is resized.
*
* @remarks
* Returns the `IgxColumnComponent` object's old and new width.
* @example
* ```html
* <igx-grid #grid [data]="localData" (columnResized)="resizing($event)" [autoGenerate]="true"></igx-grid>
* ```
*/
@Output()
public columnResized = new EventEmitter<IColumnResizeEventArgs>();
/**
* Emitted when a cell is right clicked.
*
* @remarks
* Returns the `IgxGridCell` object.
* ```html
* <igx-grid #grid [data]="localData" (contextMenu)="contextMenu($event)" [autoGenerate]="true"></igx-grid>
* ```
*/
@Output()
public contextMenu = new EventEmitter<IGridCellEventArgs>();
/**
* Emitted when a cell is double clicked.
*
* @remarks
* Returns the `IgxGridCell` object.
* @example
* ```html
* <igx-grid #grid [data]="localData" (doubleClick)="dblClick($event)" [autoGenerate]="true"></igx-grid>
* ```
*/
@Output()
public doubleClick = new EventEmitter<IGridCellEventArgs>();
/**
* Emitted before column visibility is changed.
*
* @remarks
* Args: { column: any, newValue: boolean }
* @example
* ```html
* <igx-grid (columnVisibilityChanging)="visibilityChanging($event)"></igx-grid>
* ```
*/
@Output()
public columnVisibilityChanging = new EventEmitter<IColumnVisibilityChangingEventArgs>();
/**
* Emitted after column visibility is changed.
*
* @remarks
* Args: { column: IgxColumnComponent, newValue: boolean }
* @example
* ```html
* <igx-grid (columnVisibilityChanged)="visibilityChanged($event)"></igx-grid>
* ```
*/
@Output()
public columnVisibilityChanged = new EventEmitter<IColumnVisibilityChangedEventArgs>();
/**
* Emitted when column moving starts.
*
* @remarks
* Returns the moved `IgxColumnComponent` object.
* @example
* ```html
* <igx-grid (columnMovingStart)="movingStart($event)"></igx-grid>
* ```
*/
@Output()
public columnMovingStart = new EventEmitter<IColumnMovingStartEventArgs>();
/**
* Emitted during the column moving operation.
*
* @remarks
* Returns the source and target `IgxColumnComponent` objects. This event is cancelable.
* @example
* ```html
* <igx-grid (columnMoving)="moving($event)"></igx-grid>
* ```
*/
@Output()
public columnMoving = new EventEmitter<IColumnMovingEventArgs>();
/**
* Emitted when column moving ends.
*
* @remarks
* Returns the source and target `IgxColumnComponent` objects.
* @example
* ```html
* <igx-grid (columnMovingEnd)="movingEnds($event)"></igx-grid>
* ```
*/
@Output()
public columnMovingEnd = new EventEmitter<IColumnMovingEndEventArgs>();
/**
* Emitted when keydown is triggered over element inside grid's body.
*
* @remarks
* This event is fired only if the key combination is supported in the grid.
* Return the target type, target object and the original event. This event is cancelable.
* @example
* ```html
* <igx-grid (gridKeydown)="customKeydown($event)"></igx-grid>
* ```
*/
@Output()
public gridKeydown = new EventEmitter<IGridKeydownEventArgs>();
/**
* Emitted when start dragging a row.
*
* @remarks
* Return the dragged row.
*/
@Output()
public rowDragStart = new EventEmitter<IRowDragStartEventArgs>();
/**
* Emitted when dropping a row.
*
* @remarks
* Return the dropped row.
*/
@Output()
public rowDragEnd = new EventEmitter<IRowDragEndEventArgs>();
/**
* Emitted when a copy operation is executed.
*
* @remarks
* Fired only if copy behavior is enabled through the [`clipboardOptions`]{@link IgxGridBaseDirective#clipboardOptions}.
*/
@Output()
public gridCopy = new EventEmitter<IGridClipboardEvent>();
/**
* @hidden @internal
*/
@Output()
public expansionStatesChange = new EventEmitter<Map<any, boolean>>();
/**
* Emitted when the expanded state of a row gets changed.
*
* @example
* ```html
* <igx-grid [data]="employeeData" (rowToggle)="rowToggle($event)" [autoGenerate]="true"></igx-grid>
* ```
*/
@Output()
public rowToggle = new EventEmitter<IRowToggleEventArgs>();
/**
* Emitted when the pinned state of a row is changed.
*
* @example
* ```html
* <igx-grid [data]="employeeData" (rowPinning)="rowPin($event)" [autoGenerate]="true"></igx-grid>
* ```
*/
@Output()
public rowPinning = new EventEmitter<IPinRowEventArgs>();
/**
* Emitted when the pinned state of a row is changed.
*
* @example
* ```html
* <igx-grid [data]="employeeData" (rowPinned)="rowPin($event)" [autoGenerate]="true"></igx-grid>
* ```
*/
@Output()
public rowPinned = new EventEmitter<IPinRowEventArgs>();
/**
* Emmited when the active node is changed.
*
* @example
* ```
* <igx-grid [data]="data" [autoGenerate]="true" (activeNodeChange)="activeNodeChange($event)"></igx-grid>
* ```
*/
@Output()
public activeNodeChange = new EventEmitter<IActiveNodeChangeEventArgs>();
/**
* Emitted before sorting is performed.
*
* @remarks
* Returns the sorting expressions.
* @example
* ```html
* <igx-grid #grid [data]="localData" [autoGenerate]="true" (sortingExpressionsChange)="sortingExprChange($event)"></igx-grid>
* ```
*/
@Output()
public sortingExpressionsChange = new EventEmitter<ISortingExpression[]>();
/**
* Emitted when an export process is initiated by the user.
*
* @example
* ```typescript
* toolbarExporting(event: IGridToolbarExportEventArgs){
* const toolbarExporting = event;
* }
* ```
*/
@Output()
public toolbarExporting = new EventEmitter<IGridToolbarExportEventArgs>();
/* End of toolbar related definitions */
/**
* Emitted when making a range selection.
*
* @remarks
* Range selection can be made either through drag selection or through keyboard selection.
*/
@Output()
public rangeSelected = new EventEmitter<GridSelectionRange>();
/** Emitted after the ngAfterViewInit hook. At this point the grid exists in the DOM */
@Output()
public rendered = new EventEmitter<boolean>();
/**
* @hidden @internal
*/
@Output()
public localeChange = new EventEmitter<boolean>();
/**
* @hidden @internal
*/
@ViewChild(IgxSnackbarComponent)
public addRowSnackbar: IgxSnackbarComponent;
/**
* @hidden @internal
*/
@ViewChild(IgxGridColumnResizerComponent)
public resizeLine: IgxGridColumnResizerComponent;
/**
* @hidden @internal
*/
@ViewChild('loadingOverlay', { read: IgxToggleDirective, static: true })
public loadingOverlay: IgxToggleDirective;
/**
* @hidden @internal
*/
@ViewChild('igxLoadingOverlayOutlet', { read: IgxOverlayOutletDirective, static: true })
public loadingOutlet: IgxOverlayOutletDirective;
/**
* @hidden @internal
*/
@ContentChildren(IgxColumnComponent, { read: IgxColumnComponent, descendants: true })
public columnList: QueryList<IgxColumnComponent> = new QueryList<IgxColumnComponent>();
@ContentChild(IgxActionStripComponent)
public actionStrip: IgxActionStripComponent;
/**
* @hidden @internal
*/
@ContentChild(IgxExcelStyleLoadingValuesTemplateDirective, { read: IgxExcelStyleLoadingValuesTemplateDirective, static: true })
public excelStyleLoadingValuesTemplateDirective: IgxExcelStyleLoadingValuesTemplateDirective;
/**
* A template reference for the template when the filtered grid is empty.
*
* @example
* ```
* const emptyTempalte = this.grid.emptyGridTemplate;
* ```
*/
@ViewChild('emptyFilteredGrid', { read: TemplateRef, static: true })
public emptyFilteredGridTemplate: TemplateRef<any>;
/**
* A template reference for the template when the grid is empty.
*
* @example
* ```
* const emptyTempalte = this.grid.emptyGridTemplate;
* ```
*/
@ViewChild('defaultEmptyGrid', { read: TemplateRef, static: true })
public emptyGridDefaultTemplate: TemplateRef<any>;
/**
* @hidden @internal
*/
@ViewChild('defaultLoadingGrid', { read: TemplateRef, static: true })
public loadingGridDefaultTemplate: TemplateRef<any>;
/**
* @hidden @internal
*/
@ViewChild('scrollContainer', { read: IgxGridForOfDirective, static: true })
public parentVirtDir: IgxGridForOfDirective<any>;
/**
* @hidden
* @internal
*/
@ContentChildren(IgxHeadSelectorDirective, { read: IgxHeadSelectorDirective, descendants: false })
public headSelectorsTemplates: QueryList<IgxHeadSelectorDirective>;
/**
* @hidden
* @internal
*/
@ContentChildren(IgxRowSelectorDirective, { read: IgxRowSelectorDirective, descendants: false })
public rowSelectorsTemplates: QueryList<IgxRowSelectorDirective>;
/**
* @hidden
* @internal
*/
@ContentChildren(IgxRowDragGhostDirective, { read: TemplateRef, descendants: false })
public dragGhostCustomTemplates: QueryList<TemplateRef<any>>;
/**
* @hidden @internal
*/
@ViewChild('verticalScrollContainer', { read: IgxGridForOfDirective, static: true })
public verticalScrollContainer: IgxGridForOfDirective<any>;
/**
* @hidden @internal
*/
@ViewChild('verticalScrollHolder', { read: IgxGridForOfDirective, static: true })
public verticalScroll: IgxGridForOfDirective<any>;
/**
* @hidden @internal
*/
@ViewChild('scr', { read: ElementRef, static: true })
public scr: ElementRef;
/** @hidden @internal */
@ViewChild('headSelectorBaseTemplate', { read: TemplateRef, static: true })
public headerSelectorBaseTemplate: TemplateRef<any>;
/**
* @hidden @internal
*/
@ViewChild('footer', { read: ElementRef })
public footer: ElementRef;
public get headerContainer() {
return this.theadRow.headerContainer;
}
public get headerSelectorContainer() {
return this.theadRow.headerSelectorContainer;
}
public get headerDragContainer() {
return this.theadRow.headerDragContainer;
}
public get headerGroupContainer() {
return this.theadRow.headerGroupContainer;
}
public get filteringRow() {
return this.theadRow.filterRow;
}
/** @hidden @internal */
@ViewChild(IgxGridHeaderRowComponent, { static: true })
public theadRow: IgxGridHeaderRowComponent;
/** @hidden @internal */
@ViewChild(IgxGridGroupByAreaComponent)
public groupByArea: IgxGridGroupByAreaComponent;
/**
* @hidden @internal
*/
@ViewChild('tbody', { static: true })
public tbody: ElementRef;
/**
* @hidden @internal
*/
@ViewChild('pinContainer', { read: ElementRef })
public pinContainer: ElementRef;
/**
* @hidden @internal
*/
@ViewChild('tfoot', { static: true })
public tfoot: ElementRef;
/**
* @hidden @internal
*/
@ViewChild('igxRowEditingOverlayOutlet', { read: IgxOverlayOutletDirective, static: true })
public rowEditingOutletDirective: IgxOverlayOutletDirective;
/**
* @hidden @internal
*/
@ViewChildren(IgxTemplateOutletDirective, { read: IgxTemplateOutletDirective })
public tmpOutlets: QueryList<any> = new QueryList<any>();
/**
* @hidden
* @internal
*/
@ViewChild('dragIndicatorIconBase', { read: TemplateRef, static: true })
public dragIndicatorIconBase: TemplateRef<any>;
/**
* @hidden @internal
*/
@ContentChildren(IgxRowEditTemplateDirective, { descendants: false, read: TemplateRef })
public rowEditCustomDirectives: QueryList<TemplateRef<any>>;
/**
* @hidden @internal
*/
@ContentChildren(IgxRowEditTextDirective, { descendants: false, read: TemplateRef })
public rowEditTextDirectives: QueryList<TemplateRef<any>>;
/**
* @hidden @internal
*/
@ContentChild(IgxRowAddTextDirective, { read: TemplateRef })
public rowAddText: TemplateRef<any>;
/**
* @hidden @internal
*/
@ContentChildren(IgxRowEditActionsDirective, { descendants: false, read: TemplateRef })
public rowEditActionsDirectives: QueryList<TemplateRef<any>>;
/**
* The custom template, if any, that should be used when rendering a row expand indicator.
*/
@ContentChild(IgxRowExpandedIndicatorDirective, { read: TemplateRef })
public rowExpandedIndicatorTemplate: TemplateRef<any> = null;
/**
* The custom template, if any, that should be used when rendering a row collapse indicator.
*/
@ContentChild(IgxRowCollapsedIndicatorDirective, { read: TemplateRef })
public rowCollapsedIndicatorTemplate: TemplateRef<any> = null;
/**
* The custom template, if any, that should be used when rendering a header expand indicator.
*/
@ContentChild(IgxHeaderExpandIndicatorDirective, { read: TemplateRef })
public headerExpandIndicatorTemplate: TemplateRef<any> = null;
/**
* The custom template, if any, that should be used when rendering a header collapse indicator.
*/
@ContentChild(IgxHeaderCollapseIndicatorDirective, { read: TemplateRef })
public headerCollapseIndicatorTemplate: TemplateRef<any> = null;
/**
* The custom template, if any, that should be used when rendering a row expand indicator.
*/
@ContentChild(IgxExcelStyleHeaderIconDirective, { read: TemplateRef })
public excelStyleHeaderIconTemplate: TemplateRef<any> = null;
/**
* @hidden
* @internal
*/
@ContentChildren(IgxDragIndicatorIconDirective, { read: TemplateRef, descendants: false })
public dragIndicatorIconTemplates: QueryList<TemplateRef<any>>;
/**
* @hidden @internal
*/
@ViewChildren(IgxRowEditTabStopDirective)
public rowEditTabsDEFAULT: QueryList<IgxRowEditTabStopDirective>;
/**
* @hidden @internal
*/
@ContentChildren(IgxRowEditTabStopDirective, { descendants: true })
public rowEditTabsCUSTOM: QueryList<IgxRowEditTabStopDirective>;
/**
* @hidden @internal
*/
@ViewChild('rowEditingOverlay', { read: IgxToggleDirective })
public rowEditingOverlay: IgxToggleDirective;
/**
* @hidden @internal
*/
@HostBinding('attr.tabindex')
public tabindex = 0;
/**
* @hidden @internal
*/
@HostBinding('attr.role')
public hostRole = 'grid';
/** @hidden @internal */
@ContentChildren(IgxGridToolbarComponent)
public toolbar: QueryList<IgxGridToolbarComponent>;
/** @hidden @internal */
@ContentChildren(IgxPaginatorComponent)
protected paginationComponents: QueryList<IgxPaginatorComponent>;
/**
* @hidden @internal
*/
@ViewChild('igxFilteringOverlayOutlet', { read: IgxOverlayOutletDirective, static: true })
protected _outletDirective: IgxOverlayOutletDirective;
/**
* @hidden @internal
*/
@ViewChild('defaultExpandedTemplate', { read: TemplateRef, static: true })
protected defaultExpandedTemplate: TemplateRef<any>;
/**
* @hidden @internal
*/
@ViewChild('defaultCollapsedTemplate', { read: TemplateRef, static: true })
protected defaultCollapsedTemplate: TemplateRef<any>;
/**
* @hidden @internal
*/
@ViewChild('defaultESFHeaderIcon', { read: TemplateRef, static: true })
protected defaultESFHeaderIconTemplate: TemplateRef<any>;
@ViewChildren('summaryRow', { read: IgxSummaryRowComponent })
protected _summaryRowList: QueryList<IgxSummaryRowComponent>;
@ViewChildren('row')
private _rowList: QueryList<IgxGridRowComponent>;
@ViewChildren('pinnedRow')
private _pinnedRowList: QueryList<IgxGridRowComponent>;
/**
* @hidden @internal
*/
@ViewChild('defaultRowEditTemplate', { read: TemplateRef, static: true })
private defaultRowEditTemplate: TemplateRef<any>;
@ViewChildren(IgxRowDirective, { read: IgxRowDirective })
private _dataRowList: QueryList<IgxRowDirective<IgxGridBaseDirective>>;
/**
* Gets/Sets the resource strings.
*
* @remarks
* By default it uses EN resources.
*/
@Input()
public set resourceStrings(value: IGridResourceStrings) {
this._resourceStrings = Object.assign({}, this._resourceStrings, value);
}
public get resourceStrings(): IGridResourceStrings {
if (!this._resourceStrings) {
this._resourceStrings = CurrentResourceStrings.GridResStrings;
}
return this._resourceStrings;
}
/**
* Gets/Sets the filtering logic of the `IgxGridComponent`.
*
* @remarks
* The default is AND.
* @example
* ```html
* <igx-grid [data]="Data" [autoGenerate]="true" [filteringLogic]="filtering"></igx-grid>
* ```
*/
@WatchChanges()
@Input()
public get filteringLogic() {
return this._filteringExpressionsTree.operator;
}
public set filteringLogic(value: FilteringLogic) {
this._filteringExpressionsTree.operator = value;
}
/**
* Gets/Sets the filtering state.
*
* @example
* ```html
* <igx-grid #grid [data]="Data" [autoGenerate]="true" [(filteringExpressionsTree)]="model.filteringExpressions"></igx-grid>
* ```
* @remarks
* Supports two-way binding.
*/
@WatchChanges()
@Input()
public get filteringExpressionsTree() {
return this._filteringExpressionsTree;
}
public set filteringExpressionsTree(value) {
if (value && value instanceof FilteringExpressionsTree) {
const val = (value as FilteringExpressionsTree);
for (let index = 0; index < val.filteringOperands.length; index++) {
if (!(val.filteringOperands[index] instanceof FilteringExpressionsTree)) {
const newExpressionsTree = new FilteringExpressionsTree(FilteringLogic.And, val.filteringOperands[index].fieldName);
newExpressionsTree.filteringOperands.push(val.filteringOperands[index] as IFilteringExpression);
val.filteringOperands[index] = newExpressionsTree;
}
}
value.type = FilteringExpressionsTreeType.Regular;
this._filteringExpressionsTree = value;
this.filteringPipeTrigger++;
this.filteringExpressionsTreeChange.emit(this._filteringExpressionsTree);
if (this.filteringService.isFilteringExpressionsTreeEmpty(this._filteringExpressionsTree) &&
!this.advancedFilteringExpressionsTree) {
this.filteredData = null;
}
this.filteringService.refreshExpressions();
this.selectionService.clearHeaderCBState();
this.summaryService.clearSummaryCache();
this.notifyChanges();
}
}
/**
* Gets/Sets the advanced filtering state.
*
* @example
* ```typescript
* let advancedFilteringExpressionsTree = this.grid.advancedFilteringExpressionsTree;
* this.grid.advancedFilteringExpressionsTree = logic;
* ```
*/
@WatchChanges()
@Input()
public get advancedFilteringExpressionsTree() {
return this._advancedFilteringExpressionsTree;
}
public set advancedFilteringExpressionsTree(value) {
if (value && value instanceof FilteringExpressionsTree) {
value.type = FilteringExpressionsTreeType.Advanced;
this._advancedFilteringExpressionsTree = value;
this.filteringPipeTrigger++;
} else {
this._advancedFilteringExpressionsTree = null;
}
this.advancedFilteringExpressionsTreeChange.emit(this._advancedFilteringExpressionsTree);
if (this.filteringService.isFilteringExpressionsTreeEmpty(this._advancedFilteringExpressionsTree) &&
!this.advancedFilteringExpressionsTree) {
this.filteredData = null;
}
this.selectionService.clearHeaderCBState();
this.summaryService.clearSummaryCache();
this.notifyChanges();
// Wait for the change detection to update filtered data through the pipes and then emit the event.
requestAnimationFrame(() => this.filteringDone.emit(this._advancedFilteringExpressionsTree));
}
/**
* Gets/Sets the locale.
*
* @remarks
* If not set, returns browser's language.
*/
@Input()
public get locale(): string {
return this._locale;
}
public set locale(value: string) {
if (value !== this._locale) {
this._locale = value;
this._currencyPositionLeft = undefined;
this.summaryService.clearSummaryCache();
this.pipeTrigger++;
this.notifyChanges();
this.localeChange.next();
}
}
@Input()
public get pagingMode() {
return this._pagingMode;
}
public set pagingMode(val: GridPagingMode) {
this._pagingMode = val;
this.pipeTrigger++;
this.notifyChanges(true);
}
/**
* Gets/Sets whether the paging feature is enabled.
*
* @deprecated in version 12.1.x
* @remarks
* The default state is disabled (false).
* @example
* ```html
* <igx-grid #grid [data]="Data" [autoGenerate]="true">
* <igx-paginator></igx-paginator>
* </igx-grid>
* ```
*/
@DeprecateProperty('`paging` is deprecated')
@Input()
public get paging(): boolean {
return this._paging;
}
public set paging(value: boolean) {
this._paging = value;
this.pipeTrigger++;
}
/**
* Gets/Sets the current page index.
*
* @deprecated in version 12.1.x
* @example
* ```html
* <igx-grid #grid [data]="Data" [autoGenerate]="true">
* <igx-paginator [(page)]="model.page"></igx-paginator>
* </igx-grid>
* ```
* @remarks
* Supports two-way binding.
*/
@DeprecateProperty('`page` is deprecated. Use `page` property form `paginator` component instead.')
@Input()
public get page(): number {
return this.paginator?.page || 0;
}
public set page(val: number) {
if (this.paginator) {
this.paginator.page = val;
}
}
/**
* Gets/Sets the number of visible items per page.
*
* @deprecated in version 12.1.x
* @remarks
* The default is 15.
* @example
* ```html
* <igx-grid #grid [data]="Data" [autoGenerate]="true">
* <igx-paginator [(perPage)]="model.perPage"></igx-paginator>
* </igx-grid>
* ```
*/
@DeprecateProperty('`perPage` is deprecated. Use `perPage` property from `paginator` component instead.')
@Input()
public get perPage(): number {
return this.paginator?.perPage || DEFAULT_ITEMS_PER_PAGE;
}
public set perPage(val: number) {
this._perPage = val;
if (this.paginator) {
this.paginator.perPage = val;
}
}
/**
* Gets/Sets if the row selectors are hidden.
*
* @remarks
* By default row selectors are shown
*/
@WatchChanges()
@Input()
public get hideRowSelectors() {
return this._hideRowSelectors;
}
public set hideRowSelectors(value: boolean) {
this._hideRowSelectors = value;
this.notifyChanges(true);
}
/**
* Gets/Sets whether rows can be moved.
*
* @example
* ```html
* <igx-grid #grid [rowDraggable]="true"></igx-grid>
* ```
*/
@Input()
public get rowDraggable(): boolean {
return this._rowDrag && this.hasVisibleColumns;
}
public set rowDraggable(val: boolean) {
this._rowDrag = val;
this.notifyChanges(true);
}
/**
* @hidden
* @internal
*/
public rowDragging = false;
/**
* Gets the row ID that is being dragged.
*
* @remarks
* The row ID is either the primaryKey value or the data record instance.
*/
public dragRowID = null;
/**
* Gets/Sets whether the rows are editable.
*
* @remarks
* By default it is set to false.
* @example
* ```html
* <igx-grid #grid [rowEditable]="true" [primaryKey]="'ProductID'" ></igx-grid>
* ```
*/
@WatchChanges()
@Input()
public get rowEditable(): boolean {
return this._rowEditable;
}
public set rowEditable(val: boolean) {
if (!this._init) {
this.refreshGridState();
}
this._rowEditable = val;
this.notifyChanges();
}
/**
* Gets/Sets the height.
*
* @example
* ```html
* <igx-grid #grid [data]="Data" [height]="'305px'" [autoGenerate]="true"></igx-grid>
* ```
*/
@WatchChanges()
@HostBinding('style.height')
@Input()
public get height(): string | null {
return this._height;
}
public set height(value: string | null) {
if (this._height !== value) {
this._height = value;
this.nativeElement.style.height = value;
this.notifyChanges(true);
}
}
/**
* @hidden @internal
*/
@HostBinding('style.width')
public get hostWidth() {
return this._width || this._hostWidth;
}
/**
* Gets/Sets the width of the grid.
*
* @example
* ```typescript
* let gridWidth = this.grid.width;
* ```
*/
@WatchChanges()
@Input()
public get width(): string | null {
return this._width;
}
public set width(value: string | null) {
if (this._width !== value) {
this._width = value;
this.nativeElement.style.width = value;
this.notifyChanges(true);
}
}
/**
* Gets the width of the header.
*
* @example
* ```html
* let gridHeaderWidth = this.grid.headerWidth;
* ```
*/
public get headerWidth() {
return parseInt(this.width, 10) - 17;
}
/**
* Gets/Sets the row height.
*
* @example
* ```html
* <igx-grid #grid [data]="localData" [rowHeight]="100" [autoGenerate]="true"></igx-grid>
* ```
*/
@WatchChanges()
@Input()
public get rowHeight() {
return this._rowHeight ? this._rowHeight : this.defaultRowHeight;
}
public set rowHeight(value) {
this._rowHeight = parseInt(value, 10);
}
/**
* Gets/Sets the default width of the columns.
*
* @example
* ```html
* <igx-grid #grid [data]="localData" [columnWidth]="100" [autoGenerate]="true"></igx-grid>
* ```
*/
@WatchChanges()
@Input()
public get columnWidth(): string {
return this._columnWidth;
}
public set columnWidth(value: string) {
this._columnWidth = value;
this.columnWidthSetByUser = true;
this.notifyChanges(true);
}
/**
* Get/Sets the message displayed when there are no records.
*
* @example
* ```html
* <igx-grid #grid [data]="Data" [emptyGridMessage]="'The grid is empty'" [autoGenerate]="true"></igx-grid>
* ```
*/
@Input()
public set emptyGridMessage(value: string) {
this._emptyGridMessage = value;
}
public get emptyGridMessage(): string {
return this._emptyGridMessage || this.resourceStrings.igx_grid_emptyGrid_message;
}
/**
* Gets/Sets whether the grid is going to show a loading indicator.
*
* @example
* ```html
* <igx-grid #grid [data]="Data" [isLoading]="true" [autoGenerate]="true"></igx-grid>
* ```
*/
@WatchChanges()
@Input()
public set isLoading(value: boolean) {
if (this._isLoading !== value) {
this._isLoading = value;
if (!!this.data) {
this.evaluateLoadingState();
}
}
Promise.resolve().then(() => {
// wait for the current detection cycle to end before triggering a new one.
this.notifyChanges();
});
}
public get isLoading(): boolean {
return this._isLoading;
}
/**
* Gets/Sets whether the columns should be auto-generated once again after the initialization of the grid
*
* @remarks
* This will allow to bind the grid to remote data and having auto-generated columns at the same time.
* Note that after generating the columns, this property would be disabled to avoid re-creating
* columns each time a new data is assigned.
* @example
* ```typescript
* this.grid.shouldGenerate = true;
* ```
*/
public shouldGenerate: boolean;
/**
* Gets/Sets the message displayed when there are no records and the grid is filtered.
*
* @example
* ```html
* <igx-grid #grid [data]="Data" [emptyGridMessage]="'The grid is empty'" [autoGenerate]="true"></igx-grid>
* ```
*/
@Input()
public set emptyFilteredGridMessage(value: string) {
this._emptyFilteredGridMessage = value;
}
public get emptyFilteredGridMessage(): string {
return this._emptyFilteredGridMessage || this.resourceStrings.igx_grid_emptyFilteredGrid_message;
}
/**
* Gets/Sets the initial pinning configuration.
*
* @remarks
* Allows to apply pinning the columns to the start or the end.
* Note that pinning to both sides at a time is not allowed.
* @example
* ```html
* <igx-grid [pinning]="pinningConfig"></igx-grid>
* ```
*/
@Input()
public get pinning() {
return this._pinning;
}
public set pinning(value) {
if (value !== this._pinning) {
this.resetCaches();
}
this._pinning = value;
}
/**
* Gets/Sets if the filtering is enabled.
*
* @example
* ```html
* <igx-grid #grid [data]="localData" [allowFiltering]="true" [height]="'305px'" [autoGenerate]="true"></igx-grid>
* ```
*/
@Input()
public get allowFiltering() {
return this._allowFiltering;
}
public set allowFiltering(value) {
if (this._allowFiltering !== value) {
this._allowFiltering = value;
this.filteringService.registerSVGIcons();
if (!this._init) {
this.calcGridHeadRow();
}
this.filteringService.isFilterRowVisible = false;
this.filteringService.filteredColumn = null;
this.notifyChanges(true);
}
}
/**
* Gets/Sets a value indicating whether the advanced filtering is enabled.
*
* @example
* ```html
* <igx-grid #grid [data]="localData" [allowAdvancedFiltering]="true" [autoGenerate]="true"></igx-grid>
* ```
*/
@Input()
public get allowAdvancedFiltering() {
return this._allowAdvancedFiltering;
}
public set allowAdvancedFiltering(value) {
if (this._allowAdvancedFiltering !== value) {
this._allowAdvancedFiltering = value;
this.filteringService.registerSVGIcons();
if (!this._init) {
this.notifyChanges(true);
}
}
}
/**
* Gets/Sets the filter mode.
*
* @example
* ```html
* <igx-grid #grid [data]="localData" [filterMode]="'quickFilter'" [height]="'305px'" [autoGenerate]="true"></igx-grid>
* ```
* @remarks
* By default it's set to FilterMode.quickFilter.
*/
@Input()
public get filterMode() {
return this._filterMode;
}
public set filterMode(value: FilterMode) {
this._filterMode = value;
if (this.filteringService.isFilterRowVisible) {
this.filteringRow.close();
}
this.notifyChanges(true);
}
/**
* Gets/Sets the summary position.
*
* @example
* ```html
* <igx-grid #grid [data]="localData" summaryPosition="top" [autoGenerate]="true"></igx-grid>
* ```
* @remarks
* By default it is bottom.
*/
@Input()
public get summaryPosition() {
return this._summaryPosition;
}
public set summaryPosition(value: GridSummaryPosition) {
this._summaryPosition = value;
this.notifyChanges();
}
/**
* Gets/Sets the summary calculation mode.
*
* @example
* ```html
* <igx-grid #grid [data]="localData" summaryCalculationMode="rootLevelOnly" [autoGenerate]="true"></igx-grid>
* ```
* @remarks
* By default it is rootAndChildLevels which means the summaries are calculated for the root level and each child level.
*/
@Input()
public get summaryCalculationMode() {
return this._summaryCalculationMode;
}
public set summaryCalculationMode(value: GridSummaryCalculationMode) {
this._summaryCalculationMode = value;
if (!this._init) {
this.crudService.endEdit(false);
this.summaryService.resetSummaryHeight();
this.notifyChanges(true);
}
}
/**
* Controls whether the summary row is visible when groupBy/parent row is collapsed.
*
* @example
* ```html
* <igx-grid #grid [data]="localData" [showSummaryOnCollapse]="true" [autoGenerate]="true"></igx-grid>
* ```
* @remarks
* By default showSummaryOnCollapse is set to 'false' which means that the summary row is not visible
* when the groupBy/parent row is collapsed.
*/
@Input()
public get showSummaryOnCollapse() {
return this._showSummaryOnCollapse;
}
public set showSummaryOnCollapse(value: boolean) {
this._showSummaryOnCollapse = value;
this.notifyChanges();
}
/**
* Gets/Sets the filtering strategy of the grid.
*
* @example
* ```html
* <igx-grid #grid [data]="localData" [filterStrategy]="filterStrategy"></igx-grid>
* ```
*/
@Input()
public get filterStrategy(): IFilteringStrategy {
return this._filteringStrategy;
}
public set filterStrategy(classRef: IFilteringStrategy) {
this._filteringStrategy = classRef;
}
/**
* Gets/Sets the sorting strategy of the grid.
*
* @example
* ```html
* <igx-grid #grid [data]="localData" [sortStrategy]="sortStrategy"></igx-grid>
* ```
*/
@Input()
public get sortStrategy(): IGridSortingStrategy {
return this._sortingStrategy;
}
public set sortStrategy(value: IGridSortingStrategy) {
this._sortingStrategy = value;
}
/**
* Gets/Sets the current selection state.
*
* @remarks
* Represents the selected rows' IDs (primary key or rowData)
* @example
* ```html
* <igx-grid [data]="localData" primaryKey="ID" rowSelection="multiple" [selectedRows]="[0, 1, 2]"><igx-grid>
* ```
*/
@Input()
public set selectedRows(rowIDs: any[]) {
this.selectRows(rowIDs || [], true);
}
public get selectedRows(): any[] {
return this.selectionService.getSelectedRows();
}
/**
* @hidden @internal
*/
public get excelStyleFilteringComponent() {
return this.excelStyleFilteringComponents.first;
}
/**
* A list of all `IgxGridHeaderGroupComponent`.
*
* @example
* ```typescript
* const headerGroupsList = this.grid.headerGroupsList;
* ```
*/
public get headerGroupsList(): IgxGridHeaderGroupComponent[] {
return this.theadRow.groups;
}
/**
* A list of all `IgxGridHeaderComponent`.
*
* @example
* ```typescript
* const headers = this.grid.headerCellList;
* ```
*/
public get headerCellList() {
return this.headerGroupsList.map(headerGroup => headerGroup.header).filter(header => header);
}
/**
* A list of all `IgxGridFilteringCellComponent`.
*
* @example
* ```typescript
* const filterCells = this.grid.filterCellList;
* ```
*/
public get filterCellList(): IgxGridFilteringCellComponent[] {
return this.headerGroupsList.map(group => group.filter).filter(cell => cell);
}
/**
* @hidden @internal
*/
public get summariesRowList() {
const res = new QueryList<any>();
if (!this._summaryRowList) {
return res;
}
const sumList = this._summaryRowList.filter((item) => item.element.nativeElement.parentElement !== null);
res.reset(sumList);
return res;
}
/**
* A list of `IgxGridRowComponent`.
*
* @example
* ```typescript
* const rowList = this.grid.rowList;
* ```
*/
public get rowList() {
const res = new QueryList<any>();
if (!this._rowList) {
return res;
}
const rList = this._rowList
.filter((item) => item.element.nativeElement.parentElement !== null)
.sort((a, b) => a.index - b.index);
res.reset(rList);
return res;
}
/**
* A list of currently rendered `IgxGridRowComponent`'s.
*
* @example
* ```typescript
* const dataList = this.grid.dataRowList;
* ```
*/
public get dataRowList(): QueryList<IgxRowDirective<IgxGridBaseDirective>> {
const res = new QueryList<IgxRowDirective<IgxGridBaseDirective>>();
if (!this._dataRowList) {
return res;
}
const rList = this._dataRowList.filter(item => item.element.nativeElement.parentElement !== null).sort((a, b) => a.index - b.index);
res.reset(rList);
return res;
}
/**
* @hidden
* @internal
*/
public get headSelectorTemplate(): TemplateRef<IgxHeadSelectorDirective> {
if (this.headSelectorsTemplates && this.headSelectorsTemplates.first) {
return this.headSelectorsTemplates.first.templateRef;
}
return null;
}
/**
* @hidden
* @internal
*/
public get isPinningToStart() {
return this.pinning.columns !== ColumnPinningPosition.End;
}
/**
* @hidden
* @internal
*/
public get isRowPinningToTop() {
return this.pinning.rows !== RowPinningPosition.Bottom;
}
/**
* @hidden
* @internal
*/
public get rowSelectorTemplate(): TemplateRef<IgxRowSelectorDirective> {
if (this.rowSelectorsTemplates && this.rowSelectorsTemplates.first) {
return this.rowSelectorsTemplates.first.templateRef;
}
return null;
}
/**
* @hidden @internal
*/
public get rowOutletDirective() {
return this.rowEditingOutletDirective;
}
/**
* @hidden @internal
*/
public get parentRowOutletDirective() {
return this.outlet;
}
/**
* @hidden @internal
*/
public get rowEditCustom(): TemplateRef<any> {
if (this.rowEditCustomDirectives && this.rowEditCustomDirectives.first) {
return this.rowEditCustomDirectives.first;
}
return null;
}
/**
* @hidden @internal
*/
public get rowEditText(): TemplateRef<any> {
if (this.rowEditTextDirectives && this.rowEditTextDirectives.first) {
return this.rowEditTextDirectives.first;
}
return null;
}
/**
* @hidden @internal
*/
public get rowEditActions(): TemplateRef<any> {
if (this.rowEditActionsDirectives && this.rowEditActionsDirectives.first) {
return this.rowEditActionsDirectives.first;
}
return null;
}
/**
* @hidden @internal
*/
public get rowEditContainer(): TemplateRef<any> {
return this.rowEditCustom ? this.rowEditCustom : this.defaultRowEditTemplate;
}
/**
* The custom template, if any, that should be used when rendering the row drag indicator icon
*/
public get dragIndicatorIconTemplate(): TemplateRef<any> {
return this._customDragIndicatorIconTemplate || this.dragIndicatorIconTemplates.first;
}
public set dragIndicatorIconTemplate(val: TemplateRef<any>) {
this._customDragIndicatorIconTemplate = val;
}
/**
* @hidden @internal
*/
public get firstEditableColumnIndex(): number {
const index = this.visibleColumns.filter(col => col.editable)
.map(c => c.visibleIndex).sort((a, b) => a - b);
return index.length ? index[0] : null;
}
/**
* @hidden @internal
*/
public get lastEditableColumnIndex(): number {
const index = this.visibleColumns.filter(col => col.editable)
.map(c => c.visibleIndex).sort((a, b) => a > b ? -1 : 1);
return index.length ? index[0] : null;
}
/**
* @hidden @internal
* TODO: Nav service logic doesn't handle 0 results from this querylist
*/
public get rowEditTabs(): QueryList<IgxRowEditTabStopDirective> {
return this.rowEditTabsCUSTOM.length ? this.rowEditTabsCUSTOM : this.rowEditTabsDEFAULT;
}
public get activeDescendant() {
const activeElem = this.navigation.activeNode;
if (!activeElem || !Object.keys(activeElem).length) {
return this.id;
}
return activeElem.row < 0 ?
`${this.id}_${activeElem.row}_${activeElem.mchCache.level}_${activeElem.column}` :
`${this.id}_${activeElem.row}_${activeElem.column}`;
}
/**
* @hidden @internal
*/
@HostBinding('attr.class')
public get hostClass(): string {
const classes = [this.getComponentDensityClass('igx-grid')];
// The custom classes should be at the end.
classes.push(this.class);
return classes.join(' ');
}
public get bannerClass(): string {
const position = this.rowEditPositioningStrategy.isTop ? 'igx-banner__border-top' : 'igx-banner__border-bottom';
return `${this.getComponentDensityClass('igx-banner')} ${position}`;
}
/**
* Gets/Sets the sorting state.
*
* @remarks
* Supports two-way data binding.
* @example
* ```html
* <igx-grid #grid [data]="Data" [autoGenerate]="true" [(sortingExpressions)]="model.sortingExpressions"></igx-grid>
* ```
*/
@WatchChanges()
@Input()
public get sortingExpressions(): ISortingExpression[] {
return this._sortingExpressions;
}
public set sortingExpressions(value: ISortingExpression[]) {
this._sortingExpressions = cloneArray(value);
this.sortingExpressionsChange.emit(this._sortingExpressions);
this.notifyChanges();
}
/**
* @hidden @internal
*/
public get maxLevelHeaderDepth() {
if (this._maxLevelHeaderDepth === null) {
this._maxLevelHeaderDepth = this.hasColumnLayouts ?
this.columnList.reduce((acc, col) => Math.max(acc, col.rowStart), 0) :
this.columnList.reduce((acc, col) => Math.max(acc, col.level), 0);
}
return this._maxLevelHeaderDepth;
}
/**
* Gets the number of hidden columns.
*
* @example
* ```typescript
* const hiddenCol = this.grid.hiddenColumnsCount;
* ``
*/
public get hiddenColumnsCount() {
return this.columnList.filter((col) => col.columnGroup === false && col.hidden === true).length;
}
/**
* Gets the number of pinned columns.
*/
public get pinnedColumnsCount() {
return this.pinnedColumns.filter(col => !col.columnLayout).length;
}
/**
* Gets/Sets whether the grid has batch editing enabled.
* When batch editing is enabled, changes are not made directly to the underlying data.
* Instead, they are stored as transactions, which can later be committed w/ the `commit` method.
*
* @example
* ```html
* <igx-grid [batchEditing]="true" [data]="someData">
* </igx-grid>
* ```
*/
@Input()
public get batchEditing(): boolean {
return this._batchEditing;
}
public set batchEditing(val: boolean) {
if (val !== this._batchEditing) {
delete this._transactions;
this._batchEditing = val;
this.switchTransactionService(val);
this.subscribeToTransactions();
}
}
/**
* Get transactions service for the grid.
*/
public get transactions(): TransactionService<Transaction, State> {
if (this._diTransactions && !this.batchEditing) {
return this._diTransactions;
}
return this._transactions;
}
/**
* @hidden @internal
*/
public get currentRowState(): any {
return this._currentRowState;
}
/**
* @hidden @internal
*/
public get currencyPositionLeft(): boolean {
if (this._currencyPositionLeft !== undefined) {
return this._currencyPositionLeft;
}
const format = getLocaleNumberFormat(this.locale, NumberFormatStyle.Currency);
const formatParts = format.split(',');
const i = formatParts.indexOf(formatParts.find(c => c.includes('ยค')));
return this._currencyPositionLeft = i < 1;
}
/**
* Gets/Sets whether exporting to MS Excel is enabled or disabled.
*
* @deprecated
*
* @example
* ```html
* <igx-grid [data]="localData" [showToolbar]="true" [autoGenerate]="true" [exportExcel]="true"></igx-grid>
* ```
*/
@DeprecateProperty('`exportExcel` is deprecated')
@Input()
public get exportExcel(): boolean {
return this.getExportExcel();
}
public set exportExcel(newValue: boolean) {
this._exportExcel = newValue;
this.notifyChanges();
}
/**
* Gets/Sets whether the option for exporting to CSV is enabled or disabled.
*
* @deprecated
*
* ```html
* <igx-grid [data]="localData" [showToolbar]="true" [autoGenerate]="true" [exportCsv]="true"></igx-grid>
* ```
*/
@DeprecateProperty('`exportCsv` is deprecated')
@Input()
public get exportCsv(): boolean {
return this.getExportCsv();
}
public set exportCsv(newValue: boolean) {
this._exportCsv = newValue;
this.notifyChanges();
}
/**
* Gets/Sets the textual content for the main export button.
*
* @deprecated
*
* @example
* ```html
* <igx-grid [data]="localData" [showToolbar]="true" [exportText]="'My Exporter'" [exportCsv]="true"></igx-grid>
* ```
*/
@DeprecateProperty('`exportText` is deprecated')
@Input()
public get exportText(): string {
return this._exportText;
}
public set exportText(newValue: string) {
this._exportText = newValue;
this.notifyChanges();
}
/**
* Gets/Sets the textual content for the MS Excel export button.
*
* @deprecated
*
* ```html
* <igx-grid [exportExcelText]="'My Excel Exporter" [showToolbar]="true" [exportText]="'My Exporter'" [exportCsv]="true"></igx-grid>
* ```
*/
@DeprecateProperty('`exportExcelText` is deprecated')
@Input()
public get exportExcelText(): string {
return this._exportExcelText;
}
public set exportExcelText(newValue: string) {
this._exportExcelText = newValue;
this.notifyChanges();
}
/**
* Gets/Sets the textual content for the CSV export button.
*
* @deprecated
*
* @example
* ```html
* <igx-grid [exportCsvText]="'My Csv Exporter" [showToolbar]="true" [exportText]="'My Exporter'" [exportExcel]="true"></igx-grid>
* ```
*/
@DeprecateProperty('`exportCsvText` is deprecated')
@Input()
public get exportCsvText(): string {
return this._exportCsvText;
}
public set exportCsvText(newValue: string) {
this._exportCsvText = newValue;
this.notifyChanges();
}
/**
* Gets/Sets cell selection mode.
*
* @remarks
* By default the cell selection mode is multiple
* @param selectionMode: GridSelectionMode
*/
@WatchChanges()
@Input()
public get cellSelection() {
return this._cellSelectionMode;
}
public set cellSelection(selectionMode: GridSelectionMode) {
this._cellSelectionMode = selectionMode;
if (this.gridAPI.grid) {
this.selectionService.clear(true);
this.notifyChanges();
}
}
/**
* Gets/Sets row selection mode
*
* @remarks
* By default the row selection mode is 'none'
* Note that in IgxGrid and IgxHierarchicalGrid 'multipleCascade' behaves like 'multiple'
*/
@WatchChanges()
@Input()
public get rowSelection() {
return this._rowSelectionMode;
}
public set rowSelection(selectionMode: GridSelectionMode) {
this._rowSelectionMode = selectionMode;
if (!this._init) {
this.selectionService.clearAllSelectedRows();
this.notifyChanges(true);
}
}
/**
* Gets/Sets column selection mode
*
* @remarks
* By default the row selection mode is none
* @param selectionMode: GridSelectionMode
*/
@WatchChanges()
@Input()
public get columnSelection() {
return this._columnSelectionMode;
}
public set columnSelection(selectionMode: GridSelectionMode) {
this._columnSelectionMode = selectionMode;
if (this.gridAPI.grid) {
this.selectionService.clearAllSelectedColumns();
this.notifyChanges(true);
}
}
/**
* @hidden @internal
*/
public set pagingState(value) {
this._pagingState = value;
if (this.paginator && !this._init) {
this.paginator.totalRecords = value.metadata.countRecords;
}
}
public get pagingState() {
return this._pagingState;
}
/**
* @hidden @internal
*/
public rowEditMessage;
/**
* @hidden @internal
*/
public snackbarActionText = this.resourceStrings.igx_grid_snackbar_addrow_actiontext;
/**
* @hidden @internal
*/
public calcWidth: number;
/**
* @hidden @internal
*/
public calcHeight = 0;
/**
* @hidden @internal
*/
public tfootHeight: number;
/**
* @hidden @internal
*/
public summariesHeight: number;
/**
* @hidden @internal
*/
public disableTransitions = false;
/**
* @hidden @internal
*/
public lastSearchInfo: ISearchInfo = {
searchText: '',
caseSensitive: false,
exactMatch: false,
activeMatchIndex: 0,
matchInfoCache: []
};
/**
* @hidden @internal
*/
public columnWidthSetByUser = false;
/**
* @hidden @internal
*/
public pinnedRecords: any[];
/**
* @hidden @internal
*/
public unpinnedRecords: any[];
public rendered$ = this.rendered.asObservable().pipe(shareReplay(1));
/** @hidden @internal */
public resizeNotify = new Subject();
/** @hidden @internal */
public rowAddedNotifier = new Subject<IRowDataEventArgs>();
/** @hidden @internal */
public rowDeletedNotifier = new Subject<IRowDataEventArgs>();
/** @hidden @internal */
public pipeTriggerNotifier = new Subject();
/**
* @hidden
*/
public _filteredUnpinnedData;
public _destroyed = false;
/**
* @hidden @internal
*/
public decimalPipe: DecimalPipe;
/**
* @hidden @internal
*/
public datePipe: DatePipe;
/**
* @hidden @internal
*/
public currencyPipe: CurrencyPipe;
/**
* @hidden @internal
*/
public percentPipe: PercentPipe;
/**
* @hidden @internal
*/
public _totalRecords = -1;
/**
* @hidden @internal
*/
public columnsWithNoSetWidths = null;
/**
* @hidden @internal
*/
public pipeTrigger = 0;
/**
* @hidden @internal
*/
public filteringPipeTrigger = 0;
/**
* @hidden @internal
*/
public summaryPipeTrigger = 0;
public EMPTY_DATA = [];
/**
* @hidden
*/
protected _perPage = DEFAULT_ITEMS_PER_PAGE;
/**
* @hidden
*/
protected _paging = false;
/**
* @hidden
*/
protected _pagingMode = GridPagingMode.Local;
/**
* @hidden
*/
protected _pagingState;
/**
* @hidden
*/
protected _hideRowSelectors = false;
/**
* @hidden
*/
protected _rowDrag = false;
/**
* @hidden
*/
protected _columns: IgxColumnComponent[] = [];
/**
* @hidden
*/
protected _pinnedColumns: IgxColumnComponent[] = [];
/**
* @hidden
*/
protected _unpinnedColumns: IgxColumnComponent[] = [];
/**
* @hidden
*/
protected _filteringExpressionsTree: IFilteringExpressionsTree = new FilteringExpressionsTree(FilteringLogic.And);
/**
* @hidden
*/
protected _advancedFilteringExpressionsTree: IFilteringExpressionsTree;
/**
* @hidden
*/
protected _sortingExpressions: Array<ISortingExpression> = [];
/**
* @hidden
*/
protected _maxLevelHeaderDepth = null;
/**
* @hidden
*/
protected _columnHiding = false;
/**
* @hidden
*/
protected _columnPinning = false;
protected _pinnedRecordIDs = [];
/**
* @hidden
*/
protected destroy$ = new Subject<any>();
protected _filteredSortedPinnedData: any[];
protected _filteredSortedUnpinnedData: any[];
protected _filteredPinnedData: any[];
/**
* @hidden
*/
protected _hasVisibleColumns;
protected _allowFiltering = false;
protected _allowAdvancedFiltering = false;
protected _filterMode: FilterMode = FilterMode.quickFilter;
protected _defaultTargetRecordNumber = 10;
protected _expansionStates: Map<any, boolean> = new Map<any, boolean>();
protected _defaultExpandState = false;
protected _baseFontSize: number;
protected _headerFeaturesWidth = NaN;
protected _init = true;
protected _cdrRequestRepaint = false;
protected _userOutletDirective: IgxOverlayOutletDirective;
protected _transactions: TransactionService<Transaction, State>;
protected _batchEditing = false;
/** @hidden @internal */
public get paginator() {
return this.paginationComponents?.first;
}
/**
* @hidden @internal
*/
public get scrollSize() {
return this.verticalScrollContainer.getScrollNativeSize();
}
/* Toolbar related definitions */
private _exportExcel = false;
private _exportCsv = false;
private _exportText: string;
private _exportExcelText: string;
private _exportCsvText: string;
private _rowEditable = false;
private _currentRowState: any;
private _filteredSortedData = null;
private _customDragIndicatorIconTemplate: TemplateRef<any>;
private _cdrRequests = false;
private _resourceStrings;
private _emptyGridMessage = null;
private _emptyFilteredGridMessage = null;
private _isLoading = false;
private _locale: string;
private overlayIDs = [];
private _filteringStrategy: IFilteringStrategy;
private _sortingStrategy: IGridSortingStrategy;
private _pinning: IPinningConfig = { columns: ColumnPinningPosition.Start };
private _hostWidth;
private _advancedFilteringOverlayId: string;
private _advancedFilteringPositionSettings: PositionSettings = {
verticalDirection: VerticalAlignment.Middle,
horizontalDirection: HorizontalAlignment.Center,
horizontalStartPoint: HorizontalAlignment.Center,
verticalStartPoint: VerticalAlignment.Middle
};
private _advancedFilteringOverlaySettings: OverlaySettings = {
closeOnOutsideClick: false,
modal: false,
positionStrategy: new ConnectedPositioningStrategy(this._advancedFilteringPositionSettings),
};
private columnListDiffer;
private rowListDiffer;
private _height: string | null = '100%';
private _width: string | null = '100%';
private _rowHeight;
private _horizontalForOfs: Array<IgxGridForOfDirective<any>> = [];
private _multiRowLayoutRowSize = 1;
// Caches
private _totalWidth = NaN;
private _pinnedVisible = [];
private _unpinnedVisible = [];
private _pinnedWidth = NaN;
private _unpinnedWidth = NaN;
private _visibleColumns = [];
private _columnGroups = false;
private _autoGeneratedCols = [];
private _columnWidth: string;
private _summaryPosition: GridSummaryPosition = GridSummaryPosition.bottom;
private _summaryCalculationMode: GridSummaryCalculationMode = GridSummaryCalculationMode.rootAndChildLevels;
private _showSummaryOnCollapse = false;
private _cellSelectionMode: GridSelectionMode = GridSelectionMode.multiple;
private _rowSelectionMode: GridSelectionMode = GridSelectionMode.none;
private _selectRowOnClick = true;
private _columnSelectionMode: GridSelectionMode = GridSelectionMode.none;
private lastAddedRowIndex;
private _currencyPositionLeft: boolean;
private rowEditPositioningStrategy = new RowEditPositionStrategy({
horizontalDirection: HorizontalAlignment.Right,
verticalDirection: VerticalAlignment.Bottom,
horizontalStartPoint: HorizontalAlignment.Left,
verticalStartPoint: VerticalAlignment.Bottom,
closeAnimation: null
});
private rowEditSettings: OverlaySettings = {
scrollStrategy: new AbsoluteScrollStrategy(),
modal: false,
closeOnOutsideClick: false,
outlet: this.rowOutletDirective,
positionStrategy: this.rowEditPositioningStrategy
};
private transactionChange$ = new Subject<void>();
private _rendered = false;
private readonly DRAG_SCROLL_DELTA = 10;
/**
* @hidden @internal
*/
public abstract id: string;
abstract data: any[] | null;
abstract filteredData: any[];
/**
* Returns an array containing the filtered sorted data.
*
* @example
* ```typescript
* const filteredSortedData = this.grid1.filteredSortedData;
* ```
*/
public get filteredSortedData(): any[] {
return this._filteredSortedData;
}
/**
* @hidden @internal
*/
public get rowChangesCount() {
if (!this.crudService.row) {
return 0;
}
const f = (obj: any) => {
let changes = 0;
Object.keys(obj).forEach(key => isObject(obj[key]) ? changes += f(obj[key]) : changes++);
return changes;
};
const rowChanges = this.transactions.getAggregatedValue(this.crudService.row.id, false);
return rowChanges ? f(rowChanges) : 0;
}
/**
* @hidden @internal
*/
public get dataWithAddedInTransactionRows() {
const result = cloneArray(this.gridAPI.get_all_data());
if (this.transactions.enabled) {
result.push(...this.transactions.getAggregatedChanges(true)
.filter(t => t.type === TransactionType.ADD)
.map(t => t.newValue));
}
if (this.crudService.row && this.crudService.row.getClassName() === IgxAddRow.name) {
result.splice(this.crudService.row.index, 0, this.crudService.row.data);
}
return result;
}
/**
* @hidden @internal
*/
public get dataLength() {
return this.transactions.enabled ? this.dataWithAddedInTransactionRows.length : this.gridAPI.get_all_data().length;
}
/**
* @hidden @internal
*/
public get template(): TemplateRef<any> {
if (this.isLoading && (this.hasZeroResultFilter || this.hasNoData)) {
return this.loadingGridTemplate ? this.loadingGridTemplate : this.loadingGridDefaultTemplate;
}
if (this.hasZeroResultFilter) {
return this.emptyGridTemplate ? this.emptyGridTemplate : this.emptyFilteredGridTemplate;
}
if (this.hasNoData) {
return this.emptyGridTemplate ? this.emptyGridTemplate : this.emptyGridDefaultTemplate;
}
}
/**
* @hidden @internal
*/
private get hasZeroResultFilter(): boolean {
return this.filteredData && this.filteredData.length === 0;
}
/**
* @hidden @internal
*/
private get hasNoData(): boolean {
return !this.data || this.dataLength === 0;
}
/**
* @hidden @internal
*/
public get shouldOverlayLoading(): boolean {
return this.isLoading && !this.hasNoData && !this.hasZeroResultFilter;
}
/**
* @hidden @internal
*/
public get isMultiRowSelectionEnabled(): boolean {
return this.rowSelection === GridSelectionMode.multiple
|| this.rowSelection === GridSelectionMode.multipleCascade;
}
/**
* @hidden @internal
*/
public get isRowSelectable(): boolean {
return this.rowSelection !== GridSelectionMode.none;
}
/**
* @hidden @internal
*/
public get isCellSelectable() {
return this.cellSelection !== GridSelectionMode.none;
}
/**
* @hidden @internal
*/
public get columnInDrag() {
return this.gridAPI.cms.column;
}
constructor(
public selectionService: IgxGridSelectionService,
public colResizingService: IgxColumnResizingService,
public gridAPI: GridBaseAPIService<IgxGridBaseDirective & GridType>,
protected transactionFactory: IgxFlatTransactionFactory,
private elementRef: ElementRef<HTMLElement>,
private zone: NgZone,
@Inject(DOCUMENT) public document: any,
public cdr: ChangeDetectorRef,
protected resolver: ComponentFactoryResolver,
protected differs: IterableDiffers,
protected viewRef: ViewContainerRef,
public navigation: IgxGridNavigationService,
public filteringService: IgxFilteringService,
@Inject(IgxOverlayService) protected overlayService: IgxOverlayService,
public summaryService: IgxGridSummaryService,
@Optional() @Inject(DisplayDensityToken) protected _displayDensityOptions: IDisplayDensityOptions,
@Inject(LOCALE_ID) private localeId: string,
protected platform: PlatformUtil,
@Optional() @Inject(IgxGridTransaction) protected _diTransactions?: TransactionService<Transaction, State>) {
super(_displayDensityOptions);
this.locale = this.locale || this.localeId;
this.datePipe = new DatePipe(this.locale);
this.decimalPipe = new DecimalPipe(this.locale);
this.currencyPipe = new CurrencyPipe(this.locale);
this.percentPipe = new PercentPipe(this.locale);
this._transactions = this.transactionFactory.create(TRANSACTION_TYPE.None);
this.cdr.detach();
}
/**
* @hidden
* @internal
*/
@HostListener('mouseleave')
public hideActionStrip() {
this.actionStrip?.hide();
}
/**
* @hidden
* @internal
*/
public get headerFeaturesWidth() {
return this._headerFeaturesWidth;
}
/**
* @hidden
* @internal
*/
public isDetailRecord(_rec) {
return false;
}
/**
* @hidden
* @internal
*/
public isGroupByRecord(_rec) {
return false;
}
/**
* @hidden @internal
*/
public isGhostRecord(record: any): boolean {
return record.ghostRecord !== undefined;
}
/**
* @hidden @internal
*/
public isAddRowRecord(record: any): boolean {
return record.addRow !== undefined;
}
/**
* @hidden
* Returns the row index of a row that takes into account the full view data like pinning.
*/
public getDataViewIndex(rowIndex, pinned) {
if (pinned && !this.isRowPinningToTop) {
rowIndex = rowIndex + this.unpinnedDataView.length;
} else if (!pinned && this.isRowPinningToTop) {
rowIndex = rowIndex + this.pinnedDataView.length;
}
return rowIndex;
}
/**
* @hidden
* @internal
*/
public get hasDetails() {
return false;
}
/**
* Returns the state of the grid virtualization.
*
* @remarks
* Includes the start index and how many records are rendered.
* @example
* ```typescript
* const gridVirtState = this.grid1.virtualizationState;
* ```
*/
public get virtualizationState() {
return this.verticalScrollContainer.state;
}
/**
* @hidden
*/
public set virtualizationState(state) {
this.verticalScrollContainer.state = state;
}
/**
* @hidden
* @internal
*/
public hideOverlays() {
this.overlayIDs.forEach(overlayID => {
const overlay = this.overlayService.getOverlayById(overlayID);
if (overlay?.visible && !overlay.closeAnimationPlayer?.hasStarted()) {
this.overlayService.hide(overlayID);
this.nativeElement.focus();
}
});
}
/**
* Returns whether the record is pinned or not.
*
* @param rowIndex Index of the record in the `dataView` collection.
*
* @hidden
* @internal
*/
public isRecordPinnedByViewIndex(rowIndex: number) {
return this.hasPinnedRecords && (this.isRowPinningToTop && rowIndex < this.pinnedDataView.length) ||
(!this.isRowPinningToTop && rowIndex >= this.unpinnedDataView.length);
}
/**
* Returns whether the record is pinned or not.
*
* @param rowIndex Index of the record in the `filteredSortedData` collection.
*/
public isRecordPinnedByIndex(rowIndex: number) {
return this.hasPinnedRecords && (this.isRowPinningToTop && rowIndex < this._filteredSortedPinnedData.length) ||
(!this.isRowPinningToTop && rowIndex >= this._filteredSortedUnpinnedData.length);
}
/**
* @hidden
* @internal
*/
public isRecordPinned(rec) {
return this.getInitialPinnedIndex(rec) !== -1;
}
/**
* @hidden
* @internal
* Returns the record index in order of pinning by the user. Does not consider sorting/filtering.
*/
public getInitialPinnedIndex(rec) {
const id = this.gridAPI.get_row_id(rec);
return this._pinnedRecordIDs.indexOf(id);
}
/**
* @hidden
* @internal
*/
public get hasPinnedRecords() {
return this._pinnedRecordIDs.length > 0;
}
/**
* @hidden
* @internal
*/
public get pinnedRecordsCount() {
return this._pinnedRecordIDs.length;
}
/**
* @hidden
* @internal
*/
public get crudService() {
return this.gridAPI.crudService;
}
public _setupServices() {
this.gridAPI.grid = this;
this.crudService.grid = this;
this.selectionService.grid = this;
this.navigation.grid = this;
this.filteringService.grid = this;
this.summaryService.grid = this;
}
public _setupListeners() {
const destructor = takeUntil<any>(this.destroy$);
fromEvent(this.nativeElement, 'focusout').pipe(filter(() => !!this.navigation.activeNode), destructor).subscribe((event) => {
if (this.selectionService.dragMode && this.platform.isIE) {
return;
}
if (!this.crudService.cell &&
!!this.navigation.activeNode &&
((event.target === this.tbody.nativeElement && this.navigation.activeNode.row >= 0 &&
this.navigation.activeNode.row < this.dataView.length)
|| (event.target === this.theadRow.nativeElement && this.navigation.activeNode.row === -1)
|| (event.target === this.tfoot.nativeElement && this.navigation.activeNode.row === this.dataView.length)) &&
!(this.rowEditable && this.crudService.rowEditingBlocked && this.crudService.rowInEditMode)) {
this.navigation.lastActiveNode = this.navigation.activeNode;
this.navigation.activeNode = {} as IActiveNode;
this.notifyChanges();
}
});
this.rowAddedNotifier.pipe(destructor).subscribe(args => this.refreshGridState(args));
this.rowDeletedNotifier.pipe(destructor).subscribe(args => {
this.summaryService.deleteOperation = true;
this.summaryService.clearSummaryCache(args);
});
this.subscribeToTransactions();
this.resizeNotify.pipe(
destructor,
filter(() => !this._init),
throttleTime(0, animationFrameScheduler, { leading: true, trailing: true })
)
.subscribe(() => {
this.zone.run(() => {
this.notifyChanges(true);
});
});
this.pipeTriggerNotifier.pipe(takeUntil(this.destroy$)).subscribe(() => this.pipeTrigger++);
this.columnMovingEnd.pipe(destructor).subscribe(() => this.crudService.endEdit(false));
this.overlayService.opening.pipe(destructor).subscribe((event) => {
if (this._advancedFilteringOverlayId === event.id) {
const instance = event.componentRef.instance as IgxAdvancedFilteringDialogComponent;
if (instance) {
instance.initialize(this, this.overlayService, event.id);
}
}
});
this.overlayService.opened.pipe(destructor).subscribe((event) => {
const overlaySettings = this.overlayService.getOverlayById(event.id)?.settings;
// do not hide the advanced filtering overlay on scroll
if (this._advancedFilteringOverlayId === event.id) {
const instance = event.componentRef.instance as IgxAdvancedFilteringDialogComponent;
if (instance) {
instance.lastActiveNode = this.navigation.activeNode;
instance.setAddButtonFocus();
}
return;
}
// do not hide the overlay if it's attached to a row
if (this.rowEditingOverlay?.overlayId === event.id) {
return;
}
if (overlaySettings?.outlet === this.outlet && this.overlayIDs.indexOf(event.id) === -1) {
this.overlayIDs.push(event.id);
}
});
this.overlayService.closed.pipe(destructor, filter(() => !this._init)).subscribe((event) => {
if (this._advancedFilteringOverlayId === event.id) {
this.overlayService.detach(this._advancedFilteringOverlayId);
this._advancedFilteringOverlayId = null;
return;
}
const ind = this.overlayIDs.indexOf(event.id);
if (ind !== -1) {
this.overlayIDs.splice(ind, 1);
}
});
this.verticalScrollContainer.dataChanging.pipe(destructor, filter(() => !this._init)).subscribe(($event) => {
const shouldRecalcSize = this.isPercentHeight &&
(!this.calcHeight || this.calcHeight === this.getDataBasedBodyHeight() ||
this.calcHeight === this.renderedRowHeight * this._defaultTargetRecordNumber);
if (shouldRecalcSize) {
this.calculateGridHeight();
$event.containerSize = this.calcHeight;
}
this.evaluateLoadingState();
});
this.verticalScrollContainer.scrollbarVisibilityChanged.pipe(destructor, filter(() => !this._init)).subscribe(() => {
// called to recalc all widths that may have changes as a result of
// the vert. scrollbar showing/hiding
this.notifyChanges(true);
});
this.verticalScrollContainer.contentSizeChange.pipe(destructor, filter(() => !this._init)).subscribe(() => {
this.calculateGridSizes(false);
});
this.onDensityChanged.pipe(destructor).subscribe(() => {
this.crudService.endEdit(false);
this.summaryService.summaryHeight = 0;
this.notifyChanges(true);
});
}
/**
* @hidden
*/
public ngOnInit() {
super.ngOnInit();
this._setupServices();
this._setupListeners();
this.rowListDiffer = this.differs.find([]).create(null);
this.columnListDiffer = this.differs.find([]).create(null);
this.calcWidth = this.width && this.width.indexOf('%') === -1 ? parseInt(this.width, 10) : 0;
this.shouldGenerate = this.autoGenerate;
}
/**
* @hidden
* @internal
*/
public resetColumnsCaches() {
this.columnList.forEach(column => column.resetCaches());
}
/**
* @hidden @internal
*/
public generateRowID(): string | number {
const primaryColumn = this.columnList.find(col => col.field === this.primaryKey);
const idType = this.data.length ?
this.resolveDataTypes(this.data[0][this.primaryKey]) : primaryColumn ? primaryColumn.dataType : 'string';
return idType === 'string' ? uuidv4() : FAKE_ROW_ID--;
}
/**
* @hidden
* @internal
*/
public resetForOfCache() {
const firstVirtRow = this.dataRowList.first;
if (firstVirtRow) {
if (this._cdrRequests) {
firstVirtRow.virtDirRow.cdr.detectChanges();
}
firstVirtRow.virtDirRow.assumeMaster();
}
}
/**
* @hidden
* @internal
*/
public setFilteredData(data, pinned: boolean) {
if (this.hasPinnedRecords && pinned) {
this._filteredPinnedData = data || [];
const filteredUnpinned = this._filteredUnpinnedData || [];
const filteredData = [... this._filteredPinnedData, ...filteredUnpinned];
this.filteredData = filteredData.length > 0 ? filteredData : this._filteredUnpinnedData;
} else if (this.hasPinnedRecords && !pinned) {
this._filteredUnpinnedData = data;
} else {
this.filteredData = data;
}
}
/**
* @hidden
* @internal
*/
public resetColumnCollections() {
this._visibleColumns.length = 0;
this._pinnedVisible.length = 0;
this._unpinnedVisible.length = 0;
}
/**
* @hidden
* @internal
*/
public resetCachedWidths() {
this._unpinnedWidth = NaN;
this._pinnedWidth = NaN;
this._totalWidth = NaN;
}
/**
* @hidden
* @internal
*/
public resetCaches(recalcFeatureWidth = true) {
if (recalcFeatureWidth) {
this._headerFeaturesWidth = NaN;
}
this.resetForOfCache();
this.resetColumnsCaches();
this.resetColumnCollections();
this.resetCachedWidths();
this.hasVisibleColumns = undefined;
this._columnGroups = this.columnList.some(col => col.columnGroup);
}
/**
* @hidden
*/
public ngAfterContentInit() {
this.setupColumns();
this.toolbar.changes.pipe(takeUntil(this.destroy$), filter(() => !this._init)).subscribe(() => this.notifyChanges(true));
this.setUpPaginator();
this.paginationComponents.changes.pipe(takeUntil(this.destroy$)).subscribe(() => {
this.setUpPaginator();
});
if (this.actionStrip) {
this.actionStrip.menuOverlaySettings.outlet = this.outlet;
}
}
/** @hidden @internal */
public setUpPaginator() {
if (this.paginator) {
this.paginator.pageChange.pipe(takeWhile(() => !!this.paginator), filter(() => !this._init))
.subscribe((page: number) => {
this.pageChange.emit(page);
});
this.paginator.pagingDone.pipe(takeWhile(() => !!this.paginator), filter(() => !this._init))
.subscribe((args: IPageEventArgs) => {
this.selectionService.clear(true);
this.pagingDone.emit({ previous: args.previous, current: args.current });
this.crudService.endEdit(false);
this.pipeTrigger++;
this.navigateTo(0);
this.notifyChanges();
});
this.paginator.perPageChange.pipe(takeWhile(() => !!this.paginator), filter(() => !this._init))
.subscribe((perPage: number) => {
this.selectionService.clear(true);
this.perPageChange.emit(perPage);
this.paginator.page = 0;
this.crudService.endEdit(false);
this.notifyChanges();
});
} else {
this.markForCheck();
}
}
/**
* @hidden
* @internal
*/
public setFilteredSortedData(data, pinned: boolean) {
data = data || [];
if (this.pinnedRecordsCount > 0 && pinned) {
this._filteredSortedPinnedData = data;
this.pinnedRecords = data;
this._filteredSortedData = this.isRowPinningToTop ? [... this._filteredSortedPinnedData, ... this._filteredSortedUnpinnedData] :
[... this._filteredSortedUnpinnedData, ... this._filteredSortedPinnedData];
this.refreshSearch(true, false);
} else if (this.pinnedRecordsCount > 0 && !pinned) {
this._filteredSortedUnpinnedData = data;
} else {
this._filteredSortedData = data;
this.refreshSearch(true, false);
}
}
/**
* @hidden @internal
*/
public resetHorizontalForOfs() {
const elementFilter = (item: IgxRowDirective<any> | IgxSummaryRowComponent) => this.isDefined(item.nativeElement.parentElement);
this._horizontalForOfs = [
...this._dataRowList.filter(elementFilter).map(item => item.virtDirRow),
...this._summaryRowList.filter(elementFilter).map(item => item.virtDirRow)
];
}
/**
* @hidden @internal
*/
public _setupRowObservers() {
const elementFilter = (item: IgxRowDirective<any> | IgxSummaryRowComponent) => this.isDefined(item.nativeElement.parentElement);
const extractForOfs = pipe(map((collection: any[]) => collection.filter(elementFilter).map(item => item.virtDirRow)));
const rowListObserver = extractForOfs(this._dataRowList.changes);
const summaryRowObserver = extractForOfs(this._summaryRowList.changes);
rowListObserver.pipe(takeUntil(this.destroy$)).subscribe(() => {
this.resetHorizontalForOfs();
});
summaryRowObserver.pipe(takeUntil(this.destroy$)).subscribe(() => {
this.resetHorizontalForOfs();
});
this.resetHorizontalForOfs();
}
/**
* @hidden @internal
*/
public _zoneBegoneListeners() {
this.zone.runOutsideAngular(() => {
this.verticalScrollContainer.getScroll().addEventListener('scroll', this.verticalScrollHandler.bind(this));
this.headerContainer.getScroll().addEventListener('scroll', this.horizontalScrollHandler.bind(this));
fromEvent(window, 'resize').pipe(takeUntil(this.destroy$)).subscribe(() => this.resizeNotify.next());
resizeObservable(this.nativeElement).pipe(takeUntil(this.destroy$)).subscribe(() => this.resizeNotify.next());
});
}
/**
* @hidden
*/
public ngAfterViewInit() {
this.initPinning();
this.calculateGridSizes();
this._init = false;
this.cdr.reattach();
this._setupRowObservers();
this._zoneBegoneListeners();
const vertScrDC = this.verticalScrollContainer.displayContainer;
vertScrDC.addEventListener('scroll', this.preventContainerScroll.bind(this));
this._pinnedRowList.changes
.pipe(takeUntil(this.destroy$))
.subscribe((change: QueryList<IgxGridRowComponent>) => {
this.onPinnedRowsChanged(change);
});
this.addRowSnackbar?.clicked.subscribe(() => {
const rec = this.filteredSortedData[this.lastAddedRowIndex];
this.scrollTo(rec, 0);
this.addRowSnackbar.close();
});
// Keep the stream open for future subscribers
this.rendered$.pipe(takeUntil(this.destroy$)).subscribe(() => {
if (this.paginator) {
this.paginator.perPage = this._perPage !== DEFAULT_ITEMS_PER_PAGE ? this._perPage : this.paginator.perPage;
this.paginator.totalRecords = this.totalRecords;
this.paginator.overlaySettings = { outlet: this.outlet };
}
this._rendered = true;
});
Promise.resolve().then(() => this.rendered.next(true));
}
/**
* @hidden @internal
*/
public notifyChanges(repaint = false) {
this._cdrRequests = true;
this._cdrRequestRepaint = repaint;
this.cdr.markForCheck();
}
/**
* @hidden @internal
*/
public ngDoCheck() {
super.ngDoCheck();
if (this._init) {
return;
}
if (this._cdrRequestRepaint) {
this.resetNotifyChanges();
this.calculateGridSizes();
this.refreshSearch(true);
return;
}
if (this._cdrRequests) {
this.resetNotifyChanges();
this.cdr.detectChanges();
}
}
/**
* @hidden
* @internal
*/
public getDragGhostCustomTemplate() {
if (this.dragGhostCustomTemplates && this.dragGhostCustomTemplates.first) {
return this.dragGhostCustomTemplates.first;
}
return null;
}
/**
* @hidden @internal
*/
public ngOnDestroy() {
this.tmpOutlets.forEach((tmplOutlet) => {
tmplOutlet.cleanCache();
});
this.destroy$.next(true);
this.destroy$.complete();
this.transactionChange$.next();
this.transactionChange$.complete();
this._destroyed = true;
if (this._advancedFilteringOverlayId) {
this.overlayService.detach(this._advancedFilteringOverlayId);
}
this.overlayIDs.forEach(overlayID => {
const overlay = this.overlayService.getOverlayById(overlayID);
if (overlay && !overlay.detached) {
this.overlayService.detach(overlayID);
}
});
this.zone.runOutsideAngular(() => {
this.verticalScrollContainer?.getScroll()?.removeEventListener('scroll', this.verticalScrollHandler);
this.headerContainer?.getScroll()?.removeEventListener('scroll', this.horizontalScrollHandler);
const vertScrDC = this.verticalScrollContainer?.displayContainer;
vertScrDC?.removeEventListener('scroll', this.preventContainerScroll);
});
}
/**
* Toggles the specified column's visibility.
*
* @example
* ```typescript
* this.grid1.toggleColumnVisibility({
* column: this.grid1.columns[0],
* newValue: true
* });
* ```
*/
public toggleColumnVisibility(args: IColumnVisibilityChangedEventArgs) {
const col = args.column ? this.columnList.find((c) => c === args.column) : undefined;
if (!col) {
return;
}
col.toggleVisibility(args.newValue);
}
/**
* Gets/Sets a list of key-value pairs [row ID, expansion state].
*
* @remarks
* Includes only states that differ from the default one.
* Supports two-way binding.
* @example
* ```html
* <igx-grid #grid [data]="data" [(expansionStates)]="model.expansionStates">
* </igx-grid>
* ```
*/
@Input()
public get expansionStates() {
return this._expansionStates;
}
public set expansionStates(value) {
this._expansionStates = new Map<any, boolean>(value);
this.expansionStatesChange.emit(this._expansionStates);
this.notifyChanges(true);
if (this.gridAPI.grid) {
this.cdr.detectChanges();
}
}
/**
* Expands all rows.
*
* @example
* ```typescript
* this.grid.expandAll();
* ```
*/
public expandAll() {
this._defaultExpandState = true;
this.expansionStates = new Map<any, boolean>();
}
/**
* Collapses all rows.
*
* @example
* ```typescript
* this.grid.collapseAll();
* ```
*/
public collapseAll() {
this._defaultExpandState = false;
this.expansionStates = new Map<any, boolean>();
}
/**
* Expands the row by its id.
*
* @remarks
* ID is either the primaryKey value or the data record instance.
* @example
* ```typescript
* this.grid.expandRow(rowID);
* ```
* @param rowID The row id - primaryKey value or the data record instance.
*/
public expandRow(rowID: any) {
this.gridAPI.set_row_expansion_state(rowID, true);
}
/**
* Collapses the row by its id.
*
* @remarks
* ID is either the primaryKey value or the data record instance.
* @example
* ```typescript
* this.grid.collapseRow(rowID);
* ```
* @param rowID The row id - primaryKey value or the data record instance.
*/
public collapseRow(rowID: any) {
this.gridAPI.set_row_expansion_state(rowID, false);
}
/**
* Toggles the row by its id.
*
* @remarks
* ID is either the primaryKey value or the data record instance.
* @example
* ```typescript
* this.grid.toggleRow(rowID);
* ```
* @param rowID The row id - primaryKey value or the data record instance.
*/
public toggleRow(rowID: any) {
const rec = this.gridAPI.get_rec_by_id(rowID);
const state = this.gridAPI.get_row_expansion_state(rec);
this.gridAPI.set_row_expansion_state(rowID, !state);
}
/**
* @hidden
* @internal
*/
public getDefaultExpandState(_rec: any) {
return this._defaultExpandState;
}
/**
* Gets the native element.
*
* @example
* ```typescript
* const nativeEl = this.grid.nativeElement.
* ```
*/
public get nativeElement() {
return this.elementRef.nativeElement;
}
/**
* Gets/Sets the outlet used to attach the grid's overlays to.
*
* @remark
* If set, returns the outlet defined outside the grid. Otherwise returns the grid's internal outlet directive.
*/
@Input()
public get outlet() {
return this.resolveOutlet();
}
public set outlet(val: IgxOverlayOutletDirective) {
this._userOutletDirective = val;
}
/**
* Gets the default row height.
*
* @example
* ```typescript
* const rowHeigh = this.grid.defaultRowHeight;
* ```
*/
public get defaultRowHeight(): number {
switch (this.displayDensity) {
case DisplayDensity.cosy:
return 40;
case DisplayDensity.compact:
return 32;
default:
return 50;
}
}
/**
* @hidden @internal
*/
public get defaultSummaryHeight(): number {
switch (this.displayDensity) {
case DisplayDensity.cosy:
return 30;
case DisplayDensity.compact:
return 24;
default:
return 36;
}
}
/**
* Returns the `IgxGridHeaderGroupComponent`'s minimum allowed width.
*
* @remarks
* Used internally for restricting header group component width.
* The values below depend on the header cell default right/left padding values.
*/
public get defaultHeaderGroupMinWidth(): number {
switch (this.displayDensity) {
case DisplayDensity.cosy:
return 32;
case DisplayDensity.compact:
return 24;
default:
return 48;
}
}
/**
* Gets the current width of the container for the pinned `IgxColumnComponent`s.
*
* @example
* ```typescript
* const pinnedWidth = this.grid.getPinnedWidth;
* ```
*/
public get pinnedWidth() {
if (!isNaN(this._pinnedWidth)) {
return this._pinnedWidth;
}
this._pinnedWidth = this.getPinnedWidth();
return this._pinnedWidth;
}
/**
* Gets the current width of the container for the unpinned `IgxColumnComponent`s.
*
* @example
* ```typescript
* const unpinnedWidth = this.grid.getUnpinnedWidth;
* ```
*/
public get unpinnedWidth() {
if (!isNaN(this._unpinnedWidth)) {
return this._unpinnedWidth;
}
this._unpinnedWidth = this.getUnpinnedWidth();
return this._unpinnedWidth;
}
/**
* @hidden @internal
*/
public get isHorizontalScrollHidden() {
const diff = this.unpinnedWidth - this.totalWidth;
return this.width === null || diff >= 0;
}
/**
* @hidden @internal
* Gets the combined width of the columns that are specific to the enabled grid features. They are fixed.
*/
public featureColumnsWidth(expander?: ElementRef) {
if (Number.isNaN(this._headerFeaturesWidth)) {
// TODO: platformUtil.isBrowser check
const rowSelectArea = this.headerSelectorContainer?.nativeElement?.getBoundingClientRect ?
this.headerSelectorContainer.nativeElement.getBoundingClientRect().width : 0;
const rowDragArea = this.rowDraggable && this.headerDragContainer?.nativeElement?.getBoundingClientRect ?
this.headerDragContainer.nativeElement.getBoundingClientRect().width : 0;
const groupableArea = this.headerGroupContainer?.nativeElement?.getBoundingClientRect ?
this.headerGroupContainer.nativeElement.getBoundingClientRect().width : 0;
const expanderWidth = expander?.nativeElement?.getBoundingClientRect ? expander.nativeElement.getBoundingClientRect().width : 0;
this._headerFeaturesWidth = rowSelectArea + rowDragArea + groupableArea + expanderWidth;
}
return this._headerFeaturesWidth;
}
/**
* @hidden @internal
*/
public get summariesMargin() {
return this.featureColumnsWidth();
}
/**
* @hidden
* @internal
*/
public get columns(): IgxColumnComponent[] {
return this._columns;
}
/**
* Gets an array of `IgxColumnComponent`s.
*
* @example
* ```typescript
* const colums = this.grid.columnsCollection.
* ```
*/
public get columnsCollection(): IgxColumnComponent[] {
return this._rendered ? this._columns : [];
}
/**
* Gets an array of the pinned `IgxColumnComponent`s.
*
* @example
* ```typescript
* const pinnedColumns = this.grid.pinnedColumns.
* ```
*/
public get pinnedColumns(): IgxColumnComponent[] {
if (this._pinnedVisible.length) {
return this._pinnedVisible;
}
this._pinnedVisible = this._pinnedColumns.filter(col => !col.hidden);
return this._pinnedVisible;
}
/**
* Gets an array of the pinned `IgxRowComponent`s.
*
* @example
* ```typescript
* const pinnedRow = this.grid.pinnedRows;
* ```
*/
public get pinnedRows(): IgxGridRowComponent[] {
return this._pinnedRowList.toArray().sort((a, b) => a.index - b.index);
}
/**
* Gets an array of unpinned `IgxColumnComponent`s.
*
* @example
* ```typescript
* const unpinnedColumns = this.grid.unpinnedColumns.
* ```
*/
public get unpinnedColumns(): IgxColumnComponent[] {
if (this._unpinnedVisible.length) {
return this._unpinnedVisible;
}
this._unpinnedVisible = this._unpinnedColumns.filter((col) => !col.hidden);
return this._unpinnedVisible;
}
/**
* Gets the `width` to be set on `IgxGridHeaderGroupComponent`.
*/
public getHeaderGroupWidth(column: IgxColumnComponent): string {
if (this.hasColumnLayouts) {
return '';
}
const colWidth = parseFloat(column.calcWidth);
const minWidth = this.defaultHeaderGroupMinWidth;
if (colWidth < minWidth) {
return minWidth + 'px';
}
return colWidth + 'px';
}
/**
* Returns the `IgxColumnComponent` by field name.
*
* @example
* ```typescript
* const myCol = this.grid1.getColumnByName("ID");
* ```
* @param name
*/
public getColumnByName(name: string): IgxColumnComponent {
return this.columnList.find((col) => col.field === name);
}
public getColumnByVisibleIndex(index: number): IgxColumnComponent {
return this.visibleColumns.find((col) =>
!col.columnGroup && !col.columnLayout &&
col.visibleIndex === index
);
}
/**
* Returns an array of visible `IgxColumnComponent`s.
*
* @example
* ```typescript
* const visibleColumns = this.grid.visibleColumns.
* ```
*/
public get visibleColumns(): IgxColumnComponent[] {
if (this._visibleColumns.length) {
return this._visibleColumns;
}
this._visibleColumns = this.columnList.filter(c => !c.hidden);
return this._visibleColumns;
}
/**
* Gets the total number of pages.
*
* @deprecated in version 12.1.0
* @example
* ```typescript
* const totalPages = this.grid.totalPages;
* ```
*/
@DeprecateProperty('`totalPages` is deprecated. Use the corresponding property exposed by the `igx-paginator`.')
public get totalPages(): number {
return this.paginator?.totalPages;
}
/**
* Gets if the current page is the first page.
*
* @deprecated in version 12.1.0
* @example
* ```typescript
* const firstPage = this.grid.isFirstPage;
* ```
*/
@DeprecateProperty('`isFirstPage` is deprecated. Use the corresponding property exposed by the `igx-paginator`.')
public get isFirstPage(): boolean {
return this.paginator.isLastPage;
}
/**
* Goes to the next page, if the grid is not already at the last page.
*
* @deprecated in version 12.1.0
* @example
* ```typescript
* this.grid1.nextPage();
* ```
*/
// eslint-disable-next-line @typescript-eslint/member-ordering
@DeprecateMethod('Use the corresponding method exposed by the `igx-paginator`.')
public nextPage(): void {
this.paginator?.nextPage();
}
/**
* Goes to the previous page, if the grid is not already at the first page.
*
* @deprecated in version 12.1.0
* @example
* ```typescript
* this.grid1.previousPage();
* ```
*/
// eslint-disable-next-line @typescript-eslint/member-ordering
@DeprecateMethod('Use the corresponding method exposed by the `igx-paginator`.')
public previousPage(): void {
this.paginator?.previousPage();
}
/**
* Returns the total number of records.
*
* @remarks
* Only functions when paging is enabled.
* @example
* ```typescript
* const totalRecords = this.grid.totalRecords;
* ```
*/
@Input()
public get totalRecords(): number {
return this._totalRecords >= 0 ? this._totalRecords : this.pagingState?.metadata.countRecords;
}
public set totalRecords(total: number) {
if (total >= 0) {
if (this.paginator) {
this.paginator.totalRecords = total;
}
this._totalRecords = total;
this.pipeTrigger++;
this.notifyChanges();
}
}
/**
* Returns if the current page is the last page.
*
* @deprecated in version 12.1.0
* @example
* ```typescript
* const lastPage = this.grid.isLastPage;
* ```
*/
@DeprecateProperty('`isLastPage` is deprecated. Use the corresponding property exposed by the `igx-paginator`.')
public get isLastPage(): boolean {
return this.paginator.isLastPage;
}
/**
* Returns the total width of the `IgxGridComponent`.
*
* @example
* ```typescript
* const gridWidth = this.grid.totalWidth;
* ```
*/
public get totalWidth(): number {
if (!isNaN(this._totalWidth)) {
return this._totalWidth;
}
// Take only top level columns
const cols = this.visibleColumns.filter(col => col.level === 0 && !col.pinned);
let totalWidth = 0;
let i = 0;
for (i; i < cols.length; i++) {
totalWidth += parseInt(cols[i].calcWidth, 10) || 0;
}
this._totalWidth = totalWidth;
return totalWidth;
}
/**
* @hidden
* @internal
*/
public get showRowSelectors(): boolean {
return this.isRowSelectable && this.hasVisibleColumns && !this.hideRowSelectors;
}
/**
* @hidden
* @internal
*/
public get showAddButton() {
return this.rowEditable && this.dataView.length === 0 && this.columns.length > 0;
}
/**
* @hidden
* @internal
*/
public get showDragIcons(): boolean {
return this.rowDraggable && this.columns.length > this.hiddenColumnsCount;
}
/**
* Places a column before or after the specified target column.
*
* @example
* ```typescript
* grid.moveColumn(column, target);
* ```
*/
public moveColumn(column: IgxColumnComponent, target: IgxColumnComponent, pos: DropPosition = DropPosition.AfterDropTarget) {
// M.A. May 11th, 2021 #9508 Make the event cancelable
const eventArgs: IColumnMovingEndEventArgs = { source: column, target, cancel: false };
this.columnMovingEnd.emit(eventArgs);
if (eventArgs.cancel) {
return;
}
if (column === target || (column.level !== target.level) ||
(column.topLevelParent !== target.topLevelParent)) {
return;
}
if (column.level) {
this._moveChildColumns(column.parent, column, target, pos);
}
let columnPinStateChanged;
// pinning and unpinning will work correctly even without passing index
// but is easier to calclulate the index here, and later use it in the pinning event args
if (target.pinned && !column.pinned) {
const pinnedIndex = this._pinnedColumns.indexOf(target);
const index = pos === DropPosition.AfterDropTarget ? pinnedIndex + 1 : pinnedIndex;
columnPinStateChanged = column.pin(index);
}
if (!target.pinned && column.pinned) {
const unpinnedIndex = this._unpinnedColumns.indexOf(target);
const index = pos === DropPosition.AfterDropTarget ? unpinnedIndex + 1 : unpinnedIndex;
columnPinStateChanged = column.unpin(index);
}
if (target.pinned && column.pinned && !columnPinStateChanged) {
this._reorderColumns(column, target, pos, this._pinnedColumns);
}
if (!target.pinned && !column.pinned && !columnPinStateChanged) {
this._reorderColumns(column, target, pos, this._unpinnedColumns);
}
this._moveColumns(column, target, pos);
this._columnsReordered(column);
}
/**
* Goes to the desired page index.
*
* @example
* ```typescript
* this.grid1.paginate(1);
* ```
* @param val
*/
// eslint-disable-next-line @typescript-eslint/member-ordering
@DeprecateMethod('Use the corresponding method exposed by the `igx-paginator`.')
public paginate(val: number): void {
this.paginator?.paginate(val);
}
/**
* Triggers change detection for the `IgxGridComponent`.
* Calling markForCheck also triggers the grid pipes explicitly, resulting in all updates being processed.
* May degrade performance if used when not needed, or if misused:
* ```typescript
* // DON'Ts:
* // don't call markForCheck from inside a loop
* // don't call markForCheck when a primitive has changed
* grid.data.forEach(rec => {
* rec = newValue;
* grid.markForCheck();
* });
*
* // DOs
* // call markForCheck after updating a nested property
* grid.data.forEach(rec => {
* rec.nestedProp1.nestedProp2 = newValue;
* });
* grid.markForCheck();
* ```
*
* @example
* ```typescript
* grid.markForCheck();
* ```
*/
public markForCheck() {
this.pipeTrigger++;
this.cdr.detectChanges();
}
/**
* Creates a new `IgxGridRowComponent` and adds the data record to the end of the data source.
*
* @example
* ```typescript
* this.grid1.addRow(record);
* ```
* @param data
*/
public addRow(data: any): void {
// commit pending states prior to adding a row
this.crudService.endEdit(true);
this.gridAPI.addRowToData(data);
this.rowAddedNotifier.next({ data });
this.pipeTrigger++;
this.notifyChanges();
}
/**
* Removes the `IgxGridRowComponent` and the corresponding data record by primary key.
*
* @remarks
* Requires that the `primaryKey` property is set.
* The method accept rowSelector as a parameter, which is the rowID.
* @example
* ```typescript
* this.grid1.deleteRow(0);
* ```
* @param rowSelector
*/
public deleteRow(rowSelector: any): any {
if (this.primaryKey !== undefined && this.primaryKey !== null) {
return this.deleteRowById(rowSelector);
}
}
/** @hidden */
public deleteRowById(rowId: any): any {
const args = {
rowID: rowId,
cancel: false,
rowData: this.getRowData(rowId),
oldValue: null
};
this.rowDelete.emit(args);
if (args.cancel) {
return;
}
const record = this.gridAPI.deleteRowById(rowId);
if (record !== null && record !== undefined) {
// TODO: should we emit this when cascadeOnDelete is true for each row?!?!
this.rowDeleted.emit({ data: record });
}
return record;
}
/**
* Updates the `IgxGridRowComponent` and the corresponding data record by primary key.
*
* @remarks
* Requires that the `primaryKey` property is set.
* @example
* ```typescript
* this.gridWithPK.updateCell('Updated', 1, 'ProductName');
* ```
* @param value the new value which is to be set.
* @param rowSelector corresponds to rowID.
* @param column corresponds to column field.
*/
public updateCell(value: any, rowSelector: any, column: string): void {
if (this.isDefined(this.primaryKey)) {
const col = this.columnList.toArray().find(c => c.field === column);
if (col) {
// Simplify
const rowData = this.gridAPI.getRowData(rowSelector);
const index = this.gridAPI.get_row_index_in_data(rowSelector);
// If row passed is invalid
if (index < 0) {
return;
}
const id = {
rowID: rowSelector,
columnID: col.index,
rowIndex: index
};
const cell = new IgxCell(id, index, col, rowData[col.field], value, rowData, this);
this.gridAPI.update_cell(cell);
this.cdr.detectChanges();
}
}
}
/**
* Updates the `IgxGridRowComponent`
*
* @remarks
* The row is specified by
* rowSelector parameter and the data source record with the passed value.
* This method will apply requested update only if primary key is specified in the grid.
* @example
* ```typescript
* grid.updateRow({
* ProductID: 1, ProductName: 'Spearmint', InStock: true, UnitsInStock: 1, OrderDate: new Date('2005-03-21')
* }, 1);
* ```
* @param valueโ
* @param rowSelector correspond to rowID
*/
// TODO: prevent event invocation
public updateRow(value: any, rowSelector: any): void {
if (this.isDefined(this.primaryKey)) {
const editableCell = this.crudService.cell;
if (editableCell && editableCell.id.rowID === rowSelector) {
this.crudService.endCellEdit();
}
const row = new IgxEditRow(rowSelector, -1, this.gridAPI.getRowData(rowSelector), this);
this.gridAPI.update_row(row, value);
// TODO: fix for #5934 and probably break for #5763
// consider adding of third optional boolean parameter in updateRow.
// If developer set this parameter to true we should call notifyChanges(true), and
// vise-versa if developer set it to false we should call notifyChanges(false).
// The parameter should default to false
this.notifyChanges();
}
}
/**
* Returns the data that is contained in the row component.
*
* @remarks
* If the primary key is not specified the row selector match the row data.
* @example
* ```typescript
* const data = grid.getRowData(94741);
* ```
* @param rowSelector correspond to rowID
*/
public getRowData(rowSelector: any) {
if (!this.primaryKey) {
return rowSelector;
}
const data = this.gridAPI.get_all_data(this.transactions.enabled);
const index = this.gridAPI.get_row_index_in_data(rowSelector);
return index < 0 ? {} : data[index];
}
/**
* Sort a single `IgxColumnComponent`.
*
* @remarks
* Sort the `IgxGridComponent`'s `IgxColumnComponent` based on the provided array of sorting expressions.
* @example
* ```typescript
* this.grid.sort({ fieldName: name, dir: SortingDirection.Asc, ignoreCase: false });
* ```
*/
public sort(expression: ISortingExpression | Array<ISortingExpression>): void {
const sortingState = cloneArray(this.sortingExpressions);
if (expression instanceof Array) {
for (const each of expression) {
if (each.dir === SortingDirection.None) {
this.gridAPI.remove_grouping_expression(each.fieldName);
}
this.gridAPI.prepare_sorting_expression([sortingState], each);
}
} else {
if (expression.dir === SortingDirection.None) {
this.gridAPI.remove_grouping_expression(expression.fieldName);
}
this.gridAPI.prepare_sorting_expression([sortingState], expression);
}
const eventArgs: ISortingEventArgs = { owner: this, sortingExpressions: sortingState, cancel: false };
this.sorting.emit(eventArgs);
if (eventArgs.cancel) {
return;
}
this.crudService.endEdit(false);
if (expression instanceof Array) {
this.gridAPI.sort_multiple(expression);
} else {
this.gridAPI.sort(expression);
}
requestAnimationFrame(() => this.sortingDone.emit(expression));
}
/**
* Filters a single `IgxColumnComponent`.
*
* @example
* ```typescript
* public filter(term) {
* this.grid.filter("ProductName", term, IgxStringFilteringOperand.instance().condition("contains"));
* }
* ```
* @param name
* @param value
* @param conditionOrExpressionTree
* @param ignoreCase
*/
public filter(name: string, value: any, conditionOrExpressionTree?: IFilteringOperation | IFilteringExpressionsTree,
ignoreCase?: boolean) {
this.filteringService.filter(name, value, conditionOrExpressionTree, ignoreCase);
}
/**
* Filters all the `IgxColumnComponent` in the `IgxGridComponent` with the same condition.
*
* @example
* ```typescript
* grid.filterGlobal('some', IgxStringFilteringOperand.instance().condition('contains'));
* ```
* @param value
* @param condition
* @param ignoreCase
*/
public filterGlobal(value: any, condition, ignoreCase?) {
this.filteringService.filterGlobal(value, condition, ignoreCase);
}
/**
* Enables summaries for the specified column and applies your customSummary.
*
* @remarks
* If you do not provide the customSummary, then the default summary for the column data type will be applied.
* @example
* ```typescript
* grid.enableSummaries([{ fieldName: 'ProductName' }, { fieldName: 'ID' }]);
* ```
* Enable summaries for the listed columns.
* @example
* ```typescript
* grid.enableSummaries('ProductName');
* ```
* @param rest
*/
public enableSummaries(...rest) {
if (rest.length === 1 && Array.isArray(rest[0])) {
this._multipleSummaries(rest[0], true);
} else {
this._summaries(rest[0], true, rest[1]);
}
}
/**
* Disable summaries for the specified column.
*
* @example
* ```typescript
* grid.disableSummaries('ProductName');
* ```
* @remarks
* Disable summaries for the listed columns.
* @example
* ```typescript
* grid.disableSummaries([{ fieldName: 'ProductName' }]);
* ```
*/
public disableSummaries(...rest) {
if (rest.length === 1 && Array.isArray(rest[0])) {
this._disableMultipleSummaries(rest[0]);
} else {
this._summaries(rest[0], false);
}
}
/**
* If name is provided, clears the filtering state of the corresponding `IgxColumnComponent`.
*
* @remarks
* Otherwise clears the filtering state of all `IgxColumnComponent`s.
* @example
* ```typescript
* this.grid.clearFilter();
* ```
* @param name
*/
public clearFilter(name?: string) {
this.filteringService.clearFilter(name);
}
/**
* If name is provided, clears the sorting state of the corresponding `IgxColumnComponent`.
*
* @remarks
* otherwise clears the sorting state of all `IgxColumnComponent`.
* @example
* ```typescript
* this.grid.clearSort();
* ```
* @param name
*/
public clearSort(name?: string) {
if (!name) {
this.sortingExpressions = [];
return;
}
if (!this.gridAPI.get_column_by_name(name)) {
return;
}
this.gridAPI.clear_sort(name);
}
/**
* @hidden @internal
*/
public refreshGridState(_args?) {
this.crudService.endEdit(true);
this.selectionService.clearHeaderCBState();
this.summaryService.clearSummaryCache();
this.cdr.detectChanges();
}
// TODO: We have return values here. Move them to event args ??
/**
* Pins a column by field name.
*
* @remarks
* Returns whether the operation is successful.
* @example
* ```typescript
* this.grid.pinColumn("ID");
* ```
* @param columnName
* @param index
*/
public pinColumn(columnName: string | IgxColumnComponent, index?): boolean {
const col = columnName instanceof IgxColumnComponent ? columnName : this.getColumnByName(columnName);
return col.pin(index);
}
/**
* Unpins a column by field name. Returns whether the operation is successful.
*
* @example
* ```typescript
* this.grid.pinColumn("ID");
* ```
* @param columnName
* @param index
*/
public unpinColumn(columnName: string | IgxColumnComponent, index?): boolean {
const col = columnName instanceof IgxColumnComponent ? columnName : this.getColumnByName(columnName);
return col.unpin(index);
}
/**
* Pin the row by its id.
*
* @remarks
* ID is either the primaryKey value or the data record instance.
* @example
* ```typescript
* this.grid.pinRow(rowID);
* ```
* @param rowID The row id - primaryKey value or the data record instance.
* @param index The index at which to insert the row in the pinned collection.
*/
public pinRow(rowID: any, index?: number, row?: RowType): boolean {
if (this._pinnedRecordIDs.indexOf(rowID) !== -1) {
return false;
}
const eventArgs: IPinRowEventArgs = {
insertAtIndex: index,
isPinned: true,
rowID,
row
};
this.rowPinning.emit(eventArgs);
this.crudService.endEdit(false);
const insertIndex = typeof eventArgs.insertAtIndex === 'number' ? eventArgs.insertAtIndex : this._pinnedRecordIDs.length;
this._pinnedRecordIDs.splice(insertIndex, 0, rowID);
this.pipeTrigger++;
if (this.gridAPI.grid) {
this.cdr.detectChanges();
this.rowPinned.emit(eventArgs);
}
return true;
}
/**
* Unpin the row by its id.
*
* @remarks
* ID is either the primaryKey value or the data record instance.
* @example
* ```typescript
* this.grid.unpinRow(rowID);
* ```
* @param rowID The row id - primaryKey value or the data record instance.
*/
public unpinRow(rowID: any, row?: RowType): boolean {
const index = this._pinnedRecordIDs.indexOf(rowID);
if (index === -1) {
return false;
}
const eventArgs: IPinRowEventArgs = {
isPinned: false,
rowID,
row
};
this.rowPinning.emit(eventArgs);
this.crudService.endEdit(false);
this._pinnedRecordIDs.splice(index, 1);
this.pipeTrigger++;
if (this.gridAPI.grid) {
this.cdr.detectChanges();
this.rowPinned.emit(eventArgs);
}
return true;
}
public get pinnedRowHeight() {
const containerHeight = this.pinContainer ? this.pinContainer.nativeElement.offsetHeight : 0;
return this.hasPinnedRecords ? containerHeight : 0;
}
public get totalHeight() {
return this.calcHeight ? this.calcHeight + this.pinnedRowHeight : this.calcHeight;
}
/**
* Recalculates grid width/height dimensions.
*
* @remarks
* Should be run when changing DOM elements dimentions manually that affect the grid's size.
* @example
* ```typescript
* this.grid.reflow();
* ```
*/
public reflow() {
this.calculateGridSizes();
}
/**
* Finds the next occurrence of a given string in the grid and scrolls to the cell if it isn't visible.
*
* @remarks
* Returns how many times the grid contains the string.
* @example
* ```typescript
* this.grid.findNext("financial");
* ```
* @param text the string to search.
* @param caseSensitive optionally, if the search should be case sensitive (defaults to false).
* @param exactMatch optionally, if the text should match the entire value (defaults to false).
*/
public findNext(text: string, caseSensitive?: boolean, exactMatch?: boolean): number {
return this.find(text, 1, caseSensitive, exactMatch);
}
/**
* Finds the previous occurrence of a given string in the grid and scrolls to the cell if it isn't visible.
*
* @remarks
* Returns how many times the grid contains the string.
* @example
* ```typescript
* this.grid.findPrev("financial");
* ```
* @param text the string to search.
* @param caseSensitive optionally, if the search should be case sensitive (defaults to false).
* @param exactMatch optionally, if the text should match the entire value (defaults to false).
*/
public findPrev(text: string, caseSensitive?: boolean, exactMatch?: boolean): number {
return this.find(text, -1, caseSensitive, exactMatch);
}
/**
* Reapplies the existing search.
*
* @remarks
* Returns how many times the grid contains the last search.
* @example
* ```typescript
* this.grid.refreshSearch();
* ```
* @param updateActiveInfo
*/
public refreshSearch(updateActiveInfo?: boolean, endEdit = true): number {
if (this.lastSearchInfo.searchText) {
this.rebuildMatchCache();
if (updateActiveInfo) {
const activeInfo = IgxTextHighlightDirective.highlightGroupsMap.get(this.id);
this.lastSearchInfo.matchInfoCache.forEach((match, i) => {
if (match.column === activeInfo.column &&
match.row === activeInfo.row &&
match.index === activeInfo.index &&
compareMaps(match.metadata, activeInfo.metadata)) {
this.lastSearchInfo.activeMatchIndex = i;
}
});
}
return this.find(this.lastSearchInfo.searchText,
0,
this.lastSearchInfo.caseSensitive,
this.lastSearchInfo.exactMatch,
false,
endEdit);
} else {
return 0;
}
}
/**
* Removes all the highlights in the cell.
*
* @example
* ```typescript
* this.grid.clearSearch();
* ```
*/
public clearSearch() {
this.lastSearchInfo = {
searchText: '',
caseSensitive: false,
exactMatch: false,
activeMatchIndex: 0,
matchInfoCache: []
};
this.rowList.forEach((row) => {
if (row.cells) {
row.cells.forEach((c) => {
c.clearHighlight();
});
}
});
}
/**
* Returns if the `IgxGridComponent` has sortable columns.
*
* @example
* ```typescript
* const sortableGrid = this.grid.hasSortableColumns;
* ```
*/
public get hasSortableColumns(): boolean {
return this.columnList.some((col) => col.sortable);
}
/**
* Returns if the `IgxGridComponent` has editable columns.
*
* @example
* ```typescript
* const editableGrid = this.grid.hasEditableColumns;
* ```
*/
public get hasEditableColumns(): boolean {
return this.columnList.some((col) => col.editable);
}
/**
* Returns if the `IgxGridComponent` has filterable columns.
*
* @example
* ```typescript
* const filterableGrid = this.grid.hasFilterableColumns;
* ```
*/
public get hasFilterableColumns(): boolean {
return this.columnList.some((col) => col.filterable);
}
/**
* Returns if the `IgxGridComponent` has summarized columns.
*
* @example
* ```typescript
* const summarizedGrid = this.grid.hasSummarizedColumns;
* ```
*/
public get hasSummarizedColumns(): boolean {
return this.summaryService.hasSummarizedColumns;
}
/**
* @hidden @internal
*/
public get rootSummariesEnabled(): boolean {
return this.summaryCalculationMode !== GridSummaryCalculationMode.childLevelsOnly;
}
/**
* @hidden @internal
*/
public get hasVisibleColumns(): boolean {
if (this._hasVisibleColumns === undefined) {
return this.columnList ? this.columnList.some(c => !c.hidden) : false;
}
return this._hasVisibleColumns;
}
public set hasVisibleColumns(value) {
this._hasVisibleColumns = value;
}
/**
* Returns if the `IgxGridComponent` has moveable columns.
*
* @example
* ```typescript
* const movableGrid = this.grid.hasMovableColumns;
* ```
*/
public get hasMovableColumns(): boolean {
return this.columnList && this.columnList.some((col) => col.movable);
}
/**
* Returns if the `IgxGridComponent` has column groups.
*
* @example
* ```typescript
* const groupGrid = this.grid.hasColumnGroups;
* ```
*/
public get hasColumnGroups(): boolean {
return this._columnGroups;
}
/**
* Returns if the `IgxGridComponent` has column layouts for multi-row layout definition.
*
* @example
* ```typescript
* const layoutGrid = this.grid.hasColumnLayouts;
* ```
*/
public get hasColumnLayouts() {
return !!this.columnList.some(col => col.columnLayout);
}
/**
* @hidden @internal
*/
public get multiRowLayoutRowSize() {
return this._multiRowLayoutRowSize;
}
/**
* @hidden
*/
protected get rowBasedHeight() {
return this.dataLength * this.rowHeight;
}
/**
* @hidden
*/
protected get isPercentWidth() {
return this.width && this.width.indexOf('%') !== -1;
}
/**
* @hidden @internal
*/
public get isPercentHeight() {
return this._height && this._height.indexOf('%') !== -1;
}
/**
* @hidden
*/
protected get defaultTargetBodyHeight(): number {
const allItems = this.dataLength;
return this.renderedRowHeight * Math.min(this._defaultTargetRecordNumber,
this.paginator ? Math.min(allItems, this.paginator.perPage) : allItems);
}
/**
* @hidden @internal
* The rowHeight input is bound to min-height css prop of rows that adds a 1px border in all cases
*/
public get renderedRowHeight(): number {
return this.rowHeight + 1;
}
/**
* @hidden @internal
*/
public get outerWidth() {
return this.hasVerticalScroll() ? this.calcWidth + this.scrollSize : this.calcWidth;
}
/**
* @hidden @internal
* Gets the visible content height that includes header + tbody + footer.
*/
public getVisibleContentHeight() {
let height = this.theadRow.nativeElement.clientHeight + this.tbody.nativeElement.clientHeight;
if (this.hasSummarizedColumns) {
height += this.tfoot.nativeElement.clientHeight;
}
return height;
}
/**
* @hidden @internal
*/
public getPossibleColumnWidth(baseWidth: number = null) {
let computedWidth;
if (baseWidth !== null) {
computedWidth = baseWidth;
} else {
computedWidth = this.calcWidth ||
parseInt(this.document.defaultView.getComputedStyle(this.nativeElement).getPropertyValue('width'), 10);
}
computedWidth -= this.featureColumnsWidth();
const visibleChildColumns = this.visibleColumns.filter(c => !c.columnGroup);
// Column layouts related
let visibleCols = [];
const columnBlocks = this.visibleColumns.filter(c => c.columnGroup);
const colsPerBlock = columnBlocks.map(block => block.getInitialChildColumnSizes(block.children));
const combinedBlocksSize = colsPerBlock.reduce((acc, item) => acc + item.length, 0);
colsPerBlock.forEach(blockCols => visibleCols = visibleCols.concat(blockCols));
//
const columnsWithSetWidths = this.hasColumnLayouts ?
visibleCols.filter(c => c.widthSetByUser) :
visibleChildColumns.filter(c => c.widthSetByUser);
const columnsToSize = this.hasColumnLayouts ?
combinedBlocksSize - columnsWithSetWidths.length :
visibleChildColumns.length - columnsWithSetWidths.length;
const sumExistingWidths = columnsWithSetWidths
.reduce((prev, curr) => {
const colWidth = curr.width;
const widthValue = parseInt(colWidth, 10);
const currWidth = colWidth && typeof colWidth === 'string' && colWidth.indexOf('%') !== -1 ?
widthValue / 100 * computedWidth :
widthValue;
return prev + currWidth;
}, 0);
// When all columns are hidden, return 0px width
if (!sumExistingWidths && !columnsToSize) {
return '0px';
}
const columnWidth = Math.floor(!Number.isFinite(sumExistingWidths) ?
Math.max(computedWidth / columnsToSize, MINIMUM_COLUMN_WIDTH) :
Math.max((computedWidth - sumExistingWidths) / columnsToSize, MINIMUM_COLUMN_WIDTH));
return columnWidth + 'px';
}
/**
* @hidden @internal
*/
public hasVerticalScroll() {
if (this._init) {
return false;
}
const isScrollable = this.verticalScrollContainer ? this.verticalScrollContainer.isScrollable() : false;
return !!(this.calcWidth && this.dataView && this.dataView.length > 0 && isScrollable);
}
/**
* Gets calculated width of the pinned area.
*
* @example
* ```typescript
* const pinnedWidth = this.grid.getPinnedWidth();
* ```
* @param takeHidden If we should take into account the hidden columns in the pinned area.
*/
public getPinnedWidth(takeHidden = false) {
const fc = takeHidden ? this._pinnedColumns : this.pinnedColumns;
let sum = 0;
for (const col of fc) {
if (col.level === 0) {
sum += parseInt(col.calcWidth, 10);
}
}
if (this.isPinningToStart) {
sum += this.featureColumnsWidth();
}
return sum;
}
/**
* @hidden @internal
*/
public isColumnGrouped(_fieldName: string): boolean {
return false;
}
/**
* @hidden @internal
* TODO: REMOVE
*/
public onHeaderSelectorClick(event) {
if (!this.isMultiRowSelectionEnabled) {
return;
}
if (this.selectionService.areAllRowSelected()) {
this.selectionService.clearRowSelection(event);
} else {
this.selectionService.selectAllRows(event);
}
}
/**
* @hidden @internal
*/
public get headSelectorBaseAriaLabel() {
if (this._filteringExpressionsTree.filteringOperands.length > 0) {
return this.selectionService.areAllRowSelected() ? 'Deselect all filtered' : 'Select all filtered';
}
return this.selectionService.areAllRowSelected() ? 'Deselect all' : 'Select all';
}
/**
* @hidden
* @internal
*/
public get totalRowsCountAfterFilter() {
if (this.data) {
return this.selectionService.allData.length;
}
return 0;
}
/**
* Returns the currently transformed paged/filtered/sorted/grouped pinned row data, displayed in the grid.
*
* @example
* ```typescript
* const pinnedDataView = this.grid.pinnedDataView;
* ```
*/
public get pinnedDataView(): any[] {
return this.pinnedRecords ? this.pinnedRecords : [];
}
/**
* Returns currently transformed paged/filtered/sorted/grouped unpinned row data, displayed in the grid.
*
* @example
* ```typescript
* const pinnedDataView = this.grid.pinnedDataView;
* ```
*/
public get unpinnedDataView(): any[] {
return this.unpinnedRecords ? this.unpinnedRecords : this.verticalScrollContainer.igxForOf || [];
}
/**
* Returns the currently transformed paged/filtered/sorted/grouped/pinned/unpinned row data, displayed in the grid.
*
* @example
* ```typescript
* const dataView = this.grid.dataView;
* ```
*/
public get dataView(): any[] {
return this.isRowPinningToTop ?
[...this.pinnedDataView, ...this.unpinnedDataView] :
[...this.unpinnedDataView, ...this.pinnedDataView];
}
/**
* Gets/Sets whether clicking over a row should select/deselect it
*
* @remarks
* By default it is set to true
* @param enabled: boolean
*/
@WatchChanges()
@Input()
public get selectRowOnClick() {
return this._selectRowOnClick;
}
public set selectRowOnClick(enabled: boolean) {
this._selectRowOnClick = enabled;
}
/**
* Select specified rows by ID.
*
* @example
* ```typescript
* this.grid.selectRows([1,2,5], true);
* ```
* @param rowIDs
* @param clearCurrentSelection if true clears the current selection
*/
public selectRows(rowIDs: any[], clearCurrentSelection?: boolean) {
this.selectionService.selectRowsWithNoEvent(rowIDs, clearCurrentSelection);
this.notifyChanges();
}
/**
* Deselect specified rows by ID.
*
* @example
* ```typescript
* this.grid.deselectRows([1,2,5]);
* ```
* @param rowIDs
*/
public deselectRows(rowIDs: any[]) {
this.selectionService.deselectRowsWithNoEvent(rowIDs);
this.notifyChanges();
}
/**
* Selects all rows
*
* @remarks
* By default if filtering is in place, selectAllRows() and deselectAllRows() select/deselect all filtered rows.
* If you set the parameter onlyFilterData to false that will select all rows in the grid exept deleted rows.
* @example
* ```typescript
* this.grid.selectAllRows();
* this.grid.selectAllRows(false);
* ```
* @param onlyFilterData
*/
public selectAllRows(onlyFilterData = true) {
const data = onlyFilterData && this.filteredData ? this.filteredData : this.gridAPI.get_all_data(true);
const rowIDs = this.selectionService.getRowIDs(data).filter(rID => !this.gridAPI.row_deleted_transaction(rID));
this.selectRows(rowIDs);
}
/**
* Deselects all rows
*
* @remarks
* By default if filtering is in place, selectAllRows() and deselectAllRows() select/deselect all filtered rows.
* If you set the parameter onlyFilterData to false that will deselect all rows in the grid exept deleted rows.
* @example
* ```typescript
* this.grid.deselectAllRows();
* ```
* @param onlyFilterData
*/
public deselectAllRows(onlyFilterData = true) {
if (onlyFilterData && this.filteredData && this.filteredData.length > 0) {
this.deselectRows(this.selectionService.getRowIDs(this.filteredData));
} else {
this.selectionService.clearAllSelectedRows();
this.notifyChanges();
}
}
/**
* @hidden @internal
*/
public clearCellSelection(): void {
this.selectionService.clear(true);
this.notifyChanges();
}
/**
* @hidden @internal
*/
public dragScroll(delta: { left: number; top: number }): void {
const horizontal = this.headerContainer.getScroll();
const vertical = this.verticalScrollContainer.getScroll();
const { left, top } = delta;
horizontal.scrollLeft += left * this.DRAG_SCROLL_DELTA;
vertical.scrollTop += top * this.DRAG_SCROLL_DELTA;
}
/**
* @hidden @internal
*/
public isDefined(arg: any): boolean {
return arg !== undefined && arg !== null;
}
/**
* @hidden @internal
*/
public selectRange(arg: GridSelectionRange | GridSelectionRange[] | null | undefined): void {
if (!this.isDefined(arg)) {
this.clearCellSelection();
return;
}
if (arg instanceof Array) {
arg.forEach(range => this.setSelection(range));
} else {
this.setSelection(arg);
}
this.notifyChanges();
}
/**
* @hidden @internal
*/
public columnToVisibleIndex(field: string | number): number {
const visibleColumns = this.visibleColumns;
if (typeof field === 'number') {
return field;
}
return visibleColumns.find(column => column.field === field).visibleIndex;
}
/**
* @hidden @internal
*/
public setSelection(range: GridSelectionRange): void {
const startNode = { row: range.rowStart, column: this.columnToVisibleIndex(range.columnStart) };
const endNode = { row: range.rowEnd, column: this.columnToVisibleIndex(range.columnEnd) };
this.selectionService.pointerState.node = startNode;
this.selectionService.selectRange(endNode, this.selectionService.pointerState);
this.selectionService.addRangeMeta(endNode, this.selectionService.pointerState);
this.selectionService.initPointerState();
}
/**
* @hidden @internal
*/
public getSelectedRanges(): GridSelectionRange[] {
return this.selectionService.ranges;
}
/**
*
* Returns an array of the current cell selection in the form of `[{ column.field: cell.value }, ...]`.
*
* @remarks
* If `formatters` is enabled, the cell value will be formatted by its respective column formatter (if any).
* If `headers` is enabled, it will use the column header (if any) instead of the column field.
*/
public getSelectedData(formatters = false, headers = false) {
const source = this.filteredSortedData;
return this.extractDataFromSelection(source, formatters, headers);
}
/**
* Get current selected columns.
*
* @example
* Returns an array with selected columns
* ```typescript
* const selectedColumns = this.grid.selectedColumns();
* ```
*/
public selectedColumns(): IgxColumnComponent[] {
const fields = this.selectionService.getSelectedColumns();
return fields.map(field => this.getColumnByName(field)).filter(field => field);
}
/**
* Select specified columns.
*
* @example
* ```typescript
* this.grid.selectColumns(['ID','Name'], true);
* ```
* @param columns
* @param clearCurrentSelection if true clears the current selection
*/
public selectColumns(columns: string[] | IgxColumnComponent[], clearCurrentSelection?: boolean) {
let fieldToSelect: string[] = [];
if (columns.length === 0 || typeof columns[0] === 'string') {
fieldToSelect = columns as string[];
} else {
(columns as IgxColumnComponent[]).forEach(col => {
if (col.columnGroup) {
const children = col.allChildren.filter(c => !c.columnGroup).map(c => c.field);
fieldToSelect = [...fieldToSelect, ...children];
} else {
fieldToSelect.push(col.field);
}
});
}
this.selectionService.selectColumnsWithNoEvent(fieldToSelect, clearCurrentSelection);
this.notifyChanges();
}
/**
* Deselect specified columns by filed.
*
* @example
* ```typescript
* this.grid.deselectColumns(['ID','Name']);
* ```
* @param columns
*/
public deselectColumns(columns: string[] | IgxColumnComponent[]) {
let fieldToDeselect: string[] = [];
if (columns.length === 0 || typeof columns[0] === 'string') {
fieldToDeselect = columns as string[];
} else {
(columns as IgxColumnComponent[]).forEach(col => {
if (col.columnGroup) {
const children = col.allChildren.filter(c => !c.columnGroup).map(c => c.field);
fieldToDeselect = [...fieldToDeselect, ...children];
} else {
fieldToDeselect.push(col.field);
}
});
}
this.selectionService.deselectColumnsWithNoEvent(fieldToDeselect);
this.notifyChanges();
}
/**
* Deselects all columns
*
* @example
* ```typescript
* this.grid.deselectAllColumns();
* ```
*/
public deselectAllColumns() {
this.selectionService.clearAllSelectedColumns();
this.notifyChanges();
}
/**
* Selects all columns
*
* @example
* ```typescript
* this.grid.deselectAllColumns();
* ```
*/
public selectAllColumns() {
this.selectColumns(this.columnList.filter(c => !c.columnGroup));
}
/**
*
* Returns an array of the current columns selection in the form of `[{ column.field: cell.value }, ...]`.
*
* @remarks
* If `formatters` is enabled, the cell value will be formatted by its respective column formatter (if any).
* If `headers` is enabled, it will use the column header (if any) instead of the column field.
*/
public getSelectedColumnsData(formatters = false, headers = false) {
const source = this.filteredSortedData ? this.filteredSortedData : this.data;
return this.extractDataFromColumnsSelection(source, formatters, headers);
}
public combineSelectedCellAndColumnData(columnData: any[], formatters = false, headers = false) {
const source = this.filteredSortedData;
return this.extractDataFromSelection(source, formatters, headers, columnData);
}
/**
* @hidden @internal
*/
public preventContainerScroll = (evt) => {
if (evt.target.scrollTop !== 0) {
this.verticalScrollContainer.addScrollTop(evt.target.scrollTop);
evt.target.scrollTop = 0;
}
if (evt.target.scrollLeft !== 0) {
this.headerContainer.scrollPosition += evt.target.scrollLeft;
evt.target.scrollLeft = 0;
}
};
/**
* @hidden
* @internal
*/
public copyHandler(event) {
const selectedColumns = this.gridAPI.grid.selectedColumns();
const columnData = this.getSelectedColumnsData(this.clipboardOptions.copyFormatters, this.clipboardOptions.copyHeaders);
let selectedData;
if (event.type === 'copy'){
selectedData = this.getSelectedData(this.clipboardOptions.copyFormatters, this.clipboardOptions.copyHeaders);
};
let data = [];
let result;
if (event.code === 'KeyC' && (event.ctrlKey || event.metaKey) && event.currentTarget.className === 'igx-grid-thead__wrapper') {
if (selectedData.length) {
if (columnData.length === 0) {
result = this.prepareCopyData(event, selectedData);
} else {
data = this.combineSelectedCellAndColumnData(columnData, this.clipboardOptions.copyFormatters,
this.clipboardOptions.copyHeaders);
result = this.prepareCopyData(event, data[0], data[1]);
}
} else {
data = columnData;
result = this.prepareCopyData(event, data);
}
if (this.platform.isIE) {
(window as any).clipboardData.setData('Text', result);
return;
}
navigator.clipboard.writeText(result).then().catch(e => console.error(e));
} else if (!this.clipboardOptions.enabled || this.crudService.cellInEditMode || (!this.platform.isIE && event.type === 'keydown')) {
return;
} else {
if (selectedColumns.length) {
data = this.combineSelectedCellAndColumnData(columnData, this.clipboardOptions.copyFormatters,
this.clipboardOptions.copyHeaders);
result = this.prepareCopyData(event, data[0], data[1]);
} else {
data = selectedData;
result = this.prepareCopyData(event, data);
}
if (this.platform.isIE) {
(window as any).clipboardData.setData('Text', result);
return;
}
event.clipboardData.setData('text/plain', result);
}
}
/**
* @hidden @internal
*/
public prepareCopyData(event, data, keys?) {
const ev = { data, cancel: false } as IGridClipboardEvent;
this.gridCopy.emit(ev);
if (ev.cancel) {
return;
}
const transformer = new CharSeparatedValueData(ev.data, this.clipboardOptions.separator);
let result = keys ? transformer.prepareData(keys) : transformer.prepareData();
if (!this.clipboardOptions.copyHeaders) {
result = result.substring(result.indexOf('\n') + 1);
}
event.preventDefault();
/* Necessary for the hiearachical case but will probably have to
change how getSelectedData is propagated in the hiearachical grid
*/
event.stopPropagation();
return result;
}
/**
* @hidden @internal
*/
public showSnackbarFor(index: number) {
this.addRowSnackbar.actionText = index === -1 ? '' : this.snackbarActionText;
this.lastAddedRowIndex = index;
this.addRowSnackbar.open();
}
/**
* Navigates to a position in the grid based on provided `rowindex` and `visibleColumnIndex`.
*
* @remarks
* Also can execute a custom logic over the target element,
* through a callback function that accepts { targetType: GridKeydownTargetType, target: Object }
* @example
* ```typescript
* this.grid.navigateTo(10, 3, (args) => { args.target.nativeElement.focus(); });
* ```
*/
public navigateTo(rowIndex: number, visibleColIndex = -1, cb: (args: any) => void = null) {
const totalItems = (this as any).totalItemCount ?? this.dataView.length - 1;
if (rowIndex < 0 || rowIndex > totalItems || (visibleColIndex !== -1
&& this.columnList.map(col => col.visibleIndex).indexOf(visibleColIndex) === -1)) {
return;
}
if (this.dataView.slice(rowIndex, rowIndex + 1).find(rec => rec.expression || rec.childGridsData)) {
visibleColIndex = -1;
}
// If the target row is pinned no need to scroll as well.
const shouldScrollVertically = this.navigation.shouldPerformVerticalScroll(rowIndex, visibleColIndex);
const shouldScrollHorizontally = this.navigation.shouldPerformHorizontalScroll(visibleColIndex, rowIndex);
if (shouldScrollVertically) {
this.navigation.performVerticalScrollToCell(rowIndex, visibleColIndex, () => {
if (shouldScrollHorizontally) {
this.navigation.performHorizontalScrollToCell(visibleColIndex, () =>
this.executeCallback(rowIndex, visibleColIndex, cb));
} else {
this.executeCallback(rowIndex, visibleColIndex, cb);
}
});
} else if (shouldScrollHorizontally) {
this.navigation.performHorizontalScrollToCell(visibleColIndex, () => {
if (shouldScrollVertically) {
this.navigation.performVerticalScrollToCell(rowIndex, visibleColIndex, () =>
this.executeCallback(rowIndex, visibleColIndex, cb));
} else {
this.executeCallback(rowIndex, visibleColIndex, cb);
}
});
} else {
this.executeCallback(rowIndex, visibleColIndex, cb);
}
}
/**
* Returns `ICellPosition` which defines the next cell,
* according to the current position, that match specific criteria.
*
* @remarks
* You can pass callback function as a third parameter of `getPreviousCell` method.
* The callback function accepts IgxColumnComponent as a param
* @example
* ```typescript
* const nextEditableCellPosition = this.grid.getNextCell(0, 3, (column) => column.editable);
* ```
*/
public getNextCell(currRowIndex: number, curVisibleColIndex: number,
callback: (IgxColumnComponent) => boolean = null): ICellPosition {
const columns = this.columnList.filter(col => !col.columnGroup && col.visibleIndex >= 0);
if (!this.isValidPosition(currRowIndex, curVisibleColIndex)) {
return { rowIndex: currRowIndex, visibleColumnIndex: curVisibleColIndex };
}
const colIndexes = callback ? columns.filter((col) => callback(col)).map(editCol => editCol.visibleIndex).sort((a, b) => a - b) :
columns.map(editCol => editCol.visibleIndex).sort((a, b) => a - b);
const nextCellIndex = colIndexes.find(index => index > curVisibleColIndex);
if (this.dataView.slice(currRowIndex, currRowIndex + 1)
.find(rec => !rec.expression && !rec.summaries && !rec.childGridsData && !rec.detailsData) && nextCellIndex !== undefined) {
return { rowIndex: currRowIndex, visibleColumnIndex: nextCellIndex };
} else {
if (colIndexes.length === 0 || this.getNextDataRowIndex(currRowIndex) === currRowIndex) {
return { rowIndex: currRowIndex, visibleColumnIndex: curVisibleColIndex };
} else {
return { rowIndex: this.getNextDataRowIndex(currRowIndex), visibleColumnIndex: colIndexes[0] };
}
}
}
/**
* Returns `ICellPosition` which defines the previous cell,
* according to the current position, that match specific criteria.
*
* @remarks
* You can pass callback function as a third parameter of `getPreviousCell` method.
* The callback function accepts IgxColumnComponent as a param
* @example
* ```typescript
* const previousEditableCellPosition = this.grid.getPreviousCell(0, 3, (column) => column.editable);
* ```
*/
public getPreviousCell(currRowIndex: number, curVisibleColIndex: number,
callback: (IgxColumnComponent) => boolean = null): ICellPosition {
const columns = this.columnList.filter(col => !col.columnGroup && col.visibleIndex >= 0);
if (!this.isValidPosition(currRowIndex, curVisibleColIndex)) {
return { rowIndex: currRowIndex, visibleColumnIndex: curVisibleColIndex };
}
const colIndexes = callback ? columns.filter((col) => callback(col)).map(editCol => editCol.visibleIndex).sort((a, b) => b - a) :
columns.map(editCol => editCol.visibleIndex).sort((a, b) => b - a);
const prevCellIndex = colIndexes.find(index => index < curVisibleColIndex);
if (this.dataView.slice(currRowIndex, currRowIndex + 1)
.find(rec => !rec.expression && !rec.summaries && !rec.childGridsData && !rec.detailsData) && prevCellIndex !== undefined) {
return { rowIndex: currRowIndex, visibleColumnIndex: prevCellIndex };
} else {
if (colIndexes.length === 0 || this.getNextDataRowIndex(currRowIndex, true) === currRowIndex) {
return { rowIndex: currRowIndex, visibleColumnIndex: curVisibleColIndex };
} else {
return { rowIndex: this.getNextDataRowIndex(currRowIndex, true), visibleColumnIndex: colIndexes[0] };
}
}
}
/**
* @hidden
* @internal
*/
public endRowEditTabStop(commit = true, event?: Event) {
const canceled = this.crudService.endEdit(commit, event);
if (canceled) {
return true;
}
const activeCell = this.gridAPI.grid.navigation.activeNode;
if (activeCell && activeCell.row !== -1) {
this.tbody.nativeElement.focus();
}
}
/**
* @hidden @internal
*/
public trackColumnChanges(index, col) {
return col.field + col._calcWidth;
}
/**
* @hidden
*/
public isExpandedGroup(_group: IGroupByRecord): boolean {
return undefined;
}
/**
* @hidden @internal
* TODO: MOVE to CRUD
*/
public openRowOverlay(id) {
this.configureRowEditingOverlay(id, this.rowList.length <= MIN_ROW_EDITING_COUNT_THRESHOLD);
this.rowEditingOverlay.open(this.rowEditSettings);
this.rowEditingOverlay.element.addEventListener('wheel', this.rowEditingWheelHandler.bind(this));
}
/**
* @hidden @internal
*/
public closeRowEditingOverlay() {
this.rowEditingOverlay.element.removeEventListener('wheel', this.rowEditingWheelHandler);
this.rowEditPositioningStrategy.isTopInitialPosition = null;
this.rowEditingOverlay.close();
this.rowEditingOverlay.element.parentElement.style.display = '';
}
/**
* @hidden @internal
*/
public toggleRowEditingOverlay(show) {
const rowStyle = this.rowEditingOverlay.element.style;
if (show) {
rowStyle.display = 'block';
} else {
rowStyle.display = 'none';
}
}
/**
* @hidden @internal
*/
public repositionRowEditingOverlay(row: IgxRowDirective<IgxGridBaseDirective & GridType>) {
if (row && !this.rowEditingOverlay.collapsed) {
const rowStyle = this.rowEditingOverlay.element.parentElement.style;
if (row) {
rowStyle.display = '';
this.configureRowEditingOverlay(row.rowID);
this.rowEditingOverlay.reposition();
} else {
rowStyle.display = 'none';
}
}
}
/**
* @hidden @internal
*/
public cachedViewLoaded(args: ICachedViewLoadedEventArgs) {
if (this.hasHorizontalScroll()) {
const tmplId = args.context.templateID.type;
const index = args.context.index;
args.view.detectChanges();
this.zone.onStable.pipe(first()).subscribe(() => {
const row = tmplId === 'dataRow' ? this.gridAPI.get_row_by_index(index) : null;
const summaryRow = tmplId === 'summaryRow' ? this.summariesRowList.find((sr) => sr.dataRowIndex === index) : null;
if (row && row instanceof IgxRowDirective) {
this._restoreVirtState(row);
} else if (summaryRow) {
this._restoreVirtState(summaryRow);
}
});
}
}
/**
* Opens the advanced filtering dialog.
*/
public openAdvancedFilteringDialog(overlaySettings?: OverlaySettings) {
const settings = overlaySettings ? overlaySettings : this._advancedFilteringOverlaySettings;
if (!this._advancedFilteringOverlayId) {
this._advancedFilteringOverlaySettings.target =
(this as any).rootGrid ? (this as any).rootGrid.nativeElement : this.nativeElement;
this._advancedFilteringOverlaySettings.outlet = this.outlet;
this._advancedFilteringOverlayId = this.overlayService.attach(
IgxAdvancedFilteringDialogComponent,
settings,
{
injector: this.viewRef.injector,
componentFactoryResolver: this.resolver
});
this.overlayService.show(this._advancedFilteringOverlayId);
}
}
/**
* Closes the advanced filtering dialog.
*
* @param applyChanges indicates whether the changes should be applied
*/
public closeAdvancedFilteringDialog(applyChanges: boolean) {
if (this._advancedFilteringOverlayId) {
const advancedFilteringOverlay = this.overlayService.getOverlayById(this._advancedFilteringOverlayId);
const advancedFilteringDialog = advancedFilteringOverlay.componentRef.instance as IgxAdvancedFilteringDialogComponent;
if (applyChanges) {
advancedFilteringDialog.applyChanges();
}
advancedFilteringDialog.closeDialog();
}
}
/**
* @hidden @internal
*/
public getEmptyRecordObjectFor(inRow: IgxRowDirective<IgxGridBaseDirective & GridType>) {
const row = { ...inRow?.rowData };
Object.keys(row).forEach(key => row[key] = undefined);
const id = this.generateRowID();
row[this.primaryKey] = id;
return { rowID: id, data: row, recordRef: row };
}
/**
* @hidden @internal
*/
public hasHorizontalScroll() {
return this.totalWidth - this.unpinnedWidth > 0;
}
/**
* @hidden @internal
*/
public isSummaryRow(rowData): boolean {
return rowData.summaries && (rowData.summaries instanceof Map);
}
/**
* @hidden @internal
*/
public triggerPipes() {
this.pipeTrigger++;
this.cdr.detectChanges();
}
/**
* @hidden
*/
public rowEditingWheelHandler(event: WheelEvent) {
if (event.deltaY > 0) {
this.verticalScrollContainer.scrollNext();
} else {
this.verticalScrollContainer.scrollPrev();
}
}
/**
* @hidden
*/
public getUnpinnedIndexById(id) {
return this.unpinnedRecords.findIndex(x => x[this.primaryKey] === id);
}
/**
* Finishes the row transactions on the current row.
*
* @remarks
* If `commit === true`, passes them from the pending state to the data (or transaction service)
* @example
* ```html
* <button igxButton (click)="grid.endEdit(true)">Commit Row</button>
* ```
* @param commit
*/
// TODO: Facade for crud service refactoring. To be removed
// TODO: do not remove this, as it is used in rowEditTemplate, but mark is as internal and hidden
public endEdit(commit = true, event?: Event) {
this.crudService.endEdit(commit, event);
}
/**
* Enters add mode by spawning the UI under the specified row by rowID.
*
* @remarks
* If null is passed as rowID, the row adding UI is spawned as the first record in the data view
* @remarks
* Spawning the UI to add a child for a record only works if you provide a rowID
* @example
* ```typescript
* this.grid.beginAddRowById('ALFKI');
* this.grid.beginAddRowById('ALFKI', true);
* this.grid.beginAddRowById(null);
* ```
* @param rowID - The rowID to spawn the add row UI for, or null to spawn it as the first record in the data view
* @param asChild - Whether the record should be added as a child. Only applicable to igxTreeGrid.
*/
public beginAddRowById(rowID: any, asChild?: boolean): void {
let index = rowID;
if (rowID == null) {
if (asChild) {
console.warn('The record cannot be added as a child to an unspecified record.');
return;
}
index = 0;
} else {
// find the index of the record with that PK
index = this.gridAPI.get_rec_index_by_id(rowID, this.dataView);
rowID = index;
if (index === -1) {
console.warn('No row with the specified ID was found.');
return;
}
}
if (!this.dataView.length) {
this.beginAddRowForIndex(rowID, asChild);
return;
}
// check if the index is valid - won't support anything outside the data view
if (index >= 0 && index < this.dataView.length) {
// check if the index is in the view port
if ((index < this.virtualizationState.startIndex ||
index >= this.virtualizationState.startIndex + this.virtualizationState.chunkSize) &&
!this.isRecordPinnedByViewIndex(index)) {
this.verticalScrollContainer.chunkLoad
.pipe(first(), takeUntil(this.destroy$))
.subscribe(() => {
this.beginAddRowForIndex(rowID, asChild);
});
this.navigateTo(index);
this.notifyChanges(true);
return;
}
this.beginAddRowForIndex(rowID, asChild);
} else {
console.warn('The row with the specified PK or index is outside of the current data view.');
}
}
/**
* Enters add mode by spawning the UI at the specified index.
*
* @remarks
* Accepted values for index are integers from 0 to this.grid.dataView.length
* @example
* ```typescript
* this.grid.beginAddRowByIndex(0);
* ```
* @param index - The index to spawn the UI at. Accepts integers from 0 to this.grid.dataView.length
*/
public beginAddRowByIndex(index: number): void {
if (index === 0) {
return this.beginAddRowById(null);
}
return this.beginAddRowById(this.gridAPI.get_rec_id_by_index(index - 1, this.dataView));
}
protected beginAddRowForIndex(index: number, asChild: boolean = false) {
const row: IgxRowDirective<IgxGridBaseDirective & GridType> = index == null ?
null : this.rowList.find(r => r.index === index);
if (row !== undefined) {
this.crudService.enterAddRowMode(row, asChild);
} else {
console.warn('No row with the specified PK or index was found.');
}
}
protected switchTransactionService(val: boolean) {
if (val) {
this._transactions = this.transactionFactory.create(TRANSACTION_TYPE.Base);
} else {
this._transactions = this.transactionFactory.create(TRANSACTION_TYPE.None);
}
}
protected subscribeToTransactions(): void {
this.transactionChange$.next();
this.transactions.onStateUpdate.pipe(takeUntil(merge(this.destroy$,this.transactionChange$)))
.subscribe(this.transactionStatusUpdate.bind(this));
}
protected transactionStatusUpdate(event: StateUpdateEvent) {
let actions: Action<Transaction>[] = [];
if (event.origin === TransactionEventOrigin.REDO) {
actions = event.actions ? event.actions.filter(x => x.transaction.type === TransactionType.DELETE) : [];
} else if (event.origin === TransactionEventOrigin.UNDO) {
actions = event.actions ? event.actions.filter(x => x.transaction.type === TransactionType.ADD) : [];
}
if (actions.length > 0) {
for (const action of actions) {
if (this.selectionService.isRowSelected(action.transaction.id)) {
this.selectionService.deselectRow(action.transaction.id);
}
}
}
this.selectionService.clearHeaderCBState();
this.summaryService.clearSummaryCache();
this.pipeTrigger++;
this.notifyChanges();
};
protected writeToData(rowIndex: number, value: any) {
mergeObjects(this.gridAPI.get_all_data()[rowIndex], value);
}
protected _restoreVirtState(row) {
// check virtualization state of data record added from cache
// in case state is no longer valid - update it.
const rowForOf = row.virtDirRow;
const gridScrLeft = rowForOf.getScroll().scrollLeft;
const left = -parseInt(rowForOf.dc.instance._viewContainer.element.nativeElement.style.left, 10);
const actualScrollLeft = left + rowForOf.getColumnScrollLeft(rowForOf.state.startIndex);
if (gridScrLeft !== actualScrollLeft) {
rowForOf.onHScroll(gridScrLeft);
rowForOf.cdr.detectChanges();
}
}
/**
* @hidden
*/
protected getExportExcel(): boolean {
return this._exportExcel;
}
/**
* @hidden
*/
protected getExportCsv(): boolean {
return this._exportCsv;
}
protected changeRowEditingOverlayStateOnScroll(row: IgxRowDirective<IgxGridBaseDirective & GridType>) {
if (!this.rowEditable || !this.rowEditingOverlay || this.rowEditingOverlay.collapsed) {
return;
}
if (!row) {
this.toggleRowEditingOverlay(false);
} else {
this.repositionRowEditingOverlay(row);
}
}
/**
* Should be called when data and/or isLoading input changes so that the overlay can be
* hidden/shown based on the current value of shouldOverlayLoading
*/
protected evaluateLoadingState() {
if (this.shouldOverlayLoading) {
// a new overlay should be shown
const overlaySettings: OverlaySettings = {
outlet: this.loadingOutlet,
closeOnOutsideClick: false,
positionStrategy: new ContainerPositionStrategy()
};
this.loadingOverlay.open(overlaySettings);
} else {
this.loadingOverlay.close();
}
}
/**
* @hidden
* Sets grid width i.e. this.calcWidth
*/
protected calculateGridWidth() {
let width;
if (this.isPercentWidth) {
/* width in %*/
const computed = this.document.defaultView.getComputedStyle(this.nativeElement).getPropertyValue('width');
width = computed.indexOf('%') === -1 ? parseInt(computed, 10) : null;
} else {
width = parseInt(this.width, 10);
}
if (!width && this.nativeElement) {
width = this.nativeElement.offsetWidth;
}
if (this.width === null || !width) {
width = this.getColumnWidthSum();
}
if (this.hasVerticalScroll() && this.width !== null) {
width -= this.scrollSize;
}
if ((Number.isFinite(width) || width === null) && width !== this.calcWidth) {
this.calcWidth = width;
}
this._derivePossibleWidth();
}
/**
* @hidden
* Sets columns defaultWidth property
*/
protected _derivePossibleWidth() {
if (!this.columnWidthSetByUser) {
this._columnWidth = this.width !== null ? this.getPossibleColumnWidth() : MINIMUM_COLUMN_WIDTH + 'px';
}
this.columnList.forEach((column: IgxColumnComponent) => {
if (this.hasColumnLayouts && parseInt(this._columnWidth, 10)) {
const columnWidthCombined = parseInt(this._columnWidth, 10) * (column.colEnd ? column.colEnd - column.colStart : 1);
column.defaultWidth = columnWidthCombined + 'px';
} else {
// D.K. March 29th, 2021 #9145 Consider min/max width when setting defaultWidth property
column.defaultWidth = this.getExtremumBasedColWidth(column);
column.resetCaches();
}
});
this.resetCachedWidths();
}
/**
* @hidden
* @internal
*/
protected getExtremumBasedColWidth(column: IgxColumnComponent): string {
let width = this._columnWidth;
if (width && typeof width !== 'string') {
width = String(width);
}
const minWidth = width.indexOf('%') === -1 ? column.minWidthPx : column.minWidthPercent;
const maxWidth = width.indexOf('%') === -1 ? column.maxWidthPx : column.maxWidthPercent;
if (column.hidden) {
return width;
}
if (minWidth > parseFloat(width)) {
width = String(column.minWidth);
} else if (maxWidth < parseFloat(width)) {
width = String(column.maxWidth);
}
// if no px or % are defined in maxWidth/minWidth consider it px
if (width.indexOf('%') === -1 && width.indexOf('px') === -1) {
width += 'px';
}
return width;
}
protected resetNotifyChanges() {
this._cdrRequestRepaint = false;
this._cdrRequests = false;
}
protected resolveOutlet() {
return this._userOutletDirective ? this._userOutletDirective : this._outletDirective;
}
/**
* Reorder columns in the main columnList and _columns collections.
*
* @hidden
*/
protected _moveColumns(from: IgxColumnComponent, to: IgxColumnComponent, pos: DropPosition) {
const list = this.columnList.toArray();
this._reorderColumns(from, to, pos, list);
const newList = this._resetColumnList(list);
this.columnList.reset(newList);
this.columnList.notifyOnChanges();
this._columns = this.columnList.toArray();
}
/**
* @hidden
*/
protected _resetColumnList(list?) {
if (!list) {
list = this.columnList.toArray();
}
let newList = [];
list.filter(c => c.level === 0).forEach(p => {
newList.push(p);
if (p.columnGroup) {
newList = newList.concat(p.allChildren);
}
});
return newList;
}
/**
* Reorders columns inside the passed column collection.
* When reordering column group collection, the collection is not flattened.
* In all other cases, the columns collection is flattened, this is why adittional calculations on the dropIndex are done.
*
* @hidden
*/
protected _reorderColumns(from: IgxColumnComponent, to: IgxColumnComponent, position: DropPosition, columnCollection: any[],
inGroup = false) {
const fromIndex = columnCollection.indexOf(from);
const childColumnsCount = inGroup ? 1 : from.allChildren.length + 1;
columnCollection.splice(fromIndex, childColumnsCount);
let dropIndex = columnCollection.indexOf(to);
if (position === DropPosition.AfterDropTarget) {
dropIndex++;
if (!inGroup && to.columnGroup) {
dropIndex += to.allChildren.length;
}
}
columnCollection.splice(dropIndex, 0, from);
}
/**
* Reorder column group collection.
*
* @hidden
*/
protected _moveChildColumns(parent: IgxColumnComponent, from: IgxColumnComponent, to: IgxColumnComponent, pos: DropPosition) {
const buffer = parent.children.toArray();
this._reorderColumns(from, to, pos, buffer, true);
parent.children.reset(buffer);
}
protected setupColumns() {
if (this.autoGenerate) {
this.autogenerateColumns();
}
this.initColumns(this.columnList, (col: IgxColumnComponent) => this.columnInit.emit(col));
this.columnListDiffer.diff(this.columnList);
this.columnList.changes
.pipe(takeUntil(this.destroy$))
.subscribe((change: QueryList<IgxColumnComponent>) => {
this.onColumnsChanged(change);
});
}
/**
* @hidden
*/
protected deleteRowFromData(rowID: any, index: number) {
// if there is a row (index !== 0) delete it
// if there is a row in ADD or UPDATE state change it's state to DELETE
if (index !== -1) {
if (this.transactions.enabled) {
const transaction: Transaction = { id: rowID, type: TransactionType.DELETE, newValue: null };
this.transactions.add(transaction, this.data[index]);
} else {
this.data.splice(index, 1);
}
} else {
const state: State = this.transactions.getState(rowID);
this.transactions.add({ id: rowID, type: TransactionType.DELETE, newValue: null }, state && state.recordRef);
}
}
/**
* @hidden @internal
*/
protected getDataBasedBodyHeight(): number {
return !this.data || (this.data.length < this._defaultTargetRecordNumber) ?
0 : this.defaultTargetBodyHeight;
}
/**
* @hidden @internal
*/
protected onPinnedRowsChanged(change: QueryList<IgxGridRowComponent>) {
const diff = this.rowListDiffer.diff(change);
if (diff) {
this.notifyChanges(true);
}
}
/**
* @hidden
*/
protected onColumnsChanged(change: QueryList<IgxColumnComponent>) {
const diff = this.columnListDiffer.diff(change);
if (this.autoGenerate && this.columnList.length === 0 && this._autoGeneratedCols.length > 0) {
// In Ivy if there are nested conditional templates the content children are re-evaluated
// hence autogenerated columns are cleared and need to be reset.
this.columnList.reset(this._autoGeneratedCols);
return;
}
if (diff) {
let added = false;
let removed = false;
diff.forEachAddedItem((record: IterableChangeRecord<IgxColumnComponent>) => {
this.columnInit.emit(record.item);
added = true;
if (record.item.pinned) {
this._pinnedColumns.push(record.item);
} else {
this._unpinnedColumns.push(record.item);
}
});
this.initColumns(this.columnList);
diff.forEachRemovedItem((record: IterableChangeRecord<IgxColumnComponent | IgxColumnGroupComponent>) => {
const isColumnGroup = record.item instanceof IgxColumnGroupComponent;
if (!isColumnGroup) {
// Clear Grouping
this.gridAPI.clear_groupby(record.item.field);
// Clear Filtering
this.filteringService.clear_filter(record.item.field);
// Close filter row
if (this.filteringService.isFilterRowVisible
&& this.filteringService.filteredColumn
&& this.filteringService.filteredColumn.field === record.item.field) {
this.filteringRow.close();
}
// Clear Sorting
this.gridAPI.clear_sort(record.item.field);
// Remove column selection
this.selectionService.deselectColumnsWithNoEvent([record.item.field]);
}
removed = true;
});
this.resetCaches();
if (added || removed) {
this.summaryService.clearSummaryCache();
Promise.resolve().then(() => {
// `onColumnsChanged` can be executed midway a current detectChange cycle and markForCheck will be ignored then.
// This ensures that we will wait for the current cycle to end so we can trigger a new one and ngDoCheck to fire.
this.notifyChanges(true);
});
}
}
}
/**
* @hidden
*/
protected calculateGridSizes(recalcFeatureWidth = true) {
/*
TODO: (R.K.) This layered lasagne should be refactored
ASAP. The reason I have to reset the caches so many times is because
after teach `detectChanges` call they are filled with invalid
state. Of course all of this happens midway through the grid
sizing process which of course, uses values from the caches, thus resulting
in a broken layout.
*/
this.resetCaches(recalcFeatureWidth);
this.cdr.detectChanges();
const hasScroll = this.hasVerticalScroll();
this.calculateGridWidth();
this.resetCaches(recalcFeatureWidth);
this.cdr.detectChanges();
this.calculateGridHeight();
if (this.rowEditable) {
this.repositionRowEditingOverlay(this.crudService.rowInEditMode);
}
if (this.filteringService.isFilterRowVisible) {
this.filteringRow.resetChipsArea();
}
this.cdr.detectChanges();
// in case scrollbar has appeared recalc to size correctly.
if (hasScroll !== this.hasVerticalScroll()) {
this.calculateGridWidth();
this.cdr.detectChanges();
}
if (this.zone.isStable) {
this.zone.run(() => {
this._applyWidthHostBinding();
this.cdr.detectChanges();
});
} else {
this.zone.onStable.pipe(first()).subscribe(() => {
this.zone.run(() => {
this._applyWidthHostBinding();
});
});
}
this.resetCaches(recalcFeatureWidth);
}
/**
* @hidden
* @internal
*/
protected calcGridHeadRow() {
if (this.maxLevelHeaderDepth) {
this._baseFontSize = parseFloat(getComputedStyle(this.document.documentElement).getPropertyValue('font-size'));
let minSize = (this.maxLevelHeaderDepth + 1) * this.defaultRowHeight / this._baseFontSize;
if (this._allowFiltering && this._filterMode === FilterMode.quickFilter) {
minSize += (FILTER_ROW_HEIGHT + 1) / this._baseFontSize;
}
this.theadRow.nativeElement.style.minHeight = `${minSize}rem`;
}
}
/**
* @hidden
* Sets TBODY height i.e. this.calcHeight
*/
protected calculateGridHeight() {
this.calcGridHeadRow();
this.summariesHeight = 0;
if (this.hasSummarizedColumns && this.rootSummariesEnabled) {
this.summariesHeight = this.summaryService.calcMaxSummaryHeight();
}
this.calcHeight = this._calculateGridBodyHeight();
if (this.pinnedRowHeight && this.calcHeight) {
this.calcHeight -= this.pinnedRowHeight;
}
}
/**
* @hidden
*/
protected getGroupAreaHeight(): number {
return 0;
}
/**
* @hidden
*/
protected getComputedHeight(elem) {
return elem.offsetHeight ? parseFloat(this.document.defaultView.getComputedStyle(elem).getPropertyValue('height')) : 0;
}
/**
* @hidden
*/
protected getFooterHeight(): number {
return this.summariesHeight || this.getComputedHeight(this.tfoot.nativeElement);
}
/**
* @hidden
*/
protected getTheadRowHeight(): number {
const height = this.getComputedHeight(this.theadRow.nativeElement);
return (!this.allowFiltering || (this.allowFiltering && this.filterMode !== FilterMode.quickFilter)) ?
height - this.getFilterCellHeight() :
height;
}
/**
* @hidden
*/
protected getToolbarHeight(): number {
let toolbarHeight = 0;
if (this.toolbar.first) {
toolbarHeight = this.getComputedHeight(this.toolbar.first.nativeElement);
}
return toolbarHeight;
}
/**
* @hidden
*/
protected getPagingFooterHeight(): number {
let pagingHeight = 0;
if (this.footer) {
const height = this.getComputedHeight(this.footer.nativeElement);
pagingHeight = this.footer.nativeElement.firstElementChild ?
height : 0;
}
return pagingHeight;
}
/**
* @hidden
*/
protected getFilterCellHeight(): number {
const headerGroupNativeEl = (this.headerGroupsList.length !== 0) ?
this.headerGroupsList[0].nativeElement : null;
const filterCellNativeEl = (headerGroupNativeEl) ?
headerGroupNativeEl.querySelector('igx-grid-filtering-cell') as HTMLElement : null;
return (filterCellNativeEl) ? filterCellNativeEl.offsetHeight : 0;
}
/**
* @hidden
*/
protected _calculateGridBodyHeight(): number {
if (!this._height) {
return null;
}
const actualTheadRow = this.getTheadRowHeight();
const footerHeight = this.getFooterHeight();
const toolbarHeight = this.getToolbarHeight();
const pagingHeight = this.getPagingFooterHeight();
const groupAreaHeight = this.getGroupAreaHeight();
const scrHeight = this.getComputedHeight(this.scr.nativeElement);
const renderedHeight = toolbarHeight + actualTheadRow +
footerHeight + pagingHeight + groupAreaHeight +
scrHeight;
let gridHeight = 0;
if (this.isPercentHeight) {
const computed = this.document.defaultView.getComputedStyle(this.nativeElement).getPropertyValue('height');
const autoSize = this._shouldAutoSize(renderedHeight);
if (autoSize || computed.indexOf('%') !== -1) {
const bodyHeight = this.getDataBasedBodyHeight();
return bodyHeight > 0 ? bodyHeight : null;
}
gridHeight = parseFloat(computed);
} else {
gridHeight = parseInt(this._height, 10);
}
const height = Math.abs(gridHeight - renderedHeight);
if (Math.round(height) === 0 || isNaN(gridHeight)) {
const bodyHeight = this.defaultTargetBodyHeight;
return bodyHeight > 0 ? bodyHeight : null;
}
return height;
}
protected checkContainerSizeChange() {
const origHeight = this.nativeElement.parentElement.offsetHeight;
this.nativeElement.style.display = 'none';
const height = this.nativeElement.parentElement.offsetHeight;
this.nativeElement.style.display = '';
return origHeight !== height;
}
protected _shouldAutoSize(renderedHeight) {
this.tbody.nativeElement.style.display = 'none';
let res = !this.nativeElement.parentElement ||
this.nativeElement.parentElement.clientHeight === 0 ||
this.nativeElement.parentElement.clientHeight === renderedHeight;
if (!this.platform.isChromium && !this.platform.isFirefox) {
// If grid causes the parent container to extend (for example when container is flex)
// we should always auto-size since the actual size of the container will continuously change as the grid renders elements.
res = this.checkContainerSizeChange();
}
this.tbody.nativeElement.style.display = '';
return res;
}
/**
* @hidden
* Gets calculated width of the unpinned area
* @param takeHidden If we should take into account the hidden columns in the pinned area.
*/
protected getUnpinnedWidth(takeHidden = false) {
let width = this.isPercentWidth ?
this.calcWidth :
parseInt(this.width, 10) || parseInt(this.hostWidth, 10) || this.calcWidth;
if (this.hasVerticalScroll() && !this.isPercentWidth) {
width -= this.scrollSize;
}
if (!this.isPinningToStart) {
width -= this.featureColumnsWidth();
}
return width - this.getPinnedWidth(takeHidden);
}
/**
* @hidden
*/
protected _summaries(fieldName: string, hasSummary: boolean, summaryOperand?: any) {
const column = this.gridAPI.get_column_by_name(fieldName);
if (column) {
column.hasSummary = hasSummary;
if (summaryOperand) {
if (this.rootSummariesEnabled) {
this.summaryService.retriggerRootPipe++;
}
column.summaries = summaryOperand;
}
}
}
/**
* @hidden
*/
protected _multipleSummaries(expressions: ISummaryExpression[], hasSummary: boolean) {
expressions.forEach((element) => {
this._summaries(element.fieldName, hasSummary, element.customSummary);
});
}
/**
* @hidden
*/
protected _disableMultipleSummaries(expressions) {
expressions.forEach((column) => {
const columnName = column && column.fieldName ? column.fieldName : column;
this._summaries(columnName, false);
});
}
/**
* @hidden
*/
protected resolveDataTypes(rec) {
if (typeof rec === 'number') {
return GridColumnDataType.Number;
} else if (typeof rec === 'boolean') {
return GridColumnDataType.Boolean;
} else if (typeof rec === 'object' && rec instanceof Date) {
return GridColumnDataType.Date;
}
return GridColumnDataType.String;
}
/**
* @hidden
*/
protected autogenerateColumns() {
const data = this.gridAPI.get_data();
const factory = this.resolver.resolveComponentFactory(IgxColumnComponent);
const fields = this.generateDataFields(data);
const columns = [];
fields.forEach((field) => {
const ref = factory.create(this.viewRef.injector);
ref.instance.field = field;
ref.instance.dataType = this.resolveDataTypes(data[0][field]);
ref.changeDetectorRef.detectChanges();
columns.push(ref.instance);
});
this._autoGeneratedCols = columns;
this.columnList.reset(columns);
if (data && data.length > 0) {
this.shouldGenerate = false;
}
}
protected generateDataFields(data: any[]): string[] {
return Object.keys(data && data.length !== 0 ? data[0] : []);
}
/**
* @hidden
*/
protected initColumns(collection: QueryList<IgxColumnComponent>, cb: (args: any) => void = null) {
this._columnGroups = this.columnList.some(col => col.columnGroup);
if (this.hasColumnLayouts) {
// Set overall row layout size
this.columnList.forEach((col) => {
if (col.columnLayout) {
const layoutSize = col.children ?
col.children.reduce((acc, val) => Math.max(val.rowStart + val.gridRowSpan - 1, acc), 1) :
1;
this._multiRowLayoutRowSize = Math.max(layoutSize, this._multiRowLayoutRowSize);
}
});
}
if (this.hasColumnLayouts && this.hasColumnGroups) {
// invalid configuration - multi-row and column groups
// remove column groups
const columnLayoutColumns = this.columnList.filter((col) => col.columnLayout || col.columnLayoutChild);
this.columnList.reset(columnLayoutColumns);
}
this._maxLevelHeaderDepth = null;
this._columns = this.columnList.toArray();
collection.forEach((column: IgxColumnComponent) => {
column.defaultWidth = this.columnWidthSetByUser ? this._columnWidth : column.defaultWidth ? column.defaultWidth : '';
if (cb) {
cb(column);
}
});
this.reinitPinStates();
if (this.hasColumnLayouts) {
collection.forEach((column: IgxColumnComponent) => {
column.populateVisibleIndexes();
});
}
}
/**
* @hidden
*/
protected reinitPinStates() {
this._pinnedColumns = this.columnList
.filter((c) => c.pinned).sort((a, b) => this._pinnedColumns.indexOf(a) - this._pinnedColumns.indexOf(b));
this._unpinnedColumns = this.hasColumnGroups ? this.columnList.filter((c) => !c.pinned) :
this.columnList.filter((c) => !c.pinned)
.sort((a, b) => a.index - b.index);
}
protected extractDataFromSelection(source: any[], formatters = false, headers = false, columnData?: any[]): any[] {
let columnsArray: IgxColumnComponent[];
let record = {};
let selectedData = [];
let keys = [];
const selectionCollection = new Map();
const keysAndData = [];
const activeEl = this.selectionService.activeElement;
if (this.nativeElement.tagName.toLowerCase() === 'igx-hierarchical-grid') {
const expansionRowIndexes = [];
for (const [key, value] of this.expansionStates.entries()) {
if (value) {
expansionRowIndexes.push(key);
}
}
if (this.selectionService.selection.size > 0) {
if (expansionRowIndexes.length > 0) {
for (const [key, value] of this.selectionService.selection.entries()) {
let updatedKey = key;
expansionRowIndexes.forEach(row => {
let rowIndex;
if (!isNaN(row.ID)) {
rowIndex = Number(row.ID);
} else {
rowIndex = Number(row);
}
if (updatedKey > Number(rowIndex)) {
updatedKey--;
}
});
selectionCollection.set(updatedKey, value);
}
}
} else if (activeEl) {
if (expansionRowIndexes.length > 0) {
expansionRowIndexes.forEach(row => {
if (activeEl.row > Number(row)) {
activeEl.row--;
}
});
}
}
}
const totalItems = (this as any).totalItemCount ?? 0;
const isRemote = totalItems && totalItems > this.dataView.length;
let selectionMap;
if (this.nativeElement.tagName.toLowerCase() === 'igx-hierarchical-grid' && selectionCollection.size > 0) {
selectionMap = isRemote ? Array.from(selectionCollection) :
Array.from(selectionCollection).filter((tuple) => tuple[0] < source.length);
}else {
selectionMap = isRemote ? Array.from(this.selectionService.selection) :
Array.from(this.selectionService.selection).filter((tuple) => tuple[0] < source.length);
}
if (this.cellSelection === GridSelectionMode.single && activeEl) {
selectionMap.push([activeEl.row, new Set<number>().add(activeEl.column)]);
}
if (this.cellSelection === GridSelectionMode.none && activeEl) {
selectionMap.push([activeEl.row, new Set<number>().add(activeEl.column)]);
}
if (columnData) {
selectedData = columnData;
}
// eslint-disable-next-line prefer-const
for (let [row, set] of selectionMap) {
row = this.paginator && source === this.filteredSortedData ? row + (this.paginator.perPage * this.paginator.page) : row;
row = isRemote ? row - this.virtualizationState.startIndex : row;
if (!source[row] || source[row].detailsData !== undefined) {
continue;
}
const temp = Array.from(set);
for (const each of temp) {
columnsArray = this.getSelectableColumnsAt(each);
columnsArray.forEach((col) => {
if (col) {
const key = headers ? col.header || col.field : col.field;
const rowData = source[row].ghostRecord ? source[row].recordRef : source[row];
const value = resolveNestedPath(rowData, col.field);
record[key] = formatters && col.formatter ? col.formatter(value, rowData) : value;
if (columnData) {
if (!record[key]) {
record[key] = '';
}
record[key] = record[key].toString().concat('recordRow-' + row);
}
}
});
}
if (Object.keys(record).length) {
if (columnData) {
if (!keys.length) {
keys = Object.keys(columnData[0]);
}
for (const [key, value] of Object.entries(record)) {
if (!keys.includes(key)) {
keys.push(key);
}
let c: any = value;
const rowNumber = +c.split('recordRow-')[1];
c = c.split('recordRow-')[0];
record[key] = c;
const mergedObj = Object.assign(selectedData[rowNumber], record);
selectedData[rowNumber] = mergedObj;
}
} else {
selectedData.push(record);
}
}
record = {};
}
if (keys.length) {
keysAndData.push(selectedData);
keysAndData.push(keys);
return keysAndData;
} else {
return selectedData;
}
}
protected getSelectableColumnsAt(index) {
if (this.hasColumnLayouts) {
const visibleLayoutColumns = this.visibleColumns
.filter(col => col.columnLayout)
.sort((a, b) => a.visibleIndex - b.visibleIndex);
const colLayout = visibleLayoutColumns[index];
return colLayout ? colLayout.children.toArray() : [];
} else {
const visibleColumns = this.visibleColumns
.filter(col => !col.columnGroup)
.sort((a, b) => a.visibleIndex - b.visibleIndex);
return [visibleColumns[index]];
}
}
protected extractDataFromColumnsSelection(source: any[], formatters = false, headers = false): any[] {
let record = {};
const selectedData = [];
const selectedColumns = this.selectedColumns();
if (selectedColumns.length === 0) {
return [];
}
for (const data of source) {
selectedColumns.forEach((col) => {
const key = headers ? col.header || col.field : col.field;
record[key] = formatters && col.formatter ? col.formatter(data[col.field], data)
: data[col.field];
});
if (Object.keys(record).length) {
selectedData.push(record);
}
record = {};
}
return selectedData;
}
/**
* @hidden
*/
protected initPinning() {
const pinnedColumns = [];
const unpinnedColumns = [];
this.calculateGridWidth();
this.resetCaches();
// When a column is a group or is inside a group, pin all related.
this._pinnedColumns.forEach(col => {
if (col.parent) {
col.parent.pinned = true;
}
if (col.columnGroup) {
col.children.forEach(child => child.pinned = true);
}
});
// Make sure we don't exceed unpinned area min width and get pinned and unpinned col collections.
// We take into account top level columns (top level groups and non groups).
// If top level is unpinned the pinning handles all children to be unpinned as well.
for (const column of this._columns) {
if (column.pinned && !column.parent) {
pinnedColumns.push(column);
} else if (column.pinned && column.parent) {
if (column.topLevelParent.pinned) {
pinnedColumns.push(column);
} else {
column.pinned = false;
unpinnedColumns.push(column);
}
} else {
unpinnedColumns.push(column);
}
}
// Assign the applicable collections.
this._pinnedColumns = pinnedColumns;
this._unpinnedColumns = unpinnedColumns;
this.notifyChanges();
}
/**
* @hidden
*/
protected scrollTo(row: any | number, column: any | number, inCollection = this._filteredSortedUnpinnedData): void {
let delayScrolling = false;
if (this.paginator && typeof (row) !== 'number') {
const rowIndex = inCollection.indexOf(row);
const page = Math.floor(rowIndex / this.paginator.perPage);
if (this.paginator.page !== page) {
delayScrolling = true;
this.paginator.page = page;
}
}
if (delayScrolling) {
this.verticalScrollContainer.dataChanged.pipe(first()).subscribe(() => {
this.scrollDirective(this.verticalScrollContainer,
typeof (row) === 'number' ? row : this.unpinnedDataView.indexOf(row));
});
} else {
this.scrollDirective(this.verticalScrollContainer,
typeof (row) === 'number' ? row : this.unpinnedDataView.indexOf(row));
}
this.scrollToHorizontally(column);
}
/**
* @hidden
*/
protected scrollToHorizontally(column: any | number) {
let columnIndex = typeof column === 'number' ? column : this.getColumnByName(column).visibleIndex;
const scrollRow = this.rowList.find(r => r.virtDirRow);
const virtDir = scrollRow ? scrollRow.virtDirRow : null;
if (this.isPinningToStart && this.pinnedColumns.length) {
if (columnIndex >= this.pinnedColumns.length) {
columnIndex -= this.pinnedColumns.length;
this.scrollDirective(virtDir, columnIndex);
}
} else {
this.scrollDirective(virtDir, columnIndex);
}
}
/**
* @hidden
*/
protected scrollDirective(directive: IgxGridForOfDirective<any>, goal: number): void {
if (!directive) {
return;
}
directive.scrollTo(goal);
}
private getColumnWidthSum(): number {
let colSum = 0;
const cols = this.hasColumnLayouts ?
this.visibleColumns.filter(x => x.columnLayout) : this.visibleColumns.filter(x => !x.columnGroup);
cols.forEach((item) => {
colSum += parseInt((item.calcWidth || item.defaultWidth), 10) || MINIMUM_COLUMN_WIDTH;
});
if (!colSum) {
return null;
}
this.cdr.detectChanges();
colSum += this.featureColumnsWidth();
return colSum;
}
/**
* Notify changes, reset cache and populateVisibleIndexes.
*
* @hidden
*/
private _columnsReordered(column: IgxColumnComponent) {
this.notifyChanges();
if (this.hasColumnLayouts) {
this.columns.filter(x => x.columnLayout).forEach(x => x.populateVisibleIndexes());
}
// after reordering is done reset cached column collections.
this.resetColumnCollections();
column.resetCaches();
}
private _applyWidthHostBinding() {
let width = this._width;
if (width === null) {
let currentWidth = this.calcWidth;
if (this.hasVerticalScroll()) {
currentWidth += this.scrollSize;
}
width = currentWidth + 'px';
this.resetCaches();
}
this._hostWidth = width;
this.cdr.markForCheck();
}
private verticalScrollHandler(event) {
this.verticalScrollContainer.onScroll(event);
this.disableTransitions = true;
this.zone.run(() => {
this.zone.onStable.pipe(first()).subscribe(() => {
this.verticalScrollContainer.chunkLoad.emit(this.verticalScrollContainer.state);
if (this.rowEditable) {
this.changeRowEditingOverlayStateOnScroll(this.crudService.rowInEditMode);
}
});
});
this.disableTransitions = false;
this.hideOverlays();
this.actionStrip?.hide();
if (this.actionStrip) {
this.actionStrip.context = null;
}
const args: IGridScrollEventArgs = {
direction: 'vertical',
event,
scrollPosition: this.verticalScrollContainer.scrollPosition
};
this.gridScroll.emit(args);
}
private horizontalScrollHandler(event) {
const scrollLeft = event.target.scrollLeft;
this.headerContainer.onHScroll(scrollLeft);
this._horizontalForOfs.forEach(vfor => vfor.onHScroll(scrollLeft));
this.cdr.markForCheck();
this.zone.run(() => {
this.zone.onStable.pipe(first()).subscribe(() => {
this.parentVirtDir.chunkLoad.emit(this.headerContainer.state);
});
});
this.hideOverlays();
const args: IGridScrollEventArgs = { direction: 'horizontal', event, scrollPosition: this.headerContainer.scrollPosition };
this.gridScroll.emit(args);
}
private executeCallback(rowIndex, visibleColIndex = -1, cb: (args: any) => void = null) {
if (!cb) {
return;
}
let row = this.summariesRowList.filter(s => s.index !== 0).concat(this.rowList.toArray()).find(r => r.index === rowIndex);
if (!row) {
if ((this as any).totalItemCount) {
this.verticalScrollContainer.dataChanged.pipe(first()).subscribe(() => {
this.cdr.detectChanges();
row = this.summariesRowList.filter(s => s.index !== 0).concat(this.rowList.toArray()).find(r => r.index === rowIndex);
const cbArgs = this.getNavigationArguments(row, visibleColIndex);
cb(cbArgs);
});
}
if (this.dataView[rowIndex].detailsData) {
this.navigation.setActiveNode({ row: rowIndex });
this.cdr.detectChanges();
}
return;
}
const args = this.getNavigationArguments(row, visibleColIndex);
cb(args);
}
private getNavigationArguments(row, visibleColIndex) {
let targetType: GridKeydownTargetType; let target;
switch (row.nativeElement.tagName.toLowerCase()) {
case 'igx-grid-groupby-row':
targetType = 'groupRow';
target = row;
break;
case 'igx-grid-summary-row':
targetType = 'summaryCell';
target = visibleColIndex !== -1 ?
row.summaryCells.find(c => c.visibleColumnIndex === visibleColIndex) : row.summaryCells.first;
break;
case 'igx-child-grid-row':
targetType = 'hierarchicalRow';
target = row;
break;
default:
targetType = 'dataCell';
target = visibleColIndex !== -1 ? row.cells.find(c => c.visibleColumnIndex === visibleColIndex) : row.cells.first;
break;
}
return { targetType, target };
}
private getNextDataRowIndex(currentRowIndex, previous = false): number {
if (currentRowIndex < 0 || (currentRowIndex === 0 && previous) || (currentRowIndex >= this.dataView.length - 1 && !previous)) {
return currentRowIndex;
}
// find next/prev record that is editable.
const nextRowIndex = previous ? this.findPrevEditableDataRowIndex(currentRowIndex) :
this.dataView.findIndex((rec, index) =>
index > currentRowIndex && this.isEditableDataRecordAtIndex(index));
return nextRowIndex !== -1 ? nextRowIndex : currentRowIndex;
}
/**
* Returns the previous editable row index or -1 if no such row is found.
*
* @param currentIndex The index of the current editable record.
*/
private findPrevEditableDataRowIndex(currentIndex): number {
let i = this.dataView.length;
while (i--) {
if (i < currentIndex && this.isEditableDataRecordAtIndex(i)) {
return i;
}
}
return -1;
}
/**
* Returns if the record at the specified data view index is a an editable data record.
* If record is group rec, summary rec, child rec, ghost rec. etc. it is not editable.
*
* @param dataViewIndex The index of that record in the data view.
*
*/
// TODO: Consider moving it into CRUD
private isEditableDataRecordAtIndex(dataViewIndex) {
const rec = this.dataView[dataViewIndex];
return !rec.expression && !rec.summaries && !rec.childGridsData && !rec.detailsData &&
!this.isGhostRecordAtIndex(dataViewIndex);
}
/**
* Returns if the record at the specified data view index is a ghost.
* If record is pinned but is not in pinned area then it is a ghost record.
*
* @param dataViewIndex The index of that record in the data view.
*/
private isGhostRecordAtIndex(dataViewIndex) {
const isPinned = this.isRecordPinned(this.dataView[dataViewIndex]);
const isInPinnedArea = this.isRecordPinnedByViewIndex(dataViewIndex);
return isPinned && !isInPinnedArea;
}
private isValidPosition(rowIndex, colIndex): boolean {
const rows = this.summariesRowList.filter(s => s.index !== 0).concat(this.rowList.toArray()).length;
const cols = this.columnList.filter(col => !col.columnGroup && col.visibleIndex >= 0 && !col.hidden).length;
if (rows < 1 || cols < 1) {
return false;
}
if (rowIndex > -1 && rowIndex < this.dataView.length &&
colIndex > - 1 && colIndex <= Math.max(...this.visibleColumns.map(c => c.visibleIndex))) {
return true;
}
return false;
}
private find(text: string, increment: number, caseSensitive?: boolean, exactMatch?: boolean, scroll?: boolean, endEdit = true) {
if (!this.rowList) {
return 0;
}
if (endEdit) {
this.crudService.endEdit(false);
}
if (!text) {
this.clearSearch();
return 0;
}
const caseSensitiveResolved = caseSensitive ? true : false;
const exactMatchResolved = exactMatch ? true : false;
let rebuildCache = false;
if (this.lastSearchInfo.searchText !== text ||
this.lastSearchInfo.caseSensitive !== caseSensitiveResolved ||
this.lastSearchInfo.exactMatch !== exactMatchResolved) {
this.lastSearchInfo = {
searchText: text,
activeMatchIndex: 0,
caseSensitive: caseSensitiveResolved,
exactMatch: exactMatchResolved,
matchInfoCache: []
};
rebuildCache = true;
} else {
this.lastSearchInfo.activeMatchIndex += increment;
}
if (rebuildCache) {
this.rowList.forEach((row) => {
if (row.cells) {
row.cells.forEach((c) => {
c.highlightText(text, caseSensitiveResolved, exactMatchResolved);
});
}
});
this.rebuildMatchCache();
}
if (this.lastSearchInfo.activeMatchIndex >= this.lastSearchInfo.matchInfoCache.length) {
this.lastSearchInfo.activeMatchIndex = 0;
} else if (this.lastSearchInfo.activeMatchIndex < 0) {
this.lastSearchInfo.activeMatchIndex = this.lastSearchInfo.matchInfoCache.length - 1;
}
if (this.lastSearchInfo.matchInfoCache.length) {
const matchInfo = this.lastSearchInfo.matchInfoCache[this.lastSearchInfo.activeMatchIndex];
this.lastSearchInfo = { ...this.lastSearchInfo };
if (scroll !== false) {
this.scrollTo(matchInfo.row, matchInfo.column);
}
IgxTextHighlightDirective.setActiveHighlight(this.id, {
column: matchInfo.column,
row: matchInfo.row,
index: matchInfo.index,
metadata: matchInfo.metadata,
});
} else {
IgxTextHighlightDirective.clearActiveHighlight(this.id);
}
return this.lastSearchInfo.matchInfoCache.length;
}
private rebuildMatchCache() {
this.lastSearchInfo.matchInfoCache = [];
const caseSensitive = this.lastSearchInfo.caseSensitive;
const exactMatch = this.lastSearchInfo.exactMatch;
const searchText = caseSensitive ? this.lastSearchInfo.searchText : this.lastSearchInfo.searchText.toLowerCase();
const data = this.filteredSortedData;
const columnItems = this.visibleColumns.filter((c) => !c.columnGroup).sort((c1, c2) => c1.visibleIndex - c2.visibleIndex);
data.forEach((dataRow, rowIndex) => {
columnItems.forEach((c) => {
const pipeArgs = this.getColumnByName(c.field).pipeArgs;
const value = c.formatter ? c.formatter(resolveNestedPath(dataRow, c.field), dataRow) :
c.dataType === 'number' ? this.decimalPipe.transform(resolveNestedPath(dataRow, c.field),
pipeArgs.digitsInfo, this.locale) :
c.dataType === 'date' ? this.datePipe.transform(resolveNestedPath(dataRow, c.field),
pipeArgs.format, pipeArgs.timezone, this.locale)
: resolveNestedPath(dataRow, c.field);
if (value !== undefined && value !== null && c.searchable) {
let searchValue = caseSensitive ? String(value) : String(value).toLowerCase();
if (exactMatch) {
if (searchValue === searchText) {
const metadata = new Map<string, any>();
metadata.set('pinned', this.isRecordPinnedByIndex(rowIndex));
this.lastSearchInfo.matchInfoCache.push({
row: dataRow,
column: c.field,
index: 0,
metadata,
});
}
} else {
let occurenceIndex = 0;
let searchIndex = searchValue.indexOf(searchText);
while (searchIndex !== -1) {
const metadata = new Map<string, any>();
metadata.set('pinned', this.isRecordPinnedByIndex(rowIndex));
this.lastSearchInfo.matchInfoCache.push({
row: dataRow,
column: c.field,
index: occurenceIndex++,
metadata,
});
searchValue = searchValue.substring(searchIndex + searchText.length);
searchIndex = searchValue.indexOf(searchText);
}
}
}
});
});
}
// TODO: About to Move to CRUD
private configureRowEditingOverlay(rowID: any, useOuter = false) {
let settings = this.rowEditSettings;
const overlay = this.overlayService.getOverlayById(this.rowEditingOverlay.overlayId);
if (overlay) {
settings = overlay.settings;
}
settings.outlet = useOuter ? this.parentRowOutletDirective : this.rowOutletDirective;
this.rowEditPositioningStrategy.settings.container = this.tbody.nativeElement;
const pinned = this._pinnedRecordIDs.indexOf(rowID) !== -1;
const targetRow = !pinned ? this.gridAPI.get_row_by_key(rowID) : this.pinnedRows.find(x => x.rowID === rowID);
if (!targetRow) {
return;
}
settings.target = targetRow.element.nativeElement;
this.toggleRowEditingOverlay(true);
}
} | the_stack |
import type { API, FileInfo } from 'jscodeshift';
import type { ProgramVisitorContext } from '../../../plugins/types';
import transformer from '../index';
jest.disableAutomock();
// eslint-disable-next-line @typescript-eslint/no-var-requires
const defineInlineTest = require('jscodeshift/dist/testUtils').defineInlineTest;
describe('styled-components-to-compiled imports transformer', () => {
defineInlineTest(
{ default: transformer, parser: 'tsx' },
{ plugins: [] },
"import styled from 'styled-components';",
"import { styled } from '@compiled/react';",
'it transforms default styled-components imports'
);
defineInlineTest(
{ default: transformer, parser: 'tsx' },
{ plugins: [] },
"import sc from 'styled-components';",
"import { styled as sc } from '@compiled/react';",
'it transforms default with different name than "styled" styled-components imports'
);
defineInlineTest(
{ default: transformer, parser: 'tsx' },
{ plugins: [] },
"import { css } from 'styled-components';",
"import { css } from '@compiled/react';",
'it transforms named imports when they are alone'
);
defineInlineTest(
{ default: transformer, parser: 'tsx' },
{ plugins: [] },
"import styled, { css } from 'styled-components';",
"import { css, styled } from '@compiled/react';",
'it transforms mixed default and named imports'
);
defineInlineTest(
{ default: transformer, parser: 'tsx' },
{ plugins: [] },
"import styled, { css as customLocal1, css as customLocal2, keyframes as kf } from 'styled-components';",
"import { css as customLocal1, css as customLocal2, keyframes as kf, styled } from '@compiled/react';",
"it keeps extra valid named imports' aliases intact"
);
defineInlineTest(
{ default: transformer, parser: 'tsx' },
{ plugins: [] },
`
import styled from 'styled-components';
import styled2, { css } from 'styled-components';
import { keyframes } from 'styled-components';
`,
`
import { styled } from '@compiled/react';
import { css, styled as styled2 } from '@compiled/react';
import { keyframes } from '@compiled/react';
`,
'it preserves multiple imports of styled-components'
);
defineInlineTest(
{ default: transformer, parser: 'tsx' },
{ plugins: [] },
"import styled, { keyframes as akf, css } from 'styled-components';",
"import { css, keyframes as akf, styled } from '@compiled/react';",
'it sorts imports alphabetically'
);
defineInlineTest(
{ default: transformer, parser: 'tsx' },
{ plugins: [] },
`
import styled from 'styled-components';
import * as React from 'react';
`,
`
import { styled } from '@compiled/react';
import * as React from 'react';
`,
'it ignores other imports'
);
defineInlineTest(
{ default: transformer, parser: 'tsx' },
{ plugins: [] },
`
// @top-level comment
// comment 1
import styled from 'styled-components';
// comment 2
import * as React from 'react';
`,
`
// @top-level comment
// comment 1
import { styled } from '@compiled/react';
// comment 2
import * as React from 'react';
`,
'it should not remove top level comments when transformed'
);
defineInlineTest(
{ default: transformer, parser: 'tsx' },
{ plugins: [] },
`
// @top-level comment
// comment 1
import * as React from 'react';
// comment 2
import styled from 'styled-components';
`,
`
// @top-level comment
// comment 1
import * as React from 'react';
// comment 2
import { styled } from '@compiled/react';
`,
'it should not remove comments before transformed statement when not on top'
);
defineInlineTest(
{ default: transformer, parser: 'tsx' },
{ plugins: [] },
`
import styled, { css, keyframes, createGlobalStyle, ThemeProvider, withTheme } from 'styled-components';
import * as React from 'react';
`,
`
/* TODO(@compiled/react codemod): "createGlobalStyle" is not exported from "@compiled/react" at the moment. Please find an alternative for it. */
/* TODO(@compiled/react codemod): "ThemeProvider" is not exported from "@compiled/react" at the moment. Please find an alternative for it. */
/* TODO(@compiled/react codemod): "withTheme" is not exported from "@compiled/react" at the moment. Please find an alternative for it. */
import { css, keyframes, styled } from '@compiled/react';
import * as React from 'react';
`,
'it adds TODO comment for imports which are not resolved'
);
defineInlineTest(
{ default: transformer, parser: 'tsx' },
{ plugins: [] },
`
import { multiple, unsupported, imports } from 'styled-components';
`,
`
/* TODO(@compiled/react codemod): "multiple" is not exported from "@compiled/react" at the moment. Please find an alternative for it. */
/* TODO(@compiled/react codemod): "unsupported" is not exported from "@compiled/react" at the moment. Please find an alternative for it. */
/* TODO(@compiled/react codemod): "imports" is not exported from "@compiled/react" at the moment. Please find an alternative for it. */
import '@compiled/react';
`,
'it properly handles import statements with no supported imports'
);
defineInlineTest(
{ default: transformer, parser: 'tsx' },
{ plugins: [] },
"import * as React from 'react';",
"import * as React from 'react';",
'it should not transform when styled-components imports are not present'
);
defineInlineTest(
{ default: transformer, parser: 'tsx' },
{
plugins: [
{
create: (_: FileInfo) => ({
transform: {
buildImport: ({ originalNode, currentNode }: any) => {
for (const specifier of originalNode.specifiers) {
specifier.local.name = `${specifier.local.name}Edited`;
}
return currentNode;
},
},
}),
},
],
},
"import styled, { css } from 'styled-components';",
"import { css, styled } from '@compiled/react';",
'it should not share specifier references between the original and new imports'
);
defineInlineTest(
{ default: transformer, parser: 'tsx' },
{
plugins: [
{
create: (_: FileInfo, { jscodeshift: j }: API) => ({
transform: {
buildImport: () =>
j.expressionStatement(
j.callExpression(
j.memberExpression(j.identifier('console'), j.identifier('log')),
[j.literal('Bring back Netscape')]
)
),
},
}),
},
],
},
"import styled from 'styled-components';",
"console.log('Bring back Netscape');",
'it should use the buildImport from the plugin'
);
defineInlineTest(
{ default: transformer, parser: 'tsx' },
{
plugins: [
{
create: (_: FileInfo, { jscodeshift: j }: API) => ({
transform: {
buildImport: () =>
j.expressionStatement(
j.callExpression(
j.memberExpression(j.identifier('console'), j.identifier('log')),
[j.literal('Bring back Netscape')]
)
),
},
}),
},
{
create: (_: FileInfo, { jscodeshift: j }: API) => ({
transform: {
buildImport: ({ originalNode, currentNode, specifiers, compiledImportPath }: any) => {
currentNode.comments = [
j.commentLine(j(originalNode).toSource(), true),
j.commentLine(
specifiers
.map(
(specifier: any) => `${specifier.imported.name} as ${specifier.local.name}`
)
.toString(),
true
),
j.commentLine(compiledImportPath, true),
];
return currentNode;
},
},
}),
},
],
},
`
import styled, { css } from 'styled-components';
`,
`
//import styled, { css } from 'styled-components';
//css as css,styled as styled
//@compiled/react
console.log('Bring back Netscape');
`,
'it should pass the expected parameters to the buildImport plugins'
);
defineInlineTest(
{ default: transformer, parser: 'tsx' },
{
plugins: [
{
create: (_: FileInfo, { jscodeshift: j }: API) => ({
visitor: {
program: ({ program }: ProgramVisitorContext<void>) => {
j(program)
.find(j.ImportDeclaration)
.insertBefore(() =>
j.expressionStatement(
j.callExpression(
j.memberExpression(j.identifier('console'), j.identifier('log')),
[j.literal('Bring back Netscape')]
)
)
);
},
},
}),
},
],
},
"import styled from 'styled-components';",
"console.log('Bring back Netscape');\nimport { styled } from '@compiled/react';",
'it should use the program visitor from the plugin'
);
});
describe('styled-components-to-compiled imports transformer inline comments', () => {
// Due to open recast Issue #191, for inline comment lines, trailing comments are being turned into leading comments.
// To avoid this and to preserve location information, we copy over all inline comments as block comments.
// Link: https://github.com/benjamn/recast/issues/191
// The following tests reflect this behaviour.
defineInlineTest(
{ default: transformer, parser: 'tsx' },
{ plugins: [] },
`
import {
css // a single comment line
} from 'styled-components';
`,
`import { css/* a single comment line*/ } from '@compiled/react';`,
'it preserves trailing comment lines as comment blocks when comments are inline'
);
defineInlineTest(
{ default: transformer, parser: 'tsx' },
{ plugins: [] },
`
import {
css /* a single comment block */
} from 'styled-components';
`,
`import { css/* a single comment block */ } from '@compiled/react';`,
'it preserves trailing comment blocks when comments are inline'
);
defineInlineTest(
{ default: transformer, parser: 'tsx' },
{ plugins: [] },
`
import {
/* a single comment block */ css
} from 'styled-components';
`,
`
import {
/* a single comment block */
css
} from '@compiled/react';
`,
'it preserves leading comment blocks when comments are inline'
);
defineInlineTest(
{ default: transformer, parser: 'tsx' },
{ plugins: [] },
`
import {
// a single comment block
css
} from 'styled-components';
`,
`
import {
/* a single comment block*/
css
} from '@compiled/react';
`,
'it preserves leading comment lines as comment blocks when comments are inline'
);
defineInlineTest(
{ default: transformer, parser: 'tsx' },
{ plugins: [] },
`
import {
css,
keyframes
// keyframes comment
} from 'styled-components';
`,
`import { css, keyframes/* keyframes comment*/ } from '@compiled/react';`,
'it preserves trailing comment lines as comment blocks with multiple named imports when comments are inline'
);
defineInlineTest(
{ default: transformer, parser: 'tsx' },
{ plugins: [] },
`
import {
css,
// keyframes comment
keyframes
} from 'styled-components';
`,
`
import {
css, /* keyframes comment*/
keyframes
} from '@compiled/react';
`,
'it preserves leading comment lines as comment blocks with multiple named imports when comments are inline'
);
defineInlineTest(
{ default: transformer, parser: 'tsx' },
{ plugins: [] },
`
import styled, // styled comment
{
css,
// keyframes comment
keyframes
} from 'styled-components';
`,
`
import {
css, /* keyframes comment*/
keyframes, styled/* styled comment*/
} from '@compiled/react';
`,
'it preserves comments for default imports when comments are inline'
);
defineInlineTest(
{ default: transformer, parser: 'tsx' },
{ plugins: [] },
`
import /* leading styled comment */ styled,
{
css,
// keyframes comment
keyframes
} from 'styled-components';
`,
`
import {
css, /* keyframes comment*/
keyframes, /* leading styled comment */
styled
} from '@compiled/react';
`,
'it preserves leading comment blocks for default imports when comments are inline'
);
}); | the_stack |
import {
VSN,
CHANNEL_EVENTS,
TRANSPORTS,
SOCKET_STATES,
DEFAULT_TIMEOUT,
WS_CLOSE_NORMAL,
DEFAULT_HEADERS,
} from './lib/constants'
import Timer from './lib/timer'
import RealtimeSubscription from './RealtimeSubscription'
import { w3cwebsocket as WebSocket } from 'websocket'
import Serializer from './lib/serializer'
export type Options = {
transport?: WebSocket
timeout?: number
heartbeatIntervalMs?: number
longpollerTimeout?: number
logger?: Function
encode?: Function
decode?: Function
reconnectAfterMs?: Function
headers?: { [key: string]: string }
params?: { [key: string]: string }
}
type Message = {
topic: string
event: string
payload: any
ref: string
}
const noop = () => {}
export default class RealtimeClient {
channels: RealtimeSubscription[] = []
endPoint: string = ''
headers?: { [key: string]: string } = DEFAULT_HEADERS
params?: { [key: string]: string } = {}
timeout: number = DEFAULT_TIMEOUT
transport: any = WebSocket
heartbeatIntervalMs: number = 30000
longpollerTimeout: number = 20000
heartbeatTimer: ReturnType<typeof setInterval> | undefined = undefined
pendingHeartbeatRef: string | null = null
ref: number = 0
reconnectTimer: Timer
logger: Function = noop
encode: Function
decode: Function
reconnectAfterMs: Function
conn: WebSocket | null = null
sendBuffer: Function[] = []
serializer: Serializer = new Serializer()
stateChangeCallbacks: {
open: Function[]
close: Function[]
error: Function[]
message: Function[]
} = {
open: [],
close: [],
error: [],
message: [],
}
/**
* Initializes the Socket
*
* @param endPoint The string WebSocket endpoint, ie, "ws://example.com/socket", "wss://example.com", "/socket" (inherited host & protocol)
* @param options.transport The Websocket Transport, for example WebSocket.
* @param options.timeout The default timeout in milliseconds to trigger push timeouts.
* @param options.params The optional params to pass when connecting.
* @param options.headers The optional headers to pass when connecting.
* @param options.heartbeatIntervalMs The millisec interval to send a heartbeat message.
* @param options.logger The optional function for specialized logging, ie: logger: (kind, msg, data) => { console.log(`${kind}: ${msg}`, data) }
* @param options.encode The function to encode outgoing messages. Defaults to JSON: (payload, callback) => callback(JSON.stringify(payload))
* @param options.decode The function to decode incoming messages. Defaults to Serializer's decode.
* @param options.longpollerTimeout The maximum timeout of a long poll AJAX request. Defaults to 20s (double the server long poll timer).
* @param options.reconnectAfterMs he optional function that returns the millsec reconnect interval. Defaults to stepped backoff off.
*/
constructor(endPoint: string, options?: Options) {
this.endPoint = `${endPoint}/${TRANSPORTS.websocket}`
if (options?.params) this.params = options.params
if (options?.headers) this.headers = { ...this.headers, ...options.headers }
if (options?.timeout) this.timeout = options.timeout
if (options?.logger) this.logger = options.logger
if (options?.transport) this.transport = options.transport
if (options?.heartbeatIntervalMs)
this.heartbeatIntervalMs = options.heartbeatIntervalMs
if (options?.longpollerTimeout)
this.longpollerTimeout = options.longpollerTimeout
this.reconnectAfterMs = options?.reconnectAfterMs
? options.reconnectAfterMs
: (tries: number) => {
return [1000, 2000, 5000, 10000][tries - 1] || 10000
}
this.encode = options?.encode
? options.encode
: (payload: JSON, callback: Function) => {
return callback(JSON.stringify(payload))
}
this.decode = options?.decode
? options.decode
: this.serializer.decode.bind(this.serializer)
this.reconnectTimer = new Timer(async () => {
await this.disconnect()
this.connect()
}, this.reconnectAfterMs)
}
/**
* Connects the socket.
*/
connect() {
if (this.conn) {
return
}
this.conn = new this.transport(this.endPointURL(), [], null, this.headers)
if (this.conn) {
// this.conn.timeout = this.longpollerTimeout // TYPE ERROR
this.conn.binaryType = 'arraybuffer'
this.conn.onopen = () => this._onConnOpen()
this.conn.onerror = (error) => this._onConnError(error)
this.conn.onmessage = (event) => this.onConnMessage(event)
this.conn.onclose = (event) => this._onConnClose(event)
}
}
/**
* Disconnects the socket.
*
* @param code A numeric status code to send on disconnect.
* @param reason A custom reason for the disconnect.
*/
disconnect(
code?: number,
reason?: string
): Promise<{ error: Error | null; data: boolean }> {
return new Promise((resolve, _reject) => {
try {
if (this.conn) {
this.conn.onclose = function () {} // noop
if (code) {
this.conn.close(code, reason || '')
} else {
this.conn.close()
}
this.conn = null
// remove open handles
this.heartbeatTimer && clearInterval(this.heartbeatTimer)
this.reconnectTimer.reset()
}
resolve({ error: null, data: true })
} catch (error) {
resolve({ error, data: false })
}
})
}
/**
* Logs the message. Override `this.logger` for specialized logging.
*/
log(kind: string, msg: string, data?: any) {
this.logger(kind, msg, data)
}
/**
* Registers a callback for connection state change event.
* @param callback A function to be called when the event occurs.
*
* @example
* socket.onOpen(() => console.log("Socket opened."))
*/
onOpen(callback: Function) {
this.stateChangeCallbacks.open.push(callback)
}
/**
* Registers a callbacks for connection state change events.
* @param callback A function to be called when the event occurs.
*
* @example
* socket.onOpen(() => console.log("Socket closed."))
*/
onClose(callback: Function) {
this.stateChangeCallbacks.close.push(callback)
}
/**
* Registers a callback for connection state change events.
* @param callback A function to be called when the event occurs.
*
* @example
* socket.onOpen((error) => console.log("An error occurred"))
*/
onError(callback: Function) {
this.stateChangeCallbacks.error.push(callback)
}
/**
* Calls a function any time a message is received.
* @param callback A function to be called when the event occurs.
*
* @example
* socket.onMessage((message) => console.log(message))
*/
onMessage(callback: Function) {
this.stateChangeCallbacks.message.push(callback)
}
/**
* Returns the current state of the socket.
*/
connectionState() {
switch (this.conn && this.conn.readyState) {
case SOCKET_STATES.connecting:
return 'connecting'
case SOCKET_STATES.open:
return 'open'
case SOCKET_STATES.closing:
return 'closing'
default:
return 'closed'
}
}
/**
* Retuns `true` is the connection is open.
*/
isConnected() {
return this.connectionState() === 'open'
}
/**
* Removes a subscription from the socket.
*
* @param channel An open subscription.
*/
remove(channel: RealtimeSubscription) {
this.channels = this.channels.filter(
(c: RealtimeSubscription) => c.joinRef() !== channel.joinRef()
)
}
channel(topic: string, chanParams = {}) {
let chan = new RealtimeSubscription(topic, chanParams, this)
this.channels.push(chan)
return chan
}
push(data: Message) {
let { topic, event, payload, ref } = data
let callback = () => {
this.encode(data, (result: any) => {
this.conn?.send(result)
})
}
this.log('push', `${topic} ${event} (${ref})`, payload)
if (this.isConnected()) {
callback()
} else {
this.sendBuffer.push(callback)
}
}
onConnMessage(rawMessage: any) {
this.decode(rawMessage.data, (msg: Message) => {
let { topic, event, payload, ref } = msg
if (ref && ref === this.pendingHeartbeatRef) {
this.pendingHeartbeatRef = null
} else if (event === payload?.type) {
this._resetHeartbeat()
}
this.log(
'receive',
`${payload.status || ''} ${topic} ${event} ${
(ref && '(' + ref + ')') || ''
}`,
payload
)
this.channels
.filter((channel: RealtimeSubscription) => channel.isMember(topic))
.forEach((channel: RealtimeSubscription) =>
channel.trigger(event, payload, ref)
)
this.stateChangeCallbacks.message.forEach((callback) => callback(msg))
})
}
/**
* Returns the URL of the websocket.
*/
endPointURL() {
return this._appendParams(
this.endPoint,
Object.assign({}, this.params, { vsn: VSN })
)
}
/**
* Return the next message ref, accounting for overflows
*/
makeRef() {
let newRef = this.ref + 1
if (newRef === this.ref) {
this.ref = 0
} else {
this.ref = newRef
}
return this.ref.toString()
}
private _onConnOpen() {
this.log('transport', `connected to ${this.endPointURL()}`)
this._flushSendBuffer()
this.reconnectTimer.reset()
this._resetHeartbeat()
this.stateChangeCallbacks.open.forEach((callback) => callback())!
}
private _onConnClose(event: any) {
this.log('transport', 'close', event)
this._triggerChanError()
this.heartbeatTimer && clearInterval(this.heartbeatTimer)
this.reconnectTimer.scheduleTimeout()
this.stateChangeCallbacks.close.forEach((callback) => callback(event))
}
private _onConnError(error: Error) {
this.log('transport', error.message)
this._triggerChanError()
this.stateChangeCallbacks.error.forEach((callback) => callback(error))
}
private _triggerChanError() {
this.channels.forEach((channel: RealtimeSubscription) =>
channel.trigger(CHANNEL_EVENTS.error)
)
}
private _appendParams(url: string, params: { [key: string]: string }) {
if (Object.keys(params).length === 0) {
return url
}
const prefix = url.match(/\?/) ? '&' : '?'
const query = new URLSearchParams(params)
return `${url}${prefix}${query}`
}
private _flushSendBuffer() {
if (this.isConnected() && this.sendBuffer.length > 0) {
this.sendBuffer.forEach((callback) => callback())
this.sendBuffer = []
}
}
private _resetHeartbeat() {
this.pendingHeartbeatRef = null
this.heartbeatTimer && clearInterval(this.heartbeatTimer)
this.heartbeatTimer = setInterval(
() => this._sendHeartbeat(),
this.heartbeatIntervalMs
)
}
private _sendHeartbeat() {
if (!this.isConnected()) {
return
}
if (this.pendingHeartbeatRef) {
this.pendingHeartbeatRef = null
this.log(
'transport',
'heartbeat timeout. Attempting to re-establish connection'
)
this.conn?.close(WS_CLOSE_NORMAL, 'hearbeat timeout')
return
}
this.pendingHeartbeatRef = this.makeRef()
this.push({
topic: 'phoenix',
event: 'heartbeat',
payload: {},
ref: this.pendingHeartbeatRef,
})
}
} | the_stack |
import ListItemBlock, { createListItemBlock } from './ListItemBlock';
import {
splitParentNode,
getNextLeafSibling,
getFirstLeafNode,
getTagOfNode,
collapseNodes,
unwrap,
toArray,
safeInstanceOf,
} from 'roosterjs-editor-dom';
const WORD_ONLINE_IDENTIFYING_SELECTOR =
'div.ListContainerWrapper>ul[class^="BulletListStyle"],div.ListContainerWrapper>ol[class^="NumberListStyle"],span.WACImageContainer > img';
const LIST_CONTAINER_ELEMENT_CLASS_NAME = 'ListContainerWrapper';
const IMAGE_CONTAINER_ELEMENT_CLASS_NAME = 'WACImageContainer';
/**
* @internal
*/
export function isWordOnlineWithList(fragment: DocumentFragment): boolean {
return !!(fragment && fragment.querySelector(WORD_ONLINE_IDENTIFYING_SELECTOR));
}
// Word Online pasted content DOM structure as of July 12th 2019
//<html>
// <body>
// <div class='OutlineGroup'> ----------> this layer may exist depend on the content user paste
// <div class="OutlineElement"> ----------> text content
// <p></p>
// </div>
// <div class="ListItemWrapper"> ----------> list items: for unordered list, all the items on the same level is under the same wrapper
// <ul> list items in the same list can be divided into different ListItemWrapper
// <li></li> list items in the same list can also be divided into different Outline Group;
// <li></li>
// </ul>
// </div>
// </div>
// <div class='OutlineGroup'>
// <div class="ListItemWrapper"> ----------> list items: for ordered list, each items has it's own wrapper
// <ol>
// <li></li>
// </ol>
// </div>
// <div class="ListItemWrapper">
// <ol>
// <li></li>
// </ol>
// </div>
// </div>
// </body>
//</html>
//
/**
* @internal
* Convert text copied from word online into text that's workable with rooster editor
* @param fragment Document fragment that is being pasted into editor.
*/
export default function convertPastedContentFromWordOnline(fragment: DocumentFragment) {
sanitizeListItemContainer(fragment);
const listItemBlocks: ListItemBlock[] = getListItemBlocks(fragment);
listItemBlocks.forEach(itemBlock => {
// There are cases where consecutive List Elements are separated into different nodes:
// <div>
// <div>
// <ol></ol>
// </div>
// <div>
// <ol></ol>
// </div>
// </div>
// <div>
// <div>
// <ol></ol>
// </div>
// </div>
// in the above case we want to collapse the two root level div into one and unwrap the list item nodes.
// after the following flattening the list will become following:
//
// <div>
// <ol></ol>
// </div>
// <div>
// <ol></ol>
// </div>
// <div>
// <ol></ol>
// </div>
// Then we are start processing.
flattenListBlock(fragment, itemBlock);
// Find the node to insertBefore, which is next sibling node of the end of a listItemBlock.
itemBlock.insertPositionNode = itemBlock.endElement.nextSibling;
let convertedListElement: Element;
const doc = fragment.ownerDocument;
itemBlock.listItemContainers.forEach(listItemContainer => {
let listType: 'OL' | 'UL' = getContainerListType(listItemContainer); // list type that is contained by iterator.
// Initialize processed element with proper listType if this is the first element
if (!convertedListElement) {
convertedListElement = doc.createElement(listType);
}
// Get all list items(<li>) in the current iterator element.
const currentListItems = toArray(listItemContainer.querySelectorAll('li'));
currentListItems.forEach(item => {
// If item is in root level and the type of list changes then
// insert the current list into body and then reinitialize the convertedListElement
// Word Online is using data-aria-level to determine the the depth of the list item.
const itemLevel = parseInt(item.getAttribute('data-aria-level'));
// In first level list, there are cases where a consecutive list item DIV may have different list type
// When that happens we need to insert the processed elements into the document, then change the list type
// and keep the processing going.
if (getTagOfNode(convertedListElement) != listType && itemLevel == 1) {
insertConvertedListToDoc(convertedListElement, fragment, itemBlock);
convertedListElement = doc.createElement(listType);
}
insertListItem(convertedListElement, item, listType, doc);
});
});
insertConvertedListToDoc(convertedListElement, fragment, itemBlock);
// Once we finish the process the list items and put them into a list.
// After inserting the processed element,
// we need to remove all the non processed node from the parent node.
const parentContainer = itemBlock.startElement.parentNode;
if (parentContainer) {
itemBlock.listItemContainers.forEach(listItemContainer => {
parentContainer.removeChild(listItemContainer);
});
}
});
const imageNodes = getImageNodes(fragment);
imageNodes.forEach(node => {
// Structure when pasting Word Wac Image as of 10/22/2021
// <span class='WACImageContainer'>
// <img class="WACImage" >
// <span style="display:block">
// </span>
// </span>
//
// Since the second span inside of WACImageContainer have style display block it displays an additional space at the bottom of the image.
// Removing the nodes that are not img will resolve the additional space
if (safeInstanceOf(node, 'HTMLSpanElement')) {
node.childNodes.forEach(childNode => {
if (getTagOfNode(childNode) != 'IMG') {
childNode.parentElement.removeChild(childNode);
}
});
}
});
}
/**
* The node processing is based on the premise of only ol/ul is in ListContainerWrapper class
* However the html might be malformed, this function is to split all the other elements out of ListContainerWrapper
* @param fragment pasted document that contains all the list element.
*/
function sanitizeListItemContainer(fragment: DocumentFragment) {
const listItemContainerListEl = toArray(
fragment.querySelectorAll(WORD_ONLINE_IDENTIFYING_SELECTOR)
);
listItemContainerListEl.forEach(el => {
const replaceRegex = new RegExp(`\\b${LIST_CONTAINER_ELEMENT_CLASS_NAME}\\b`, 'g');
if (el.previousSibling) {
const prevParent = splitParentNode(el, true) as HTMLElement;
prevParent.className = prevParent.className.replace(replaceRegex, '');
}
if (el.nextSibling) {
const nextParent = splitParentNode(el, false) as HTMLElement;
nextParent.className = nextParent.className.replace(replaceRegex, '');
}
});
}
/**
* Take all the list items in the document, and group the consecutive list times in a list block;
* @param fragment pasted document that contains all the list element.
*/
function getListItemBlocks(fragment: DocumentFragment): ListItemBlock[] {
const listElements = fragment.querySelectorAll('.' + LIST_CONTAINER_ELEMENT_CLASS_NAME);
const result: ListItemBlock[] = [];
let curListItemBlock: ListItemBlock;
for (let i = 0; i < listElements.length; i++) {
let curItem = listElements[i];
if (!curListItemBlock) {
curListItemBlock = createListItemBlock(curItem);
} else {
const { listItemContainers } = curListItemBlock;
const lastItemInCurBlock = listItemContainers[listItemContainers.length - 1];
if (
curItem == lastItemInCurBlock.nextSibling ||
getFirstLeafNode(curItem) ==
getNextLeafSibling(lastItemInCurBlock.parentNode, lastItemInCurBlock)
) {
listItemContainers.push(curItem);
curListItemBlock.endElement = curItem;
} else {
curListItemBlock.endElement = lastItemInCurBlock;
result.push(curListItemBlock);
curListItemBlock = createListItemBlock(curItem);
}
}
}
if (curListItemBlock?.listItemContainers.length > 0) {
result.push(curListItemBlock);
}
return result;
}
/**
* Flatten the list items, so that all the consecutive list items are under the same parent.
* @param fragment Root element of that contains the element.
* @param listItemBlock The list item block needed to be flattened.
*/
function flattenListBlock(fragment: DocumentFragment, listItemBlock: ListItemBlock) {
const collapsedListItemSections = collapseNodes(
fragment,
listItemBlock.startElement,
listItemBlock.endElement,
true
);
collapsedListItemSections.forEach(section => {
if (getTagOfNode(section.firstChild) == 'DIV') {
unwrap(section);
}
});
}
/**
* Get the list type that the container contains. If there is no list in the container
* return null;
* @param listItemContainer Container that contains a list
*/
function getContainerListType(listItemContainer: Element): 'OL' | 'UL' | null {
const tag = getTagOfNode(listItemContainer.firstChild);
return tag == 'UL' || tag == 'OL' ? tag : null;
}
/**
* Insert list item into the correct position of a list
* @param listRootElement Root element of the list that is accepting a coming element.
* @param itemToInsert List item that needed to be inserted.
* @param listType Type of list(ul/ol)
*/
function insertListItem(
listRootElement: Element,
itemToInsert: HTMLElement,
listType: string,
doc: HTMLDocument
): void {
if (!listType) {
return;
}
// Get item level from 'data-aria-level' attribute
let itemLevel = parseInt(itemToInsert.getAttribute('data-aria-level'));
let curListLevel = listRootElement; // Level iterator to find the correct place for the current element.
// if the itemLevel is 1 it means the level iterator is at the correct place.
while (itemLevel > 1) {
if (!curListLevel.firstChild) {
// If the current level is empty, create empty list within the current level
// then move the level iterator into the next level.
curListLevel.appendChild(doc.createElement(listType));
curListLevel = curListLevel.firstElementChild;
} else {
// If the current level is not empty, the last item in the needs to be a UL or OL
// and the level iterator should move to the UL/OL at the last position.
let lastChild = curListLevel.lastElementChild;
let lastChildTag = getTagOfNode(lastChild);
if (lastChildTag == 'UL' || lastChildTag == 'OL') {
// If the last child is a list(UL/OL), then move the level iterator to last child.
curListLevel = lastChild;
} else {
// If the last child is not a list, then append a new list to the level
// and move the level iterator to the new level.
curListLevel.appendChild(doc.createElement(listType));
curListLevel = curListLevel.lastElementChild;
}
}
itemLevel--;
}
// Once the level iterator is at the right place, then append the list item in the level.
curListLevel.appendChild(itemToInsert);
}
/**
* Insert the converted list item into the correct place.
* @param convertedListElement List element that is converted from list item block
* @param fragment Root element of that contains the converted listItemBlock
* @param listItemBlock List item block that was converted.
*/
function insertConvertedListToDoc(
convertedListElement: Element,
fragment: DocumentFragment,
listItemBlock: ListItemBlock
) {
if (!convertedListElement) {
return;
}
const { insertPositionNode } = listItemBlock;
if (insertPositionNode) {
const parentNode = insertPositionNode.parentNode;
if (parentNode) {
parentNode.insertBefore(convertedListElement, insertPositionNode);
}
} else {
const parentNode = listItemBlock.startElement.parentNode;
if (parentNode) {
parentNode.appendChild(convertedListElement);
} else {
fragment.appendChild(convertedListElement);
}
}
}
function getImageNodes(fragment: DocumentFragment) {
return fragment.querySelectorAll('.' + IMAGE_CONTAINER_ELEMENT_CLASS_NAME);
} | the_stack |
* @module RealityData
*/
import { URL } from "url";
import { Angle } from "@itwin/core-geometry";
import { IModelConnection, SpatialModelState } from "@itwin/core-frontend";
import { CartographicRange, ContextRealityModelProps, OrbitGtBlobProps } from "@itwin/core-common";
import { AccessToken, Guid, GuidString } from "@itwin/core-bentley";
import { getArrayBuffer, getJson, RequestQueryOptions } from "@bentley/itwin-client";
import { ECJsonTypeMap, WsgInstance } from "./wsg/ECJsonTypeMap";
import { WsgClient } from "./wsg/WsgClient";
/** Currently supported ProjectWise ContextShare reality data types
* @internal
*/
export enum DefaultSupportedTypes {
RealityMesh3dTiles = "RealityMesh3DTiles", // Web Ready 3D Scalable Mesh
OPC = "OPC", // Web Ready Orbit Point Cloud
Terrain3dTiles = "Terrain3DTiles", // Web Ready Terrain Scalable Mesh
OMR = "OMR", // Orbit Mapping Resource
Cesium3dTiles = "Cesium3DTiles" // Cesium 3D Tiles
}
/** RealityData
* This class implements a Reality Data stored in ProjectWise Context Share (Reality Data Service)
* Data is accessed directly through methods of the reality data instance.
* Access to the data required a properly entitled token though the access to the blob is controlled through
* an Azure blob URL, the token may be required to obtain this Azure blob URL or refresh it.
* The Azure blob URL is considered valid for an hour and is refreshed after 50 minutes.
* In addition to the reality data properties, and Azure blob URL and internal states, a reality data also contains
* the identification of the iTwin to be used for access permissions and
* may contain a RealityDataClient to obtain the WSG client specialization to communicate with ProjectWise Context Share (to obtain the Azure blob URL).
* @internal
*/
@ECJsonTypeMap.classToJson("wsg", "S3MX.RealityData", { schemaPropertyName: "schemaName", classPropertyName: "className" })
export class RealityData extends WsgInstance {
@ECJsonTypeMap.propertyToJson("wsg", "properties.Id")
public id?: string;
@ECJsonTypeMap.propertyToJson("wsg", "properties.OrganizationId")
public organizationId?: string;
@ECJsonTypeMap.propertyToJson("wsg", "properties.UltimateId")
public ultimateId?: string;
@ECJsonTypeMap.propertyToJson("wsg", "properties.UltimateSite")
public ultimateSite?: string;
/** This is typically the iModelId */
@ECJsonTypeMap.propertyToJson("wsg", "properties.ContainerName")
public containerName?: string;
@ECJsonTypeMap.propertyToJson("wsg", "properties.DataLocationGuid")
public dataLocationGuid?: string;
@ECJsonTypeMap.propertyToJson("wsg", "properties.Name")
public name?: string;
@ECJsonTypeMap.propertyToJson("wsg", "properties.Dataset")
public dataSet?: string;
@ECJsonTypeMap.propertyToJson("wsg", "properties.Group")
public group?: string;
@ECJsonTypeMap.propertyToJson("wsg", "properties.Description")
public description?: string;
@ECJsonTypeMap.propertyToJson("wsg", "properties.RootDocument")
public rootDocument?: string;
@ECJsonTypeMap.propertyToJson("wsg", "properties.Size")
public size?: string;
@ECJsonTypeMap.propertyToJson("wsg", "properties.SizeUpToDate")
public sizeUpToDate?: boolean;
@ECJsonTypeMap.propertyToJson("wsg", "properties.Classification")
public classification?: string;
@ECJsonTypeMap.propertyToJson("wsg", "properties.Streamed")
public streamed?: boolean;
@ECJsonTypeMap.propertyToJson("wsg", "properties.Type")
public type?: string;
@ECJsonTypeMap.propertyToJson("wsg", "properties.ReferenceElevation")
public referenceElevation?: number;
@ECJsonTypeMap.propertyToJson("wsg", "properties.Footprint")
public footprint?: string;
@ECJsonTypeMap.propertyToJson("wsg", "properties.ApproximateFootprint")
public approximateFootprint?: boolean;
@ECJsonTypeMap.propertyToJson("wsg", "properties.ThumbnailDocument")
public thumbnailDocument?: string;
@ECJsonTypeMap.propertyToJson("wsg", "properties.MetadataUrl")
public metadataUrl?: string;
@ECJsonTypeMap.propertyToJson("wsg", "properties.Copyright")
public copyright?: string;
@ECJsonTypeMap.propertyToJson("wsg", "properties.TermsOfUse")
public termsOfUse?: string;
@ECJsonTypeMap.propertyToJson("wsg", "properties.AccuracyInMeters")
public accuracyInMeters?: string;
@ECJsonTypeMap.propertyToJson("wsg", "properties.ResolutionInMeters")
public resolutionInMeters?: string;
@ECJsonTypeMap.propertyToJson("wsg", "properties.DataAcquisitionDate")
public dataAcquisitionDate?: string;
@ECJsonTypeMap.propertyToJson("wsg", "properties.DataAcquisitionStartDate")
public dataAcquisitionStartDate?: string;
@ECJsonTypeMap.propertyToJson("wsg", "properties.DataAcquisitionEndDate")
public dataAcquisitionEndDate?: string;
@ECJsonTypeMap.propertyToJson("wsg", "properties.DataAcquirer")
public dataAcquirer?: string;
@ECJsonTypeMap.propertyToJson("wsg", "properties.Visibility")
public visibility?: string;
@ECJsonTypeMap.propertyToJson("wsg", "properties.Listable")
public listable?: boolean;
@ECJsonTypeMap.propertyToJson("wsg", "properties.ModifiedTimestamp")
public modifiedTimestamp?: string;
@ECJsonTypeMap.propertyToJson("wsg", "properties.LastAccessedTimestamp")
public lastAccessedTimestamp?: string;
@ECJsonTypeMap.propertyToJson("wsg", "properties.CreatedTimestamp")
public createdTimestamp?: string;
@ECJsonTypeMap.propertyToJson("wsg", "properties.OwnedBy")
public ownedBy?: string;
@ECJsonTypeMap.propertyToJson("wsg", "properties.OwnerId")
public ownerId?: string;
@ECJsonTypeMap.propertyToJson("wsg", "properties.CreatorId")
public creatorId?: string;
@ECJsonTypeMap.propertyToJson("wsg", "properties.Version")
public version?: string;
// Delegate permission is read-only and irrelevant for use so it is omitted.
@ECJsonTypeMap.propertyToJson("wsg", "properties.Hidden")
public hidden?: boolean;
// Cache parameters for reality data access. Contains the blob url, the timestamp to refresh (every 50 minutes) the url and the root document path.
private _blobUrl: any;
private _blobTimeStamp?: Date;
private _blobRooDocumentPath: undefined | string; // Path relative to blob root of root document. It is slash terminated if not empty
// Link to client to fetch the blob url
public client: undefined | RealityDataAccessClient;
// The GUID of the iTwin used when using the client or "Server" to indicate access is performed out of context (for accessing PUBLIC or ENTERPRISE data).
// If undefined when accessing reality data tiles then it will automatically be set to "Server"
public iTwinId: undefined | string;
/**
* Gets string url to fetch blob data from. Access is read-only.
* @param name name or path of tile
* @param nameRelativeToRootDocumentPath (optional default is false) Indicates if the given name is relative to the root document path.
* @returns string url for blob data
*/
public async getBlobStringUrl(accessToken: AccessToken, name: string, nameRelativeToRootDocumentPath: boolean = false): Promise<string> {
const url = await this.getBlobUrl(accessToken);
let host: string = "";
if (nameRelativeToRootDocumentPath && this._blobRooDocumentPath && this._blobRooDocumentPath !== "")
host = `${url.origin + url.pathname}/${this._blobRooDocumentPath}`; // _blobRootDocumentPath is always '/' terminated if not empty
else
host = `${url.origin + url.pathname}/`;
const query = url.search;
return `${host}${name}${query}`;
}
/**
* Gets a tile access url URL object
* @param writeAccess Optional boolean indicating if write access is requested. Default is false for read-only access.
* @returns app URL object for blob url
*/
public async getBlobUrl(accessToken: AccessToken, writeAccess: boolean = false): Promise<URL> {
// Normally the client is set when the reality data is extracted for the client but it could be undefined
// if the reality data instance is created manually.
if (!this.client)
this.client = new RealityDataAccessClient();
if (!this.iTwinId)
this.iTwinId = "Server";
if (!this.id)
throw new Error("id not set");
const blobUrlRequiresRefresh = !this._blobTimeStamp || (Date.now() - this._blobTimeStamp.getTime()) > 3000000; // 3 million milliseconds or 50 minutes
if (undefined === this._blobUrl || blobUrlRequiresRefresh) {
const fileAccess: FileAccessKey[] = await this.client.getFileAccessKey(accessToken, this.iTwinId, this.id, writeAccess);
if (fileAccess.length !== 1)
throw new Error(`Could not obtain blob file access key for reality data: ${this.id}`);
const urlString = fileAccess[0].url!;
this._blobUrl = (typeof window !== "undefined") ? new window.URL(urlString) : new URL(urlString);
this._blobTimeStamp = new Date(Date.now());
if (!this._blobRooDocumentPath && this.rootDocument) {
const urlParts = this.rootDocument.split("/");
urlParts.pop();
if (urlParts.length === 0)
this._blobRooDocumentPath = "";
else
this._blobRooDocumentPath = `${urlParts.join("/")}/`;
}
}
return this._blobUrl;
}
/**
* Gets a tileset's app data json
* @param name name or path of tile
* @param nameRelativeToRootDocumentPath (optional default is false) Indicates if the given name is relative to the root document path.
* @returns app data json object
*/
public async getTileJson(accessToken: AccessToken, name: string, nameRelativeToRootDocumentPath: boolean = false): Promise<any> {
const stringUrl = await this.getBlobStringUrl(accessToken, name, nameRelativeToRootDocumentPath);
const data = await getJson(stringUrl);
return data;
}
/**
* Gets tile content
* @param name name or path of tile
* @param nameRelativeToRootDocumentPath (optional default is false) Indicates if the given name is relative to the root document path.
* @returns array buffer of tile content
*/
public async getTileContent(accessToken: AccessToken, name: string, nameRelativeToRootDocumentPath: boolean = false): Promise<any> {
const stringUrl = await this.getBlobStringUrl(accessToken, name, nameRelativeToRootDocumentPath);
const data = await getArrayBuffer(stringUrl);
return data;
}
/**
* Gets a reality data root document json
* @returns tile data json
*/
public async getRootDocumentJson(accessToken: AccessToken): Promise<any> {
if (!this.rootDocument)
throw new Error(`Root document not defined for reality data: ${this.id}`);
const root = this.rootDocument;
const rootJson = await this.getTileJson(accessToken, root, false);
return rootJson;
}
}
/** File Access Key
* This class is used by the RealityDataServicesClient to extract an Azure blob URL
* @internal
*/
@ECJsonTypeMap.classToJson("wsg", "FileAccess.FileAccessKey", { schemaPropertyName: "schemaName", classPropertyName: "className" })
export class FileAccessKey extends WsgInstance {
@ECJsonTypeMap.propertyToJson("wsg", "properties.Url")
public url?: string;
@ECJsonTypeMap.propertyToJson("wsg", "properties.Type")
public type?: string;
@ECJsonTypeMap.propertyToJson("wsg", "properties.Permissions")
public permissions?: string;
@ECJsonTypeMap.propertyToJson("wsg", "properties.RequiresConfirmation")
public requiresConfirmation?: string;
}
/** RealityDataRelationship
* This class is used to represent relationships with a Reality Data and iTwin
* @internal
*/
@ECJsonTypeMap.classToJson("wsg", "S3MX.RealityDataRelationship", { schemaPropertyName: "schemaName", classPropertyName: "className" })
export class RealityDataRelationship extends WsgInstance {
// @ECJsonTypeMap.propertyToJson("wsg", "instanceId")
// public id?: string;
@ECJsonTypeMap.propertyToJson("wsg", "properties.RealityDataId")
public realityDataId?: string;
@ECJsonTypeMap.propertyToJson("wsg", "properties.RelationType")
public relationType?: string;
@ECJsonTypeMap.propertyToJson("wsg", "properties.RelatedId")
public relatedId?: string;
@ECJsonTypeMap.propertyToJson("wsg", "properties.ModifiedTimestamp")
public modifiedTimestamp?: string;
@ECJsonTypeMap.propertyToJson("wsg", "properties.CreatedTimestamp")
public createdTimestamp?: string;
}
/** Query options for RealityDataServiceRequest
* @Internal
*/
export interface RealityDataRequestQueryOptions extends RequestQueryOptions {
/** Set to limit result to a single iTwin */
iTwin?: string;
/** Set a polygon string to query for overlap */
polygon?: string;
/** Set an action for the Query. Either ALL, USE or ASSIGN */
action?: string;
}
/** Criteria used to query for reality data associated with an iTwin context.
* @see [[queryRealityData]].
* @public
*/
export interface RealityDataQueryCriteria {
/** The Id of the iTwin context. */
iTwinId: GuidString;
/** If supplied, only reality data overlapping this range will be included. */
range?: CartographicRange;
/** If supplied, reality data already referenced by a [[GeometricModelState]] within this iModel will be excluded. */
filterIModel?: IModelConnection;
}
/** DataLocation
* This class is used to represent a data location
* @internal
*/
@ECJsonTypeMap.classToJson("wsg", "S3MX.DataLocation", { schemaPropertyName: "schemaName", classPropertyName: "className" })
export class DataLocation extends WsgInstance {
@ECJsonTypeMap.propertyToJson("wsg", "instanceId")
public id?: string;
@ECJsonTypeMap.propertyToJson("wsg", "properties.Provider")
public provider?: string;
@ECJsonTypeMap.propertyToJson("wsg", "properties.Location")
public location?: string;
}
/**
* Client wrapper to Reality Data Service.
* An instance of this class is used to extract reality data from the ProjectWise Context Share (Reality Data Service)
* Most important methods enable to obtain a specific reality data, fetch all reality data associated with an iTwin and
* all reality data of an iTwin within a provided spatial extent.
* This class also implements extraction of the Azure blob address.
* @internal
*/
export class RealityDataAccessClient extends WsgClient {
/**
* Creates an instance of RealityDataServicesClient.
*/
public constructor() {
super("v1");
this.baseUrl = "https://api.bentley.com/contextshare";
}
/**
* This method returns the URL to obtain the Reality Data details from PW Context Share.
* Technically it should never be required as the RealityData object returned should have all the information to obtain the
* data.
* @param iTwinId id of associated iTwin
* @param tilesId realityDataInstance id, called tilesId when returned from tile generator job
* @returns string containing the URL to reality data for indicated tile.
*/
public async getRealityDataUrl(iTwinId: string | undefined, tilesId: string): Promise<string> {
const serverUrl: string = await this.getUrl();
if (!iTwinId || iTwinId === "")
iTwinId = "Server";
return `${serverUrl}/Repositories/S3MXECPlugin--${iTwinId}/S3MX/RealityData/${tilesId}`;
}
/**
* Gets reality data with all of its properties
* @param iTwinId id of associated iTwin
* @param tilesId realityDataInstance id, called tilesId when returned from tile generator job
* @returns The requested reality data.
*/
public async getRealityData(accessToken: AccessToken, iTwinId: string | undefined, tilesId: string): Promise<RealityData> {
if (!iTwinId || iTwinId === "")
iTwinId = "Server";
const realityDatas: RealityData[] = await this.getInstances<RealityData>(accessToken, RealityData, `/Repositories/S3MXECPlugin--${iTwinId}/S3MX/RealityData/${tilesId}`);
if (realityDatas.length !== 1)
throw new Error(`Could not fetch reality data: ${tilesId}`);
realityDatas[0].client = this;
realityDatas[0].iTwinId = iTwinId;
return realityDatas[0];
}
/** Return the filter string used to query all supported Reality Data types or only the input type if defined
* @param type reality data type to query or all supported type if undefined
* @returns the filter string to use
* @internal
*/
private getRealityDataTypesFilter(type?: string): string {
let filter: string = "";
if (!type) {
// If type not specified, add all supported known types
let isFirst = true;
for (const supportedType of Object.values(DefaultSupportedTypes)) {
if (isFirst)
isFirst = false;
else
filter += `+or+`;
filter += `Type+eq+'${supportedType}'`;
}
} else {
filter = `Type+eq+'${type}'`;
}
return filter;
}
/**
* Gets all reality data associated with the iTwin. Consider using getRealityDataInITwinOverlapping() if spatial extent is known.
* @param iTwinId id of associated iTwin
* @param type reality data type to query or all supported type if undefined
* @returns an array of RealityData that are associated to the iTwin.
*/
public async getRealityDataInITwin(accessToken: AccessToken, iTwinId: string, type?: string): Promise<RealityData[]> {
const newQueryOptions = { iTwin: iTwinId } as RequestQueryOptions;
newQueryOptions.$filter = this.getRealityDataTypesFilter(type);
const realityDatas: RealityData[] = await this.getRealityDatas(accessToken, iTwinId, newQueryOptions);
return realityDatas;
}
/**
* Gets all reality data that has a footprint defined that overlaps the given area and that are associated with the iTwin. Reality Data returned must be accessible by user
* as public, enterprise data, private or accessible through context RBAC rights attributed to user.
* @param iTwinId id of associated iTwin
* @param minLongDeg The minimum longitude in degrees of a 2d range to search.
* @param maxLongDeg The maximum longitude in degrees of a 2d range to search.
* @param minLatDeg The minimum latitude in degrees of a 2d range to search.
* @param maxLatDeg The maximum longitude in degrees of a 2d range to search.
* @returns an array of RealityData
*/
public async getRealityDataInITwinOverlapping(accessToken: AccessToken, iTwinId: string, minLongDeg: number, maxLongDeg: number, minLatDeg: number, maxLatDeg: number, type?: string): Promise<RealityData[]> {
const polygonString = `{\"points\":[[${minLongDeg},${minLatDeg}],[${maxLongDeg},${minLatDeg}],[${maxLongDeg},${maxLatDeg}],[${minLongDeg},${maxLatDeg}],[${minLongDeg},${minLatDeg}]], \"coordinate_system\":\"4326\"}`;
const newQueryOptions = { iTwin: iTwinId, polygon: polygonString } as RequestQueryOptions;
newQueryOptions.$filter = this.getRealityDataTypesFilter(type);
return this.getRealityDatas(accessToken, iTwinId, newQueryOptions);
}
/** Query for reality data associated with an iTwin.
* @param criteria Criteria by which to query.
* @returns Properties of reality data associated with the context, filtered according to the criteria.
* @public
*/
public async queryRealityData(accessToken: AccessToken, criteria: RealityDataQueryCriteria): Promise<ContextRealityModelProps[]> {
const iTwinId = criteria.iTwinId;
const availableRealityModels: ContextRealityModelProps[] = [];
if (!accessToken)
return availableRealityModels;
const client = new RealityDataAccessClient();
let realityData: RealityData[];
if (criteria.range) {
const iModelRange = criteria.range.getLongitudeLatitudeBoundingBox();
realityData = await client.getRealityDataInITwinOverlapping(accessToken, iTwinId, Angle.radiansToDegrees(iModelRange.low.x),
Angle.radiansToDegrees(iModelRange.high.x),
Angle.radiansToDegrees(iModelRange.low.y),
Angle.radiansToDegrees(iModelRange.high.y));
} else {
realityData = await client.getRealityDataInITwin(accessToken, iTwinId);
}
// Get set of URLs that are directly attached to the model.
const modelRealityDataIds = new Set<string>();
if (criteria.filterIModel) {
const query = { from: SpatialModelState.classFullName, wantPrivate: false };
const props = await criteria.filterIModel.models.queryProps(query);
for (const prop of props)
if (prop.jsonProperties !== undefined && prop.jsonProperties.tilesetUrl) {
const realityDataId = client.getRealityDataIdFromUrl(prop.jsonProperties.tilesetUrl);
if (realityDataId)
modelRealityDataIds.add(realityDataId);
}
}
// We obtain the reality data name, and RDS URL for each RD returned.
for (const currentRealityData of realityData) {
let realityDataName: string = "";
let validRd: boolean = true;
if (currentRealityData.name && currentRealityData.name !== "") {
realityDataName = currentRealityData.name;
} else if (currentRealityData.rootDocument) {
// In case root document contains a relative path we only keep the filename
const rootDocParts = (currentRealityData.rootDocument).split("/");
realityDataName = rootDocParts[rootDocParts.length - 1];
} else {
// This case would not occur normally but if it does the RD is considered invalid
validRd = false;
}
// If the RealityData is valid then we add it to the list.
if (currentRealityData.id && validRd === true) {
const url = await client.getRealityDataUrl(iTwinId, currentRealityData.id);
let opcConfig: OrbitGtBlobProps | undefined;
if (currentRealityData.type && (currentRealityData.type.toUpperCase() === "OPC") && currentRealityData.rootDocument !== undefined) {
const rootDocUrl: string = await currentRealityData.getBlobStringUrl(accessToken, currentRealityData.rootDocument);
opcConfig = {
rdsUrl: "",
containerName: "",
blobFileName: rootDocUrl,
accountName: "",
sasToken: "",
};
}
if (!modelRealityDataIds.has(currentRealityData.id))
availableRealityModels.push({
tilesetUrl: url, name: realityDataName, description: (currentRealityData.description ? currentRealityData.description : ""),
realityDataId: currentRealityData.id, orbitGtBlob: opcConfig,
});
}
}
return availableRealityModels;
}
/**
* Gets reality datas with all of its properties
* @param iTwinId id of associated iTwin.
* @param queryOptions RealityDataServicesRequestQueryOptions of the request.
* @returns The requested reality data.
*/
public async getRealityDatas(accessToken: AccessToken, iTwinId: string | undefined, queryOptions: RealityDataRequestQueryOptions): Promise<RealityData[]> {
if (!iTwinId || iTwinId === "")
iTwinId = "Server";
const realityDatas: RealityData[] = await this.getInstances<RealityData>(accessToken, RealityData, `/Repositories/S3MXECPlugin--${iTwinId}/S3MX/RealityData`, queryOptions);
realityDatas.forEach((realityData) => { realityData.client = this; realityData.iTwinId = iTwinId; });
return realityDatas;
}
/**
* Creates a reality data with given properties
* @param iTwinId id of associated iTwin
* @param realityData The reality data to create. The Id of the reality data is usually left empty indicating for the service to assign
* one. If set then the reality id must not exist on the server.
* realityDataInstance id, called tilesId when returned from tile generator job
* @returns The new reality data with all read-only properties set.
*/
public async createRealityData(accessToken: AccessToken, iTwinId: string | undefined, realityData: RealityData): Promise<RealityData> {
if (!iTwinId || iTwinId === "")
iTwinId = "Server";
const resultRealityData: RealityData = await this.postInstance<RealityData>(accessToken, RealityData, `/Repositories/S3MXECPlugin--${iTwinId}/S3MX/RealityData`, realityData);
if (!resultRealityData)
throw new Error(`Could not create new reality data: ${realityData.id ? realityData.id : realityData.name}`);
resultRealityData.client = this;
resultRealityData.iTwinId = iTwinId;
return resultRealityData;
}
/**
* Updates a reality data with given properties
* @param iTwinId id of associated iTwin
* @param realityData The reality data to update. The Id must contain the identifier of the reality data to update.
* NOTE: As a probable known defect some specific read-only attributes must be undefined prior to passing the reality data.
* These are: organizationId, sizeUpToDate, ownedBy, ownerId
* @returns The newly modified reality data.
*/
public async updateRealityData(accessToken: AccessToken, iTwinId: string | undefined, realityData: RealityData): Promise<RealityData> {
if (!iTwinId || iTwinId === "")
iTwinId = "Server";
const resultRealityData: RealityData = await this.postInstance<RealityData>(accessToken, RealityData, `/Repositories/S3MXECPlugin--${iTwinId}/S3MX/RealityData/${realityData.id}`, realityData);
if (!resultRealityData)
throw new Error(`Could not update reality data: ${realityData.id ? realityData.id : realityData.name}`);
resultRealityData.client = this;
resultRealityData.iTwinId = iTwinId;
return resultRealityData;
}
/**
* Deletes a reality data.
* @param iTwinId id of associated iTwin
* @param realityDataId The identifier of the reality data to delete.
* @returns a void Promise.
*/
public async deleteRealityData(accessToken: AccessToken, iTwinId: string | undefined, realityDataId: string): Promise<void> {
if (!iTwinId || iTwinId === "")
iTwinId = "Server";
return this.deleteInstance<RealityData>(accessToken, `/Repositories/S3MXECPlugin--${iTwinId}/S3MX/RealityData/${realityDataId}`);
}
/**
* Gets all reality data relationships associated to the given reality id, not only the relationship for given iTwin.
* @param iTwinId id of associated iTwin in which to make to call for permission reason
* @param realityDataId realityDataInstance id to obtain the relationships for.
* @returns All relationships associated to reality data. The requested reality data.
*/
public async getRealityDataRelationships(accessToken: AccessToken, iTwinId: string, realityDataId: string): Promise<RealityDataRelationship[]> {
const relationships: RealityDataRelationship[] = await this.getInstances<RealityDataRelationship>(accessToken, RealityDataRelationship, `/Repositories/S3MXECPlugin--${iTwinId}/S3MX/RealityDataRelationship?$filter=RealityDataId+eq+'${realityDataId}'`);
return relationships;
}
/**
* Gets all reality data relationships associated to the given reality id, not only the relationship for given iTwin.
* @param iTwinId id of associated iTwin in which to make to call for permission reason
* @param realityDataId realityDataInstance id to obtain the relationships for.
* @returns All relationships associated to reality data. The requested reality data.
*/
public async createRealityDataRelationship(accessToken: AccessToken, iTwinId: string, relationship: RealityDataRelationship): Promise<RealityDataRelationship> {
const resultRealityDataRelationship: RealityDataRelationship = await this.postInstance<RealityDataRelationship>(accessToken, RealityDataRelationship, `/Repositories/S3MXECPlugin--${iTwinId}/S3MX/RealityDataRelationship`, relationship);
if (!resultRealityDataRelationship)
throw new Error(`Could not create new reality data relationship between reality data: ${relationship.realityDataId ? relationship.realityDataId : ""} and context: ${relationship.relatedId ? relationship.relatedId : ""}`);
return resultRealityDataRelationship;
}
/**
* Gets all reality data relationships associated to the given reality id, not only the relationship for given iTwin.
* @param iTwinId id of associated iTwin in which to make to call for permission reason
* @param realityDataId realityDataInstance id to obtain the relationships for.
* @returns All relationships associated to reality data. The requested reality data.
*/
public async deleteRealityDataRelationship(accessToken: AccessToken, iTwinId: string, relationshipId: string): Promise<void> {
return this.deleteInstance<RealityDataRelationship>(accessToken, `/Repositories/S3MXECPlugin--${iTwinId}/S3MX/RealityDataRelationship/${relationshipId}`);
}
/**
* Gets a tile file access key
* @param iTwinId id of associated iTwin
* @param tilesId realityDataInstance id, called tilesId when returned from tile generator job.
* @param writeAccess Optional boolean indicating if write access is requested. Default is false for read-only access.
* @returns a FileAccessKey object containing the Azure blob address.
*/
public async getFileAccessKey(accessToken: AccessToken, iTwinId: string | undefined, tilesId: string, writeAccess: boolean = false): Promise<FileAccessKey[]> {
const path = encodeURIComponent(tilesId);
if (!iTwinId || iTwinId === "")
iTwinId = "Server";
if (writeAccess)
return this.getInstances<FileAccessKey>(accessToken, FileAccessKey, `/Repositories/S3MXECPlugin--${iTwinId}/S3MX/RealityData/${path}/FileAccess.FileAccessKey?$filter=Permissions+eq+%27Write%27`);
else
return this.getInstances<FileAccessKey>(accessToken, FileAccessKey, `/Repositories/S3MXECPlugin--${iTwinId}/S3MX/RealityData/${path}/FileAccess.FileAccessKey?$filter=Permissions+eq+%27Read%27`);
}
// ###TODO temporary means of extracting the tileId and iTwinId from the given url
// This is the method that determines if the url refers to Reality Data stored on PW Context Share. If not then undefined is returned.
/**
* This is the method that determines if the url refers to Reality Data stored on PW Context Share. If not then undefined is returned.
* @param url A fully formed URL to a reality data or a reality data folder or document of the form:
* https://{Host}/{version}/Repositories/S3MXECPlugin--{ITwinId}/S3MX/RealityData/{RealityDataId}
* https://{Host}/{version}/Repositories/S3MXECPlugin--{ITwinId}/S3MX/Folder/{RealityDataId}~2F{Folder}
* https://{Host}/{version}/Repositories/S3MXECPlugin--{ITwinId}/S3MX/Document/{RealityDataId}~2F{Full Document Path and name}'
* Where {Host} represents the Reality Data Service server (ex: connect-realitydataservices.bentley.com). This value is ignored since the
* actual host server name depends on the environment or can be changed in the future.
* Where {version} is the Bentley Web Service Gateway protocol version. This value is ignored but the version must be supported by Reality Data Service.
* Where {Folder} and {Document} are the full folder or document path relative to the Reality Data root.
* {RealityDataId} is extracted after validation of the URL and returned.
* {ITwinId} is ignored.
* @returns A string containing the Reality Data Identifier (otherwise named tile id). If the URL is not a reality data service URL then undefined is returned.
*/
public getRealityDataIdFromUrl(url: string): string | undefined {
let realityDataId: string | undefined;
const formattedUrl = url.replace(/~2F/g, "/").replace(/\\/g, "/");
const urlParts = formattedUrl.split("/").map((entry: string) => entry.replace(/%2D/g, "-"));
const partOffset: number = ((urlParts[1] === "") ? 4 : 3);
if ((urlParts[partOffset] === "Repositories") && urlParts[partOffset + 1].match("S3MXECPlugin--*") && (urlParts[partOffset + 2] === "S3MX")) {
// URL appears tpo be a correctly formed URL to Reality Data Service ... obtain the first GUID
realityDataId = urlParts.find(Guid.isGuid);
}
return realityDataId;
}
/**
* Gets the list of all data locations supported by PW Context Share.
* @returns The requested data locations list.
*/
public async getDataLocation(accessToken: AccessToken): Promise<DataLocation[]> {
const dataLocation: DataLocation[] = await this.getInstances<DataLocation>(accessToken, DataLocation, `/Repositories/S3MXECPlugin--Server/S3MX/DataLocation`);
return dataLocation;
}
} | the_stack |
import { createApiService, ApplicationsUtil, LoginPage, UserFiltersUtil, UsersActions } from '@alfresco/adf-testing';
import { NavigationBarPage } from '../../core/pages/navigation-bar.page';
import { ProcessServicesPage } from './../pages/process-services.page';
import { TasksPage } from './../pages/tasks.page';
import { TasksListPage } from './../pages/tasks-list.page';
import { TaskDetailsPage } from './../pages/task-details.page';
import { TaskFiltersDemoPage } from './../pages/task-filters-demo.page';
import { UserProcessInstanceFilterRepresentation } from '@alfresco/js-api';
import { browser } from 'protractor';
describe('Task Filters Sorting', () => {
const app = browser.params.resources.Files.APP_WITH_PROCESSES;
const loginPage = new LoginPage();
const navigationBarPage = new NavigationBarPage();
const processServicesPage = new ProcessServicesPage();
const tasksPage = new TasksPage();
const tasksListPage = new TasksListPage();
const taskDetailsPage = new TaskDetailsPage();
const taskFiltersDemoPage = new TaskFiltersDemoPage();
const apiService = createApiService();
const usersActions = new UsersActions(apiService);
const userFiltersUtil = new UserFiltersUtil(apiService);
let user;
let appId;
const tasks = [
{ name: 'Task 1 Completed', dueDate: '01/01/2019' },
{ name: 'Task 2 Completed', dueDate: '02/01/2019' },
{ name: 'Task 3 Completed', dueDate: '03/01/2019' },
{ name: 'Task 4', dueDate: '01/01/2019' },
{ name: 'Task 5', dueDate: '02/01/2019' },
{ name: 'Task 6', dueDate: '03/01/2019' }];
beforeAll(async () => {
await apiService.loginWithProfile('admin');
user = await usersActions.createUser();
await apiService.login(user.username, user.password);
const applicationsService = new ApplicationsUtil(apiService);
const appModel = await applicationsService.importPublishDeployApp(app.file_path);
appId = await applicationsService.getAppDefinitionId(appModel.id);
await loginPage.login(user.username, user.password);
await navigationBarPage.navigateToProcessServicesPage();
await processServicesPage.checkApsContainer();
await processServicesPage.goToApp(app.title);
await tasksPage.createTask({name: tasks[0].name, dueDate: tasks[0].dueDate});
await taskDetailsPage.clickCompleteTask();
await tasksPage.createTask({name: tasks[1].name, dueDate: tasks[1].dueDate});
await taskDetailsPage.clickCompleteTask();
await tasksPage.createTask({name: tasks[2].name, dueDate: tasks[2].dueDate});
await taskDetailsPage.clickCompleteTask();
await tasksPage.createTask({name: tasks[3].name, dueDate: tasks[3].dueDate});
await tasksPage.createTask({name: tasks[4].name, dueDate: tasks[4].dueDate});
await tasksPage.createTask({name: tasks[5].name, dueDate: tasks[5].dueDate});
});
afterAll( async () => {
await apiService.loginWithProfile('admin');
await usersActions.deleteTenant(user.tenantId);
});
it('[C277254] Should display tasks under new filter from newest to oldest when they are completed', async () => {
const newFilter = new UserProcessInstanceFilterRepresentation({
appId,
name : 'Newest first',
icon: 'glyphicon-filter',
filter: { sort: 'created-desc', state: 'completed', assignment: 'involved' }
});
await userFiltersUtil.createUserTaskFilter(newFilter);
await browser.refresh();
await taskFiltersDemoPage.customTaskFilter(newFilter.name).clickTaskFilter();
await expect(await tasksListPage.getDataTable().contentInPosition(1)).toBe(tasks[2].name);
await expect(await tasksListPage.getDataTable().contentInPosition(2)).toBe(tasks[1].name);
await expect(await tasksListPage.getDataTable().contentInPosition(3)).toBe(tasks[0].name);
});
it('[C277255] Should display tasks under new filter from oldest to newest when they are completed', async () => {
const newFilter = new UserProcessInstanceFilterRepresentation({
appId,
name : 'Newest last',
icon: 'glyphicon-filter',
filter: { sort: 'created-asc', state: 'completed', assignment: 'involved' }
});
await userFiltersUtil.createUserTaskFilter(newFilter);
await browser.refresh();
await taskFiltersDemoPage.customTaskFilter(newFilter.name).clickTaskFilter();
await expect(await tasksListPage.getDataTable().contentInPosition(1)).toBe(tasks[0].name);
await expect(await tasksListPage.getDataTable().contentInPosition(2)).toBe(tasks[1].name);
await expect(await tasksListPage.getDataTable().contentInPosition(3)).toBe(tasks[2].name);
});
it('[C277256] Should display tasks under new filter from closest due date to farthest when they are completed', async () => {
const newFilter = new UserProcessInstanceFilterRepresentation({
appId,
name : 'Due first',
icon: 'glyphicon-filter',
filter: { sort: 'due-desc', state: 'completed', assignment: 'involved' }
});
await userFiltersUtil.createUserTaskFilter(newFilter);
await browser.refresh();
await taskFiltersDemoPage.customTaskFilter(newFilter.name).clickTaskFilter();
await expect(await tasksListPage.getDataTable().contentInPosition(1)).toBe(tasks[2].name);
await expect(await tasksListPage.getDataTable().contentInPosition(2)).toBe(tasks[1].name);
await expect(await tasksListPage.getDataTable().contentInPosition(3)).toBe(tasks[0].name);
});
it('[C277257] Should display tasks under new filter from farthest due date to closest when they are completed', async () => {
const newFilter = new UserProcessInstanceFilterRepresentation({
appId,
name : 'Due last',
icon: 'glyphicon-filter',
filter: { sort: 'due-asc', state: 'completed', assignment: 'involved' }
});
await userFiltersUtil.createUserTaskFilter(newFilter);
await browser.refresh();
await taskFiltersDemoPage.customTaskFilter(newFilter.name).clickTaskFilter();
await expect(await tasksListPage.getDataTable().contentInPosition(1)).toBe(tasks[0].name);
await expect(await tasksListPage.getDataTable().contentInPosition(2)).toBe(tasks[1].name);
await expect(await tasksListPage.getDataTable().contentInPosition(3)).toBe(tasks[2].name);
});
it('[C277258] Should display tasks under new filter from newest to oldest when they are open ', async () => {
const newFilter = new UserProcessInstanceFilterRepresentation({
appId,
name : 'Newest first Open',
icon: 'glyphicon-filter',
filter: { sort: 'created-desc', state: 'open', assignment: 'involved' }
});
await userFiltersUtil.createUserTaskFilter(newFilter);
await browser.refresh();
await taskFiltersDemoPage.customTaskFilter(newFilter.name).clickTaskFilter();
await expect(await tasksListPage.getDataTable().contentInPosition(1)).toBe(tasks[5].name);
await expect(await tasksListPage.getDataTable().contentInPosition(2)).toBe(tasks[4].name);
await expect(await tasksListPage.getDataTable().contentInPosition(3)).toBe(tasks[3].name);
});
it('[C277259] Should display tasks under new filter from oldest to newest when they are open', async () => {
const newFilter = new UserProcessInstanceFilterRepresentation({
appId,
name : 'Newest last Open',
icon: 'glyphicon-filter',
filter: { sort: 'created-asc', state: 'open', assignment: 'involved' }
});
await userFiltersUtil.createUserTaskFilter(newFilter);
await browser.refresh();
await taskFiltersDemoPage.customTaskFilter(newFilter.name).clickTaskFilter();
await expect(await tasksListPage.getDataTable().contentInPosition(1)).toBe(tasks[3].name);
await expect(await tasksListPage.getDataTable().contentInPosition(2)).toBe(tasks[4].name);
await expect(await tasksListPage.getDataTable().contentInPosition(3)).toBe(tasks[5].name);
});
it('[C277260] Should display tasks under new filter from closest due date to farthest when they are open', async () => {
const newFilter = new UserProcessInstanceFilterRepresentation({
appId,
name : 'Due first Open',
icon: 'glyphicon-filter',
filter: { sort: 'due-desc', state: 'open', assignment: 'involved' }
});
await userFiltersUtil.createUserTaskFilter(newFilter);
await browser.refresh();
await taskFiltersDemoPage.customTaskFilter(newFilter.name).clickTaskFilter();
await expect(await tasksListPage.getDataTable().contentInPosition(1)).toBe(tasks[5].name);
await expect(await tasksListPage.getDataTable().contentInPosition(2)).toBe(tasks[4].name);
await expect(await tasksListPage.getDataTable().contentInPosition(3)).toBe(tasks[3].name);
});
it('[C277261] Should display tasks under new filter from farthest due date to closest when they are open', async () => {
const newFilter = new UserProcessInstanceFilterRepresentation({
appId,
name : 'Due last Open',
icon: 'glyphicon-filter',
filter: { sort: 'due-asc', state: 'open', assignment: 'involved' }
});
await userFiltersUtil.createUserTaskFilter(newFilter);
await browser.refresh();
await taskFiltersDemoPage.customTaskFilter(newFilter.name).clickTaskFilter();
await expect(await tasksListPage.getDataTable().contentInPosition(1)).toBe(tasks[3].name);
await expect(await tasksListPage.getDataTable().contentInPosition(2)).toBe(tasks[4].name);
await expect(await tasksListPage.getDataTable().contentInPosition(3)).toBe(tasks[5].name);
});
}); | the_stack |
import path from 'path';
import fs from 'fs-extra';
import slash from 'slash';
import { addLast, addDefaults, merge, set as timmSet, omit } from 'timm';
import { mainStory, chalk } from 'storyboard';
import { v4 as uuidv4 } from 'uuid';
import { decode } from 'js-base64';
import debounce from 'lodash/debounce';
import type {
Config,
Key,
Keys,
Translation,
Translations,
TranslationWithoutKeyId,
} from './types';
import { init as initFileWatcher } from './fileWatcher';
import { parseAll, parseOne } from './parseSources';
import compile from './compileTranslations';
import {
init as initAutoTranslations,
translate as autoTranslate,
} from './autoTranslate';
const SRC = 'mady-db';
const JSON_OPTIONS = { spaces: 2 };
const DEBOUNCE_COMPILE = 2000;
const { UNIT_TESTING } = process.env;
const DEFAULT_CONFIG: Config = {
srcPaths: ['src'],
srcExtensions: ['.js', '.jsx', '.ts', '.tsx'],
langs: ['en'],
originalLang: 'en',
msgFunctionNames: ['_t'],
msgRegexps: [],
fMinify: false,
fJsOutput: true,
};
// ==============================================
// Declarations
// ==============================================
let _localeDir: string;
let _otherLocaleDirs: string[] = [];
let _autoTranslateNewKeys: boolean;
let _onChange: Function | null | undefined;
let _configPath: string;
let _config: Config = DEFAULT_CONFIG;
let _keyPath: string;
let _keys: Keys = {};
let _translations: Translations = {};
let _tUpdated = new Date().getTime();
type Options = {
localeDir: string;
otherLocaleDirs?: string[];
watch?: boolean;
autoTranslateNewKeys?: boolean;
onChange?: Function;
};
// ==============================================
// Init
// ==============================================
const init = (options: Options) => {
_localeDir = options.localeDir;
_otherLocaleDirs = options.otherLocaleDirs || [];
_autoTranslateNewKeys = !!options.autoTranslateNewKeys;
_onChange = options.onChange;
fs.ensureDirSync(_localeDir);
initConfig();
initKeys();
initAutoTranslations({ localeDir: _localeDir });
initTranslations();
if (options.watch) {
initFileWatcher({
paths: addLast(_config.srcPaths, _configPath),
onEvent: onFileChange,
});
} else {
initFileWatcher({ paths: [_configPath], onEvent: onFileChange });
}
};
const _setLocaleDir = (localeDir: string) => {
_localeDir = localeDir;
};
const getTUpdated = () => _tUpdated;
// ==============================================
// Config
// ==============================================
const _setConfigPath = (configPath: string) => {
_configPath = configPath;
};
const getConfig = () => _config;
const _setConfig = (config: Config) => {
_config = config;
};
const initConfig = () => {
_configPath = path.join(_localeDir, 'config.json');
mainStory.info(SRC, `Reading file ${chalk.cyan(_configPath)}...`);
let hasChanged = false;
if (fs.pathExistsSync(_configPath)) {
const config = fs.readJsonSync(_configPath);
_config = addDefaults(config, DEFAULT_CONFIG);
if (_config !== config) hasChanged = true;
} else {
hasChanged = true;
}
if (hasChanged) fs.writeJsonSync(_configPath, _config, JSON_OPTIONS);
};
// ==============================================
// Keys
// ==============================================
const _setKeyPath = (keyPath: string) => {
_keyPath = keyPath;
};
const initKeys = () => {
_keyPath = path.join(_localeDir, 'keys.json');
mainStory.info(SRC, `Reading file ${chalk.cyan(_keyPath)}...`);
if (fs.pathExistsSync(_keyPath)) {
_keys = fs.readJsonSync(_keyPath);
} else {
saveKeys();
}
};
const saveKeys = () => {
mainStory.debug(SRC, `Writing ${chalk.cyan(_keyPath)}...`);
fs.writeJsonSync(_keyPath, _keys, JSON_OPTIONS);
_tUpdated = new Date().getTime();
};
const getKeys = ({ scope }: { scope?: string | null }) =>
Object.values(_keys).filter((key) => {
if (key.isDeleted) return false;
if (scope !== undefined && key.scope != scope) return false;
return true;
});
const getKeysWithTranslations = ({
langs,
scope,
}: {
langs: string[];
scope?: string | null;
}) => {
const keys: Record<
string,
Key & { translations: Record<string, TranslationWithoutKeyId> }
> = {};
// Find suitable keys
Object.values(_keys).forEach((key) => {
if (key.isDeleted) return;
if (scope !== undefined && key.scope != scope) return;
const keyId = key.id;
keys[keyId] = timmSet(key, 'translations', {});
});
// Iterate over all translations
Object.values(_translations).forEach((translation) => {
if (translation.isDeleted) return;
const { keyId, lang } = translation;
const key = keys[keyId];
if (!key) return;
if (langs.indexOf(lang) < 0) return;
if (key.translations[lang]) return; // already translated
key.translations[lang] = omit(translation, ['keyId']);
});
return Object.values(keys);
};
const _setKeys = (keys: Keys) => {
_keys = keys;
};
const getKey = (id: string) => _keys[id];
const createKey = async (newAttrs: Partial<Key>) => {
const text = newAttrs.text as string;
const id =
newAttrs.context != null ? `${newAttrs.context}_${text}` : (text as string);
const newKey = {
id,
context: newAttrs.context,
text,
firstUsed: newAttrs.firstUsed,
unusedSince: newAttrs.unusedSince || null,
sources: [],
};
_keys[id] = newKey;
saveKeys();
debouncedCompileTranslations();
return newKey;
};
const updateKey = async (id: string, newAttrs: Partial<Key>) => {
const updatedKey = merge(_keys[id], newAttrs) as Key;
_keys[id] = updatedKey;
saveKeys();
debouncedCompileTranslations();
return updatedKey;
};
// List all scopes being used in keys
const getScopes = () => {
const scopes: Record<string, boolean> = {};
Object.keys(_keys).forEach((id) => {
const { scope } = _keys[id];
if (scope != null) scopes[scope] = true;
});
return Object.keys(scopes);
};
const purgeKeys = () => {
const removeIds = Object.values(_keys)
.filter((key) => key.isDeleted)
.map((key) => key.id);
removeIds.forEach((id) => delete _keys[id]);
if (removeIds.length) saveKeys();
mainStory.info(SRC, `Purged keys: ${chalk.cyan(removeIds.length)}`);
};
const deleteUnusedKeys = () => {
const removeIds = Object.values(_keys)
.filter((key) => key.unusedSince != null)
.map((key) => key.id);
removeIds.forEach((id) => delete _keys[id]);
if (removeIds.length) saveKeys();
mainStory.info(SRC, `Deleted unused keys: ${chalk.cyan(removeIds.length)}`);
};
// ==============================================
// Translations
// ==============================================
const getLangPath = (lang: string) => path.join(_localeDir, `${lang}.json`);
const getCompiledLangPath = (lang: string, scope: string | null): string =>
scope != null
? path.join(_localeDir, 'scoped', `${scope}-${lang}.js`)
: path.join(_localeDir, `${lang}.js`);
const initTranslations = () => {
_config.langs.forEach((lang) => {
const langPath = getLangPath(lang);
mainStory.info(SRC, `Reading file ${chalk.cyan(langPath)}...`);
if (fs.pathExistsSync(langPath)) {
const translations = fs.readJsonSync(getLangPath(lang));
if (translations) _translations = merge(_translations, translations);
} else {
fs.writeJsonSync(langPath, {}, JSON_OPTIONS);
}
});
};
const readTranslationsFromAnotherDir = (dir: string) => {
let out = {};
_config.langs.forEach((lang) => {
const langPath = path.join(dir, `${lang}.json`);
if (fs.pathExistsSync(langPath)) {
mainStory.info(SRC, `Reading file ${chalk.cyan(langPath)}...`);
out = merge(out, fs.readJsonSync(langPath));
}
});
return out;
};
const saveTranslations = (lang: string) => {
const langTranslations: Translations = {};
Object.keys(_translations).forEach((translationId) => {
const translation = _translations[translationId];
if (translation.lang === lang) {
langTranslations[translation.id] = translation;
}
});
const langPath = getLangPath(lang);
mainStory.debug(SRC, `Writing ${chalk.cyan(langPath)}...`);
fs.writeJsonSync(langPath, langTranslations, JSON_OPTIONS);
_tUpdated = new Date().getTime();
};
const getTranslations = () => Object.values(_translations);
const _setTranslations = (translations: Translations) => {
_translations = translations;
};
type GetTranslationsOptions = { lang: string; scope?: string | null };
const getLangTranslations = (options: GetTranslationsOptions) =>
_getLangTranslations(options, _translations);
const _getLangTranslations = (
{ lang, scope }: GetTranslationsOptions,
refTranslations: Translations
) =>
Object.values(refTranslations).filter((translation) => {
if (translation.isDeleted) return false;
if (translation.lang !== lang) return false;
if (scope !== undefined) {
const key = _keys[translation.keyId];
if (!key) return false;
if (key.isDeleted) return false;
if (key.scope != scope) return false;
}
return true;
});
const getKeyTranslations = (keyId: string, lang?: string) =>
Object.values(_translations).filter(
(o) =>
!o.isDeleted && o.keyId === keyId && (lang == null || o.lang === lang)
);
const getTranslation = (id: string) => _translations[id];
const createTranslation = async (newAttrs: Partial<Translation>) => {
const { id, lang, translation, fuzzy, keyId } = newAttrs;
if (!lang) throw new Error('Translation language must be specified');
if (keyId == null) throw new Error('Translation key must be specified');
const newTranslation = {
id,
isDeleted: false,
lang,
translation,
fuzzy,
keyId,
} as Translation;
_translations[id!] = newTranslation;
saveTranslations(lang);
debouncedCompileTranslations();
return newTranslation;
};
const updateTranslation = async (
id: string,
newAttrs: Partial<Translation>
) => {
const updatedTranslation = merge(_translations[id], newAttrs) as Translation;
_translations[id] = updatedTranslation;
saveTranslations(updatedTranslation.lang);
debouncedCompileTranslations();
return updatedTranslation;
};
// Purge deleted translations + translations of missing/deleted keys
const purgeTranslations = () => {
const removeIds = Object.values(_translations)
.filter((translation) => {
if (translation.isDeleted) return true;
const key = _keys[translation.keyId];
if (!key) return true;
if (key.isDeleted) return true;
return false;
})
.map((translation) => translation.id);
removeIds.forEach((id) => delete _translations[id]);
if (removeIds.length) {
_config.langs.forEach(saveTranslations);
debouncedCompileTranslations();
}
mainStory.info(SRC, `Purged translations: ${chalk.cyan(removeIds.length)}`);
};
// ==============================================
// Parsing and delta-parsing
// ==============================================
const parseSrcFiles = async () => {
const { srcPaths, srcExtensions, msgFunctionNames, msgRegexps } = _config;
const curKeys = parseAll({
srcPaths,
srcExtensions,
msgFunctionNames,
msgRegexps,
localeDir: _localeDir,
});
const now = new Date().toISOString();
// Go through the previous list of keys and:
// - If key is still used, copy `firstUsed` attr from the previous list
// - If key is no longer used, copy the whole key and initialise (if needed) `unusedSince`
const unusedKeys: string[] = [];
Object.keys(_keys).forEach((id) => {
const key = _keys[id];
if (curKeys[id]) {
curKeys[id].firstUsed = key.firstUsed;
} else {
unusedKeys.push(id);
curKeys[id] = key;
key.unusedSince = key.unusedSince || now;
key.sources = [];
}
});
if (unusedKeys.length) {
mainStory.debug(SRC, `${chalk.bold('Unused')} keys: ${unusedKeys.length}`, {
attach: unusedKeys.map(decode),
});
}
// Go through the new list of keys and initialise (if needed) `firstUsed`
const newKeys: string[] = [];
Object.keys(curKeys).forEach((id) => {
const key = curKeys[id];
if (!key.firstUsed) {
newKeys.push(id);
key.firstUsed = now;
}
_keys[id] = key;
});
if (newKeys.length) {
mainStory.debug(SRC, `${chalk.bold('New')} keys: ${newKeys.length}`, {
attach: newKeys.map(decode),
});
}
saveKeys();
debouncedCompileTranslations();
// Try to add automatic translations
if (_autoTranslateNewKeys) {
mainStory.info(SRC, 'Fetching auto translations...');
newKeys.forEach(fetchAutomaticTranslationsForKey);
}
return Object.values(_keys);
};
const onFileChange = async (eventType: string, filePath0: string) => {
if (filePath0 === _configPath) {
initConfig();
return;
}
const filePath = slash(filePath0);
if (eventType === 'unlink') {
onSrcFileDeleted(filePath, { save: true });
} else if (eventType === 'add') {
onSrcFileAdded(filePath, { save: true });
// The general case (change) is equivalent to deleting the file and adding it anew
} else if (eventType === 'change') {
await onSrcFileDeleted(filePath, { save: false });
onSrcFileAdded(filePath, { save: true, forceSave: true });
}
};
const onSrcFileDeleted = async (
filePath: string,
{ save }: { save?: boolean } = {}
) => {
let hasChanged = false;
const now = new Date().toISOString();
const keyIds = Object.keys(_keys);
for (let i = 0; i < keyIds.length; i++) {
const key = _keys[keyIds[i]];
if (key.sources && key.sources.indexOf(filePath) >= 0) {
key.sources = key.sources.filter((o) => o !== filePath);
hasChanged = true;
if (!key.sources.length) key.unusedSince = now;
}
}
if (hasChanged && save) {
saveKeys();
debouncedCompileTranslations();
}
};
const onSrcFileAdded = async (
filePath: string,
{ save, forceSave }: { save?: boolean; forceSave?: boolean } = {}
) => {
let hasChanged = false;
const now = new Date().toISOString();
const { msgFunctionNames, msgRegexps } = _config;
const newKeys = parseOne({ filePath, msgFunctionNames, msgRegexps });
const newKeyIds = Object.keys(newKeys);
for (let i = 0; i < newKeyIds.length; i++) {
hasChanged = true;
const newKeyId = newKeyIds[i];
const newKey = newKeys[newKeyId];
if (_keys[newKeyId]) {
_keys[newKeyId].sources.push(filePath);
_keys[newKeyId].unusedSince = null; // just in case
} else {
_keys[newKeyId] = newKey;
_keys[newKeyId].firstUsed = now;
}
}
if ((hasChanged && save) || forceSave) {
saveKeys();
debouncedCompileTranslations();
}
// Try to add automatic translations
if (_autoTranslateNewKeys) {
mainStory.info(SRC, 'Fetching auto translations...');
newKeyIds.forEach(fetchAutomaticTranslationsForKey);
}
};
const fetchAutomaticTranslationsForKey = (keyId: string) => {
const key = _keys[keyId];
const { text } = key;
// Abort if message has MessageFormat tags (unreliable)
if (text.indexOf('{') >= 0) return;
_config.langs.forEach(async (lang) => {
if (lang.startsWith(_config.originalLang)) return;
if (getKeyTranslations(keyId, lang).length) return;
const translation = await autoTranslate({ text, lang });
if (translation != null) {
const id = uuidv4();
createTranslation({ id, lang, translation, fuzzy: true, keyId });
}
});
};
// ==============================================
// Compiling translations
// ==============================================
const compileTranslations = async () => {
mainStory.info(SRC, 'Compiling translations...');
// Gather all keys (incl. otherLocaleDirs)
mainStory.debug(SRC, 'Gathering keys...');
const keys: Keys = {};
const loadKeys = (myKeys: Keys) => {
Object.keys(myKeys).forEach((name) => {
const key = myKeys[name];
if (!key.isDeleted) keys[name] = key;
});
};
_otherLocaleDirs.forEach((dir) => {
const otherKeys = fs.readJsonSync(path.join(dir, 'keys.json'));
loadKeys(otherKeys);
});
loadKeys(_keys);
try {
// Gather all translations (incl. otherLocaleDirs)
mainStory.debug(SRC, 'Gathering translations...');
const allTranslations: Record<string, Translation[]> = {};
const { langs } = _config;
langs.forEach((lang) => {
allTranslations[lang] = [];
});
const loadTranslations = (refTranslations: Translations) => {
const temp = getAllTranslations(langs, refTranslations);
langs.forEach((lang) => {
allTranslations[lang] = allTranslations[lang].concat(temp[lang] || []);
});
};
_otherLocaleDirs.forEach((dir) => {
const otherTranslations = readTranslationsFromAnotherDir(dir);
loadTranslations(otherTranslations);
});
loadTranslations(_translations);
// Generate all translations outputs
const allLangs = Object.keys(allTranslations);
for (let i = 0; i < allLangs.length; i++) {
const lang = allLangs[i];
const translations = allTranslations[lang];
// Generate JS output
if (_config.fJsOutput) {
const scopes = ([null] as Array<string | null>).concat(getScopes());
for (let k = 0; k < scopes.length; k++) {
const scope = scopes[k];
const translationSubset = translations.filter(({ keyId }) => {
const key = keys[keyId];
return key && key.scope == scope;
});
const compiledLangPath = getCompiledLangPath(lang, scope);
fs.ensureDirSync(path.dirname(compiledLangPath));
const fnTranslate = await compile({
lang,
keys,
translations: translationSubset,
scope,
fMinify: _config.fMinify,
});
mainStory.debug(SRC, `Writing ${chalk.cyan(compiledLangPath)}...`);
fs.writeFileSync(compiledLangPath, fnTranslate, 'utf8');
}
}
}
if (_onChange) _onChange();
} catch (err) {
mainStory.error(SRC, 'Could not compile translations:', { attach: err });
}
mainStory.info(SRC, 'Compiling done');
};
const debouncedCompileTranslations = UNIT_TESTING
? compileTranslations
: debounce(compileTranslations, DEBOUNCE_COMPILE);
type LangNode = {
parent: string | null;
children: string[];
translations: Translation[];
};
type LangStructure = Record<string, LangNode>;
const getAllTranslations = (langs: string[], refTranslations: Translations) => {
// Determine lang structure
const langStructure: LangStructure = {};
const sortedLangs = langs.slice().sort();
sortedLangs.forEach((lang) => {
langStructure[lang] = { parent: null, children: [], translations: [] };
const tokens = lang.split(/[_-]/);
for (let i = 0; i < tokens.length; i++) {
const tmpLang = tokens.slice(0, i + 1).join('-');
if (!langStructure[tmpLang]) {
langStructure[tmpLang] = {
parent: null,
children: [],
translations: [],
};
}
if (i > 0) {
const parentLang = tokens.slice(0, i).join('-');
langStructure[parentLang].children.push(tmpLang);
langStructure[tmpLang].parent = parentLang;
}
}
});
// story.debug(SRC, 'Language tree', { attach: langStructure });
// Collect all translations for languages, from top to bottom:
// - Add all children translations (backup)
// - Add ancestor translations (including those coming up from other branches)
// - Add own translations
// This algorithm may result in multiple translations for the same key, but the latest one
// should have higher priority (this is used by `debouncedCompileTranslations()` during flattening).
// Higher priority is guaranteed by the order in which languages are processed,
// and the order in which translations are added to the array.
const allLangs = Object.keys(langStructure).sort();
allLangs.forEach((lang) => {
const childrenTranslations = getChildrenTranslations(
langStructure,
lang,
refTranslations,
[]
);
// story.debug(SRC, `Children translations for ${lang}`, { attach: childrenTranslations });
const parentTranslations = getParentTranslations(langStructure, lang);
// story.debug(SRC, `Parent translations for ${lang}`, { attach: parentTranslations });
const ownTranslations = _getLangTranslations({ lang }, refTranslations);
// story.debug(SRC, `Own translations for ${lang}`, { attach: ownTranslations });
langStructure[lang].translations = [
...childrenTranslations,
...parentTranslations,
...ownTranslations,
];
});
// Replace lang structure by the translations themselves
const out: Record<string, Translation[]> = {};
Object.keys(langStructure).forEach((lang) => {
out[lang] = langStructure[lang].translations;
});
// story.debug(SRC, 'All translations', { attach: out });
return out;
};
// Recursive
const getChildrenTranslations = (
langStructure: LangStructure,
lang: string,
refTranslations: Translations,
translations0: Translation[]
): Translation[] => {
let translations = translations0;
langStructure[lang].children.forEach((childLang) => {
translations = translations.concat(
_getLangTranslations({ lang: childLang }, refTranslations)
);
translations = getChildrenTranslations(
langStructure,
childLang,
refTranslations,
translations
);
});
return translations;
};
const getParentTranslations = (langStructure: LangStructure, lang: string) => {
let out: Translation[] = [];
const tokens = lang.split(/[_-]/);
if (tokens.length < 1) return out;
for (let i = 0; i < tokens.length - 1; i++) {
const tmpLang = tokens.slice(0, i + 1).join('-');
out = out.concat(langStructure[tmpLang].translations);
}
return out;
};
// ==============================================
// Purge
// ==============================================
const purge = async () => {
purgeKeys();
purgeTranslations();
};
// ==============================================
// Public
// ==============================================
export {
DEFAULT_CONFIG as _DEFAULT_CONFIG,
// --
init,
_setLocaleDir,
getTUpdated,
// --
_setConfigPath,
getConfig,
_setConfig,
// --
_setKeyPath,
getKeys,
getKeysWithTranslations,
_setKeys,
getKey,
createKey,
updateKey,
deleteUnusedKeys,
// --
getTranslations,
_setTranslations,
getLangTranslations,
getKeyTranslations,
getTranslation,
createTranslation,
updateTranslation,
// --
parseSrcFiles,
// --
compileTranslations,
debouncedCompileTranslations,
// --
purge,
}; | the_stack |
module es {
export class Color {
/**
* ็บข่ฒ้้
*/
public r: number;
/**
* ็ปฟ่ฒ้้
*/
public g: number;
/**
* ่่ฒ้้
*/
public b: number;
/**
* ้ๆๅบฆ้้ (ไป
0-1ไน้ด)
*/
public a: number;
/**
* ่ฒ่ฐ
*/
public h: number;
/**
* ้ฅฑๅ
*/
public s: number;
/**
* ไบฎๅบฆ
*/
public l: number;
/**
* ไป r, g, b, a ๅๅปบไธไธชๆฐ็ Color ๅฎไพ
*
* @param r ้ข่ฒ็็บข่ฒๅ้ (0-255)
* @param g ้ข่ฒ็็ปฟ่ฒๆๅ (0-255)
* @param b ้ข่ฒ็่่ฒๅ้ (0-255)
* @param a ้ข่ฒ็ alpha ๅ้ (0-1.0)
*/
constructor(r: number, g: number, b: number, a?: number) {
this.r = r;
this.g = g;
this.b = b;
this.a = a != null ? a : 1;
}
/**
* ไป r, g, b, a ๅๅปบไธไธชๆฐ็ Color ๅฎไพ
*
* @param r ้ข่ฒ็็บข่ฒๅ้ (0-255)
* @param g ้ข่ฒ็็ปฟ่ฒๆๅ (0-255)
* @param b ้ข่ฒ็่่ฒๅ้ (0-255)
* @param a ้ข่ฒ็ alpha ๅ้ (0-1.0)
*/
public static fromRGB(r: number, g: number, b: number, a?: number): Color {
return new Color(r, g, b, a);
}
/**
* ไปๅๅ
ญ่ฟๅถๅญ็ฌฆไธฒๅๅปบไธไธชๆฐ็ Color ๅฎไพ
*
* @param hex #ffffff ๅฝขๅผ็ CSS ้ข่ฒๅญ็ฌฆไธฒ๏ผalpha ็ปไปถๆฏๅฏ้็
*/
public static createFromHex(hex: string): Color {
const color = new Color(1, 1, 1);
color.fromHex(hex);
return color;
}
/**
* ไป hsl ๅผๅๅปบไธไธชๆฐ็ Color ๅฎไพ
*
* @param h ่ฒ่ฐ่กจ็คบ [0-1]
* @param s ้ฅฑๅๅบฆ่กจ็คบไธบ [0-1]
* @param l ไบฎๅบฆ่กจ็คบ [0-1]
* @param a ้ๆๅบฆ่กจ็คบ [0-1]
*/
public static fromHSL(
h: number,
s: number,
l: number,
a: number = 1.0
): Color {
const temp = new HSLColor(h, s, l, a);
return temp.toRGBA();
}
/**
* ๅฐๅฝๅ้ข่ฒ่ฐไบฎๆๅฎ็้
*
* @param factor
*/
public lighten(factor: number = 0.1): Color {
const temp = HSLColor.fromRGBA(this.r, this.g, this.b, this.a);
temp.l += temp.l * factor;
return temp.toRGBA();
}
/**
* ๅฐๅฝๅ้ข่ฒๅๆๆๅฎ็้
*
* @param factor
*/
public darken(factor: number = 0.1): Color {
const temp = HSLColor.fromRGBA(this.r, this.g, this.b, this.a);
temp.l -= temp.l * factor;
return temp.toRGBA();
}
/**
* ไฝฟๅฝๅ้ข่ฒ้ฅฑๅๆๅฎ็้
*
* @param factor
*/
public saturate(factor: number = 0.1): Color {
const temp = HSLColor.fromRGBA(this.r, this.g, this.b, this.a);
temp.s += temp.s * factor;
return temp.toRGBA();
}
/**
* ๆๆๅฎ้้ไฝๅฝๅ้ข่ฒ็้ฅฑๅๅบฆ
*
* @param factor
*/
public desaturate(factor: number = 0.1): Color {
const temp = HSLColor.fromRGBA(this.r, this.g, this.b, this.a);
temp.s -= temp.s * factor;
return temp.toRGBA();
}
/**
* ๅฐไธ็ง้ข่ฒไนไปฅๅฆไธ็ง้ข่ฒ๏ผๅพๅฐๆดๆทฑ็้ข่ฒ
*
* @param color
*/
public mulitiply(color: Color): Color {
const newR = (((color.r / 255) * this.r) / 255) * 255;
const newG = (((color.g / 255) * this.g) / 255) * 255;
const newB = (((color.b / 255) * this.b) / 255) * 255;
const newA = color.a * this.a;
return new Color(newR, newG, newB, newA);
}
/**
* ็ญ้ๅฆไธ็ง้ข่ฒ๏ผๅฏผ่ด้ข่ฒ่พๆต
*
* @param color
*/
public screen(color: Color): Color {
const color1 = color.invert();
const color2 = color.invert();
return color1.mulitiply(color2).invert();
}
/**
* ๅ่ฝฌๅฝๅ้ข่ฒ
*/
public invert(): Color {
return new Color(255 - this.r, 255 - this.g, 255 - this.b, 1.0 - this.a);
}
/**
* ๅฐๅฝๅ้ข่ฒไธๅฆไธไธช้ข่ฒๅนณๅ
*
* @param color
*/
public average(color: Color): Color {
const newR = (color.r + this.r) / 2;
const newG = (color.g + this.g) / 2;
const newB = (color.b + this.b) / 2;
const newA = (color.a + this.a) / 2;
return new Color(newR, newG, newB, newA);
}
/**
* ่ฟๅ้ข่ฒ็ CSS ๅญ็ฌฆไธฒ่กจ็คบๅฝขๅผใ
*
* @param format
*/
public toString(format: 'rgb' | 'hsl' | 'hex' = 'rgb') {
switch (format) {
case 'rgb':
return this.toRGBA();
case 'hsl':
return this.toHSLA();
case 'hex':
return this.toHex();
default:
throw new Error('Invalid Color format');
}
}
/**
* ่ฟๅ้ข่ฒๅ้็ๅๅ
ญ่ฟๅถๅผ
* @param c
* @see https://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb
*/
private _componentToHex(c: number) {
const hex = c.toString(16);
return hex.length === 1 ? '0' + hex : hex;
}
/**
*่ฟๅ้ข่ฒ็ๅๅ
ญ่ฟๅถ่กจ็คบ
*/
public toHex(): string {
return (
'#' +
this._componentToHex(this.r) +
this._componentToHex(this.g) +
this._componentToHex(this.b) +
this._componentToHex(this.a)
);
}
/**
* ไปๅๅ
ญ่ฟๅถๅญ็ฌฆไธฒ่ฎพ็ฝฎ้ข่ฒ
*
* @param hex #ffffff ๅฝขๅผ็ CSS ้ข่ฒๅญ็ฌฆไธฒ๏ผalpha ็ปไปถๆฏๅฏ้็
*/
public fromHex(hex: string) {
const hexRegEx: RegExp = /^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})?$/i;
const match = hex.match(hexRegEx);
if (match) {
const r = parseInt(match[1], 16);
const g = parseInt(match[2], 16);
const b = parseInt(match[3], 16);
let a = 1;
if (match[4]) {
a = parseInt(match[4], 16) / 255;
}
this.r = r;
this.g = g;
this.b = b;
this.a = a;
} else {
throw new Error('Invalid hex string: ' + hex);
}
}
/**
* ่ฟๅ้ข่ฒ็ RGBA ่กจ็คบ
*/
public toRGBA() {
const result =
String(this.r.toFixed(0)) +
', ' +
String(this.g.toFixed(0)) +
', ' +
String(this.b.toFixed(0));
if (this.a !== undefined || this.a != null) {
return 'rgba(' + result + ', ' + String(this.a) + ')';
}
return 'rgb(' + result + ')';
}
/**
* ่ฟๅ้ข่ฒ็ HSLA ่กจ็คบ
*/
public toHSLA() {
return HSLColor.fromRGBA(this.r, this.g, this.b, this.a).toString();
}
/**
* ่ฟๅ้ข่ฒ็ CSS ๅญ็ฌฆไธฒ่กจ็คบๅฝขๅผ
*/
public fillStyle() {
return this.toString();
}
/**
* ่ฟๅๅฝๅ้ข่ฒ็ๅ
้
*/
public clone(): Color {
return new Color(this.r, this.g, this.b, this.a);
}
/**
* Black (#000000)
*/
public static Black: Color = Color.createFromHex('#000000');
/**
* White (#FFFFFF)
*/
public static White: Color = Color.createFromHex('#FFFFFF');
/**
* Gray (#808080)
*/
public static Gray: Color = Color.createFromHex('#808080');
/**
* Light gray (#D3D3D3)
*/
public static LightGray: Color = Color.createFromHex('#D3D3D3');
/**
* Dark gray (#A9A9A9)
*/
public static DarkGray: Color = Color.createFromHex('#A9A9A9');
/**
* Yellow (#FFFF00)
*/
public static Yellow: Color = Color.createFromHex('#FFFF00');
/**
* Orange (#FFA500)
*/
public static Orange: Color = Color.createFromHex('#FFA500');
/**
* Red (#FF0000)
*/
public static Red: Color = Color.createFromHex('#FF0000');
/**
* Vermillion (#FF5B31)
*/
public static Vermillion: Color = Color.createFromHex('#FF5B31');
/**
* Rose (#FF007F)
*/
public static Rose: Color = Color.createFromHex('#FF007F');
/**
* Magenta (#FF00FF)
*/
public static Magenta: Color = Color.createFromHex('#FF00FF');
/**
* Violet (#7F00FF)
*/
public static Violet: Color = Color.createFromHex('#7F00FF');
/**
* Blue (#0000FF)
*/
public static Blue: Color = Color.createFromHex('#0000FF');
/**
* Azure (#007FFF)
*/
public static Azure: Color = Color.createFromHex('#007FFF');
/**
* Cyan (#00FFFF)
*/
public static Cyan: Color = Color.createFromHex('#00FFFF');
/**
* Viridian (#59978F)
*/
public static Viridian: Color = Color.createFromHex('#59978F');
/**
* Green (#00FF00)
*/
public static Green: Color = Color.createFromHex('#00FF00');
/**
* Chartreuse (#7FFF00)
*/
public static Chartreuse: Color = Color.createFromHex('#7FFF00');
/**
* Transparent (#FFFFFF00)
*/
public static Transparent: Color = Color.createFromHex('#FFFFFF00');
}
/**
* ๅ
้จ HSL ้ข่ฒ่กจ็คบ
*
* http://en.wikipedia.org/wiki/HSL_and_HSV
* http://axonflux.com/handy-rgb-to-hsl-and-rgb-to-hsv-color-model-c
*/
class HSLColor {
constructor(
public h: number,
public s: number,
public l: number,
public a: number
) { }
public static hue2rgb(p: number, q: number, t: number): number {
if (t < 0) {
t += 1;
}
if (t > 1) {
t -= 1;
}
if (t < 1 / 6) {
return p + (q - p) * 6 * t;
}
if (t < 1 / 2) {
return q;
}
if (t < 2 / 3) {
return p + (q - p) * (2 / 3 - t) * 6;
}
return p;
}
public static fromRGBA(
r: number,
g: number,
b: number,
a: number
): HSLColor {
r /= 255;
g /= 255;
b /= 255;
const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
let h = (max + min) / 2;
let s = h;
const l = h;
if (max === min) {
h = s = 0; // achromatic
} else {
const d = max - min;
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
switch (max) {
case r:
h = (g - b) / d + (g < b ? 6 : 0);
break;
case g:
h = (b - r) / d + 2;
break;
case b:
h = (r - g) / d + 4;
break;
}
h /= 6;
}
return new HSLColor(h, s, l, a);
}
public toRGBA(): Color {
let r: number;
let g: number;
let b: number;
if (this.s === 0) {
r = g = b = this.l; // achromatic
} else {
const q =
this.l < 0.5
? this.l * (1 + this.s)
: this.l + this.s - this.l * this.s;
const p = 2 * this.l - q;
r = HSLColor.hue2rgb(p, q, this.h + 1 / 3);
g = HSLColor.hue2rgb(p, q, this.h);
b = HSLColor.hue2rgb(p, q, this.h - 1 / 3);
}
return new Color(r * 255, g * 255, b * 255, this.a);
}
public toString(): string {
const h = this.h.toFixed(0);
const s = this.s.toFixed(0);
const l = this.l.toFixed(0);
const a = this.a.toFixed(0);
return `hsla(${h}, ${s}, ${l}, ${a})`;
}
}
} | the_stack |
jest.unmock('../../../src/setup-wizard/tasks/setup-jest-cmdline');
jest.unmock('../test-helper');
jest.unmock('./task-test-helper');
import * as vscode from 'vscode';
import * as helper from '../../../src/setup-wizard/wizard-helper';
import {
setupJestCmdLine,
CLSetupActionId,
} from '../../../src/setup-wizard/tasks/setup-jest-cmdline';
import { mockWizardHelper } from '../test-helper';
import { validateTaskConfigUpdate, createWizardContext } from './task-test-helper';
import * as path from 'path';
const mockHelper = helper as jest.Mocked<any>;
const { mockShowActionMenu, mockShowActionMessage, mockHelperSetup } = mockWizardHelper(mockHelper);
describe('wizard-tasks', () => {
const mockSaveConfig = jest.fn();
const debugConfigProvider = {};
let wizardSettings: { [key: string]: any };
beforeEach(() => {
jest.resetAllMocks();
vscode.workspace.getConfiguration = jest.fn().mockReturnValue({
// get: mockConfigGet,
update: mockSaveConfig,
});
wizardSettings = {};
mockHelperSetup();
// default helper function
mockHelper.showActionMenu.mockReturnValue('success');
mockHelper.showActionInputBox.mockImplementation(({ value }) => value);
mockSaveConfig.mockImplementation(() => Promise.resolve());
mockHelper.showActionMessage.mockImplementation((_, options) => {
return options?.action?.();
});
mockHelper.getWizardSettings.mockImplementation(() => wizardSettings);
mockHelper.createSaveConfig.mockReturnValue(mockSaveConfig);
});
describe('setupJestCmdLine', () => {
const validateConfigUpdate = (callBack?: (value?: string) => void) =>
validateTaskConfigUpdate(mockSaveConfig, 'jest.jestCommandLine', callBack);
let context;
beforeEach(() => {
context = createWizardContext('single-root', debugConfigProvider);
});
describe('wthout existing command settings should ask user to input it', () => {
it.each`
desc | settings
${'no setting'} | ${{}}
${'only jestConfig'} | ${{ pathToConfig: 'jest-config.js' }}
`('$desc is considered "no existing settings"', async () => {
expect.hasAssertions();
mockHelper.getConfirmation = jest.fn().mockReturnValue(Promise.resolve(true));
await setupJestCmdLine(context);
expect(mockHelper.getConfirmation).toHaveBeenCalled();
expect(mockHelper.showActionInputBox).toHaveBeenCalled();
});
it('abort wizard if user can not run jest tests in terminal yet', async () => {
expect.hasAssertions();
mockHelper.getConfirmation = jest.fn().mockReturnValue(Promise.resolve(false));
// mock the info message
mockShowActionMessage('warning', CLSetupActionId.info);
await expect(setupJestCmdLine(context)).resolves.toEqual('error');
expect(mockHelper.getConfirmation).toHaveBeenCalled();
expect(mockHelper.showActionMessage).toHaveBeenCalled();
expect(mockHelper.showActionInputBox).not.toHaveBeenCalled();
});
describe('when use can run jest in terminal', () => {
beforeEach(() => {
mockHelper.getConfirmation = jest.fn().mockReturnValue(Promise.resolve(true));
});
it.each`
input | jestCmdLine | result
${''} | ${''} | ${'abort'}
${'abc'} | ${'abc'} | ${'success'}
${'jest --coverage '} | ${'jest --coverage'} | ${'success'}
${' \t '} | ${''} | ${'abort'}
${undefined} | ${undefined} | ${'abort'}
`('with "$input" => $result', async ({ input, jestCmdLine, result }) => {
expect.hasAssertions();
mockHelper.showActionInputBox = jest.fn().mockReturnValue(Promise.resolve(input));
await expect(setupJestCmdLine(context)).resolves.toEqual(result);
// prompt user input for commandLine
expect(mockHelper.getConfirmation).toHaveBeenCalled();
expect(mockHelper.showActionInputBox).toHaveBeenCalled();
if (result === 'success') {
validateConfigUpdate((cmdLine) => expect(cmdLine).toEqual(jestCmdLine));
} else {
// jestCommandLine will not be changed nor saved
validateConfigUpdate();
}
});
it('will abort task if input is abort (returns undefined)', async () => {
expect.hasAssertions();
mockHelper.getConfirmation = jest.fn().mockReturnValue(Promise.resolve(true));
// user click ok in the info panel
mockShowActionMessage('info', CLSetupActionId.info);
await expect(setupJestCmdLine(context)).resolves.toEqual('abort');
expect(mockHelper.showActionInputBox).toHaveBeenCalled();
});
});
});
describe.each`
desc | settings | expectedCmdLine
${'pathToJest'} | ${{ pathToJest: 'abc -x' }} | ${'abc -x'}
${'pathToJest and pathToConfig'} | ${{ pathToJest: 'abc -x', pathToConfig: `"${path.join('dir with space', 'shared-jest.json')}"` }} | ${`abc -x --config "${path.join('dir with space', 'shared-jest.json')}"`}
`('with legacy command settings: $desc', ({ settings, expectedCmdLine }) => {
it.each`
menuId | result
${CLSetupActionId.upgrade} | ${'success'}
${undefined} | ${undefined}
`('menu $menuId returns $result', async ({ menuId, result }) => {
expect.hasAssertions();
wizardSettings = settings;
// user click on menu
mockShowActionMenu(menuId);
await expect(setupJestCmdLine(context)).resolves.toEqual(result);
// user will be able to editing it before update
if (menuId != null) {
expect(mockHelper.showActionInputBox).toBeCalled();
// both jestCommandLine and debug config should be updated
validateConfigUpdate((cmdLine) => expect(cmdLine).toEqual(expectedCmdLine));
} else {
// user abort the menu
expect(mockHelper.showActionInputBox).not.toBeCalled();
validateConfigUpdate();
}
});
});
describe.each`
desc | settings | expectedCmdLine
${'jestCommandLine'} | ${{ jestCommandLine: 'abc -x' }} | ${'abc -x'}
${'jestCommandLine, pathToJest and pathToConfig'} | ${{ jestCommandLine: 'abc -y ', pathToJest: 'abc', pathToConfig: '../shared-jest.json' }} | ${'abc -y'}
`('with jestCommandLine settings: $desc', ({ settings, expectedCmdLine }) => {
it.each`
menuId | result | updatedCmdLine
${CLSetupActionId.acceptExisting} | ${'success'} | ${false}
${CLSetupActionId.edit} | ${'success'} | ${true}
${undefined} | ${undefined} | ${false}
`('menu $menuId returns $result', async ({ menuId, result, updatedCmdLine }) => {
expect.hasAssertions();
wizardSettings = settings;
// user click on menu
mockShowActionMenu(menuId);
await expect(setupJestCmdLine(context)).resolves.toEqual(result);
// user will be able to editing it before update
if (updatedCmdLine) {
expect(mockHelper.showActionInputBox).toBeCalled();
// both jestCommandLine and debug config should be updated
validateConfigUpdate((cmdLine) => expect(cmdLine).toEqual(expectedCmdLine));
} else {
// user abort the menu
expect(mockHelper.showActionInputBox).not.toBeCalled();
validateConfigUpdate();
}
});
});
describe('when user enter an invalid commandLine, a warning message will be shown for correction', () => {
beforeEach(() => {
mockHelper.getConfirmation = jest.fn().mockReturnValue(Promise.resolve(true));
mockHelper.showActionInputBox = jest.fn().mockReturnValue('an invalid command line');
mockHelper.validateCommandLine = jest.fn().mockReturnValueOnce('invalid command');
});
describe('when no existing settings', () => {
it('user can choose to re-edit the command', async () => {
expect.hasAssertions();
mockShowActionMessage('warning', CLSetupActionId.editInvalidCmdLine);
await expect(setupJestCmdLine(context)).resolves.toEqual('success');
// showing warniing
expect(mockHelper.showActionMessage).toBeCalledTimes(1);
// show input box for editing and reediting
expect(mockHelper.showActionInputBox).toBeCalledTimes(2);
});
it('user can still choose to accept the command as it is', async () => {
expect.hasAssertions();
mockShowActionMessage('warning', CLSetupActionId.acceptInvalidCmdLine);
await expect(setupJestCmdLine(context)).resolves.toEqual('success');
// showing warniing
expect(mockHelper.showActionMessage).toBeCalledTimes(1);
// show input box for editing
expect(mockHelper.showActionInputBox).toBeCalledTimes(1);
});
});
describe('when existing jestCommandLine is invalid: shows a warning panel', () => {
beforeEach(() => {
wizardSettings = { jestCommandLine: 'npm test' };
});
it('use can still choose to accept the command line', async () => {
expect.hasAssertions();
mockShowActionMessage('warning', CLSetupActionId.acceptInvalidCmdLine);
await expect(setupJestCmdLine(context)).resolves.toEqual('success');
// showing warniing
expect(mockHelper.showActionMessage).toBeCalledTimes(1);
// no input box
expect(mockHelper.showActionInputBox).not.toBeCalled();
// no menu will be shown
expect(mockHelper.showActionMenu).not.toHaveBeenCalled();
});
describe('use can choose to edit the command line', () => {
beforeEach(() => {
mockShowActionMessage('warning', CLSetupActionId.editInvalidCmdLine);
});
it('an input box will be prompt', async () => {
expect.hasAssertions();
await expect(setupJestCmdLine(context)).resolves.toEqual('success');
// showing warniing
expect(mockHelper.showActionMessage).toBeCalledTimes(1);
// show input box for editing
expect(mockHelper.showActionInputBox).toBeCalledTimes(1);
// no menu will be shown
expect(mockHelper.showActionMenu).not.toHaveBeenCalled();
});
it('if user still input an invalid cmdLine, the warning panel will be shown again', async () => {
expect.hasAssertions();
mockHelper.validateCommandLine.mockReturnValueOnce('invalid command still');
await expect(setupJestCmdLine(context)).resolves.toEqual('success');
// showing warniing twice
expect(mockHelper.showActionMessage).toBeCalledTimes(2);
// show input box for editing twice
expect(mockHelper.showActionInputBox).toBeCalledTimes(2);
// no menu will be shown
expect(mockHelper.showActionMenu).not.toHaveBeenCalled();
});
});
});
});
});
}); | the_stack |
import sorty from '@inovua/reactdatagrid-community/packages/sorty';
const EMPTY_OBJECT = {};
const sortAsc = (a: number, b: number) => a - b;
const identity = <T>(a: T): T => a;
const augmentNode = (
n,
parentNode: any,
index: number,
config: any = EMPTY_OBJECT
) => {
const idProperty = config.idProperty || 'id';
const pathSeparator = config.pathSeparator || '/';
const nodesName = config.nodesName || 'nodes';
const expandedNodes = config.expandedNodes || EMPTY_OBJECT;
const dataSourceCache = config.dataSourceCache || EMPTY_OBJECT;
const nodeCache = config.nodeCache || EMPTY_OBJECT;
const loadingNodes = config.loadingNodes || EMPTY_OBJECT;
const parentNodeId = parentNode ? parentNode[idProperty] : undefined;
const path = parentNode
? `${parentNodeId}${pathSeparator}${n[idProperty]}`
: `${n[idProperty]}`;
const cacheKey = config.generateIdFromPath ? path : n[idProperty];
const initialNodes = n[nodesName];
if (dataSourceCache[cacheKey]) {
n = { ...n, ...dataSourceCache[cacheKey] };
}
if (nodeCache[cacheKey]) {
n = { ...n, ...nodeCache[cacheKey] };
}
const itemNodes = n[nodesName];
const nodeProps = (config.nodeProps || identity)(
{
leafNode: itemNodes === undefined,
asyncNode: itemNodes === null,
expanded: !!expandedNodes[cacheKey],
loading: !!loadingNodes[cacheKey],
initialNodes,
parentNodeId,
path,
key: cacheKey,
childIndex: index,
itemNodesCount: Array.isArray(itemNodes) ? itemNodes.length : 0,
depth: parentNode
? parentNode.__nodeProps
? parentNode.__nodeProps.depth + 1
: 1
: 0,
},
n
);
if (config.isNodeLeaf) {
nodeProps.leafNode = config.isNodeLeaf({ node: n, nodeProps });
}
if (config.isNodeAsync) {
nodeProps.asyncNode = config.isNodeAsync({ node: n, nodeProps });
}
const result = {
...n,
__nodeProps: nodeProps,
};
if (config.generateIdFromPath) {
result[idProperty] = path;
}
return result;
};
const expandAtIndexWithInfo = (
dataArray: any[],
index: number,
config: any = EMPTY_OBJECT
) => {
const nodesName = config.nodesName || 'nodes';
const idProperty = config.idProperty || 'id';
const generateIdFromPath = config.generateIdFromPath;
const pathSeparator = config.pathSeparator || '/';
let node = dataArray[index];
if (!node) {
return { data: dataArray, insertCount: 0 };
}
const nextNode = dataArray[index + 1];
const parentNodeId = node[idProperty];
let nodes = node[nodesName];
if (
!Array.isArray(nodes) ||
!nodes.length ||
(nextNode &&
nextNode.__nodeProps &&
nextNode.__nodeProps.parentNodeId === parentNodeId) /* already expanded */
) {
return { data: dataArray, insertCount: 0 };
}
const insertIds = {};
nodes = nodes.map((n, index) => {
return augmentNode(n, node, index, config);
});
return {
data: dataArray
.slice(0, index)
.concat(node)
.concat(nodes)
.concat(dataArray.slice(index + 1)),
insertNodes: nodes,
insertIds,
insertCount: nodes.length,
};
};
export const expandAtIndexes = (
dataArray: any[],
indexes: number[] | any,
config = EMPTY_OBJECT
) => {
indexes = indexes.sort(sortAsc);
let alreadyInserted = 0;
if (!Array.isArray(indexes) || !indexes.length) {
return dataArray;
}
return indexes.reduce((dataSource, index) => {
const { data, insertCount } = expandAtIndexWithInfo(
dataSource,
index + alreadyInserted,
config
);
alreadyInserted += insertCount;
return data;
}, dataArray);
};
export const collapseAtIndexes = (
dataArray: any[],
indexes: number[] | any,
config = EMPTY_OBJECT
) => {
indexes = indexes.sort(sortAsc);
let alreadyRemoved = 0;
if (!Array.isArray(indexes) || !indexes.length) {
return dataArray;
}
return indexes.reduce((dataSource, index) => {
const { data, removeCount } = collapseAtIndexWithInfo(
dataSource,
index - alreadyRemoved,
config
);
alreadyRemoved += removeCount;
return data;
}, dataArray);
};
export const expandAtIndex = (
dataArray: any[],
index: number,
config = EMPTY_OBJECT
) => {
const { data } = expandAtIndexWithInfo(dataArray, index, config);
return data;
};
export const expandByIds = (
dataArray: any[],
idMap: {} | undefined,
config = EMPTY_OBJECT
) => {
const { data } = expandByIdsWithInfo(dataArray, idMap, config);
return data;
};
export const expandByIdsWithInfo = (
dataArray: any[],
config: any = EMPTY_OBJECT,
parentNode?: {} | undefined,
result: any[] = [],
idToIndexMap: any = {},
dataMap: any = {},
startIndex: number = 0,
nodesToExpand: any[] = []
) => {
const idProperty = config.idProperty || 'id';
const nodesName = config.nodesName || 'nodes';
const nodeCache = config.nodeCache || EMPTY_OBJECT;
const expandedNodes = config.expandedNodes || EMPTY_OBJECT;
let nextItem;
let itemAlreadyExpanded;
let itemId;
let itemNodes;
dataArray.forEach((item: any, i) => {
item = augmentNode(item, parentNode, i /* + startIndex*/, config);
itemId = item[idProperty];
itemNodes = item[nodesName];
idToIndexMap[itemId] = i + startIndex;
dataMap[itemId] = item;
result.push(item);
if (expandedNodes[itemId]) {
if (Array.isArray(itemNodes)) {
nextItem = dataArray[i + 1];
itemAlreadyExpanded =
nextItem &&
nextItem.__nodeProps &&
nextItem.__nodeProps.parentNodeId === itemId;
if (!itemAlreadyExpanded) {
let startFrom = result.length;
expandByIdsWithInfo(
itemNodes,
config,
item,
result,
idToIndexMap,
dataMap,
startFrom,
nodesToExpand
);
startIndex += result.length - startFrom;
}
} else if (
item.__nodeProps.expanded &&
!item.__nodeProps.loading &&
item.__nodeProps.asyncNode &&
!item.__nodeProps.itemNodesCount &&
(!config.collapsingNodes || !config.collapsingNodes[itemId])
) {
nodesToExpand.push(item);
}
}
});
return {
data: result,
dataMap,
idToIndexMap,
nodesToExpand,
};
};
type IdMap = { [key: string]: any };
export const collapseByIds = (
dataArray: any[],
idMap: IdMap,
config: any = EMPTY_OBJECT
) => {
const idToIndexMap = config.idToIndexMap;
if (!idToIndexMap) {
throw new Error(
`The last argument to "collapseByIds" should contain a "idToIndexMap" property. No such property found!`
);
}
const indexes = [];
let index;
for (let id in idMap) {
index = idToIndexMap[id];
if (index !== undefined) {
indexes.push(index);
}
}
return collapseAtIndexes(dataArray, indexes, config);
};
export const collapseAtIndexWithInfo = (
dataArray: any[],
index: number,
config: any = EMPTY_OBJECT
) => {
const node = dataArray[index];
const idProperty = config.idProperty || 'id';
if (!node) {
return { data: dataArray, removeCount: 0 };
}
const parentNodeId = node[idProperty];
const nodesName = config.nodesName || 'nodes';
const nodes = node[nodesName];
const nextNode = dataArray[index + 1];
if (
!Array.isArray(nodes) ||
!nodes.length ||
(nextNode &&
(!nextNode.__nodeProps ||
nextNode.__nodeProps.parentNodeId !==
parentNodeId)) /* already collapsed */
) {
return { data: dataArray, removeCount: 0 };
}
return {
data: dataArray
.slice(0, index)
.concat(node)
.concat(dataArray.slice(index + nodes.length + 1)),
removeCount: nodes.length,
};
};
export const collapseAtIndex = (
dataArray: any[],
index: number,
config: any = EMPTY_OBJECT
) => {
const { data } = collapseAtIndexWithInfo(dataArray, index, config);
return data;
};
export const sortTreeData = (
sortInfo,
dataArray,
{ depth = 0, deep } = EMPTY_OBJECT
) => {
let { data, maxDepth } = sortTreeDataWithInfo(sortInfo, dataArray, depth);
if (deep) {
let currentDepth = depth;
while (currentDepth < maxDepth) {
currentDepth++;
data = sortTreeDataWithInfo(sortInfo, data, currentDepth).data;
}
}
return data;
};
export const sortTreeDataWithInfo = (sortInfo, dataArray: any[], depth = 0) => {
let item;
let index = 0;
let arrayAtDepth = [];
let currentDepth;
let currentPath;
let prevItemDepth = -1;
let prevPath;
let prevMatchingDepthPath;
let depthStart = -1;
let depthEnd = -1;
let arrayToSort: any[] | undefined;
let currentNodeChildren = [];
let map = {};
let sortIndexStart;
let maxDepth = 0;
while ((item = dataArray[index])) {
currentDepth = item.__nodeProps.depth;
currentPath = item.__nodeProps.path;
maxDepth = Math.max(maxDepth, currentDepth);
if (currentDepth === depth) {
if (currentDepth > prevItemDepth) {
arrayToSort = [];
sortIndexStart = index;
}
arrayToSort.push(item);
}
if (prevItemDepth >= depth && currentDepth <= depth) {
if (currentNodeChildren.length) {
map[prevMatchingDepthPath] = currentNodeChildren;
currentNodeChildren = [];
}
}
if (currentDepth > depth) {
currentNodeChildren.push(item);
}
if (currentDepth < depth && arrayToSort && arrayToSort.length) {
sorty(sortInfo, arrayToSort);
for (
let i = 0, sortItemChildren, sortItemPath, sortItem;
;
i < arrayToSort.length
) {
sortItem = arrayToSort[i];
if (!sortItem) {
break;
}
sortItemPath = sortItem.__nodeProps.path;
sortItemChildren = map[sortItemPath];
if (Array.isArray(sortItemChildren)) {
arrayToSort.splice(i + 1, 0, ...sortItemChildren);
i += sortItemChildren.length;
}
i++;
}
dataArray.splice(sortIndexStart, arrayToSort.length, ...arrayToSort);
arrayToSort = [];
}
index++;
if (currentDepth === depth) {
prevMatchingDepthPath = currentPath;
}
prevItemDepth = currentDepth;
prevPath = currentPath;
}
if (currentNodeChildren.length) {
map[prevMatchingDepthPath] = currentNodeChildren;
}
if (arrayToSort && arrayToSort.length) {
sorty(sortInfo, arrayToSort);
let idx = 0;
let sortItemChildren;
let sortItemPath;
let sortItem;
for (; ; idx < arrayToSort.length) {
sortItem = arrayToSort[idx];
if (!sortItem) {
break;
}
sortItemPath = sortItem.__nodeProps.path;
sortItemChildren = map[sortItemPath];
if (Array.isArray(sortItemChildren)) {
arrayToSort.splice(idx + 1, 0, ...sortItemChildren);
idx += sortItemChildren.length;
}
idx++;
}
dataArray.splice(sortIndexStart, arrayToSort.length, ...arrayToSort);
}
return { data: dataArray, maxDepth };
}; | the_stack |
import { mount } from 'enzyme';
import 'jest';
import * as React from 'react';
import { Provider } from 'react-redux';
import configureStore from 'redux-mock-store';
import { render } from '@testing-library/react';
import { bytesInOneMB, FileUploadComponent, IFileUploadProps } from '../../../src/components/base/FileUploadComponent';
import { getFileEnding, removeFileEnding } from '../../../src/utils/attachment';
import { getFileUploadComponentValidations } from '../../../src/utils/formComponentUtils';
describe('>>> components/base/FileUploadComponent.tsx', () => {
let mockDisplayMode: string;
let mockId: string;
let mockIsValid: boolean;
let mockMaxFileSizeInMB: number;
let mockMaxNumberOfAttachments: number;
let mockMinNumberOfAttachments: number;
let mockReadOnly: boolean;
let mockAttachments: any[];
let mockFileList: File[];
let mockInitialState: any;
let mockStore: any;
beforeEach(() => {
const createStore = configureStore();
mockId = 'mockId';
mockAttachments = [
{ name: 'attachment-name-1', id: 'attachment-id-1', size: '1200', uploaded: true, deleting: false },
{ name: 'attachment-name-2', id: 'attachment-id-2', size: '800', uploaded: false, deleting: false },
{ name: 'attachment-name-3', id: 'attachment-id-3', size: '400', uploaded: true, deleting: true },
];
mockInitialState = {
attachments: {
attachments: {
mockId: mockAttachments,
},
validationResults: {
mockId: {
simpleBinding: {
errors: ['mock error message'],
},
},
},
},
};
mockMaxNumberOfAttachments = 4;
mockMinNumberOfAttachments = 1;
mockMaxFileSizeInMB = 2;
mockDisplayMode = 'simple';
mockIsValid = true;
mockReadOnly = false;
mockFileList = [
{ name: 'mock-name-1.txt', lastModified: null, size: 100, slice: null, type: null, arrayBuffer: null, stream: null, text: null, webkitRelativePath: null },
{ name: 'mock-name-2.txt', lastModified: null, size: 100, slice: null, type: null, arrayBuffer: null, stream: null, text: null, webkitRelativePath: null },
{ name: 'mock-name-3.txt', lastModified: null, size: 100, slice: null, type: null, arrayBuffer: null, stream: null, text: null, webkitRelativePath: null },
{ name: 'mock-name-4.txt', lastModified: null, size: 200 * bytesInOneMB, slice: null, type: null, arrayBuffer: null, stream: null, text: null, webkitRelativePath: null },
{ name: 'mock-name-5.txt', lastModified: null, size: 200 * bytesInOneMB, slice: null, type: null, arrayBuffer: null, stream: null, text: null, webkitRelativePath: null },
];
mockStore = createStore(mockInitialState);
});
it('+++ should match snapshot', () => {
const {asFragment} = renderFileUploadComponent();
expect(asFragment()).toMatchSnapshot();
});
it('+++ should show spinner when file is uploading or deleting', () => {
const wrapper = mount(
<Provider store={mockStore}>
<FileUploadComponent
displayMode={mockDisplayMode}
id={mockId}
isValid={mockIsValid}
language={{}}
maxFileSizeInMB={mockMaxFileSizeInMB}
maxNumberOfAttachments={mockMaxNumberOfAttachments}
minNumberOfAttachments={mockMinNumberOfAttachments}
readOnly={mockReadOnly}
/>
</Provider>
);
expect(wrapper.find('#loader-upload')).toHaveLength(2); // div and react node
expect(wrapper.find('#loader-delete')).toHaveLength(2); // div and react node
});
// it('+++ should add validation error on onDrop rejection', () => {
// const wrapper = mount(
// <FileUploadComponentClass
// displayMode={mockDisplayMode}
// id={mockId}
// isValid={mockIsValid}
// language={{}}
// maxFileSizeInMB={mockMaxFileSizeInMB}
// maxNumberOfAttachments={mockMaxNumberOfAttachments}
// minNumberOfAttachments={mockMinNumberOfAttachments}
// readOnly={mockReadOnly}
// attachments={mockAttachments}
// />,
// );
// const instance = wrapper.instance() as FileUploadComponentClass;
// expect(instance.state.validations.length).toBe(0);
// instance.onDrop([], mockFileList);
// expect(instance.state.validations.length).toBe(1);
// });
// it('+++ should not upload any files if number of files are greater than max files', () => {
// const wrapper = mount(
// <FileUploadComponentClass
// displayMode={mockDisplayMode}
// id={mockId}
// isValid={mockIsValid}
// language={{}}
// maxFileSizeInMB={mockMaxFileSizeInMB}
// maxNumberOfAttachments={mockMaxNumberOfAttachments}
// minNumberOfAttachments={mockMinNumberOfAttachments}
// readOnly={mockReadOnly}
// attachments={mockAttachments}
// />,
// );
// const instance = wrapper.instance() as FileUploadComponentClass;
// const spy = jest.spyOn(instance, 'setState');
// instance.onDrop(mockFileList, []);
// const call = spy.mock.calls[0][0] as any;
// expect(call.attachments.length).toBe(mockAttachments.length);
// });
// it('+++ should upload all files if number of accepted files are less then max allowed files', () => {
// const mockAccepted = [{ name: 'mock-name-1.txt', lastModified: null, size: 100, slice: null, type: null }];
// const wrapper = mount(
// <FileUploadComponentClass
// displayMode={mockDisplayMode}
// id={mockId}
// isValid={mockIsValid}
// language={{}}
// maxFileSizeInMB={mockMaxFileSizeInMB}
// maxNumberOfAttachments={mockMaxNumberOfAttachments}
// minNumberOfAttachments={mockMinNumberOfAttachments}
// readOnly={mockReadOnly}
// attachments={mockAttachments}
// />,
// );
// const instance = wrapper.instance() as FileUploadComponentClass;
// const spy = jest.spyOn(instance, 'setState');
// instance.onDrop(mockAccepted, []);
// const call = spy.mock.calls[0][0] as any;
// expect(call.attachments.length).toBe(mockAttachments.length + mockAccepted.length);
// });
// it('+++ should add validation messages if file is rejected', () => {
// const wrapper = mount(
// <FileUploadComponentClass
// displayMode={mockDisplayMode}
// id={mockId}
// isValid={mockIsValid}
// language={{}}
// maxFileSizeInMB={10}
// maxNumberOfAttachments={10}
// minNumberOfAttachments={mockMinNumberOfAttachments}
// readOnly={mockReadOnly}
// attachments={mockAttachments}
// />,
// );
// const instance = wrapper.instance() as FileUploadComponentClass;
// const spy = jest.spyOn(instance, 'setState');
// instance.onDrop([], mockFileList);
// const call = spy.mock.calls[0][0] as any;
// expect(call.validations.length).toBe(mockFileList.length);
// expect(call.validations[0]).toBe('form_filler.file_uploader_validation_error_general_1 mock-name-1.txt form_filler.file_uploader_validation_error_general_2');
// expect(call.validations[3]).toBe('mock-name-4.txt form_filler.file_uploader_validation_error_file_size');
// });
// it('+++ should trigger onDelete on when delete is clicked and update state to deleting for that attachment', () => {
// const wrapper = mount(
// <FileUploadComponentClass
// displayMode={mockDisplayMode}
// id={mockId}
// isValid={mockIsValid}
// language={{}}
// maxFileSizeInMB={mockMaxFileSizeInMB}
// maxNumberOfAttachments={mockMaxNumberOfAttachments}
// minNumberOfAttachments={mockMinNumberOfAttachments}
// readOnly={mockReadOnly}
// attachments={mockAttachments}
// />,
// );
// const instance = wrapper.instance() as FileUploadComponentClass;
// const spy = jest.spyOn(instance, 'handleDeleteFile');
// wrapper.find('#attachment-delete-0').simulate('click');
// // workaround - have to click twice the first time
// wrapper.find('#attachment-delete-0').simulate('click');
// expect(instance.state.attachments[0].deleting).toBe(true);
// expect(spy).toHaveBeenCalled();
// });
it('+++ should not display drop area when in simple mode and attachments exists', () => {
const wrapper = mount(
<Provider store={mockStore}>
<FileUploadComponent
displayMode={mockDisplayMode}
id={mockId}
isValid={mockIsValid}
language={{}}
maxFileSizeInMB={mockMaxFileSizeInMB}
maxNumberOfAttachments={mockMaxNumberOfAttachments}
minNumberOfAttachments={mockMinNumberOfAttachments}
readOnly={mockReadOnly}
/>
</Provider>
);
expect(wrapper.find(`#altinn-drop-zone-${mockId}`)).toHaveLength(0);
});
it('+++ getFileUploadComponentValidations should return correct validation', () => {
const mockLanguage = {
language: {
form_filler: {
file_uploader_validation_error_delete: 'Noe gikk galt under slettingen av filen, prรธv igjen senere.',
file_uploader_validation_error_upload: 'Noe gikk galt under opplastingen av filen, prรธv igjen senere',
},
},
};
let validation = getFileUploadComponentValidations('upload', mockLanguage.language);
expect(validation).toEqual({ simpleBinding: { errors: ['Noe gikk galt under opplastingen av filen, prรธv igjen senere'], warnings: [] } });
validation = getFileUploadComponentValidations('delete', mockLanguage.language);
expect(validation).toEqual({ simpleBinding: { errors: ['Noe gikk galt under slettingen av filen, prรธv igjen senere.'], warnings: [] } });
});
it('+++ should get file ending correctly', () => {
expect(getFileEnding('test.jpg')).toEqual('.jpg');
expect(getFileEnding('navn.med.punktum.xml')).toEqual('.xml');
expect(getFileEnding('navnutenfilendelse')).toEqual('');
expect(getFileEnding(null)).toEqual('');
});
it('+++ should remove file ending correctly', () => {
expect(removeFileEnding('test.jpg')).toEqual('test');
expect(removeFileEnding('navn.med.punktum.xml')).toEqual('navn.med.punktum');
expect(removeFileEnding('navnutenfilendelse')).toEqual('navnutenfilendelse');
expect(removeFileEnding(null)).toEqual('');
});
// it('+++ should not show file upload when max files is reached', () => {
// const wrapper = mount(
// <FileUploadComponentClass
// displayMode={mockDisplayMode}
// id={mockId}
// isValid={mockIsValid}
// language={{}}
// maxFileSizeInMB={mockMaxFileSizeInMB}
// maxNumberOfAttachments={3}
// minNumberOfAttachments={mockMinNumberOfAttachments}
// readOnly={mockReadOnly}
// attachments={mockAttachments}
// />,
// );
// const instance = wrapper.instance() as FileUploadComponentClass;
// const result = instance.shouldShowFileUpload();
// expect(result).toBe(false);
// });
function renderFileUploadComponent(props: Partial<IFileUploadProps> = {}) {
const defaultProps: IFileUploadProps = {
id: mockId,
displayMode: mockDisplayMode,
language: {},
maxFileSizeInMB: mockMaxFileSizeInMB,
maxNumberOfAttachments: mockMaxNumberOfAttachments,
minNumberOfAttachments: mockMinNumberOfAttachments,
isValid: mockIsValid,
readOnly: mockReadOnly,
};
return render(
<Provider store={mockStore}>
<FileUploadComponent {...defaultProps} {...props}/>
</Provider>
);
}
}); | the_stack |
import { CacheContext } from '../context';
import { GraphSnapshot } from '../GraphSnapshot';
import { ParsedQuery, ParsedQueryNode } from '../ParsedQueryNode';
import { JsonObject, JsonValue, PathPart } from '../primitive';
import { NodeId, OperationInstance, RawOperation, StaticNodeId } from '../schema';
import { isNil, isObject, walkOperation, deepGet } from '../util';
import { nodeIdForParameterizedValue } from './SnapshotEditor';
export interface QueryResult {
/** The value of the root requested by a query. */
result?: JsonObject;
/** Whether the query's selection set was satisfied. */
complete: boolean;
/** The ids of entity nodes selected by the query. */
entityIds?: Set<NodeId>;
/** The ids of nodes overlaid on top of static cache results. */
dynamicNodeIds?: Set<NodeId>;
}
export interface QueryResultWithNodeIds extends QueryResult {
/** The ids of entity nodes selected by the query. */
entityIds: Set<NodeId>;
}
/**
* Get you some data.
*/
export function read(context: CacheContext, raw: RawOperation, snapshot: GraphSnapshot, includeNodeIds: true): QueryResultWithNodeIds;
export function read(context: CacheContext, raw: RawOperation, snapshot: GraphSnapshot, includeNodeIds?: boolean): QueryResult;
export function read(context: CacheContext, raw: RawOperation, snapshot: GraphSnapshot, includeNodeIds?: boolean) {
let tracerContext;
if (context.tracer.readStart) {
tracerContext = context.tracer.readStart(raw);
}
const operation = context.parseOperation(raw);
// Retrieve the previous result (may be partially complete), or start anew.
const queryResult = snapshot.readCache.get(operation) || {} as Partial<QueryResultWithNodeIds>;
snapshot.readCache.set(operation, queryResult as QueryResult);
let cacheHit = true;
if (!queryResult.result) {
cacheHit = false;
queryResult.result = snapshot.getNodeData(operation.rootId);
if (!operation.isStatic) {
const dynamicNodeIds = new Set<NodeId>();
queryResult.result = _walkAndOverlayDynamicValues(operation, context, snapshot, queryResult.result, dynamicNodeIds!);
queryResult.dynamicNodeIds = dynamicNodeIds;
}
queryResult.entityIds = includeNodeIds ? new Set<NodeId>() : undefined;
// When strict mode is disabled, we carry completeness forward for observed
// queries. Once complete, always complete.
if (typeof queryResult.complete !== 'boolean') {
queryResult.complete = _visitSelection(operation, context, queryResult.result, queryResult.entityIds);
}
}
// We can potentially ask for results without node ids first, and then follow
// up with an ask for them. In that case, we need to fill in the cache a bit
// more.
if (includeNodeIds && !queryResult.entityIds) {
cacheHit = false;
const entityIds = new Set<NodeId>();
const complete = _visitSelection(operation, context, queryResult.result, entityIds);
queryResult.complete = complete;
queryResult.entityIds = entityIds;
}
if (context.tracer.readEnd) {
const result = { result: queryResult as QueryResult, cacheHit };
context.tracer.readEnd(operation, result, tracerContext);
}
return queryResult;
}
class OverlayWalkNode {
constructor(
public readonly value: JsonObject,
public readonly containerId: NodeId,
public readonly parsedMap: ParsedQuery,
public readonly path: PathPart[],
) {}
}
/**
* Walks a parameterized field map, overlaying values at those paths on top of
* existing results.
*
* Overlaid values are objects with prototypes pointing to the original results,
* and new properties pointing to the parameterized values (or objects that
* contain them).
*/
export function _walkAndOverlayDynamicValues(
query: OperationInstance,
context: CacheContext,
snapshot: GraphSnapshot,
result: JsonObject | undefined,
dynamicNodeIds: Set<NodeId>,
): JsonObject | undefined {
// Corner case: We stop walking once we reach a parameterized field with no
// snapshot, but we should also preemptively stop walking if there are no
// dynamic values to be overlaid
const rootSnapshot = snapshot.getNodeSnapshot(query.rootId);
if (isNil(rootSnapshot)) return result;
// TODO: A better approach here might be to walk the outbound references from
// each node, rather than walking the result set. We'd have to store the path
// on parameterized value nodes to make that happen.
const newResult = _wrapValue(result, context) as JsonObject;
// TODO: This logic sucks. We'd do much better if we had knowledge of the
// schema. Can we layer that on in such a way that we can support uses w/ and
// w/o a schema compilation step?
const queue = [new OverlayWalkNode(newResult, query.rootId, query.parsedQuery, [])];
while (queue.length) {
const walkNode = queue.pop()!;
const { value, parsedMap } = walkNode;
let { containerId, path } = walkNode;
const valueId = context.entityIdForValue(value);
if (valueId) {
containerId = valueId;
path = [];
}
for (const key in parsedMap) {
const node = parsedMap[key];
let child;
let fieldName = key;
// This is an alias if we have a schemaName declared.
fieldName = node.schemaName ? node.schemaName : key;
let nextContainerId = containerId;
let nextPath = path;
if (node.args) {
let childId = nodeIdForParameterizedValue(containerId, [...path, fieldName], node.args);
let childSnapshot = snapshot.getNodeSnapshot(childId);
if (!childSnapshot) {
let typeName = value.__typename as string;
if (!typeName && containerId === StaticNodeId.QueryRoot) {
typeName = 'Query'; // Preserve the default cache's behavior.
}
// Should we fall back to a redirect?
const redirect: CacheContext.ResolverRedirect | undefined = deepGet(context.resolverRedirects, [typeName, fieldName]) as any;
if (redirect) {
childId = redirect(node.args);
if (!isNil(childId)) {
childSnapshot = snapshot.getNodeSnapshot(childId);
}
}
}
// Still no snapshot? Ok we're done here.
if (!childSnapshot) continue;
dynamicNodeIds.add(childId);
nextContainerId = childId;
nextPath = [];
child = childSnapshot.data;
} else {
nextPath = [...path, fieldName];
child = value[fieldName];
}
// Have we reached a leaf (either in the query, or in the cache)?
if (_shouldWalkChildren(child, node)) {
child = _recursivelyWrapValue(child, context);
const allChildValues = _flattenGraphQLObject(child, nextPath);
for (let i = 0; i < allChildValues.length; i++) {
const item = allChildValues[i];
queue.push(new OverlayWalkNode(item.value, nextContainerId, node.children ?? {}, item.path));
}
}
// Because key is already a field alias, result will be written correctly
// using alias as key.
value[key] = child as JsonValue;
}
}
return newResult;
}
/**
* Private: Represents the possible types of a GraphQL object.
*
* Since we are not using the schema when walking through the result and
* overlaying values, we do not know if a field represents an object, an array
* of objects, or a multidimensional array of objects. The query alone is
* ambiguous.
*/
type UnknownGraphQLObject = JsonObject | null | UnknownGraphQLObjectArray;
interface UnknownGraphQLObjectArray extends Array<UnknownGraphQLObject> {}
/**
* Check if `value` is an object and if any of its children are parameterized.
* We can skip this part of the graph if there are no parameterized children
* to resolve.
*/
function _shouldWalkChildren(
value: JsonValue | undefined,
node: ParsedQueryNode
): value is UnknownGraphQLObject {
return !!node.hasParameterizedChildren && !!node.children && value !== null;
}
/**
* Private: Represents and location and value of objects discovered while
* flattening the value of a graphql object field.
*/
type FlattenedGraphQLObject = { value: JsonObject, path: PathPart[] };
/**
* Finds all of the actual objects in `value` which can be a single object, an
* array of objects, or a multidimensional array of objects, and returns them
* as a flat list.
*/
function _flattenGraphQLObject(value: UnknownGraphQLObject, path: PathPart[]): FlattenedGraphQLObject[] {
if (value === null) return [];
if (!Array.isArray(value)) return [{ value, path }];
const flattened = [];
for (let i = 0; i < value.length; i++) {
const item = value[i];
const list = _flattenGraphQLObject(item, [...path, i]);
flattened.push(...list);
}
return flattened;
}
function _recursivelyWrapValue<T extends JsonValue>(value: T | undefined, context: CacheContext): T {
if (!Array.isArray(value)) {
return _wrapValue(value, context);
}
const newValue = [];
// Note that we're careful to iterate over all indexes, in case this is a
// sparse array.
for (let i = 0; i < value.length; i++) {
newValue[i] = _recursivelyWrapValue(value[i], context);
}
return newValue as T;
}
function _wrapValue<T extends JsonValue>(value: T | undefined, context: CacheContext): T {
if (value === undefined) {
return {} as T;
}
if (Array.isArray(value)) {
return [...value] as T;
}
if (isObject(value)) {
const newValue = { ...(value as any) };
if (context.entityTransformer && context.entityIdForValue(value)) {
context.entityTransformer(newValue);
}
return newValue;
}
return value;
}
/**
* Determines whether `result` satisfies the properties requested by
* `selection`.
*/
export function _visitSelection(
query: OperationInstance,
context: CacheContext,
result?: JsonObject,
nodeIds?: Set<NodeId>,
): boolean {
let complete = true;
if (nodeIds && result !== undefined) {
nodeIds.add(query.rootId);
}
// TODO: Memoize per query, and propagate through cache snapshots.
walkOperation(query.info.parsed, result, (value, fields) => {
if (value === undefined) {
complete = false;
}
// If we're not including node ids, we can stop the walk right here.
if (!complete) return !nodeIds;
if (!isObject(value)) return false;
if (nodeIds && isObject(value)) {
const nodeId = context.entityIdForValue(value);
if (nodeId !== undefined) {
nodeIds.add(nodeId);
}
}
for (const field of fields) {
if (!(field in value)) {
complete = false;
break;
}
}
return false;
});
return complete;
} | the_stack |
import { ITextModelContentProvider, ITextModelService } from 'vs/editor/common/services/resolverService';
import { URI } from 'vs/base/common/uri';
import { IModeService } from 'vs/editor/common/services/modeService';
import { IModelService } from 'vs/editor/common/services/modelService';
import { createTextBufferFactoryFromSnapshot } from 'vs/editor/common/model/textModel';
import { WorkspaceEditMetadata } from 'vs/editor/common/modes';
import { DisposableStore } from 'vs/base/common/lifecycle';
import { coalesceInPlace } from 'vs/base/common/arrays';
import { Range } from 'vs/editor/common/core/range';
import { EditOperation } from 'vs/editor/common/core/editOperation';
import { ServicesAccessor, IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IFileService } from 'vs/platform/files/common/files';
import { Emitter, Event } from 'vs/base/common/event';
import { IIdentifiedSingleEditOperation } from 'vs/editor/common/model';
import { ConflictDetector } from 'vs/workbench/contrib/bulkEdit/browser/conflicts';
import { ResourceMap } from 'vs/base/common/map';
import { localize } from 'vs/nls';
import { extUri } from 'vs/base/common/resources';
import { ResourceEdit, ResourceFileEdit, ResourceTextEdit } from 'vs/editor/browser/services/bulkEditService';
import { Codicon } from 'vs/base/common/codicons';
export class CheckedStates<T extends object> {
private readonly _states = new WeakMap<T, boolean>();
private _checkedCount: number = 0;
private readonly _onDidChange = new Emitter<T>();
readonly onDidChange: Event<T> = this._onDidChange.event;
dispose(): void {
this._onDidChange.dispose();
}
get checkedCount() {
return this._checkedCount;
}
isChecked(obj: T): boolean {
return this._states.get(obj) ?? false;
}
updateChecked(obj: T, value: boolean): void {
const valueNow = this._states.get(obj);
if (valueNow === value) {
return;
}
if (valueNow === undefined) {
if (value) {
this._checkedCount += 1;
}
} else {
if (value) {
this._checkedCount += 1;
} else {
this._checkedCount -= 1;
}
}
this._states.set(obj, value);
this._onDidChange.fire(obj);
}
}
export class BulkTextEdit {
constructor(
readonly parent: BulkFileOperation,
readonly textEdit: ResourceTextEdit
) { }
}
export const enum BulkFileOperationType {
TextEdit = 1,
Create = 2,
Delete = 4,
Rename = 8,
}
export class BulkFileOperation {
type: BulkFileOperationType = 0;
textEdits: BulkTextEdit[] = [];
originalEdits = new Map<number, ResourceTextEdit | ResourceFileEdit>();
newUri?: URI;
constructor(
readonly uri: URI,
readonly parent: BulkFileOperations
) { }
addEdit(index: number, type: BulkFileOperationType, edit: ResourceTextEdit | ResourceFileEdit) {
this.type |= type;
this.originalEdits.set(index, edit);
if (edit instanceof ResourceTextEdit) {
this.textEdits.push(new BulkTextEdit(this, edit));
} else if (type === BulkFileOperationType.Rename) {
this.newUri = edit.newResource;
}
}
needsConfirmation(): boolean {
for (let [, edit] of this.originalEdits) {
if (!this.parent.checked.isChecked(edit)) {
return true;
}
}
return false;
}
}
export class BulkCategory {
private static readonly _defaultMetadata = Object.freeze({
label: localize('default', "Other"),
icon: Codicon.symbolFile,
needsConfirmation: false
});
static keyOf(metadata?: WorkspaceEditMetadata) {
return metadata?.label || '<default>';
}
readonly operationByResource = new Map<string, BulkFileOperation>();
constructor(readonly metadata: WorkspaceEditMetadata = BulkCategory._defaultMetadata) { }
get fileOperations(): IterableIterator<BulkFileOperation> {
return this.operationByResource.values();
}
}
export class BulkFileOperations {
static async create(accessor: ServicesAccessor, bulkEdit: ResourceEdit[]): Promise<BulkFileOperations> {
const result = accessor.get(IInstantiationService).createInstance(BulkFileOperations, bulkEdit);
return await result._init();
}
readonly checked = new CheckedStates<ResourceEdit>();
readonly fileOperations: BulkFileOperation[] = [];
readonly categories: BulkCategory[] = [];
readonly conflicts: ConflictDetector;
constructor(
private readonly _bulkEdit: ResourceEdit[],
@IFileService private readonly _fileService: IFileService,
@IInstantiationService instaService: IInstantiationService,
) {
this.conflicts = instaService.createInstance(ConflictDetector, _bulkEdit);
}
dispose(): void {
this.checked.dispose();
this.conflicts.dispose();
}
async _init() {
const operationByResource = new Map<string, BulkFileOperation>();
const operationByCategory = new Map<string, BulkCategory>();
const newToOldUri = new ResourceMap<URI>();
for (let idx = 0; idx < this._bulkEdit.length; idx++) {
const edit = this._bulkEdit[idx];
let uri: URI;
let type: BulkFileOperationType;
// store inital checked state
this.checked.updateChecked(edit, !edit.metadata?.needsConfirmation);
if (edit instanceof ResourceTextEdit) {
type = BulkFileOperationType.TextEdit;
uri = edit.resource;
} else if (edit instanceof ResourceFileEdit) {
if (edit.newResource && edit.oldResource) {
type = BulkFileOperationType.Rename;
uri = edit.oldResource;
if (edit.options?.overwrite === undefined && edit.options?.ignoreIfExists && await this._fileService.exists(uri)) {
// noop -> "soft" rename to something that already exists
continue;
}
// map newResource onto oldResource so that text-edit appear for
// the same file element
newToOldUri.set(edit.newResource, uri);
} else if (edit.oldResource) {
type = BulkFileOperationType.Delete;
uri = edit.oldResource;
if (edit.options?.ignoreIfNotExists && !await this._fileService.exists(uri)) {
// noop -> "soft" delete something that doesn't exist
continue;
}
} else if (edit.newResource) {
type = BulkFileOperationType.Create;
uri = edit.newResource;
if (edit.options?.overwrite === undefined && edit.options?.ignoreIfExists && await this._fileService.exists(uri)) {
// noop -> "soft" create something that already exists
continue;
}
} else {
// invalid edit -> skip
continue;
}
} else {
// unsupported edit
continue;
}
const insert = (uri: URI, map: Map<string, BulkFileOperation>) => {
let key = extUri.getComparisonKey(uri, true);
let operation = map.get(key);
// rename
if (!operation && newToOldUri.has(uri)) {
uri = newToOldUri.get(uri)!;
key = extUri.getComparisonKey(uri, true);
operation = map.get(key);
}
if (!operation) {
operation = new BulkFileOperation(uri, this);
map.set(key, operation);
}
operation.addEdit(idx, type, edit);
};
insert(uri, operationByResource);
// insert into "this" category
let key = BulkCategory.keyOf(edit.metadata);
let category = operationByCategory.get(key);
if (!category) {
category = new BulkCategory(edit.metadata);
operationByCategory.set(key, category);
}
insert(uri, category.operationByResource);
}
operationByResource.forEach(value => this.fileOperations.push(value));
operationByCategory.forEach(value => this.categories.push(value));
// "correct" invalid parent-check child states that is
// unchecked file edits (rename, create, delete) uncheck
// all edits for a file, e.g no text change without rename
for (let file of this.fileOperations) {
if (file.type !== BulkFileOperationType.TextEdit) {
let checked = true;
for (const edit of file.originalEdits.values()) {
if (edit instanceof ResourceFileEdit) {
checked = checked && this.checked.isChecked(edit);
}
}
if (!checked) {
for (const edit of file.originalEdits.values()) {
this.checked.updateChecked(edit, checked);
}
}
}
}
// sort (once) categories atop which have unconfirmed edits
this.categories.sort((a, b) => {
if (a.metadata.needsConfirmation === b.metadata.needsConfirmation) {
return a.metadata.label.localeCompare(b.metadata.label);
} else if (a.metadata.needsConfirmation) {
return -1;
} else {
return 1;
}
});
return this;
}
getWorkspaceEdit(): ResourceEdit[] {
const result: ResourceEdit[] = [];
let allAccepted = true;
for (let i = 0; i < this._bulkEdit.length; i++) {
const edit = this._bulkEdit[i];
if (this.checked.isChecked(edit)) {
result[i] = edit;
continue;
}
allAccepted = false;
}
if (allAccepted) {
return this._bulkEdit;
}
// not all edits have been accepted
coalesceInPlace(result);
return result;
}
getFileEdits(uri: URI): IIdentifiedSingleEditOperation[] {
for (let file of this.fileOperations) {
if (file.uri.toString() === uri.toString()) {
const result: IIdentifiedSingleEditOperation[] = [];
let ignoreAll = false;
for (const edit of file.originalEdits.values()) {
if (edit instanceof ResourceTextEdit) {
if (this.checked.isChecked(edit)) {
result.push(EditOperation.replaceMove(Range.lift(edit.textEdit.range), edit.textEdit.text));
}
} else if (!this.checked.isChecked(edit)) {
// UNCHECKED WorkspaceFileEdit disables all text edits
ignoreAll = true;
}
}
if (ignoreAll) {
return [];
}
return result.sort((a, b) => Range.compareRangesUsingStarts(a.range, b.range));
}
}
return [];
}
getUriOfEdit(edit: ResourceEdit): URI {
for (let file of this.fileOperations) {
for (const value of file.originalEdits.values()) {
if (value === edit) {
return file.uri;
}
}
}
throw new Error('invalid edit');
}
}
export class BulkEditPreviewProvider implements ITextModelContentProvider {
static readonly Schema = 'vscode-bulkeditpreview';
static emptyPreview = URI.from({ scheme: BulkEditPreviewProvider.Schema, fragment: 'empty' });
static asPreviewUri(uri: URI): URI {
return URI.from({ scheme: BulkEditPreviewProvider.Schema, path: uri.path, query: uri.toString() });
}
static fromPreviewUri(uri: URI): URI {
return URI.parse(uri.query);
}
private readonly _disposables = new DisposableStore();
private readonly _ready: Promise<any>;
private readonly _modelPreviewEdits = new Map<string, IIdentifiedSingleEditOperation[]>();
constructor(
private readonly _operations: BulkFileOperations,
@IModeService private readonly _modeService: IModeService,
@IModelService private readonly _modelService: IModelService,
@ITextModelService private readonly _textModelResolverService: ITextModelService
) {
this._disposables.add(this._textModelResolverService.registerTextModelContentProvider(BulkEditPreviewProvider.Schema, this));
this._ready = this._init();
}
dispose(): void {
this._disposables.dispose();
}
private async _init() {
for (let operation of this._operations.fileOperations) {
await this._applyTextEditsToPreviewModel(operation.uri);
}
this._disposables.add(this._operations.checked.onDidChange(e => {
const uri = this._operations.getUriOfEdit(e);
this._applyTextEditsToPreviewModel(uri);
}));
}
private async _applyTextEditsToPreviewModel(uri: URI) {
const model = await this._getOrCreatePreviewModel(uri);
// undo edits that have been done before
let undoEdits = this._modelPreviewEdits.get(model.id);
if (undoEdits) {
model.applyEdits(undoEdits);
}
// apply new edits and keep (future) undo edits
const newEdits = this._operations.getFileEdits(uri);
const newUndoEdits = model.applyEdits(newEdits, true);
this._modelPreviewEdits.set(model.id, newUndoEdits);
}
private async _getOrCreatePreviewModel(uri: URI) {
const previewUri = BulkEditPreviewProvider.asPreviewUri(uri);
let model = this._modelService.getModel(previewUri);
if (!model) {
try {
// try: copy existing
const ref = await this._textModelResolverService.createModelReference(uri);
const sourceModel = ref.object.textEditorModel;
model = this._modelService.createModel(
createTextBufferFactoryFromSnapshot(sourceModel.createSnapshot()),
this._modeService.create(sourceModel.getLanguageIdentifier().language),
previewUri
);
ref.dispose();
} catch {
// create NEW model
model = this._modelService.createModel(
'',
this._modeService.createByFilepathOrFirstLine(previewUri),
previewUri
);
}
// this is a little weird but otherwise editors and other cusomers
// will dispose my models before they should be disposed...
// And all of this is off the eventloop to prevent endless recursion
new Promise(async () => this._disposables.add(await this._textModelResolverService.createModelReference(model!.uri)));
}
return model;
}
async provideTextContent(previewUri: URI) {
if (previewUri.toString() === BulkEditPreviewProvider.emptyPreview.toString()) {
return this._modelService.createModel('', null, previewUri);
}
await this._ready;
return this._modelService.getModel(previewUri);
}
} | the_stack |
import { flatten } from "../clientUtils/Util"
import { CoreColumnStore, Time, CoreValueType } from "./CoreTableConstants"
import { CoreColumnDef } from "./CoreColumnDef"
import {
ErrorValue,
ErrorValueTypes,
isNotErrorValue,
MissingValuePlaceholder,
ValueTooLow,
DivideByZeroError,
} from "./ErrorValues"
import { ColumnSlug } from "../clientUtils/owidTypes"
// In Grapher we return just the years for which we have values for. This puts MissingValuePlaceholder
// in the spots where we are missing values (added to make computing rolling windows easier).
// Takes an array of value/year pairs and expands it so that there is an undefined
// for each missing value from the first year to the last year, preserving the position of
// the existing values.
export const insertMissingValuePlaceholders = (
values: number[],
times: number[]
): (number | MissingValuePlaceholder)[] => {
const startTime = times[0]
const endTime = times[times.length - 1]
const filledRange = []
let time = startTime
const timeToValueIndex = new Map()
times.forEach((time, index) => {
timeToValueIndex.set(time, index)
})
while (time <= endTime) {
filledRange.push(
timeToValueIndex.has(time)
? values[timeToValueIndex.get(time)]
: ErrorValueTypes.MissingValuePlaceholder
)
time++
}
return filledRange
}
// todo: add the precision param to ensure no floating point effects
export function computeRollingAverage(
numbers: (number | undefined | null | ErrorValue)[],
windowSize: number,
align: "right" | "center" = "right"
): (number | ErrorValue)[] {
const result: (number | ErrorValue)[] = []
for (let valueIndex = 0; valueIndex < numbers.length; valueIndex++) {
// If a value is undefined in the original input, keep it undefined in the output
const currentVal = numbers[valueIndex]
if (currentVal === null) {
result[valueIndex] = ErrorValueTypes.NullButShouldBeNumber
continue
} else if (currentVal === undefined) {
result[valueIndex] = ErrorValueTypes.UndefinedButShouldBeNumber
continue
} else if (currentVal instanceof ErrorValue) {
result[valueIndex] = currentVal
continue
}
// Take away 1 for the current value (windowSize=1 means no smoothing & no expansion)
const expand = windowSize - 1
// With centered smoothing, expand uneven windows asymmetrically (ceil & floor) to ensure
// a correct number of window values get taken into account.
// Arbitrarily biased towards left (past).
const expandLeft = align === "center" ? Math.ceil(expand / 2) : expand
const expandRight = align === "center" ? Math.floor(expand / 2) : 0
const startIndex = Math.max(valueIndex - expandLeft, 0)
const endIndex = Math.min(valueIndex + expandRight, numbers.length - 1)
let count = 0
let sum = 0
for (
let windowIndex = startIndex;
windowIndex <= endIndex;
windowIndex++
) {
const value = numbers[windowIndex]
if (
value !== undefined &&
value !== null &&
!(value instanceof ErrorValue)
) {
sum += value!
count++
}
}
result[valueIndex] = sum / count
}
return result
}
// Assumptions: data is sorted by entity, then time
// todo: move tests over from CE
const timeSinceEntityExceededThreshold = (
columnStore: CoreColumnStore,
timeSlug: ColumnSlug,
entitySlug: ColumnSlug,
columnSlug: ColumnSlug,
thresholdAsString: string
): (number | ValueTooLow)[] => {
const threshold = parseFloat(thresholdAsString)
const groupValues = columnStore[entitySlug] as string[]
const columnValues = columnStore[columnSlug] as number[]
const timeValues = columnStore[timeSlug] as number[]
let currentGroup: string
let groupExceededThresholdAtTime: number
return columnValues.map((value, index) => {
const group = groupValues[index]
const currentTime = timeValues[index]
if (group !== currentGroup) {
if (!isNotErrorValue(value)) return value
if (value < threshold) return ErrorValueTypes.ValueTooLow
currentGroup = group
groupExceededThresholdAtTime = currentTime
}
return currentTime - groupExceededThresholdAtTime
})
}
// Assumptions: data is sorted by entity, then time
// todo: move tests over from CE
const rollingAverage = (
columnStore: CoreColumnStore,
timeSlug: ColumnSlug,
entitySlug: ColumnSlug,
columnSlug: ColumnSlug,
windowSize: number
): (number | ErrorValue)[] => {
const entityNames = columnStore[entitySlug] as string[]
const columnValues = columnStore[columnSlug] as number[]
const timeValues = columnStore[timeSlug] as number[]
const len = entityNames.length
if (!len) return []
let currentEntity = entityNames[0]
let currentValues: number[] = []
let currentTimes: Time[] = []
const groups: (number | ErrorValue)[][] = []
for (let rowIndex = 0; rowIndex <= len; rowIndex++) {
const entityName = entityNames[rowIndex]
const value = columnValues[rowIndex]
const time = timeValues[rowIndex]
if (currentEntity !== entityName) {
const averages = computeRollingAverage(
insertMissingValuePlaceholders(currentValues, currentTimes),
windowSize
).filter(
(value) => !(value === ErrorValueTypes.MissingValuePlaceholder)
) // filter the placeholders back out
groups.push(averages)
if (value === undefined) break // We iterate to <= so that we push the last row
currentValues = []
currentTimes = []
currentEntity = entityName
}
currentValues.push(value)
currentTimes.push(time)
}
return flatten(groups)
}
const divideBy = (
columnStore: CoreColumnStore,
numeratorSlug: ColumnSlug,
denominatorSlug: ColumnSlug
): (number | DivideByZeroError)[] => {
const numeratorValues = columnStore[numeratorSlug] as number[]
const denominatorValues = columnStore[denominatorSlug] as number[]
return denominatorValues.map((denominator, index) => {
if (denominator === 0) return ErrorValueTypes.DivideByZeroError
const numerator = numeratorValues[index]
if (!isNotErrorValue(numerator)) return numerator
if (!isNotErrorValue(denominator)) return denominator
return numerator / denominator
})
}
const multiplyBy = (
columnStore: CoreColumnStore,
columnSlug: ColumnSlug,
factor: number
) =>
columnStore[columnSlug].map((value) =>
isNotErrorValue(value) ? (value as number) * factor : value
)
const subtract = (
columnStore: CoreColumnStore,
columnSlugA: ColumnSlug,
columnSlugB: ColumnSlug
) => {
const values = columnStore[columnSlugA] as number[]
const subValues = columnStore[columnSlugB] as number[]
return subValues.map((subValue, index) => {
const value = values[index]
if (!isNotErrorValue(value)) return value
if (!isNotErrorValue(subValue)) return subValue
return value - subValue
})
}
enum WhereOperators {
is = "is",
isNot = "isNot",
isGreaterThan = "isGreaterThan",
isGreaterThanOrEqual = "isGreaterThanOrEqual",
isLessThan = "isLessThan",
isLessThanOrEqual = "isLessThanOrEqual",
}
// Todo: add tests/expand capabilities/remove?
// Currently this just supports `columnSlug where someColumnSlug (isNot|is) this or that or this`
const where = (
columnStore: CoreColumnStore,
columnSlug: ColumnSlug,
conditionSlug: ColumnSlug,
...condition: string[]
): CoreValueType[] => {
const values = columnStore[columnSlug]
const conditionValues = columnStore[conditionSlug]
const operator = condition.shift()
let passes = (value: any) => true
if (operator === WhereOperators.isNot || operator === WhereOperators.is) {
const result = operator === "isNot" ? false : true
const list = condition.join(" ").split(" or ")
const set = new Set(list)
passes = (value: any) => (set.has(value) ? result : !result)
} else if (operator === WhereOperators.isGreaterThan)
passes = (value: any) => value > parseFloat(condition.join(""))
else if (operator === WhereOperators.isGreaterThanOrEqual)
passes = (value: any) => value >= parseFloat(condition.join(""))
else if (operator === WhereOperators.isLessThan)
passes = (value: any) => value < parseFloat(condition.join(""))
else if (operator === WhereOperators.isLessThanOrEqual)
passes = (value: any) => value <= parseFloat(condition.join(""))
return values.map((value, index) =>
passes(conditionValues[index]) ? value : ErrorValueTypes.FilteredValue
)
}
// Assumptions: data is sorted by entity, then time, and time is a continous integer with a row for each time step.
// todo: move tests over from CE
const percentChange = (
columnStore: CoreColumnStore,
timeSlug: ColumnSlug,
entitySlug: ColumnSlug,
columnSlug: ColumnSlug,
windowSize: number
): (number | ErrorValue)[] => {
const entityNames = columnStore[entitySlug] as string[]
const columnValues = columnStore[columnSlug] as number[]
// If windowSize is 0 then there is zero change for every valid value
if (!windowSize)
return columnValues.map((val) => (isNotErrorValue(val) ? 0 : val))
let currentEntity: string
return columnValues.map((value: any, index) => {
const entity = entityNames[index]
const previousEntity = entityNames[index - windowSize] as any
const previousValue = columnValues[index - windowSize] as any
if (
!currentEntity ||
currentEntity !== entity ||
previousEntity !== entity
) {
currentEntity = entity
return ErrorValueTypes.NoValueToCompareAgainst
}
if (previousValue instanceof ErrorValue) return previousValue
if (value instanceof ErrorValue) return value
if (previousValue === 0) return ErrorValueTypes.DivideByZeroError
if (previousValue === undefined)
return ErrorValueTypes.NoValueToCompareAgainst
return (100 * (value - previousValue)) / previousValue
})
}
// Todo: remove?
const asPercentageOf = (
columnStore: CoreColumnStore,
numeratorSlug: ColumnSlug,
denominatorSlug: ColumnSlug
): (number | DivideByZeroError)[] =>
divideBy(columnStore, numeratorSlug, denominatorSlug).map((num) =>
typeof num === "number" ? 100 * num : num
)
const availableTransforms: any = {
asPercentageOf: asPercentageOf,
timeSinceEntityExceededThreshold: timeSinceEntityExceededThreshold,
divideBy: divideBy,
rollingAverage: rollingAverage,
percentChange: percentChange,
multiplyBy: multiplyBy,
subtract: subtract,
where: where,
} as const
export const AvailableTransforms = Object.keys(availableTransforms)
export const applyTransforms = (
columnStore: CoreColumnStore,
defs: CoreColumnDef[]
): CoreColumnStore => {
defs.forEach((def) => {
const words = def.transform!.split(" ")
const transformName = words.find(
(word) => availableTransforms[word] !== undefined
)
if (!transformName) {
console.warn(`Warning: transform '${transformName}' not found`)
return
}
const params = words.filter((word) => word !== transformName)
const fn = availableTransforms[transformName]
try {
columnStore[def.slug] = fn(columnStore, ...params)
} catch (err) {
console.error(
`Error performing transform '${def.transform}' for column '${
def.slug
}'. Expected args: ${fn.length}. Provided args: ${
1 + params.length
}. Ran as ${transformName}(columnStore, ${params
.map((param) => `"${param}"`)
.join(",")}).`
)
console.error(err)
}
})
return columnStore
} | the_stack |
'use strict';
import {EXPO_PROJECT_BRANCH, RN_PROJECT_BRANCH} from './const';
import {
TemplateType,
camelize,
exitIfNotDoobooRepo,
exitIfNotV5,
resolveComponent,
resolveTemplate,
upperCamelize,
} from '../utils/functions';
import {cbResultExpo, cbResultReact, cbResultReactNative} from './cb';
import boxen from 'boxen';
import chalk from 'chalk';
import ora from 'ora';
import fs = require('fs');
import inquirer = require('inquirer');
import os = require('os');
import selectShell = require('select-shell');
import shell = require('shelljs');
import path = require('path');
import commander = require('commander');
import updateNotifier = require('update-notifier');
import pkg = require('../package.json');
const welcome = `
_| _ _ |_ _ _ | _ |_
(_|(_)(_)|_)(_)(_)|(_||_)
`;
export enum TYPE_OF_APP {
REACT = 1,
REACT_NATIVE = 2,
EXPO = 3,
}
export enum TYPE_OF_RN_NAVIGATION {
BottomTabNavigator = 'BottomTabNavigator',
DrawerNavigator = 'DrawerNavigator',
MaterialBottomTabNavigator = 'MaterialBottomTabNavigator',
MaterialTopTabNavigator = 'MaterialTopTabNavigator',
NativeStackNavigator = 'NativeStackNavigator',
StackNavigator = 'StackNavigator',
}
export enum TYPE_OF_PROVIDER {
ReducerProvider = 'ReducerProvider',
StateProvider = 'StateProvider',
}
const program = new commander.Command();
const notifier = updateNotifier({
pkg,
updateCheckInterval: 1000 * 60 * 60 * 24, // 1 day
});
if (notifier.update) {
shell.echo(
chalk.blueBright(
boxen(`Update available: ${notifier.update.latest}`, {padding: 1}),
),
);
}
const list = selectShell({
pointer: ' โธ ',
pointerColor: 'yellow',
checked: ' โ ',
unchecked: ' โ ',
checkedColor: 'blue',
msgCancel: 'No selected options!',
msgCancelColor: 'orange',
multiSelect: false,
inverse: true,
prepend: true,
});
/**
* init
*/
program
.version(pkg.version)
.command('init')
.description('init boilerplate of dooboo generated app.')
.action(() => {
// sed -i 's/original/new/g' file.txt
// https://askubuntu.com/questions/20414/find-and-replace-text-within-a-file-using-commands
shell.echo(chalk.cyanBright(welcome));
shell.echo(
chalk.yellow('Select which app you want to generate from dooboo.'),
);
// const stream = process.stdin;
list
.option(' React App (typescript) ', TYPE_OF_APP.REACT)
.option(' React Native App (typescript) ', TYPE_OF_APP.REACT_NATIVE)
.option(' Expo App (typescript) ', TYPE_OF_APP.EXPO)
.list();
list.on('select', (options) => {
shell.echo(chalk.yellow('select the name of the app.'));
inquirer
.prompt([
{
name: 'value',
message: 'name of your app (alphaNumeric): ',
},
])
.then((answer) => {
const nameOfApp = answer.value;
if (!nameOfApp) {
shell.echo(chalk.redBright('please provide name of your app.'));
process.exit(0);
} else if (!/^[a-z0-9]+$/i.test(nameOfApp)) {
shell.echo(chalk.redBright('app name should be alphaNumeric.'));
process.exit(0);
}
let template = '';
switch (options[0].value) {
case TYPE_OF_APP.REACT:
template =
'-b master https://github.com/dooboolab/dooboo-frontend-ts.git';
break;
case TYPE_OF_APP.REACT_NATIVE:
template = `-b ${RN_PROJECT_BRANCH} https://github.com/dooboolab/dooboo-native-ts.git`;
break;
case TYPE_OF_APP.EXPO:
template = `-b ${EXPO_PROJECT_BRANCH} https://github.com/dooboolab/dooboo-expo.git`;
break;
}
if (!template) {
shell.echo(
chalk.redBright(
'There is no template for current choice. Please try again.',
),
);
process.exit(0);
}
const spinner = ora('creating app ' + nameOfApp + '...\n');
spinner.start();
if (options[0].value === TYPE_OF_APP.REACT_NATIVE) {
if (!shell.which('npx')) {
shell.echo(
chalk.redBright(
'Sorry, this script requires npx to be installed.',
),
);
shell.exit(1);
}
if (!shell.which('git')) {
shell.echo(
chalk.redBright(
'Sorry, this script requires git to be installed.',
),
);
shell.exit(1);
}
if (!shell.which('yarn')) {
shell.echo(
chalk.redBright(
'Sorry, this script requires yarn to be installed.',
),
);
shell.exit(1);
}
if (os.type() === 'Darwin') {
if (!shell.which('pod')) {
shell.echo(
chalk.redBright(
`Sorry, this script requires cocoapod to be installed.
Are you on mac OS (darwin)?`,
),
);
shell.exit(1);
}
}
cbResultReactNative(template, nameOfApp, answer, options, spinner);
} else if (options[0].value === TYPE_OF_APP.EXPO) {
cbResultExpo(template, nameOfApp, answer, options, spinner);
} else {
cbResultReact(template, nameOfApp, answer, options, spinner);
}
});
});
list.on('cancel', (options: string) => {
shell.echo(
`Operation has been canceled, ${options.length} option was selected.`,
);
process.exit(0);
});
});
program
.command('start')
.description('start the project.')
.action(async () => {
const spinner = ora('configuring project...\n');
spinner.start();
try {
let exists = fs.existsSync('.dooboo');
if (!exists) {
shell.echo(
chalk.redBright(
'\nproject is not in dooboo repository. Are you sure you are in correct dir?',
),
);
spinner.stop();
process.exit(0);
}
exists = fs.existsSync('node_modules');
if (!exists) {
shell.echo(chalk.cyanBright('installing dependencies...'));
// childProcess.execSync(`yarn`, {stdio: 'inherit'})
shell.exec('yarn', (code) => {
if (code === 0) {
shell.echo(chalk.cyanBright('running project...\n'));
shell.exec('yarn run dev');
// childProcess.execSync(`yarn run dev`, {stdio: 'inherit'});
return;
}
shell.echo(
chalk.redBright(
'failed installing dependencies. Please try again with yarn.',
),
);
});
return;
}
shell.echo(chalk.cyanBright('running project...'));
// shell.exec(`yarn start`);
shell.exec('yarn run dev');
// childProcess.execFileSync('yarn', ['start'], {stdio: 'inherit'});
} catch (err) {
shell.echo(chalk.red(err));
shell.echo(
chalk.redBright(
'failed installing dependencies. Please try again with yarn.',
),
);
} finally {
spinner.stop();
process.exit(0);
}
});
program
.command('test')
.description('run test for your project.')
.action(async () => {
const spinner = ora('configuring project...');
spinner.start();
exitIfNotDoobooRepo();
shell.echo(chalk.cyanBright('\nchecking packages...'));
const exists = fs.existsSync('node_modules');
if (!exists) {
shell.echo(chalk.cyanBright('installing dependencies...'));
shell.exec('yarn', (code) => {
if (code === 0) {
shell.echo(chalk.cyanBright('running project...'));
shell.exec('yarn test');
spinner.stop();
// process.exit(0);
return;
}
shell.echo(
chalk.redBright(
'failed installing dependencies. Please try again with yarn.',
),
);
});
return;
}
shell.echo(chalk.cyanBright('testing project...'));
// shell.exec(`yarn start`);
shell.exec('yarn test');
spinner.stop();
// process.exit(0);
});
program
.command('navigation <c>')
.description('generate navigation component.')
.action(async (c) => {
exitIfNotDoobooRepo();
const upperCamel = upperCamelize(c); // file name is upperCamelCase.
const component = resolveComponent('navigation', upperCamel);
let exists = fs.existsSync(component.file);
if (exists) {
shell.echo(
chalk.redBright(
`${upperCamel} navigation already exists. Delete or rename existing component first.`,
),
);
process.exit(0);
}
exists = fs.existsSync('.dooboo/react');
if (exists) {
const template = resolveTemplate(
'react',
'navigation',
'SwitchNavigator',
);
shell.echo(chalk.cyanBright('creating navigation component...'));
shell.cp(template.file, component.file);
shell.cp(template.testFile, component.testFile);
shell.sed('-i', 'SwitchNavigator', `${upperCamel}`, component.testFile);
shell.sed(
'-i',
'../SwithNavigator',
`../${upperCamel}`,
component.testFile,
);
shell.echo(
chalk.green(
`generated: ${component.file}${'\n'}testFile: ${component.testFile}`,
),
);
process.exit(0);
}
exists = fs.existsSync('.dooboo/react-native');
if (exists) {
list
.option(
' BottomTabNavigator ',
TYPE_OF_RN_NAVIGATION.BottomTabNavigator,
)
.option(' DrawerNavigator ', TYPE_OF_RN_NAVIGATION.DrawerNavigator)
.option(
' MaterialBottomTabNavigator ',
TYPE_OF_RN_NAVIGATION.MaterialBottomTabNavigator,
)
.option(
' MaterialTopTabNavigator ',
TYPE_OF_RN_NAVIGATION.MaterialTopTabNavigator,
)
.option(
' NativeStackNavigator ',
TYPE_OF_RN_NAVIGATION.NativeStackNavigator,
)
.option(' StackNavigator ', TYPE_OF_RN_NAVIGATION.StackNavigator)
.list();
let template: TemplateType;
list.on('select', (options) => {
const navigationType = options[0].value;
template = resolveTemplate(
'react-native',
'navigation',
navigationType,
);
shell.echo(chalk.cyanBright('creating navigation component...'));
shell.cp(template.file, component.file);
shell.cp(template.testFile, component.testFile);
shell.echo(
chalk.green(
`generated: ${component.file}${'\n'}testFile: ${
component.testFile
}`,
),
);
process.exit(0);
});
}
});
program
.command('page <c>')
.description('generate page (aka screen) component.')
.action(async (c) => {
exitIfNotDoobooRepo();
// const camel = camelize(c); // inside component is camelCase.
const upperCamel = upperCamelize(c); // file name is upperCamelCase.
// const isTypescript = await fsExists('.dooboo/typescript');
// const fileExt = isTypescript ? 'tsx' : 'js';
const fileExt = 'tsx';
const component = resolveComponent('page', upperCamel, fileExt);
let exists = fs.existsSync(component.file);
if (exists) {
shell.echo(
chalk.redBright(
`${upperCamel} page already exists. Delete or rename existing component first.`,
),
);
process.exit(0);
}
exists = fs.existsSync('.dooboo/react');
if (exists) {
const template = resolveTemplate('react', 'page', 'Page');
shell.echo(chalk.cyanBright('creating page component...'));
shell.cp(template.file, component.file);
shell.cp(template.testFile, component.testFile);
shell.sed('-i', 'Page', `${upperCamel}`, component.file);
shell.sed('-i', '../Page', `'../${upperCamel}`, component.testFile);
shell.echo(
chalk.green(
`generated: ${component.file}${'\n'}testFile: ${component.testFile}`,
),
);
process.exit(0);
}
/**
* Below is the case where the templates are different between
* expo and react-native project.
*
* This should be checked beforehand if there is differences
* since react-native overlaps all conditions.
*/
exists = fs.existsSync('.dooboo/expo');
if (exists) {
exitIfNotV5();
const template = resolveTemplate('react-native-expo', 'page', 'Page');
shell.echo(chalk.cyanBright('creating page component...'));
shell.cp(template.file, component.file);
shell.cp(template.testFile, component.testFile);
shell.sed('-i', 'Page', `${upperCamel}`, component.file);
shell.sed('-i', '../Page', `'../${upperCamel}`, component.testFile);
shell.echo(
chalk.green(
`generated: ${component.file}${'\n'}testFile: ${component.testFile}`,
),
);
process.exit(0);
}
exists = fs.existsSync('.dooboo/react-native');
if (exists) {
exitIfNotV5();
const template = resolveTemplate('react-native', 'page', 'Page');
shell.echo(chalk.cyanBright('creating page component...'));
shell.cp(template.file, component.file);
shell.cp(template.testFile, component.testFile);
shell.sed('-i', 'Page', `${upperCamel}`, component.file);
shell.sed('-i', '../Page', `'../${upperCamel}`, component.testFile);
shell.echo(
chalk.green(
`generated: ${component.file}${'\n'}testFile: ${component.testFile}`,
),
);
process.exit(0);
}
shell.echo(
chalk.redBright(
`\nproject is not under dooboo repository.
If you deleted any of file in .dooboo, you are not able to use dooboo-cli.`,
),
);
process.exit(0);
});
program
.command('ui <c>')
.description('generate ui component.')
.action(async (c) => {
exitIfNotDoobooRepo();
// const camel = camelize(c); // inside component is camelCase.
const upperCamel = upperCamelize(c); // file name is upperCamelCase.
// const isTypescript = await fsExists('.dooboo/typescript');
// const fileExt = isTypescript ? 'tsx' : 'js';
const component = resolveComponent('ui', upperCamel);
let exists = fs.existsSync(component.file);
if (exists) {
shell.echo(
chalk.redBright(
`${upperCamel} template already exists. Delete or rename existing component first.`,
),
);
process.exit(0);
}
exists = fs.existsSync('.dooboo/react');
if (exists) {
const template = resolveTemplate('react', 'template', 'Template');
shell.echo(chalk.cyanBright('creating template component...'));
shell.cp(template.file, component.file);
shell.cp(template.testFile, component.testFile);
shell.sed('-i', 'Template', `${upperCamel}`, component.file);
shell.sed('-i', '../Template', `'../${upperCamel}`, component.testFile);
shell.echo(
chalk.green(
`generated: ${component.file}${'\n'}testFile: ${component.testFile}`,
),
);
process.exit(0);
}
exists = fs.existsSync('.dooboo/react-native');
if (exists) {
const template = resolveTemplate('react-native', 'template', 'Template');
shell.echo(chalk.cyanBright('creating template component...'));
shell.cp(template.file, component.file);
shell.cp(template.testFile, component.testFile);
shell.sed('-i', 'Template', `${upperCamel}`, component.file);
shell.sed('-i', '../Template', `'../${upperCamel}`, component.testFile);
shell.echo(
chalk.green(
`generated: ${component.file}${'\n'}testFile: ${component.testFile}`,
),
);
process.exit(0);
}
shell.echo(
chalk.redBright(
`\nproject is not in dooboo repository.
If you deleted any of file in .dooboo, you are not able to use dooboo-cli.`,
),
);
process.exit(0);
});
program
.command('api <c>')
.description('generate file for api call format.')
.action(async (c) => {
exitIfNotDoobooRepo();
const isTypescript = fs.existsSync('.dooboo/typescript');
const fileExt = isTypescript ? 'tsx' : 'js';
const camel = camelize(c);
const upperCamel = upperCamelize(c);
const apiFile = `./src/apis/${camel}.${fileExt}`;
const exists = fs.existsSync(apiFile);
if (exists) {
shell.echo(
chalk.redBright(
`${upperCamel} store already exists. Delete or rename existing file first.`,
),
);
process.exit(0);
}
const template = path.resolve(
__dirname,
'..',
`templates/common/Api.${fileExt}`,
);
shell.cp(template, apiFile);
shell.echo(chalk.cyanBright('creating api file...'));
shell.echo(chalk.green(`generated: src/apis/${camel}.${fileExt}`));
process.exit(0);
});
program
.command('provider <c>')
.description('generate provider file to use context api.')
.action(async (c) => {
exitIfNotDoobooRepo();
const upperCamel = upperCamelize(c);
const providerFile = `./src/providers/${upperCamel}.tsx`;
const providerTestFile = `./src/providers/__tests__/${upperCamel}.test.tsx`;
const exists = fs.existsSync(providerFile);
if (exists) {
shell.echo(
chalk.redBright(
`${upperCamel} store already exists. Delete or rename existing file first.`,
),
);
process.exit(0);
}
list
.option(' Provider (Reducer Type) ', TYPE_OF_PROVIDER.ReducerProvider)
.option(' Provider (State Type) ', TYPE_OF_PROVIDER.StateProvider)
.list();
list.on('select', (options) => {
const providerType = options[0].value;
const template = path.resolve(
__dirname,
'..',
`templates/common/providers/${providerType}.tsx`,
);
const testTemplate = path.resolve(
__dirname,
'..',
`templates/common/providers/${providerType}.test.tsx`,
);
shell.cp(template, providerFile);
shell.cp(testTemplate, providerTestFile);
shell.sed('-i', providerType, `${upperCamel}`, providerFile);
shell.sed('-i', `${providerType}`, `${upperCamel}`, providerTestFile);
shell.sed(
'-i',
`../${providerType}`,
`../${upperCamel}`,
providerTestFile,
);
shell.echo(chalk.cyanBright('creating provider file...'));
shell.echo(
chalk.green(
`generated: ${providerFile}${'\n'}testFile: ${providerTestFile}`,
),
);
process.exit(0);
});
});
program.parse(process.argv);
let validCommands = program.commands.map((cmd) => {
return cmd.name;
});
if (validCommands.length && process.argv[2]) {
switch (process.argv[2]) {
case 'init':
case 'start':
case 'test':
case 'navigation':
case 'page':
case 'template':
case 'provider':
case 'api':
break;
default:
validCommands = program.commands.map((cmd) => {
return cmd.name;
});
shell.echo(
`\n [ERROR] - Invalid command:
"%s". See "-h or --help" for a list of available commands.\n`,
);
break;
}
}
// program.parse([process.argv[0], process.argv[1], '-h']); | the_stack |
import {
ColumnDescription,
DataType,
RelationDescription,
RelationType,
} from "../model.ts";
import type { DatabaseResult, DatabaseValues } from "../adapters/adapter.ts";
import { Reflect } from "../utils/reflect.ts";
import { metadata } from "../constants.ts";
// --------------------------------------------------------------------------------
// INTERFACES
// --------------------------------------------------------------------------------
/** Model values from the query result */
interface ModelValues {
[key: string]: DatabaseValues | ModelValues | ModelValues[];
}
/** Model values which can be sent to the database to insert or update */
interface ModelDatabaseValues {
[key: string]: DatabaseValues;
}
/** The result of comparing the current model with its original value. */
interface ModelComparisonResult {
isDirty: boolean;
diff: ModelDatabaseValues;
}
// --------------------------------------------------------------------------------
// MODEL INFORMATION
// --------------------------------------------------------------------------------
/**
* Get the table name from a model.
*
* @param modelClass the model class you want to get the information from.
*/
export function getTableName(modelClass: Function): string {
const tableName = Reflect.getMetadata(metadata.tableName, modelClass);
if (!tableName) {
throw new Error(
`Class '${modelClass.name}' must be wrapped with @Model decorator!`,
);
}
return tableName;
}
/**
* Get all column definitions from a model.
*
* @param modelClass the model class you want to get the information from.
*/
export function getColumns(modelClass: Function): ColumnDescription[] {
const columns: ColumnDescription[] = Reflect.getMetadata(
metadata.columns,
modelClass.prototype,
);
if (!columns) {
throw new Error(
`Model '${modelClass.name}' must have at least one column!`,
);
}
return columns;
}
/**
* Find a single column information from a model. This can be used to
* get `select: false` column which you cannot get from `getColumns`
* by default.
*
* @param modelClass the model class you want to get the information from.
* @param propertyName the column property key
*/
export function findColumn(
modelClass: Function,
propertyName: string,
): ColumnDescription | undefined {
return getColumns(modelClass)
.find((item) => item.propertyKey === propertyName);
}
/**
* Get all relationship definitions from a model.
*
* @param modelClass the model class you want to get the information from.
* @param includes include several relations and ignore the rest.
*/
export function getRelations(
modelClass: Function,
includes?: string[],
): RelationDescription[] {
const relations: RelationDescription[] =
Reflect.hasMetadata(metadata.relations, modelClass.prototype)
? Reflect.getMetadata(metadata.relations, modelClass.prototype)
: [];
return includes
? relations.filter((item) => includes.includes(item.propertyKey))
: relations;
}
/**
* Get the primary key column information from a model.
*
* @param modelClass the model class you want to get the information from.
*/
export function getPrimaryKeyInfo(modelClass: Function): ColumnDescription {
const primaryKey = getColumns(modelClass)
.find((item) => item.isPrimaryKey);
if (!primaryKey) {
throw new Error(`Model '${modelClass.name}' must have a primary key!`);
}
return primaryKey;
}
// --------------------------------------------------------------------------------
// MODEL STATE
// --------------------------------------------------------------------------------
/** Map of models' original values */
const originalValues = new WeakMap<Object, ModelValues>();
/** Map of models' `isSaved` status */
const isSavedValues = new WeakMap<Object, boolean>();
/**
* Check wether this model is saved to the database.
*
* @param model the model you want to check the status of
*/
export function isSaved(model: Object): boolean {
return isSavedValues.get(model) ? true : false;
}
/**
* Update the `isSaved` status of a model, save the original value,
* and populate model with default values.
*
* @param model the model you want to change the status of
* @param value the status of the model (saved or not saved)
*/
export function setSaved(model: Object, value: boolean) {
isSavedValues.set(model, value);
if (value) {
const values = getValues(model);
originalValues.set(model, values);
Object.assign(
model,
mapValueProperties(model.constructor, values, "propertyKey"),
);
} else {
originalValues.delete(model);
}
}
/**
* Update the `isSaved` status of a model and save the original value.
*
* @param model the model you want to change the status of
* @param value the status of the model (saved or not saved)
*/
export function getOriginal(model: Object): ModelValues | undefined {
return originalValues.get(model);
}
/**
* Compare the current values against the last saved data
*
* @param model the model you want to compare
*/
export function compareWithOriginal(model: Object): ModelComparisonResult {
const originalValue = getOriginal(model);
// If there's is no original value, the object is not saved to the database yet
// which means it's dirty.
if (!originalValue) {
return { isDirty: true, diff: {} };
}
let isDirty = false;
const diff: ModelDatabaseValues = {};
// Loop for the fields, if one of the fields doesn't match, the object is dirty
for (const column of getColumns(model.constructor)) {
const value = (model as any)[column.propertyKey];
if (value !== originalValue[column.name]) {
isDirty = true;
diff[column.name] = getNormalizedValue(column.type, value);
}
}
return { isDirty, diff };
}
/**
* Get model values as a plain JavaScript object
*
* @param model the model you want to get the values from
*/
export function getValues(model: Object): ModelDatabaseValues {
// If the `columns` parameter is provided, return only the selected columns
const columns = getColumns(model.constructor)
.filter((item) => item.isPrimaryKey && !isSaved(model) ? false : true);
// Hold the data temporarily
const data: { [key: string]: DatabaseValues } = {};
// Loop through the columns
for (const column of columns) {
const value = (model as any)[column.propertyKey];
// If one of the selected columns is the primary key, the record needs to be saved first.
if (column.isPrimaryKey) {
if (isSaved(model)) {
data[column.name] = value as number;
}
} else {
if (typeof value === "undefined") {
// If the value is undefined, check the default value. Otherwise, set it to null.
if (typeof column.default !== "undefined") {
// If the default value is a function, execute it and get the returned value
const defaultValue = typeof column.default === "function"
? column.default()
: column.default;
data[column.name] = getNormalizedValue(column.type, defaultValue);
} else {
data[column.name] = null;
}
} else {
data[column.name] = getNormalizedValue(
column.type,
(model as any)[column.propertyKey],
);
}
}
}
return data;
}
/**
* Get relational values in a model.
*
* @param model the model object you want to check the relations
* @param relations include specific relation names and ignore the rest
*/
export function getRelationValues(model: Object, relations?: string[]) {
const data: {
description: RelationDescription;
value: number | number[];
}[] = [];
for (const relation of getRelations(model.constructor, relations)) {
const relationData = (model as any)[relation.propertyKey];
// Add belongs to relationships to `data`
if (
relation.type === RelationType.BelongsTo &&
relationData &&
relationData instanceof relation.getModel()
) {
// If the target record is not saved yet, throw an error.
if (!isSaved(relationData)) {
throw new Error(
`Unsaved relationships found when trying to insert '${model.constructor.name}' model!`,
);
}
// Get the primary key propertyKey of the related model
const relationIdProperty =
getPrimaryKeyInfo(relation.getModel()).propertyKey;
data.push({
description: relation,
value: relationData[relationIdProperty],
});
}
// Add has many relationships to `data`
if (
relation.type === RelationType.HasMany &&
Array.isArray(relationData) &&
relationData.length >= 1
) {
// Get the primary key propertyKey of the related model
const relationIdProperty =
getPrimaryKeyInfo(relation.getModel()).propertyKey;
// Get all relationships primary key, if one of those isn't saved yet, throw an error.
const value = relationData.map((item) => {
if (!isSaved(item)) {
throw new Error(
`Unsaved relationships found when trying to insert '${model.constructor.name}' model!`,
);
}
return item[relationIdProperty];
});
data.push({ description: relation, value });
}
}
return data;
}
/**
* Map values from `getValues` to be compatible with model properties vice versa.
*
* @param modelClass the model class of those values.
* @param values the model values.
* @param to the property naming convention you want to convert.
*/
export function mapValueProperties(
modelClass: Function,
values: ModelDatabaseValues,
to: "propertyKey" | "name",
): ModelDatabaseValues {
const data: ModelDatabaseValues = {};
const columns = getColumns(modelClass);
for (const key in values) {
const column = columns
.find((item) => item[to === "name" ? "propertyKey" : "name"] === key);
if (column) {
data[column[to]] = values[key];
}
}
return data;
}
// --------------------------------------------------------------------------------
// HELPERS
// --------------------------------------------------------------------------------
/**
* Get data type from type metadata.
*
* @param type the design:type value from `Reflect.getMetadata`
*/
export function getDataType(type: any): DataType | null {
if (type === String) {
return DataType.String;
} else if (type === Number) {
return DataType.Number;
} else if (type === Date) {
return DataType.Date;
} else if (type === Boolean) {
return DataType.Boolean;
} else {
return null;
}
}
/**
* Normalize value to a database compatible values.
*
* @param type the data type of the column
* @param original the original data
* @param throws define whether this should throw an error if the value type isn't as expected.
*/
export function getNormalizedValue(
type: DataType,
original: DatabaseValues,
): DatabaseValues {
// If the original value is either null or undefined, return null.
if (typeof original === "undefined" || original === null) {
return null;
}
// If the expected type is Date, and the original value is string or number,
// convert it to Date object.
if (
type === DataType.Date &&
(typeof original === "string" || typeof original === "number")
) {
return new Date(original);
}
// If the expected type is String, and the original value doesn't,
// convert it to String.
if (type === DataType.String && typeof original !== "string") {
return String(original);
}
// Do the same thing for numbers.
if (type === DataType.Number && typeof original !== "number") {
const num = Number(original);
if (isNaN(num)) {
throw new Error(
`Found NaN when converting '${typeof original}' to number!`,
);
}
return Number(original);
}
// If the expected type is Boolean, and the original value doesn't,
// convert it to either true if it's truthy (like 1) and false if
// it's falsy (like 0).
if (type === DataType.Boolean && typeof original !== "boolean") {
return Boolean(original);
}
return original;
}
// --------------------------------------------------------------------------------
// EXTRACT DATA FROM QUERY RESUT
// --------------------------------------------------------------------------------
/**
* Map the query builder result for creating a model.
*/
export function mapQueryResult(
modelClass: Function,
result: DatabaseResult[],
includes?: string[],
): ModelValues[] {
const relations = includes ? getRelations(modelClass, includes) : [];
const primaryKey = getPrimaryKeyInfo(modelClass);
return result.reduce<ModelValues[]>((prev, next) => {
if (
prev.length !== 0 &&
prev[prev.length - 1][primaryKey.propertyKey] ===
next[getTableName(modelClass) + "__" + primaryKey.name]
) {
for (const relation of relations) {
if (relation.type === RelationType.HasMany) {
const data = mapSingleQueryResult(
relation.getModel(),
next,
);
const previousData: ModelValues[] =
prev[prev.length - 1][relation.propertyKey] as ModelValues[];
if (Array.isArray(previousData)) {
prev[prev.length - 1][relation.propertyKey] = previousData
.concat([data]);
} else {
prev[prev.length - 1][relation.propertyKey] = [data];
}
}
}
} else {
const data = mapSingleQueryResult(modelClass, next);
for (const relation of relations) {
const tableName = getTableName(relation.getModel());
const relationPrimaryKey = getPrimaryKeyInfo(relation.getModel()).name;
if (relation.type === RelationType.HasMany) {
if (next[tableName + "__" + relationPrimaryKey] === null) {
data[relation.propertyKey] = [];
} else {
data[relation.propertyKey] = [
mapSingleQueryResult(relation.getModel(), next),
];
}
} else if (relation.type === RelationType.BelongsTo) {
if (next[tableName + "__" + relationPrimaryKey] === null) {
data[relation.propertyKey] = null;
} else {
data[relation.propertyKey] = mapSingleQueryResult(
relation.getModel(),
next,
);
}
}
}
prev.push(data);
}
return prev;
}, []);
}
/**
* Map a single record from the query builder result for creating a model.
*/
export function mapSingleQueryResult(
modelClass: Function,
result: DatabaseResult,
): ModelValues {
const values: ModelValues = {};
const tableName = getTableName(modelClass);
const columns = getColumns(modelClass);
for (const column in result) {
if (column.startsWith(tableName + "__")) {
const columnName = column.slice(tableName.length + 2);
const propertyKey = columns.find((item) => item.name === columnName)
?.propertyKey;
if (propertyKey) {
values[propertyKey] = result[column];
}
}
}
return values;
}
// --------------------------------------------------------------------------------
// CREATE MODEL
// --------------------------------------------------------------------------------
/**
* Transform single plain JavaScript object to Model class.
*
* @param modelClass The model class which all the data will be transformed into
* @param data A plain JavaScript object that holds the model data
* @param fromDatabase Check whether the data is saved to the database or not
*/
export function createModel<T>(
modelClass: { new (): T },
data: ModelValues,
fromDatabase: boolean = false,
): T {
const values: { [key: string]: DatabaseValues | Object | Object[] } = {};
for (const column of getColumns(modelClass)) {
const value = data[column.propertyKey];
// If one of the selected columns is the primary key, the record needs to be saved first.
if (column.isPrimaryKey) {
if (fromDatabase) {
values[column.propertyKey] = value as number;
}
} else {
if (value === undefined) {
// If the value is undefined, check the default value.
if (typeof column.default !== "undefined") {
// If the default value is a function, execute it and get the returned value
const defaultValue = typeof column.default === "function"
? column.default()
: column.default;
values[column.propertyKey] = getNormalizedValue(
column.type,
defaultValue,
);
}
} else {
values[column.propertyKey] = getNormalizedValue(
column.type,
value as DatabaseValues,
);
}
}
}
for (const relation of getRelations(modelClass)) {
const relationModel = relation.getModel();
const relationData = data[relation.propertyKey] as ModelValues;
if (relation.type === RelationType.BelongsTo) {
if (relationData) {
values[relation.propertyKey] = createModel(
relationModel,
relationData,
fromDatabase,
);
}
} else if (relation.type === RelationType.HasMany) {
if (Array.isArray(relationData)) {
if (relationData.length >= 1) {
values[relation.propertyKey] = createModels(
relationModel,
relationData,
fromDatabase,
);
} else {
values[relation.propertyKey] = [];
}
}
}
}
// Create the model object
const model = Object.assign(Object.create(modelClass.prototype), values);
// Set the isSaved value
if (fromDatabase) {
setSaved(model, true);
}
return model;
}
/**
* Transform an array of plain JavaScript objects to multiple Model classes.
*
* @param modelClass The model class which all the data will be transformed into
* @param data A plain JavaScript object that holds the model data
*/
export function createModels<T>(
modelClass: { new (): T },
data: ModelValues[],
fromDatabase: boolean = false,
): T[] {
return data.map((item) => createModel(modelClass, item, fromDatabase));
} | the_stack |
import { IQueryInfo, Permission, AccessControlError } from '../core';
import { Action, Possession } from '../enums';
import { utils } from '../utils';
/**
* Represents the inner `Query` class that helps build an access information
* for querying and checking permissions, from the underlying grants model.
* You can get a first instance of this class by calling
* `AccessControl#can(<role>)` method.
* @class
* @inner
* @memberof AccessControl
*/
class Query {
/**
* Inner `IQueryInfo` object.
* @protected
* @type {IQueryInfo}
*/
protected _: IQueryInfo = {};
/**
* Main grants object.
* @protected
* @type {Any}
*/
protected _grants: any;
/**
* Initializes a new instance of `Query`.
* @private
*
* @param {Any} grants
* Underlying grants model against which the permissions will be
* queried and checked.
* @param {string|Array<String>|IQueryInfo} [roleOrInfo]
* Either a single or array of roles or an
* {@link ?api=ac#AccessControl~IQueryInfo|`IQueryInfo` arbitrary object}.
*/
constructor(grants: any, roleOrInfo?: string | string[] | IQueryInfo) {
this._grants = grants;
if (typeof roleOrInfo === 'string' || Array.isArray(roleOrInfo)) {
// if this is just role(s); a string or array; we start building
// the grant object for this.
this.role(roleOrInfo);
} else if (utils.type(roleOrInfo) === 'object') {
// if this is a (permission) object, we directly build attributes
// from grants.
if (Object.keys(roleOrInfo).length === 0) {
throw new AccessControlError('Invalid IQueryInfo: {}');
}
this._ = roleOrInfo as IQueryInfo;
} else if (roleOrInfo !== undefined) {
// undefined is allowed (`role` can be omitted) but throw if some
// other type is passed.
throw new AccessControlError('Invalid role(s), expected a valid string, string[] or IQueryInfo.');
}
}
// -------------------------------
// PUBLIC METHODS
// -------------------------------
/**
* A chainer method that sets the role(s) for this `Query` instance.
* @param {String|Array<String>} roles
* A single or array of roles.
* @returns {Query}
* Self instance of `Query`.
*/
role(role: string | string[]): Query {
this._.role = role;
return this;
}
/**
* A chainer method that sets the resource for this `Query` instance.
* @param {String} resource
* Target resource for this `Query` instance.
* @returns {Query}
* Self instance of `Query`.
*/
resource(resource: string): Query {
this._.resource = resource;
return this;
}
/**
* Queries the underlying grant model and checks whether the current
* role(s) can "create" their "own" resource.
*
* @param {String} [resource]
* Defines the target resource to be checked.
* This is only optional if the target resource is previously
* defined. If not defined and omitted, this will throw.
*
* @throws {Error} If the access query instance to be committed has any
* invalid data.
*
* @returns {Permission}
* An object that defines whether the permission is granted; and
* the resource attributes that the permission is granted for.
*/
createOwn(resource?: string): Permission {
return this._getPermission(Action.CREATE, Possession.OWN, resource);
}
/**
* Queries the underlying grant model and checks whether the current
* role(s) can "create" "any" resource.
*
* @param {String} [resource]
* Defines the target resource to be checked.
* This is only optional if the target resource is previously
* defined. If not defined and omitted, this will throw.
*
* @throws {Error} If the access query instance to be committed has any
* invalid data.
*
* @returns {Permission}
* An object that defines whether the permission is granted; and
* the resource attributes that the permission is granted for.
*/
createAny(resource?: string): Permission {
return this._getPermission(Action.CREATE, Possession.ANY, resource);
}
/**
* Alias if `createAny`
* @private
*/
create(resource?: string): Permission {
return this.createAny(resource);
}
/**
* Queries the underlying grant model and checks whether the current
* role(s) can "read" their "own" resource.
*
* @param {String} [resource]
* Defines the target resource to be checked.
* This is only optional if the target resource is previously
* defined. If not defined and omitted, this will throw.
*
* @throws {Error} If the access query instance to be committed has any
* invalid data.
*
* @returns {Permission}
* An object that defines whether the permission is granted; and
* the resource attributes that the permission is granted for.
*/
readOwn(resource?: string): Permission {
return this._getPermission(Action.READ, Possession.OWN, resource);
}
/**
* Queries the underlying grant model and checks whether the current
* role(s) can "read" "any" resource.
*
* @param {String} [resource]
* Defines the target resource to be checked.
* This is only optional if the target resource is previously
* defined. If not defined and omitted, this will throw.
*
* @throws {Error} If the access query instance to be committed has any
* invalid data.
*
* @returns {Permission}
* An object that defines whether the permission is granted; and
* the resource attributes that the permission is granted for.
*/
readAny(resource?: string): Permission {
return this._getPermission(Action.READ, Possession.ANY, resource);
}
/**
* Alias if `readAny`
* @private
*/
read(resource?: string): Permission {
return this.readAny(resource);
}
/**
* Queries the underlying grant model and checks whether the current
* role(s) can "update" their "own" resource.
*
* @param {String} [resource]
* Defines the target resource to be checked.
* This is only optional if the target resource is previously
* defined. If not defined and omitted, this will throw.
*
* @throws {Error} If the access query instance to be committed has any
* invalid data.
*
* @returns {Permission}
* An object that defines whether the permission is granted; and
* the resource attributes that the permission is granted for.
*/
updateOwn(resource?: string): Permission {
return this._getPermission(Action.UPDATE, Possession.OWN, resource);
}
/**
* Queries the underlying grant model and checks whether the current
* role(s) can "update" "any" resource.
*
* @param {String} [resource]
* Defines the target resource to be checked.
* This is only optional if the target resource is previously
* defined. If not defined and omitted, this will throw.
*
* @throws {Error} If the access query instance to be committed has any
* invalid data.
*
* @returns {Permission}
* An object that defines whether the permission is granted; and
* the resource attributes that the permission is granted for.
*/
updateAny(resource?: string): Permission {
return this._getPermission(Action.UPDATE, Possession.ANY, resource);
}
/**
* Alias if `updateAny`
* @private
*/
update(resource?: string): Permission {
return this.updateAny(resource);
}
/**
* Queries the underlying grant model and checks whether the current
* role(s) can "delete" their "own" resource.
*
* @param {String} [resource]
* Defines the target resource to be checked.
* This is only optional if the target resource is previously
* defined. If not defined and omitted, this will throw.
*
* @throws {Error} If the access query instance to be committed has any
* invalid data.
*
* @returns {Permission}
* An object that defines whether the permission is granted; and
* the resource attributes that the permission is granted for.
*/
deleteOwn(resource?: string): Permission {
return this._getPermission(Action.DELETE, Possession.OWN, resource);
}
/**
* Queries the underlying grant model and checks whether the current
* role(s) can "delete" "any" resource.
*
* @param {String} [resource]
* Defines the target resource to be checked.
* This is only optional if the target resource is previously
* defined. If not defined and omitted, this will throw.
*
* @throws {Error} If the access query instance to be committed has any
* invalid data.
*
* @returns {Permission}
* An object that defines whether the permission is granted; and
* the resource attributes that the permission is granted for.
*/
deleteAny(resource?: string): Permission {
return this._getPermission(Action.DELETE, Possession.ANY, resource);
}
/**
* Alias if `deleteAny`
* @private
*/
delete(resource?: string): Permission {
return this.deleteAny(resource);
}
// -------------------------------
// PRIVATE METHODS
// -------------------------------
/**
* @private
* @param {String} action
* @param {String} possession
* @param {String} [resource]
* @returns {Permission}
*/
private _getPermission(action: string, possession: string, resource?: string): Permission {
this._.action = action;
this._.possession = possession;
if (resource) this._.resource = resource;
return new Permission(this._grants, this._);
}
}
export { Query }; | the_stack |
import isEqual from 'lodash/isEqual';
import { Key, QueryInput, Converter } from 'aws-sdk/clients/dynamodb';
import { Context } from '../context';
import { DocumentWithId, WrappedDocument } from '../base/common';
import {
getCollection,
unwrap,
assembleIndexedValue,
IndexedValue,
} from '../base/util';
import { Collection } from '../base/collection';
import {
InvalidQueryException,
ConfigurationException,
InvalidIndexedFieldValueException,
} from '../base/exceptions';
import {
KeyPath,
AccessPattern,
AccessPatternOptions,
} from '../base/access_pattern';
import { SecondaryIndexLayout } from '../base/layout';
import debugDynamo from '../debug/debugDynamo';
import { CompositeCondition } from '../base/conditions';
import { createNameMapper, createValueMapper } from '../base/mappers';
import { parseCompositeCondition } from '../base/conditions_parser';
/**
* The query operator to use in the `KeyConditionExpression` to `QueryItem`
* as called by [[find]]
*/
export type QueryOperator =
| 'match'
| 'equals'
| 'gte'
| 'gt'
| 'lte'
| 'lt'
| 'between';
/**
* A find query. This is a map of key paths (specified dot-separated)
* to values to match.
*
* The query you specify must match an access pattern on the collection,
* otherwise an [[IndexNotFoundException]] will be thrown by [[find]]
*/
export type FindQuery = { [matchKey: string]: string | [string, string] };
/**
* The results of a [[find]] operation.
*/
export type FindResults<DocumentType extends DocumentWithId> = {
/** The items in this batch of results */
items: DocumentType[];
/** The pagination token. This value is specified when
* there are more results to fetch; pass it to another [[find]] call
* to get the next batch. It will be `undefined` when there is no
* more results.
*/
nextToken?: Key;
};
/**
* @internal
*
* Compare key paths and return if they are equal.
*/
export const isEqualKey = (
lhs: string[] | string,
rhs: string[] | string
): boolean => {
const normalisedLhs = typeof lhs === 'string' ? lhs.split('.') : lhs;
const normalisedRhs = typeof rhs === 'string' ? rhs.split('.') : rhs;
return isEqual(normalisedLhs, normalisedRhs);
};
/**
* @internal
*
* Find the access pattern for the specified query.
*/
export const findAccessPattern = (
collection: Collection,
query: FindQuery
): AccessPattern | undefined => {
return (collection.accessPatterns || []).find((ap) => {
const unmatchedQueryKeys = [...Object.keys(query)];
for (const apKey of ap.partitionKeys) {
const matchingQueryKeyIndex = unmatchedQueryKeys.findIndex((queryKey) =>
isEqualKey(apKey, queryKey)
);
if (matchingQueryKeyIndex >= 0) {
unmatchedQueryKeys.splice(matchingQueryKeyIndex, 1);
} else {
return false;
}
}
if (ap.sortKeys) {
for (const apKey of ap.sortKeys) {
const matchingQueryKeyIndex = unmatchedQueryKeys.findIndex((queryKey) =>
isEqualKey(apKey, queryKey)
);
if (matchingQueryKeyIndex >= 0) {
unmatchedQueryKeys.splice(matchingQueryKeyIndex, 1);
} else {
break;
}
}
}
return unmatchedQueryKeys.length === 0;
});
};
/**
* @internal
*
* Find the access pattern layout for the specified access pattern
*/
export const findAccessPatternLayout = (
findKeys: SecondaryIndexLayout[],
ap: AccessPattern
): SecondaryIndexLayout | undefined =>
findKeys.find((fk) => fk.indexName === ap.indexName);
/**
* @internal
*
* Assemble a value into the query, taking into account string normalizer options.
*/
export const assembleQueryValue = (
type: 'partition' | 'sort' | 'sort2',
collectionName: string,
query: FindQuery,
options: AccessPatternOptions,
paths?: KeyPath[],
separator?: string
): IndexedValue => {
if (paths) {
const values: IndexedValue[] = [];
for (const path of paths) {
const keyPath = path.join('.');
const pathValue = query[keyPath];
if (!pathValue) break;
const scalarPathValue =
type === 'partition' || type === 'sort'
? Array.isArray(pathValue)
? pathValue[0]
: pathValue
: Array.isArray(pathValue)
? pathValue[1]
: undefined;
if (!scalarPathValue)
throw new InvalidIndexedFieldValueException(
'$between queries must specify an array for sort key values',
{ collection: collectionName, keyPath: path }
);
const transformedValue = options.stringNormalizer
? options.stringNormalizer(path, scalarPathValue)
: scalarPathValue;
values.push(transformedValue);
}
return assembleIndexedValue(
type === 'sort2' ? 'sort' : type,
collectionName,
values,
separator
);
}
return undefined;
};
// FIXME: distinguish `=` and `begins_with` based on specified sort keys
/**
* @internal
*/
const getQueryOperator = (
sortKeyName: string,
sortValueName: string,
sortValueName2: string | undefined,
qo?: QueryOperator
): string => {
switch (qo) {
case 'lte':
return `${sortKeyName} <= ${sortValueName}`;
case 'lt':
return `${sortKeyName} < ${sortValueName}`;
case 'gte':
return `${sortKeyName} >= ${sortValueName}`;
case 'gt':
return `${sortKeyName} > ${sortValueName}`;
case 'equals':
return `${sortKeyName} = ${sortValueName}`;
case 'between':
return `${sortKeyName} BETWEEN ${sortValueName} AND ${sortValueName2}`;
default:
case 'match':
return `begins_with(${sortKeyName}, ${sortValueName})`;
}
throw new Error('unreachable');
};
/**
* The options for a [[find]] operation
*/
export type FindOptions = {
/**
* The sort key condition to use
*/
queryOperator?: QueryOperator;
/*
* The item limit to pass to DynamoDB
*/
limit?: number;
/**
* `true` (default) to scan the index forward, `false` to scan it backward
*/
scanForward?: boolean;
/**
* An optional filter expression for the
* find operation
*/
filter?: CompositeCondition;
};
/**
* Find an item using one of its collection's access patterns
*
* This method is very strict about how the query object is used. Failure
* to specify it
*
* Each of its keys is one of the keys paths to a field in the collection objects
* (separated by a full-stop `.`), with the values set to the value to
* match against. The value is a direct string comparison, so only string
* values can be looked up (the query object cannot contain nested values
* or values of types other than string)
*
* Every path that is specified must be part of the same access pattern.
* You cannot have extraneous fields to match or mix keys from different
* access patterns.
*
* All of the key paths in the partition key part of the access pattern
* must be specified.
*
* You do not have to specify all of the sort keys,
* **but** because they are stored as a composite key, and we can only do
* `begins_with` match, you must specify the keys in the order they appear,
* only leaving off those at the end.
*
* For example, if your sort key is defined as:
*
* `[['state'], ['city'], ['street', 'name'], ['street', 'number']]`
*
* you could specify any of the following combinations:
* - `{ state: '...' }`
* - `{ state: '...', city: '...' }`
* - `{ state: '...', city: '...', 'street.name': '...' }`
* - `{ state: '...', city: '...', 'street.name': '...', 'street.number': '...' }`
*
* But these would be invalid:
* - `{ city: '...' }`
* - `{ state: '...', 'street.name': '...' }`
* - `{ city: '...', 'street.name': '...', 'street.number': '...' }`
*
*
* @param ctx the context object
* @param collectionName the collection name
* @param query an object, with each of its keys set to the path of
* each field in the search object to match and their corresponding
* values to match (see above)s
* @param nextToken pagination token
* @param options options controlling the query
* @param options.queryOperator query operator to use (defaults to `begins_with()`)
* @param options.limit number of records to return
* @param options.scanForward scan direction, true for forward across the index (default) or false for backward
* @param options.filter a filter expression
* @returns an object containing the items found and a pagination token
* (if there is more results)
* @throws [[`CollectionNotFoundException`]] when the collection is not found in the context
* @throws [[`InvalidQueryException`]] when the access pattern cannot be found for the specfied combination of query key paths
*/
export async function find<DocumentType extends DocumentWithId>(
ctx: Context,
collectionName: string,
query: FindQuery,
nextToken?: Key,
options: FindOptions = {}
): Promise<FindResults<DocumentType>> {
const collection = getCollection(ctx, collectionName);
const ap = findAccessPattern(collection, query);
if (!ap) {
throw new InvalidQueryException(
'Unable to find access pattern matching query',
{
collection: collectionName,
query,
}
);
}
const layout = findAccessPatternLayout(collection.layout?.findKeys ?? [], ap);
if (!layout) {
throw new ConfigurationException(
`Unable to find layout for index specified in access pattern`,
{
info: { collectionName, indexName: ap.indexName },
}
);
}
const partitionKeyValue = assembleQueryValue(
'partition',
collection.name,
query,
ap.options || {},
ap.partitionKeys,
collection.layout.indexKeySeparator
);
const sortKeyValue = assembleQueryValue(
'sort',
collection.name,
query,
ap.options || {},
ap.sortKeys,
collection.layout.indexKeySeparator
);
const sortKeyValue2 =
options?.queryOperator === 'between'
? assembleQueryValue(
'sort2',
collection.name,
query,
ap.options || {},
ap.sortKeys,
collection.layout.indexKeySeparator
)
: undefined;
const nameMapper = createNameMapper();
const valueMapper = createValueMapper();
const sortKeyOp =
sortKeyValue &&
getQueryOperator(
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
nameMapper.map(layout.sortKey!, '#indexSortKey'),
valueMapper.map(sortKeyValue),
options?.queryOperator === 'between'
? valueMapper.map(sortKeyValue2)
: undefined,
options?.queryOperator
);
const keyConditionExpression = `${nameMapper.map(
layout.partitionKey,
'#indexPartitionKey'
)} = ${valueMapper.map(partitionKeyValue)}${
sortKeyValue ? ` AND ${sortKeyOp}` : ''
}`;
let filterExpression;
if (options?.filter) {
filterExpression = parseCompositeCondition(options.filter, {
nameMapper,
valueMapper,
parsePath: [],
});
}
const queryRequest: QueryInput = {
TableName: collection.layout.tableName,
IndexName: ap.indexName,
KeyConditionExpression: keyConditionExpression,
ExpressionAttributeNames: nameMapper.get(),
ExpressionAttributeValues: valueMapper.get(),
ExclusiveStartKey: nextToken,
Limit: options?.limit,
ScanIndexForward: options?.scanForward ?? true,
FilterExpression: filterExpression,
};
debugDynamo('Query', queryRequest);
const { Items: items, LastEvaluatedKey: lastEvaluatedKey } = await ctx.ddb
.query(queryRequest)
.promise();
const unwrappedItems = items
? items.map((item) =>
unwrap(Converter.unmarshall(item) as WrappedDocument<DocumentType>)
)
: [];
return {
items: unwrappedItems,
nextToken: lastEvaluatedKey,
};
} | the_stack |
import * as React from "react";
import { renderHook, act } from "@testing-library/react-hooks";
import {
addDoc,
collection,
CollectionReference,
DocumentSnapshot,
Firestore,
limit,
loadBundle,
orderBy,
query,
QuerySnapshot,
startAfter,
} from "firebase/firestore";
import bundles from "./bundles";
import { genId, init } from "./helpers";
import {
useFirestoreQuery,
useFirestoreQueryData,
namedQuery,
useFirestoreInfiniteQuery,
useFirestoreInfiniteQueryData,
} from "../src";
describe("useFirestoreQuery", () => {
let wrapper: React.FC<{ children: React.ReactNode }>;
let firestore: Firestore;
beforeEach(() => {
const config = init();
wrapper = config.wrapper;
firestore = config.firestore;
});
describe("useFirestoreQuery", () => {
test("it returns a QuerySnapshot", async () => {
const hookId = genId();
const id = genId();
const ref = collection(firestore, id);
const { result, waitFor } = renderHook(
() => useFirestoreQuery(hookId, ref),
{ wrapper }
);
await waitFor(() => result.current.isSuccess, { timeout: 5000 });
expect(result.current.data).toBeDefined();
expect(result.current.data).toBeInstanceOf(QuerySnapshot);
const snapshot = result.current.data;
expect(snapshot!.size).toBe(0);
});
test("it returns a QuerySnapshot using a data cache source", async () => {
const hookId = genId();
const id = genId();
const ref = collection(firestore, id);
await addDoc(ref, { foo: "bar" });
const { result, waitFor } = renderHook(
() =>
useFirestoreQuery(hookId, ref, {
source: "cache",
}),
{ wrapper }
);
await waitFor(() => result.current.isSuccess, { timeout: 5000 });
const snapshot = result.current.data;
expect(snapshot!.metadata.fromCache).toBe(true);
});
test("it returns a QuerySnapshot using a data server source", async () => {
const hookId = genId();
const id = genId();
const ref = collection(firestore, id);
await addDoc(ref, { foo: "bar" });
const { result, waitFor } = renderHook(
() =>
useFirestoreQuery(hookId, ref, {
source: "server",
}),
{ wrapper }
);
await waitFor(() => result.current.isSuccess, { timeout: 5000 });
const snapshot = result.current.data;
expect(snapshot!.metadata.fromCache).toBe(false);
});
test("it overrides DocumentData generic", async () => {
const hookId = genId();
type Foo = {
bar: number;
};
// Quick cast a reference.
const id = genId();
const ref = collection(firestore, id) as CollectionReference<Foo>;
await addDoc(ref, { bar: 123 });
const { result, waitFor } = renderHook(
() => useFirestoreQuery(hookId, ref),
{
wrapper,
}
);
await waitFor(() => result.current.isSuccess, { timeout: 5000 });
const snapshot = result.current.data;
expect(snapshot!.size).toBe(1);
expect(snapshot!.docs[0].data().bar).toBe(123);
// @ts-expect-error
expect(snapshot.docs[0].data().baz).toBe(undefined);
});
test("it overrides ReturnType generic", async () => {
const hookId = genId();
type Foo = {
bar: number;
};
type Bar = {
bar: string;
};
// Quick cast a reference.
const id = genId();
const ref = collection(firestore, id) as CollectionReference<Foo>;
await addDoc(ref, { bar: 123 });
const { result, waitFor } = renderHook(
() =>
useFirestoreQuery<Foo, Bar>(hookId, ref, undefined, {
select(snapshot) {
return {
bar: snapshot.docs[0].data().bar.toString(),
};
},
}),
{
wrapper,
}
);
await waitFor(() => result.current.isSuccess, { timeout: 5000 });
const data = result.current.data;
expect(data!.bar).toBe("123");
// @ts-expect-error
expect(data.baz).toBe(undefined);
});
test("it subscribes and unsubscribes to data events", async () => {
const hookId = genId();
const id = genId();
const col = collection(firestore, id);
const ref = query(col, orderBy("order", "asc"));
const mock = jest.fn();
const { result, waitFor, unmount } = renderHook(
() =>
useFirestoreQuery(
hookId,
ref,
{
subscribe: true,
},
{
onSuccess(snapshot) {
if (snapshot.size > 0) {
mock(snapshot);
}
},
}
),
{
wrapper,
}
);
await waitFor(() => result.current.isSuccess, { timeout: 5000 });
await act(async () => {
await addDoc(col, { foo: "bar", order: 0 });
await addDoc(col, { foo: "baz", order: 1 });
});
// Trigger an unmount - this should unsubscribe the listener.
unmount();
// Trigger an update to ensure the mock wasn't called again.
await act(async () => {
await addDoc(col, { foo: "..." });
});
// getDocs, onSubscribe, onSubscribe (add), onSubscribe (add),
expect(mock).toHaveBeenCalledTimes(2);
const call1 = mock.mock.calls[0][0];
const call2 = mock.mock.calls[1][0];
expect(call1.size).toEqual(1);
expect(call1.docs[0].data().foo).toEqual("bar");
expect(call2.size).toEqual(2);
// New should be first, previous last.
expect(call2.docs[0].data().foo).toEqual("bar");
expect(call2.docs[1].data().foo).toEqual("baz");
});
test("it re-subscribes when the key changes", async () => {
const hookId1 = genId();
const hookId2 = genId();
const id1 = `1-${genId()}`;
const id2 = `2-${genId()}`;
const ref1 = collection(firestore, id1);
const ref2 = collection(firestore, id2);
await addDoc(ref1, { foo: "bar" });
await addDoc(ref2, { foo: "bar" });
const mock = jest.fn();
const { result, waitFor, unmount, rerender } = renderHook<
{
id: string;
reference: CollectionReference;
},
any
>(
({ id, reference }) =>
useFirestoreQuery(
id,
reference,
{
subscribe: true,
},
{
onSuccess(snapshot) {
mock(snapshot);
},
}
),
{
wrapper: (props) => wrapper({ children: props.children }),
initialProps: {
id: hookId1,
reference: ref1,
},
}
);
await waitFor(() => result.current.isSuccess, { timeout: 5000 });
function getDoc(value: any): DocumentSnapshot {
return value as DocumentSnapshot;
}
expect(mock.mock.calls[0][0].size).toBe(1);
// Subscribe 1
expect(getDoc(mock.mock.calls[0][0].docs[0]).ref.parent.id).toBe(id1);
rerender({ id: hookId2, reference: ref2 });
await waitFor(() => result.current.isSuccess, { timeout: 5000 });
expect(getDoc(mock.mock.calls[1][0].docs[0]).ref.parent.id).toBe(id2);
// Trigger an unmount - this should unsubscribe the listener.
unmount();
expect(mock).toHaveBeenCalledTimes(2);
});
});
describe("useFirestoreQueryData", () => {
test("it returns document data and not a snapshot", async () => {
const hookId = genId();
const id = genId();
const ref = collection(firestore, id);
await addDoc(ref, { foo: "bar" });
const { result, waitFor } = renderHook(
() => useFirestoreQueryData(hookId, ref),
{ wrapper }
);
await waitFor(() => result.current.isSuccess, { timeout: 5000 });
expect(result.current.data).toEqual(
expect.arrayContaining([{ foo: "bar" }])
);
});
test("it overrides the select option", async () => {
const hookId = genId();
const id = genId();
const ref = collection(firestore, id);
await addDoc(ref, { foo: "bar" });
const { result, waitFor } = renderHook(
() =>
useFirestoreQueryData(hookId, ref, undefined, {
select() {
return [
{
baz: "ben",
},
];
},
}),
{ wrapper }
);
await waitFor(() => result.current.isSuccess, { timeout: 5000 });
expect(result.current.data).toEqual(
expect.arrayContaining([{ baz: "ben" }])
);
});
test("it provides the id key", async () => {
const hookId = genId();
const id = genId();
const ref = collection(firestore, id);
await addDoc(ref, { foo: "bar" });
const { result, waitFor } = renderHook(
() =>
useFirestoreQueryData<"id">(hookId, ref, {
idField: "id",
}),
{ wrapper }
);
await waitFor(() => result.current.isSuccess, { timeout: 5000 });
expect(result.current.data[0].foo).toEqual("bar");
expect(typeof result.current.data[0].id).toBe("string");
});
});
// TODO(ehesp): Test works, but Jest throws an "unimplemented" error when calling loadBundle.
// The test passes but this error throws causing the test to fail.
xdescribe("useFirestoreQuery Named Query", () => {
it("uses a named query fn", async () => {
const bundle = "named-bundle-test-1";
await loadBundle(firestore, bundles[bundle]);
const hookId = genId();
const { result, waitFor } = renderHook(
() => useFirestoreQueryData(hookId, namedQuery(firestore, bundle)),
{ wrapper }
);
await waitFor(() => result.current.isSuccess, { timeout: 5000 });
expect(result.current.data!.length).toBeGreaterThan(0);
});
});
describe("useFirestoreInfiniteQuery", () => {
test("it returns a snapshot", async () => {
const hookId = genId();
const id = genId();
const ref = collection(firestore, id);
await Promise.all([
addDoc(ref, { foo: 1 }),
addDoc(ref, { foo: 2 }),
addDoc(ref, { foo: 3 }),
addDoc(ref, { foo: 4 }),
addDoc(ref, { foo: 5 }),
]);
const q = query(ref, limit(2));
const mock = jest.fn();
const { result, waitFor } = renderHook(
() =>
useFirestoreInfiniteQuery(hookId, q, (snapshot) => {
mock(snapshot);
return undefined;
}),
{ wrapper }
);
await waitFor(() => result.current.isSuccess, { timeout: 5000 });
expect(result.current.data.pages.length).toBe(1); // QuerySnapshot
expect(result.current.data.pages[0].docs.length).toBe(2);
act(() => {
result.current.fetchNextPage();
});
await waitFor(() => result.current.isSuccess, { timeout: 5000 });
const snapshot: QuerySnapshot = mock.mock.calls[0][0];
expect(snapshot.size).toBe(2);
expect(result.current.hasNextPage).toBe(false);
});
test("it loads the next page of snapshots", async () => {
const hookId = genId();
const id = genId();
const ref = collection(firestore, id);
await Promise.all([
addDoc(ref, { foo: 1 }),
addDoc(ref, { foo: 2 }),
addDoc(ref, { foo: 3 }),
addDoc(ref, { foo: 4 }),
addDoc(ref, { foo: 5 }),
]);
const q = query(ref, limit(2));
const { result, waitFor } = renderHook(
() =>
useFirestoreInfiniteQuery(hookId, q, (snapshot) => {
return query(q, startAfter(snapshot.docs[1]));
}),
{ wrapper }
);
await waitFor(() => result.current.isSuccess, { timeout: 5000 });
expect(result.current.data.pages.length).toBe(1); // QuerySnapshot
expect(result.current.data.pages[0].docs.length).toBe(2);
await act(async () => {
await result.current.fetchNextPage();
});
await waitFor(() => result.current.isSuccess, { timeout: 5000 });
expect(result.current.data.pages.length).toBe(2);
expect(result.current.data.pages[1].docs.length).toBe(2);
});
});
describe("useFirestoreInfiniteQueryData", () => {
test("it returns a data", async () => {
const hookId = genId();
const id = genId();
const ref = collection(firestore, id);
await Promise.all([
addDoc(ref, { foo: 1 }),
addDoc(ref, { foo: 2 }),
addDoc(ref, { foo: 3 }),
addDoc(ref, { foo: 4 }),
addDoc(ref, { foo: 5 }),
]);
const q = query(ref, limit(2), orderBy("foo"));
const mock = jest.fn();
const { result, waitFor } = renderHook(
() =>
useFirestoreInfiniteQueryData(hookId, q, (data) => {
mock(data);
return undefined;
}),
{ wrapper }
);
await waitFor(() => result.current.isSuccess, { timeout: 5000 });
expect(result.current.data.pages.length).toBe(1);
expect(result.current.data.pages[0].length).toBe(2);
expect(result.current.data.pages[0]).toEqual([{ foo: 1 }, { foo: 2 }]);
act(() => {
result.current.fetchNextPage();
});
await waitFor(() => result.current.isSuccess, { timeout: 5000 });
const data: any = mock.mock.calls[0][0];
expect(data.length).toBe(2);
expect(result.current.hasNextPage).toBe(false);
});
test("it loads the next page of data", async () => {
const hookId = genId();
const id = genId();
const ref = collection(firestore, id);
await Promise.all([
addDoc(ref, { foo: 1 }),
addDoc(ref, { foo: 2 }),
addDoc(ref, { foo: 3 }),
addDoc(ref, { foo: 4 }),
addDoc(ref, { foo: 5 }),
]);
const q = query(ref, limit(2), orderBy("foo"));
const { result, waitFor } = renderHook(
() =>
useFirestoreInfiniteQueryData(hookId, q, () => {
return query(q, startAfter(2));
}),
{ wrapper }
);
await waitFor(() => result.current.isSuccess, { timeout: 5000 });
expect(result.current.data.pages[0].length).toBe(2);
expect(result.current.data.pages[0]).toEqual([{ foo: 1 }, { foo: 2 }]);
await act(async () => {
await result.current.fetchNextPage();
});
await waitFor(() => result.current.isSuccess, { timeout: 5000 });
expect(result.current.data.pages.length).toBe(2);
expect(result.current.data.pages[1].length).toBe(2);
expect(result.current.data.pages[1]).toEqual([{ foo: 3 }, { foo: 4 }]);
});
test("it provides the idField", async () => {
const hookId = genId();
const id = genId();
const ref = collection(firestore, id);
await Promise.all([
addDoc(ref, { foo: 1 }),
addDoc(ref, { foo: 2 }),
addDoc(ref, { foo: 3 }),
addDoc(ref, { foo: 4 }),
addDoc(ref, { foo: 5 }),
]);
const q = query(ref, limit(2), orderBy("foo"));
const { result, waitFor } = renderHook(
() =>
useFirestoreInfiniteQueryData<"id">(
hookId,
q,
() => {
return query(q, startAfter(2));
},
{
idField: "id",
}
),
{ wrapper }
);
await waitFor(() => result.current.isSuccess, { timeout: 5000 });
expect(result.current.data.pages[0].length).toBe(2);
expect(result.current.data.pages[0][0].foo).toEqual(1);
expect(typeof result.current.data.pages[0][0].id).toBe("string");
expect(result.current.data.pages[0][1].foo).toEqual(2);
expect(typeof result.current.data.pages[0][1].id).toBe("string");
await act(async () => {
await result.current.fetchNextPage();
});
await waitFor(() => result.current.isSuccess, { timeout: 5000 });
expect(result.current.data.pages.length).toBe(2);
expect(result.current.data.pages[1].length).toBe(2);
expect(result.current.data.pages[1][0].foo).toEqual(3);
expect(typeof result.current.data.pages[1][0].id).toBe("string");
expect(result.current.data.pages[1][1].foo).toEqual(4);
expect(typeof result.current.data.pages[1][1].id).toBe("string");
});
});
}); | the_stack |
import { AfterViewInit, ChangeDetectorRef, Component, EmbeddedViewRef, OnDestroy, OnInit, QueryList, TemplateRef, ViewChild, ViewChildren, ViewContainerRef } from '@angular/core';
import { Course } from 'app/entities/course.model';
import { CourseManagementService } from '../course/manage/course-management.service';
import { ActivatedRoute } from '@angular/router';
import { forkJoin, Subject, Subscription } from 'rxjs';
import { HttpErrorResponse, HttpResponse } from '@angular/common/http';
import { CourseScoreCalculationService } from 'app/overview/course-score-calculation.service';
import { CachingStrategy } from 'app/shared/image/secured-image.component';
import { TeamService } from 'app/exercises/shared/team/team.service';
import { TeamAssignmentPayload } from 'app/entities/team.model';
import { participationStatus } from 'app/exercises/shared/exercise/exercise.utils';
import { JhiWebsocketService } from 'app/core/websocket/websocket.service';
import { QuizExercise } from 'app/entities/quiz/quiz-exercise.model';
import dayjs from 'dayjs/esm';
import { ArtemisServerDateService } from 'app/shared/server-date.service';
import { AlertService, AlertType } from 'app/core/util/alert.service';
import { faCircleNotch, faSync } from '@fortawesome/free-solid-svg-icons';
import { CourseExerciseService } from 'app/exercises/shared/course-exercises/course-exercise.service';
import { ARTEMIS_DEFAULT_COLOR } from 'app/app.constants';
import { LearningGoalService } from 'app/course/learning-goals/learningGoal.service';
const DESCRIPTION_READ = 'isDescriptionRead';
export interface BarControlConfiguration {
subject?: Subject<TemplateRef<any>>;
useIndentation: boolean;
}
export interface BarControlConfigurationProvider {
controlConfiguration: BarControlConfiguration;
}
@Component({
selector: 'jhi-course-overview',
templateUrl: './course-overview.component.html',
styleUrls: ['course-overview.scss'],
})
export class CourseOverviewComponent implements OnInit, OnDestroy, AfterViewInit {
readonly ARTEMIS_DEFAULT_COLOR = ARTEMIS_DEFAULT_COLOR;
CachingStrategy = CachingStrategy;
private courseId: number;
private subscription: Subscription;
public course?: Course;
public refreshingCourse = false;
public courseDescription: string | undefined;
public enableShowMore = false;
public longDescriptionShown = false;
private teamAssignmentUpdateListener: Subscription;
private quizExercisesChannel: string;
// Rendered embedded view for controls in the bar so we can destroy it if needed
private controlsEmbeddedView?: EmbeddedViewRef<any>;
// Subscription to listen to changes on the control configuration
private controlsSubscription?: Subscription;
// Subscription to listen for the ng-container for controls to be mounted
private vcSubscription?: Subscription;
// The current controls template from the sub-route component to render
private controls?: TemplateRef<any>;
// The current controls configuration from the sub-route component
public controlConfiguration?: BarControlConfiguration;
// ng-container mount point extracted from our own template so we can render sth in it
@ViewChild('controlsViewContainer', { read: ViewContainerRef }) controlsViewContainer: ViewContainerRef;
// Using a list query to be able to listen for changes (late mount); need both as this only returns native nodes
@ViewChildren('controlsViewContainer') controlsViewContainerAsList: QueryList<ViewContainerRef>;
// Icons
faSync = faSync;
faCircleNotch = faCircleNotch;
constructor(
private courseService: CourseManagementService,
private courseExerciseService: CourseExerciseService,
private courseCalculationService: CourseScoreCalculationService,
private learningGoalService: LearningGoalService,
private route: ActivatedRoute,
private teamService: TeamService,
private jhiWebsocketService: JhiWebsocketService,
private serverDateService: ArtemisServerDateService,
private alertService: AlertService,
private changeDetectorRef: ChangeDetectorRef,
) {}
async ngOnInit() {
this.subscription = this.route.params.subscribe((params) => {
this.courseId = parseInt(params['courseId'], 10);
});
this.course = this.courseCalculationService.getCourse(this.courseId);
if (!this.course) {
this.loadCourse();
} else if (!this.course.learningGoals || !this.course.prerequisites) {
// If the course is present but without learning goals (e.g. loaded in Artemis overview), we only need to fetch those
this.loadLearningGoals();
}
this.adjustCourseDescription();
await this.subscribeToTeamAssignmentUpdates();
this.subscribeForQuizChanges();
}
ngAfterViewInit() {
// Check if controls mount point is available, if not, wait for it
if (this.controlsViewContainer) {
this.tryRenderControls();
} else {
this.vcSubscription = this.controlsViewContainerAsList.changes.subscribe(() => this.tryRenderControls());
}
}
/**
* Accepts a component reference of the subcomponent rendered based on the current route.
* If it provides a controlsConfiguration, we try to render the controls component
* @param componentRef the sub route component that has been mounted into the router outlet
*/
onSubRouteActivate(componentRef: any) {
if (componentRef.controlConfiguration) {
const provider = componentRef as BarControlConfigurationProvider;
this.controlConfiguration = provider.controlConfiguration as BarControlConfiguration;
// Listen for changes to the control configuration; works for initial config as well
this.controlsSubscription =
this.controlConfiguration.subject?.subscribe((controls: TemplateRef<any>) => {
this.controls = controls;
this.tryRenderControls();
// Since we might be pulling data upwards during a render cycle, we need to re-run change detection
this.changeDetectorRef.detectChanges();
}) || undefined;
}
}
/**
* Removes the controls component from the DOM and cancels the listener for controls changes.
* Called by the router outlet as soon as the currently mounted component is removed
*/
onSubRouteDeactivate() {
this.removeCurrentControlsView();
this.controls = undefined;
this.controlConfiguration = undefined;
this.controlsSubscription?.unsubscribe();
this.changeDetectorRef.detectChanges();
}
private removeCurrentControlsView() {
this.controlsEmbeddedView?.detach();
this.controlsEmbeddedView?.destroy();
}
/**
* Mounts the controls as specified by the currently mounted sub-route component to the ng-container in the top bar
* if all required data is available.
*/
tryRenderControls() {
if (this.controlConfiguration && this.controls && this.controlsViewContainer) {
this.removeCurrentControlsView();
this.controlsEmbeddedView = this.controlsViewContainer.createEmbeddedView(this.controls);
this.controlsEmbeddedView.detectChanges();
}
}
/**
* Fetch the course from the server including all exercises, lectures, exams and learning goals
* @param refresh Whether this is a force refresh (displays loader animation)
*/
loadCourse(refresh = false) {
this.refreshingCourse = refresh;
this.courseService.findOneForDashboard(this.courseId).subscribe({
next: (res: HttpResponse<Course>) => {
this.courseCalculationService.updateCourse(res.body!);
this.course = this.courseCalculationService.getCourse(this.courseId);
this.adjustCourseDescription();
setTimeout(() => (this.refreshingCourse = false), 500); // ensure min animation duration
},
error: (error: HttpErrorResponse) => {
const errorMessage = error.headers.get('X-artemisApp-message')!;
this.alertService.addAlert({
type: AlertType.DANGER,
message: errorMessage,
disableTranslation: true,
});
},
});
}
ngOnDestroy() {
if (this.teamAssignmentUpdateListener) {
this.teamAssignmentUpdateListener.unsubscribe();
}
if (this.quizExercisesChannel) {
this.jhiWebsocketService.unsubscribe(this.quizExercisesChannel);
}
this.controlsSubscription?.unsubscribe();
this.vcSubscription?.unsubscribe();
}
subscribeForQuizChanges() {
// subscribe to quizzes which get visible
if (!this.quizExercisesChannel) {
this.quizExercisesChannel = '/topic/courses/' + this.courseId + '/quizExercises';
// quizExercise channel => react to changes made to quizExercise (e.g. start date)
this.jhiWebsocketService.subscribe(this.quizExercisesChannel);
this.jhiWebsocketService.receive(this.quizExercisesChannel).subscribe((quizExercise: QuizExercise) => {
quizExercise = this.courseExerciseService.convertDateFromServer(quizExercise);
// the quiz was set to visible or started, we should add it to the exercise list and display it at the top
if (this.course && this.course.exercises) {
this.course.exercises = this.course.exercises.filter((exercise) => exercise.id !== quizExercise.id);
this.course.exercises.push(quizExercise);
}
});
}
}
loadLearningGoals() {
forkJoin([this.learningGoalService.getAllForCourse(this.courseId), this.learningGoalService.getAllPrerequisitesForCourse(this.courseId)]).subscribe({
next: ([learningGoals, prerequisites]) => {
if (this.course) {
this.course.learningGoals = learningGoals.body!;
this.course.prerequisites = prerequisites.body!;
this.courseCalculationService.updateCourse(this.course);
}
},
error: () => {},
});
}
/**
* Adjusts the course description and shows toggle buttons (if it is too long)
* This also depends on whether the user has already seen the full description (stored in local storage)
*/
adjustCourseDescription() {
if (this.course && this.course.description) {
this.enableShowMore = this.course.description.length > 50;
if (this.enableShowMore && !this.longDescriptionShown && localStorage.getItem(DESCRIPTION_READ + this.course.shortName)) {
this.courseDescription = this.course.description.slice(0, 50) + 'โฆ';
this.longDescriptionShown = false;
} else {
this.courseDescription = this.course.description;
this.longDescriptionShown = true;
localStorage.setItem(DESCRIPTION_READ + this.course.shortName, 'true');
}
}
}
/**
* Toggle between showing the long and abbreviated course description
*/
toggleCourseDescription() {
this.longDescriptionShown = !this.longDescriptionShown;
this.adjustCourseDescription();
}
/**
* check if there is at least one exam which should be shown
*/
hasVisibleExams(): boolean {
for (const exam of this.course?.exams!) {
if (exam.visibleDate && dayjs(exam.visibleDate).isBefore(this.serverDateService.now())) {
return true;
}
}
return false;
}
/**
* Check if the course has any learning goals or prerequisites
*/
hasLearningGoals(): boolean {
return !!(this.course?.learningGoals?.length || this.course?.prerequisites?.length);
}
/**
* Receives team assignment changes and updates related attributes of the affected exercise
*/
async subscribeToTeamAssignmentUpdates() {
this.teamAssignmentUpdateListener = (await this.teamService.teamAssignmentUpdates).subscribe((teamAssignment: TeamAssignmentPayload) => {
const exercise = this.course?.exercises?.find((courseExercise) => courseExercise.id === teamAssignment.exerciseId);
if (exercise) {
exercise.studentAssignedTeamId = teamAssignment.teamId;
exercise.studentParticipations = teamAssignment.studentParticipations;
exercise.participationStatus = participationStatus(exercise);
}
});
}
} | the_stack |
namespace dragonBones {
/**
* @private
*/
export class DisplayFrame extends BaseObject {
public static toString(): string {
return "[class dragonBones.DisplayFrame]";
}
public rawDisplayData: DisplayData | null;
public displayData: DisplayData | null;
public textureData: TextureData | null;
public display: any | Armature | null;
public readonly deformVertices: Array<number> = [];
protected _onClear(): void {
this.rawDisplayData = null;
this.displayData = null;
this.textureData = null;
this.display = null;
this.deformVertices.length = 0;
}
public updateDeformVertices(): void {
if (this.rawDisplayData === null || this.deformVertices.length !== 0) {
return;
}
let rawGeometryData: GeometryData;
if (this.rawDisplayData.type === DisplayType.Mesh) {
rawGeometryData = (this.rawDisplayData as MeshDisplayData).geometry;
}
else if (this.rawDisplayData.type === DisplayType.Path) {
rawGeometryData = (this.rawDisplayData as PathDisplayData).geometry;
}
else {
return;
}
let vertexCount = 0;
if (rawGeometryData.weight !== null) {
vertexCount = rawGeometryData.weight.count * 2;
}
else {
vertexCount = rawGeometryData.data.intArray[rawGeometryData.offset + BinaryOffset.GeometryVertexCount] * 2;
}
this.deformVertices.length = vertexCount;
for (let i = 0, l = this.deformVertices.length; i < l; ++i) {
this.deformVertices[i] = 0.0;
}
}
public getGeometryData(): GeometryData | null {
if (this.displayData !== null) {
if (this.displayData.type === DisplayType.Mesh) {
return (this.displayData as MeshDisplayData).geometry;
}
if (this.displayData.type === DisplayType.Path) {
return (this.displayData as PathDisplayData).geometry;
}
}
if (this.rawDisplayData !== null) {
if (this.rawDisplayData.type === DisplayType.Mesh) {
return (this.rawDisplayData as MeshDisplayData).geometry;
}
if (this.rawDisplayData.type === DisplayType.Path) {
return (this.rawDisplayData as PathDisplayData).geometry;
}
}
return null;
}
public getBoundingBox(): BoundingBoxData | null {
if (this.displayData !== null && this.displayData.type === DisplayType.BoundingBox) {
return (this.displayData as BoundingBoxDisplayData).boundingBox;
}
if (this.rawDisplayData !== null && this.rawDisplayData.type === DisplayType.BoundingBox) {
return (this.rawDisplayData as BoundingBoxDisplayData).boundingBox;
}
return null;
}
public getTextureData(): TextureData | null {
if (this.displayData !== null) {
if (this.displayData.type === DisplayType.Image) {
return (this.displayData as ImageDisplayData).texture;
}
if (this.displayData.type === DisplayType.Mesh) {
return (this.displayData as MeshDisplayData).texture;
}
}
if (this.textureData !== null) {
return this.textureData;
}
if (this.rawDisplayData !== null) {
if (this.rawDisplayData.type === DisplayType.Image) {
return (this.rawDisplayData as ImageDisplayData).texture;
}
if (this.rawDisplayData.type === DisplayType.Mesh) {
return (this.rawDisplayData as MeshDisplayData).texture;
}
}
return null;
}
}
/**
* - The slot attached to the armature, controls the display status and properties of the display object.
* A bone can contain multiple slots.
* A slot can contain multiple display objects, displaying only one of the display objects at a time,
* but you can toggle the display object into frame animation while the animation is playing.
* The display object can be a normal texture, or it can be a display of a child armature, a grid display object,
* and a custom other display object.
* @see dragonBones.Armature
* @see dragonBones.Bone
* @see dragonBones.SlotData
* @version DragonBones 3.0
* @language en_US
*/
/**
* - ๆๆงฝ้็ๅจ้ชจ้ชผไธ๏ผๆงๅถๆพ็คบๅฏน่ฑก็ๆพ็คบ็ถๆๅๅฑๆงใ
* ไธไธช้ชจ้ชผไธๅฏไปฅๅ
ๅซๅคไธชๆๆงฝใ
* ไธไธชๆๆงฝไธญๅฏไปฅๅ
ๅซๅคไธชๆพ็คบๅฏน่ฑก๏ผๅไธๆถ้ดๅช่ฝๆพ็คบๅ
ถไธญ็ไธไธชๆพ็คบๅฏน่ฑก๏ผไฝๅฏไปฅๅจๅจ็ปๆญๆพ็่ฟ็จไธญๅๆขๆพ็คบๅฏน่ฑกๅฎ็ฐๅธงๅจ็ปใ
* ๆพ็คบๅฏน่ฑกๅฏไปฅๆฏๆฎ้็ๅพ็็บน็๏ผไนๅฏไปฅๆฏๅญ้ชจๆถ็ๆพ็คบๅฎนๅจ๏ผ็ฝๆ ผๆพ็คบๅฏน่ฑก๏ผ่ฟๅฏไปฅๆฏ่ชๅฎไน็ๅ
ถไปๆพ็คบๅฏน่ฑกใ
* @see dragonBones.Armature
* @see dragonBones.Bone
* @see dragonBones.SlotData
* @version DragonBones 3.0
* @language zh_CN
*/
export abstract class Slot extends TransformObject {
/**
* - Displays the animated state or mixed group name controlled by the object, set to null to be controlled by all animation states.
* @default null
* @see dragonBones.AnimationState#displayControl
* @see dragonBones.AnimationState#name
* @see dragonBones.AnimationState#group
* @version DragonBones 4.5
* @language en_US
*/
/**
* - ๆพ็คบๅฏน่ฑกๅๅฐๆงๅถ็ๅจ็ป็ถๆๆๆททๅ็ปๅ็งฐ๏ผ่ฎพ็ฝฎไธบ null ๅ่กจ็คบๅๆๆ็ๅจ็ป็ถๆๆงๅถใ
* @default null
* @see dragonBones.AnimationState#displayControl
* @see dragonBones.AnimationState#name
* @see dragonBones.AnimationState#group
* @version DragonBones 4.5
* @language zh_CN
*/
public displayController: string | null;
protected _displayDataDirty: boolean;
protected _displayDirty: boolean;
protected _geometryDirty: boolean;
protected _textureDirty: boolean;
protected _visibleDirty: boolean;
protected _blendModeDirty: boolean;
protected _zOrderDirty: boolean;
/**
* @internal
*/
public _colorDirty: boolean;
/**
* @internal
*/
public _verticesDirty: boolean;
protected _transformDirty: boolean;
protected _visible: boolean;
protected _blendMode: BlendMode;
protected _displayIndex: number;
protected _animationDisplayIndex: number;
protected _cachedFrameIndex: number;
/**
* @internal
*/
public _zOrder: number;
/**
* @internal
*/
public _zIndex: number;
/**
* @internal
*/
public _pivotX: number;
/**
* @internal
*/
public _pivotY: number;
protected readonly _localMatrix: Matrix = new Matrix();
/**
* @internal
*/
public readonly _colorTransform: ColorTransform = new ColorTransform();
/**
* @internal
*/
public readonly _displayFrames: Array<DisplayFrame> = [];
/**
* @internal
*/
public readonly _geometryBones: Array<Bone | null> = [];
/**
* @internal
*/
public _slotData: SlotData;
/**
* @internal
*/
public _displayFrame: DisplayFrame | null;
/**
* @internal
*/
public _geometryData: GeometryData | null;
protected _boundingBoxData: BoundingBoxData | null;
protected _textureData: TextureData | null;
protected _rawDisplay: any = null; // Initial value.
protected _meshDisplay: any = null; // Initial value.
protected _display: any | null = null;
protected _childArmature: Armature | null;
/**
* @private
*/
protected _parent: Bone;
/**
* @internal
*/
public _cachedFrameIndices: Array<number> | null;
protected _onClear(): void {
super._onClear();
const disposeDisplayList: Array<any> = [];
for (const dispayFrame of this._displayFrames) {
const display = dispayFrame.display;
if (
display !== this._rawDisplay && display !== this._meshDisplay &&
disposeDisplayList.indexOf(display) < 0
) {
disposeDisplayList.push(display);
}
dispayFrame.returnToPool();
}
for (const eachDisplay of disposeDisplayList) {
if (eachDisplay instanceof Armature) {
eachDisplay.dispose();
}
else {
this._disposeDisplay(eachDisplay, true);
}
}
if (this._meshDisplay !== null && this._meshDisplay !== this._rawDisplay) { // May be _meshDisplay and _rawDisplay is the same one.
this._disposeDisplay(this._meshDisplay, false);
}
if (this._rawDisplay !== null) {
this._disposeDisplay(this._rawDisplay, false);
}
this.displayController = null;
this._displayDataDirty = false;
this._displayDirty = false;
this._geometryDirty = false;
this._textureDirty = false;
this._visibleDirty = false;
this._blendModeDirty = false;
this._zOrderDirty = false;
this._colorDirty = false;
this._verticesDirty = false;
this._transformDirty = false;
this._visible = true;
this._blendMode = BlendMode.Normal;
this._displayIndex = -1;
this._animationDisplayIndex = -1;
this._zOrder = 0;
this._zIndex = 0;
this._cachedFrameIndex = -1;
this._pivotX = 0.0;
this._pivotY = 0.0;
this._localMatrix.identity();
this._colorTransform.identity();
this._displayFrames.length = 0;
this._geometryBones.length = 0;
this._slotData = null as any; //
this._displayFrame = null;
this._geometryData = null;
this._boundingBoxData = null;
this._textureData = null;
this._rawDisplay = null;
this._meshDisplay = null;
this._display = null;
this._childArmature = null;
this._parent = null as any; //
this._cachedFrameIndices = null;
}
protected abstract _initDisplay(value: any, isRetain: boolean): void;
protected abstract _disposeDisplay(value: any, isRelease: boolean): void;
protected abstract _onUpdateDisplay(): void;
protected abstract _addDisplay(): void;
protected abstract _replaceDisplay(value: any): void;
protected abstract _removeDisplay(): void;
protected abstract _updateZOrder(): void;
/**
* @internal
*/
public abstract _updateVisible(): void;
protected abstract _updateBlendMode(): void;
protected abstract _updateColor(): void;
protected abstract _updateFrame(): void;
protected abstract _updateMesh(): void;
protected abstract _updateTransform(): void;
protected abstract _identityTransform(): void;
protected _hasDisplay(display: any): boolean {
for (const displayFrame of this._displayFrames) {
if (displayFrame.display === display) {
return true;
}
}
return false;
}
/**
* @internal
*/
public _isBonesUpdate(): boolean {
for (const bone of this._geometryBones) {
if (bone !== null && bone._childrenTransformDirty) {
return true;
}
}
return false;
}
/**
* @internal
*/
public _updateAlpha() {
const globalAlpha = this._alpha * this._parent._globalAlpha;
if (this._globalAlpha !== globalAlpha) {
this._globalAlpha = globalAlpha;
this._colorDirty = true;
}
}
protected _updateDisplayData(): void {
const prevDisplayFrame = this._displayFrame;
const prevGeometryData = this._geometryData;
const prevTextureData = this._textureData;
let rawDisplayData: DisplayData | null = null;
let displayData: DisplayData | null = null;
this._displayFrame = null;
this._geometryData = null;
this._boundingBoxData = null;
this._textureData = null;
if (this._displayIndex >= 0 && this._displayIndex < this._displayFrames.length) {
this._displayFrame = this._displayFrames[this._displayIndex];
rawDisplayData = this._displayFrame.rawDisplayData;
displayData = this._displayFrame.displayData;
this._geometryData = this._displayFrame.getGeometryData();
this._boundingBoxData = this._displayFrame.getBoundingBox();
this._textureData = this._displayFrame.getTextureData();
}
if (
this._displayFrame !== prevDisplayFrame ||
this._geometryData !== prevGeometryData || this._textureData !== prevTextureData
) {
// Update pivot offset.
if (this._geometryData === null && this._textureData !== null) {
const imageDisplayData = ((displayData !== null && displayData.type === DisplayType.Image) ? displayData : rawDisplayData) as ImageDisplayData; //
const scale = this._textureData.parent.scale * this._armature._armatureData.scale;
const frame = this._textureData.frame;
this._pivotX = imageDisplayData.pivot.x;
this._pivotY = imageDisplayData.pivot.y;
const rect = frame !== null ? frame : this._textureData.region;
let width = rect.width;
let height = rect.height;
if (this._textureData.rotated && frame === null) {
width = rect.height;
height = rect.width;
}
this._pivotX *= width * scale;
this._pivotY *= height * scale;
if (frame !== null) {
this._pivotX += frame.x * scale;
this._pivotY += frame.y * scale;
}
// Update replace pivot. TODO
if (rawDisplayData !== null && imageDisplayData !== rawDisplayData) {
rawDisplayData.transform.toMatrix(Slot._helpMatrix);
Slot._helpMatrix.invert();
Slot._helpMatrix.transformPoint(0.0, 0.0, Slot._helpPoint);
this._pivotX -= Slot._helpPoint.x;
this._pivotY -= Slot._helpPoint.y;
imageDisplayData.transform.toMatrix(Slot._helpMatrix);
Slot._helpMatrix.invert();
Slot._helpMatrix.transformPoint(0.0, 0.0, Slot._helpPoint);
this._pivotX += Slot._helpPoint.x;
this._pivotY += Slot._helpPoint.y;
}
if (!DragonBones.yDown) {
this._pivotY = (this._textureData.rotated ? this._textureData.region.width : this._textureData.region.height) * scale - this._pivotY;
}
}
else {
this._pivotX = 0.0;
this._pivotY = 0.0;
}
// Update original transform.
if (rawDisplayData !== null) { // Compatible.
this.origin = rawDisplayData.transform;
}
else if (displayData !== null) { // Compatible.
this.origin = displayData.transform;
}
else {
this.origin = null;
}
// TODO remove slot offset.
if (this.origin !== null) {
this.global.copyFrom(this.origin).add(this.offset).toMatrix(this._localMatrix);
}
else {
this.global.copyFrom(this.offset).toMatrix(this._localMatrix);
}
// Update geometry.
if (this._geometryData !== prevGeometryData) {
this._geometryDirty = true;
this._verticesDirty = true;
if (this._geometryData !== null) {
this._geometryBones.length = 0;
if (this._geometryData.weight !== null) {
for (let i = 0, l = this._geometryData.weight.bones.length; i < l; ++i) {
const bone = this._armature.getBone(this._geometryData.weight.bones[i].name);
this._geometryBones.push(bone);
}
}
}
else {
this._geometryBones.length = 0;
this._geometryData = null;
}
}
this._textureDirty = this._textureData !== prevTextureData;
this._transformDirty = true;
}
}
protected _updateDisplay(): void {
const prevDisplay = this._display !== null ? this._display : this._rawDisplay;
const prevChildArmature = this._childArmature;
// Update display and child armature.
if (this._displayFrame !== null) {
this._display = this._displayFrame.display;
if (this._display !== null && this._display instanceof Armature) {
this._childArmature = this._display as Armature;
this._display = this._childArmature.display;
}
else {
this._childArmature = null;
}
}
else {
this._display = null;
this._childArmature = null;
}
// Update display.
const currentDisplay = this._display !== null ? this._display : this._rawDisplay;
if (currentDisplay !== prevDisplay) {
this._textureDirty = true;
this._visibleDirty = true;
this._blendModeDirty = true;
// this._zOrderDirty = true;
this._colorDirty = true;
this._transformDirty = true;
this._onUpdateDisplay();
this._replaceDisplay(prevDisplay);
}
// Update child armature.
if (this._childArmature !== prevChildArmature) {
if (prevChildArmature !== null) {
prevChildArmature._parent = null; // Update child armature parent.
prevChildArmature.clock = null;
if (prevChildArmature.inheritAnimation) {
prevChildArmature.animation.reset();
}
}
if (this._childArmature !== null) {
this._childArmature._parent = this; // Update child armature parent.
this._childArmature.clock = this._armature.clock;
if (this._childArmature.inheritAnimation) { // Set child armature cache frameRate.
if (this._childArmature.cacheFrameRate === 0) {
const cacheFrameRate = this._armature.cacheFrameRate;
if (cacheFrameRate !== 0) {
this._childArmature.cacheFrameRate = cacheFrameRate;
}
}
// Child armature action.
if (this._displayFrame !== null) {
let actions: Array<ActionData> | null = null;
let displayData = this._displayFrame.displayData !== null ? this._displayFrame.displayData : this._displayFrame.rawDisplayData;
if (displayData !== null && displayData.type === DisplayType.Armature) {
actions = (displayData as ArmatureDisplayData).actions;
}
if (actions !== null && actions.length > 0) {
for (const action of actions) {
const eventObject = BaseObject.borrowObject(EventObject);
EventObject.actionDataToInstance(action, eventObject, this._armature);
eventObject.slot = this;
this._armature._bufferAction(eventObject, false);
}
}
else {
this._childArmature.animation.play();
}
}
}
}
}
}
protected _updateGlobalTransformMatrix(isCache: boolean): void {
const parentMatrix = this._parent._boneData.type === BoneType.Bone ? this._parent.globalTransformMatrix : (this._parent as Surface)._getGlobalTransformMatrix(this.global.x, this.global.y);
this.globalTransformMatrix.copyFrom(this._localMatrix);
this.globalTransformMatrix.concat(parentMatrix);
if (isCache) {
this.global.fromMatrix(this.globalTransformMatrix);
}
else {
this._globalDirty = true;
}
}
/**
* @internal
*/
public _setDisplayIndex(value: number, isAnimation: boolean = false): void {
if (isAnimation) {
if (this._animationDisplayIndex === value) {
return;
}
this._animationDisplayIndex = value;
}
if (this._displayIndex === value) {
return;
}
this._displayIndex = value < this._displayFrames.length ? value : this._displayFrames.length - 1;
this._displayDataDirty = true;
this._displayDirty = this._displayIndex < 0 || this._display !== this._displayFrames[this._displayIndex].display;
}
/**
* @internal
*/
public _setZOrder(value: number): boolean {
if (this._zOrder === value) {
// return false;
}
this._zOrder = value;
this._zOrderDirty = true;
return this._zOrderDirty;
}
/**
* @internal
*/
public _setColor(value: ColorTransform): boolean {
this._colorTransform.copyFrom(value);
return this._colorDirty = true;
}
/**
* @internal
*/
public init(slotData: SlotData, armatureValue: Armature, rawDisplay: any, meshDisplay: any): void {
if (this._slotData !== null) {
return;
}
this._slotData = slotData;
this._colorDirty = true; //
this._blendModeDirty = true; //
this._blendMode = this._slotData.blendMode;
this._zOrder = this._slotData.zOrder;
this._zIndex = this._slotData.zIndex;
this._alpha = this._slotData.alpha;
this._colorTransform.copyFrom(this._slotData.color);
this._rawDisplay = rawDisplay;
this._meshDisplay = meshDisplay;
//
this._armature = armatureValue;
const slotParent = this._armature.getBone(this._slotData.parent.name);
if (slotParent !== null) {
this._parent = slotParent;
}
else {
// Never;
}
this._armature._addSlot(this);
//
this._initDisplay(this._rawDisplay, false);
if (this._rawDisplay !== this._meshDisplay) {
this._initDisplay(this._meshDisplay, false);
}
this._onUpdateDisplay();
this._addDisplay();
}
/**
* @internal
*/
public update(cacheFrameIndex: number): void {
if (this._displayDataDirty) {
this._updateDisplayData();
this._displayDataDirty = false;
}
if (this._displayDirty) {
this._updateDisplay();
this._displayDirty = false;
}
if (this._geometryDirty || this._textureDirty) {
if (this._display === null || this._display === this._rawDisplay || this._display === this._meshDisplay) {
this._updateFrame();
}
this._geometryDirty = false;
this._textureDirty = false;
}
if (this._display === null) {
return;
}
if (this._visibleDirty) {
this._updateVisible();
this._visibleDirty = false;
}
if (this._blendModeDirty) {
this._updateBlendMode();
this._blendModeDirty = false;
}
if (this._colorDirty) {
this._updateColor();
this._colorDirty = false;
}
if (this._zOrderDirty) {
this._updateZOrder();
this._zOrderDirty = false;
}
if (this._geometryData !== null && this._display === this._meshDisplay) {
const isSkinned = this._geometryData.weight !== null;
const isSurface = this._parent._boneData.type !== BoneType.Bone;
if (
this._verticesDirty ||
(isSkinned && this._isBonesUpdate()) ||
(isSurface && this._parent._childrenTransformDirty)
) {
this._verticesDirty = false; // Allow update mesh to reset the dirty value.
this._updateMesh();
}
if (isSkinned || isSurface) { // Compatible.
return;
}
}
if (cacheFrameIndex >= 0 && this._cachedFrameIndices !== null) {
const cachedFrameIndex = this._cachedFrameIndices[cacheFrameIndex];
if (cachedFrameIndex >= 0 && this._cachedFrameIndex === cachedFrameIndex) { // Same cache.
this._transformDirty = false;
}
else if (cachedFrameIndex >= 0) { // Has been Cached.
this._transformDirty = true;
this._cachedFrameIndex = cachedFrameIndex;
}
else if (this._transformDirty || this._parent._childrenTransformDirty) { // Dirty.
this._transformDirty = true;
this._cachedFrameIndex = -1;
}
else if (this._cachedFrameIndex >= 0) { // Same cache, but not set index yet.
this._transformDirty = false;
this._cachedFrameIndices[cacheFrameIndex] = this._cachedFrameIndex;
}
else { // Dirty.
this._transformDirty = true;
this._cachedFrameIndex = -1;
}
}
else if (this._transformDirty || this._parent._childrenTransformDirty) { // Dirty.
cacheFrameIndex = -1;
this._transformDirty = true;
this._cachedFrameIndex = -1;
}
if (this._transformDirty) {
if (this._cachedFrameIndex < 0) {
const isCache = cacheFrameIndex >= 0;
this._updateGlobalTransformMatrix(isCache);
if (isCache && this._cachedFrameIndices !== null) {
this._cachedFrameIndex = this._cachedFrameIndices[cacheFrameIndex] = this._armature._armatureData.setCacheFrame(this.globalTransformMatrix, this.global);
}
}
else {
this._armature._armatureData.getCacheFrame(this.globalTransformMatrix, this.global, this._cachedFrameIndex);
}
this._updateTransform();
this._transformDirty = false;
}
}
/**
* - Forces the slot to update the state of the display object in the next frame.
* @version DragonBones 4.5
* @language en_US
*/
/**
* - ๅผบๅถๆๆงฝๅจไธไธๅธงๆดๆฐๆพ็คบๅฏน่ฑก็็ถๆใ
* @version DragonBones 4.5
* @language zh_CN
*/
public invalidUpdate(): void {
this._displayDataDirty = true;
this._displayDirty = true;
//
this._transformDirty = true;
}
/**
* @private
*/
public updateTransformAndMatrix(): void {
if (this._transformDirty) {
this._updateGlobalTransformMatrix(false);
this._transformDirty = false;
}
}
/**
* @private
*/
public replaceRawDisplayData(displayData: DisplayData | null, index: number = -1): void {
if (index < 0) {
index = this._displayIndex < 0 ? 0 : this._displayIndex;
}
else if (index >= this._displayFrames.length) {
return;
}
const displayFrame = this._displayFrames[index];
if (displayFrame.rawDisplayData !== displayData) {
displayFrame.deformVertices.length = 0;
displayFrame.rawDisplayData = displayData;
if (displayFrame.rawDisplayData === null) {
const defaultSkin = this._armature._armatureData.defaultSkin;
if (defaultSkin !== null) {
const defaultRawDisplayDatas = defaultSkin.getDisplays(this._slotData.name);
if (defaultRawDisplayDatas !== null && index < defaultRawDisplayDatas.length) {
displayFrame.rawDisplayData = defaultRawDisplayDatas[index];
}
}
}
if (index === this._displayIndex) {
this._displayDataDirty = true;
}
}
}
/**
* @private
*/
public replaceDisplayData(displayData: DisplayData | null, index: number = -1): void {
if (index < 0) {
index = this._displayIndex < 0 ? 0 : this._displayIndex;
}
else if (index >= this._displayFrames.length) {
return;
}
const displayFrame = this._displayFrames[index];
if (displayFrame.displayData !== displayData && displayFrame.rawDisplayData !== displayData) {
displayFrame.displayData = displayData;
if (index === this._displayIndex) {
this._displayDataDirty = true;
}
}
}
/**
* @private
*/
public replaceTextureData(textureData: TextureData | null, index: number = -1): void {
if (index < 0) {
index = this._displayIndex < 0 ? 0 : this._displayIndex;
}
else if (index >= this._displayFrames.length) {
return;
}
const displayFrame = this._displayFrames[index];
if (displayFrame.textureData !== textureData) {
displayFrame.textureData = textureData;
if (index === this._displayIndex) {
this._displayDataDirty = true;
}
}
}
/**
* @private
*/
public replaceDisplay(value: any | Armature | null, index: number = -1): void {
if (index < 0) {
index = this._displayIndex < 0 ? 0 : this._displayIndex;
}
else if (index >= this._displayFrames.length) {
return;
}
const displayFrame = this._displayFrames[index];
if (displayFrame.display !== value) {
const prevDisplay = displayFrame.display;
displayFrame.display = value;
if (
prevDisplay !== null &&
prevDisplay !== this._rawDisplay && prevDisplay !== this._meshDisplay &&
!this._hasDisplay(prevDisplay)
) {
if (prevDisplay instanceof Armature) {
// (eachDisplay as Armature).dispose();
}
else {
this._disposeDisplay(prevDisplay, true);
}
}
if (
value !== null &&
value !== this._rawDisplay && value !== this._meshDisplay &&
!this._hasDisplay(prevDisplay) &&
!(value instanceof Armature)
) {
this._initDisplay(value, true);
}
if (index === this._displayIndex) {
this._displayDirty = true;
}
}
}
/**
* - Check whether a specific point is inside a custom bounding box in the slot.
* The coordinate system of the point is the inner coordinate system of the armature.
* Custom bounding boxes need to be customized in Dragonbones Pro.
* @param x - The horizontal coordinate of the point.
* @param y - The vertical coordinate of the point.
* @version DragonBones 5.0
* @language en_US
*/
/**
* - ๆฃๆฅ็นๅฎ็นๆฏๅฆๅจๆๆงฝ็่ชๅฎไน่พน็ๆกๅ
ใ
* ็น็ๅๆ ็ณปไธบ้ชจๆถๅ
ๅๆ ็ณปใ
* ่ชๅฎไน่พน็ๆก้่ฆๅจ DragonBones Pro ไธญ่ชๅฎไนใ
* @param x - ็น็ๆฐดๅนณๅๆ ใ
* @param y - ็น็ๅ็ดๅๆ ใ
* @version DragonBones 5.0
* @language zh_CN
*/
public containsPoint(x: number, y: number): boolean {
if (this._boundingBoxData === null) {
return false;
}
this.updateTransformAndMatrix();
Slot._helpMatrix.copyFrom(this.globalTransformMatrix);
Slot._helpMatrix.invert();
Slot._helpMatrix.transformPoint(x, y, Slot._helpPoint);
return this._boundingBoxData.containsPoint(Slot._helpPoint.x, Slot._helpPoint.y);
}
/**
* - Check whether a specific segment intersects a custom bounding box for the slot.
* The coordinate system of the segment and intersection is the inner coordinate system of the armature.
* Custom bounding boxes need to be customized in Dragonbones Pro.
* @param xA - The horizontal coordinate of the beginning of the segment.
* @param yA - The vertical coordinate of the beginning of the segment.
* @param xB - The horizontal coordinate of the end point of the segment.
* @param yB - The vertical coordinate of the end point of the segment.
* @param intersectionPointA - The first intersection at which a line segment intersects the bounding box from the beginning to the end. (If not set, the intersection point will not calculated)
* @param intersectionPointB - The first intersection at which a line segment intersects the bounding box from the end to the beginning. (If not set, the intersection point will not calculated)
* @param normalRadians - The normal radians of the tangent of the intersection boundary box. [x: Normal radian of the first intersection tangent, y: Normal radian of the second intersection tangent] (If not set, the normal will not calculated)
* @returns Intersection situation. [1: Disjoint and segments within the bounding box, 0: Disjoint, 1: Intersecting and having a nodal point and ending in the bounding box, 2: Intersecting and having a nodal point and starting at the bounding box, 3: Intersecting and having two intersections, N: Intersecting and having N intersections]
* @version DragonBones 5.0
* @language en_US
*/
/**
* - ๆฃๆฅ็นๅฎ็บฟๆฎตๆฏๅฆไธๆๆงฝ็่ชๅฎไน่พน็ๆก็ธไบคใ
* ็บฟๆฎตๅไบค็น็ๅๆ ็ณปๅไธบ้ชจๆถๅ
ๅๆ ็ณปใ
* ่ชๅฎไน่พน็ๆก้่ฆๅจ DragonBones Pro ไธญ่ชๅฎไนใ
* @param xA - ็บฟๆฎต่ตท็น็ๆฐดๅนณๅๆ ใ
* @param yA - ็บฟๆฎต่ตท็น็ๅ็ดๅๆ ใ
* @param xB - ็บฟๆฎต็ป็น็ๆฐดๅนณๅๆ ใ
* @param yB - ็บฟๆฎต็ป็น็ๅ็ดๅๆ ใ
* @param intersectionPointA - ็บฟๆฎตไป่ตท็นๅฐ็ป็นไธ่พน็ๆก็ธไบค็็ฌฌไธไธชไบค็นใ ๏ผๅฆๆๆช่ฎพ็ฝฎ๏ผๅไธ่ฎก็ฎไบค็น๏ผ
* @param intersectionPointB - ็บฟๆฎตไป็ป็นๅฐ่ตท็นไธ่พน็ๆก็ธไบค็็ฌฌไธไธชไบค็นใ ๏ผๅฆๆๆช่ฎพ็ฝฎ๏ผๅไธ่ฎก็ฎไบค็น๏ผ
* @param normalRadians - ไบค็น่พน็ๆกๅ็บฟ็ๆณ็บฟๅผงๅบฆใ [x: ็ฌฌไธไธชไบค็นๅ็บฟ็ๆณ็บฟๅผงๅบฆ, y: ็ฌฌไบไธชไบค็นๅ็บฟ็ๆณ็บฟๅผงๅบฆ] ๏ผๅฆๆๆช่ฎพ็ฝฎ๏ผๅไธ่ฎก็ฎๆณ็บฟ๏ผ
* @returns ็ธไบค็ๆ
ๅตใ [-1: ไธ็ธไบคไธ็บฟๆฎตๅจๅ
ๅด็ๅ
, 0: ไธ็ธไบค, 1: ็ธไบคไธๆไธไธชไบค็นไธ็ป็นๅจๅ
ๅด็ๅ
, 2: ็ธไบคไธๆไธไธชไบค็นไธ่ตท็นๅจๅ
ๅด็ๅ
, 3: ็ธไบคไธๆไธคไธชไบค็น, N: ็ธไบคไธๆ N ไธชไบค็น]
* @version DragonBones 5.0
* @language zh_CN
*/
public intersectsSegment(
xA: number, yA: number, xB: number, yB: number,
intersectionPointA: { x: number, y: number } | null = null,
intersectionPointB: { x: number, y: number } | null = null,
normalRadians: { x: number, y: number } | null = null
): number {
if (this._boundingBoxData === null) {
return 0;
}
this.updateTransformAndMatrix();
Slot._helpMatrix.copyFrom(this.globalTransformMatrix);
Slot._helpMatrix.invert();
Slot._helpMatrix.transformPoint(xA, yA, Slot._helpPoint);
xA = Slot._helpPoint.x;
yA = Slot._helpPoint.y;
Slot._helpMatrix.transformPoint(xB, yB, Slot._helpPoint);
xB = Slot._helpPoint.x;
yB = Slot._helpPoint.y;
const intersectionCount = this._boundingBoxData.intersectsSegment(xA, yA, xB, yB, intersectionPointA, intersectionPointB, normalRadians);
if (intersectionCount > 0) {
if (intersectionCount === 1 || intersectionCount === 2) {
if (intersectionPointA !== null) {
this.globalTransformMatrix.transformPoint(intersectionPointA.x, intersectionPointA.y, intersectionPointA);
if (intersectionPointB !== null) {
intersectionPointB.x = intersectionPointA.x;
intersectionPointB.y = intersectionPointA.y;
}
}
else if (intersectionPointB !== null) {
this.globalTransformMatrix.transformPoint(intersectionPointB.x, intersectionPointB.y, intersectionPointB);
}
}
else {
if (intersectionPointA !== null) {
this.globalTransformMatrix.transformPoint(intersectionPointA.x, intersectionPointA.y, intersectionPointA);
}
if (intersectionPointB !== null) {
this.globalTransformMatrix.transformPoint(intersectionPointB.x, intersectionPointB.y, intersectionPointB);
}
}
if (normalRadians !== null) {
this.globalTransformMatrix.transformPoint(Math.cos(normalRadians.x), Math.sin(normalRadians.x), Slot._helpPoint, true);
normalRadians.x = Math.atan2(Slot._helpPoint.y, Slot._helpPoint.x);
this.globalTransformMatrix.transformPoint(Math.cos(normalRadians.y), Math.sin(normalRadians.y), Slot._helpPoint, true);
normalRadians.y = Math.atan2(Slot._helpPoint.y, Slot._helpPoint.x);
}
}
return intersectionCount;
}
/**
* @private
*/
public getDisplayFrameAt(index: number): DisplayFrame {
return this._displayFrames[index];
}
/**
* - The visible of slot's display object.
* @default true
* @version DragonBones 5.6
* @language en_US
*/
/**
* - ๆๆงฝ็ๆพ็คบๅฏน่ฑก็ๅฏ่งใ
* @default true
* @version DragonBones 5.6
* @language zh_CN
*/
public get visible(): boolean {
return this._visible;
}
public set visible(value: boolean) {
if (this._visible === value) {
return;
}
this._visible = value;
this._updateVisible();
}
/**
* @private
*/
public get displayFrameCount(): number {
return this._displayFrames.length;
}
public set displayFrameCount(value: number) {
const prevCount = this._displayFrames.length;
if (prevCount < value) {
this._displayFrames.length = value;
for (let i = prevCount; i < value; ++i) {
this._displayFrames[i] = BaseObject.borrowObject(DisplayFrame);
}
}
else if (prevCount > value) {
for (let i = prevCount - 1; i < value; --i) {
this.replaceDisplay(null, i);
this._displayFrames[i].returnToPool();
}
this._displayFrames.length = value;
}
}
/**
* - The index of the display object displayed in the display list.
* @example
* <pre>
* let slot = armature.getSlot("weapon");
* slot.displayIndex = 3;
* slot.displayController = "none";
* </pre>
* @version DragonBones 4.5
* @language en_US
*/
/**
* - ๆญคๆถๆพ็คบ็ๆพ็คบๅฏน่ฑกๅจๆพ็คบๅ่กจไธญ็็ดขๅผใ
* @example
* <pre>
* let slot = armature.getSlot("weapon");
* slot.displayIndex = 3;
* slot.displayController = "none";
* </pre>
* @version DragonBones 4.5
* @language zh_CN
*/
public get displayIndex(): number {
return this._displayIndex;
}
public set displayIndex(value: number) {
this._setDisplayIndex(value);
this.update(-1);
}
/**
* - The slot name.
* @see dragonBones.SlotData#name
* @version DragonBones 3.0
* @language en_US
*/
/**
* - ๆๆงฝๅ็งฐใ
* @see dragonBones.SlotData#name
* @version DragonBones 3.0
* @language zh_CN
*/
public get name(): string {
return this._slotData.name;
}
/**
* - Contains a display list of display objects or child armatures.
* @version DragonBones 3.0
* @language en_US
*/
/**
* - ๅ
ๅซๆพ็คบๅฏน่ฑกๆๅญ้ชจๆถ็ๆพ็คบๅ่กจใ
* @version DragonBones 3.0
* @language zh_CN
*/
public get displayList(): Array<any> {
const displays = new Array<any>();
for (const displayFrame of this._displayFrames) {
displays.push(displayFrame.display);
}
return displays;
}
public set displayList(value: Array<any>) {
this.displayFrameCount = value.length;
let index = 0;
for (const eachDisplay of value) {
this.replaceDisplay(eachDisplay, index++);
}
}
/**
* - The slot data.
* @see dragonBones.SlotData
* @version DragonBones 4.5
* @language en_US
*/
/**
* - ๆๆงฝๆฐๆฎใ
* @see dragonBones.SlotData
* @version DragonBones 4.5
* @language zh_CN
*/
public get slotData(): SlotData {
return this._slotData;
}
/**
* - The custom bounding box data for the slot at current time.
* @version DragonBones 5.0
* @language en_US
*/
/**
* - ๆๆงฝๆญคๆถ็่ชๅฎไนๅ
ๅด็ๆฐๆฎใ
* @version DragonBones 5.0
* @language zh_CN
*/
public get boundingBoxData(): BoundingBoxData | null {
return this._boundingBoxData;
}
/**
* @private
*/
public get rawDisplay(): any {
return this._rawDisplay;
}
/**
* @private
*/
public get meshDisplay(): any {
return this._meshDisplay;
}
/**
* - The display object that the slot displays at this time.
* @example
* <pre>
* let slot = armature.getSlot("text");
* slot.display = new yourEngine.TextField();
* </pre>
* @version DragonBones 3.0
* @language en_US
*/
/**
* - ๆๆงฝๆญคๆถๆพ็คบ็ๆพ็คบๅฏน่ฑกใ
* @example
* <pre>
* let slot = armature.getSlot("text");
* slot.display = new yourEngine.TextField();
* </pre>
* @version DragonBones 3.0
* @language zh_CN
*/
public get display(): any {
return this._display;
}
public set display(value: any) {
if (this._display === value) {
return;
}
if (this._displayFrames.length === 0) {
this.displayFrameCount = 1;
this._displayIndex = 0;
}
this.replaceDisplay(value, this._displayIndex);
}
/**
* - The child armature that the slot displayed at current time.
* @example
* <pre>
* let slot = armature.getSlot("weapon");
* let prevChildArmature = slot.childArmature;
* if (prevChildArmature) {
* prevChildArmature.dispose();
* }
* slot.childArmature = factory.buildArmature("weapon_blabla", "weapon_blabla_project");
* </pre>
* @version DragonBones 3.0
* @language en_US
*/
/**
* - ๆๆงฝๆญคๆถๆพ็คบ็ๅญ้ชจๆถใ
* ๆณจๆ๏ผ่ขซๆฟๆข็ๅฏน่ฑกๆๅญ้ชจๆถๅนถไธไผ่ขซๅๆถ๏ผๆ นๆฎ่ฏญ่จๅๅผๆ็ไธๅ๏ผ้่ฆ้ขๅคๅค็ใ
* @example
* <pre>
* let slot = armature.getSlot("weapon");
* let prevChildArmature = slot.childArmature;
* if (prevChildArmature) {
* prevChildArmature.dispose();
* }
* slot.childArmature = factory.buildArmature("weapon_blabla", "weapon_blabla_project");
* </pre>
* @version DragonBones 3.0
* @language zh_CN
*/
public get childArmature(): Armature | null {
return this._childArmature;
}
public set childArmature(value: Armature | null) {
if (this._childArmature === value) {
return;
}
this.display = value;
}
/**
* - The parent bone to which it belongs.
* @version DragonBones 3.0
* @language en_US
*/
/**
* - ๆๅฑ็็ถ้ชจ้ชผใ
* @version DragonBones 3.0
* @language zh_CN
*/
public get parent(): Bone {
return this._parent;
}
/**
* - Deprecated, please refer to {@link #display}.
* @deprecated
* @language en_US
*/
/**
* - ๅทฒๅบๅผ๏ผ่ฏทๅ่ {@link #display}ใ
* @deprecated
* @language zh_CN
*/
public getDisplay(): any {
return this._display;
}
/**
* - Deprecated, please refer to {@link #display}.
* @deprecated
* @language en_US
*/
/**
* - ๅทฒๅบๅผ๏ผ่ฏทๅ่ {@link #display}ใ
* @deprecated
* @language zh_CN
*/
public setDisplay(value: any) {
this.display = value;
}
}
} | the_stack |
import * as path from 'path';
import * as fs from 'fs-extra';
import { KVStore, formatInt, NotFoundError } from '@liskhq/lisk-db';
import { codec } from '@liskhq/lisk-codec';
import { Storage } from '../../../src/data_access/storage';
import {
createValidDefaultBlock,
encodeDefaultBlockHeader,
encodedDefaultBlock,
registeredBlockHeaders,
} from '../../utils/block';
import { getTransaction } from '../../utils/transaction';
import { Block, Transaction } from '../../../src';
import { DataAccess } from '../../../src/data_access';
import { stateDiffSchema } from '../../../src/schema';
import { defaultAccountSchema, createFakeDefaultAccount } from '../../utils/account';
import { DB_KEY_ACCOUNTS_ADDRESS } from '../../../src/data_access/constants';
describe('dataAccess.blocks', () => {
const emptyEncodedDiff = codec.encode(stateDiffSchema, {
created: [],
updated: [],
deleted: [],
});
let db: KVStore;
let storage: Storage;
let dataAccess: DataAccess;
let blocks: Block[];
beforeAll(() => {
const parentPath = path.join(__dirname, '../../tmp/blocks');
fs.ensureDirSync(parentPath);
db = new KVStore(path.join(parentPath, '/test-blocks.db'));
storage = new Storage(db);
});
beforeEach(async () => {
dataAccess = new DataAccess({
db,
accountSchema: defaultAccountSchema,
registeredBlockHeaders,
minBlockHeaderCache: 3,
maxBlockHeaderCache: 5,
});
// Prepare sample data
const block300 = await createValidDefaultBlock({
header: { height: 300 },
payload: [getTransaction()],
});
const block301 = await createValidDefaultBlock({ header: { height: 301 } });
const block302 = await createValidDefaultBlock({
header: { height: 302 },
payload: [getTransaction({ nonce: BigInt(1) }), getTransaction({ nonce: BigInt(2) })],
});
const block303 = await createValidDefaultBlock({ header: { height: 303 } });
blocks = [block300, block301, block302, block303];
const batch = db.batch();
for (const block of blocks) {
const { payload, header } = block;
batch.put(`blocks:id:${header.id.toString('binary')}`, encodeDefaultBlockHeader(header));
batch.put(`blocks:height:${formatInt(header.height)}`, header.id);
if (payload.length) {
batch.put(
`transactions:blockID:${header.id.toString('binary')}`,
Buffer.concat(payload.map(tx => tx.id)),
);
for (const tx of payload) {
batch.put(`transactions:id:${tx.id.toString('binary')}`, tx.getBytes());
}
}
batch.put(
`tempBlocks:height:${formatInt(blocks[2].header.height)}`,
encodedDefaultBlock(blocks[2]),
);
batch.put(
`tempBlocks:height:${formatInt(blocks[3].header.height)}`,
encodedDefaultBlock(blocks[3]),
);
batch.put(
// eslint-disable-next-line @typescript-eslint/restrict-plus-operands
`tempBlocks:height:${formatInt(blocks[3].header.height + 1)}`,
encodedDefaultBlock(blocks[3]),
);
batch.put(`diff:${formatInt(block.header.height)}`, emptyEncodedDiff);
}
await batch.write();
dataAccess.resetBlockHeaderCache();
});
afterEach(async () => {
await db.clear();
dataAccess.resetBlockHeaderCache();
});
describe('getBlockHeaderByID', () => {
it('should throw not found error if non existent ID is specified', async () => {
expect.assertions(1);
try {
await storage.getBlockHeaderByID(Buffer.from('randomId'));
} catch (error) {
// eslint-disable-next-line jest/no-try-expect
expect(error).toBeInstanceOf(NotFoundError);
}
});
it('should return block header by ID', async () => {
const header = await dataAccess.getBlockHeaderByID(blocks[0].header.id);
expect(header).toStrictEqual(blocks[0].header);
});
});
describe('getBlockHeadersByIDs', () => {
it('should not throw "not found" error if non existent ID is specified', async () => {
await expect(
dataAccess.getBlockHeadersByIDs([Buffer.from('random-id'), blocks[1].header.id]),
).resolves.toEqual([blocks[1].header]);
});
it('should return existent blocks headers if non existent ID is specified', async () => {
const res = await dataAccess.getBlockHeadersByIDs([
blocks[0].header.id,
Buffer.from('random-id'),
blocks[1].header.id,
]);
expect(res).toEqual([blocks[0].header, blocks[1].header]);
});
it('should return block headers by ID', async () => {
const headers = await dataAccess.getBlockHeadersByIDs([
blocks[1].header.id,
blocks[0].header.id,
]);
const { header } = blocks[1];
expect(headers[0]).toEqual(header);
expect(headers).toHaveLength(2);
});
});
describe('getBlocksByIDs', () => {
it('should not throw "not found" error if non existent ID is specified', async () => {
await expect(
dataAccess.getBlocksByIDs([Buffer.from('random-id'), blocks[1].header.id]),
).resolves.toEqual([blocks[1]]);
});
it('should return existent blocks if non existent ID is specified', async () => {
const blocksFound = await dataAccess.getBlocksByIDs([
blocks[0].header.id,
Buffer.from('random-id'),
blocks[1].header.id,
]);
expect(blocksFound[0].header).toEqual(blocks[0].header);
expect(blocksFound[0].payload[0]).toBeInstanceOf(Transaction);
expect(blocksFound[0].payload[0].id).toEqual(blocks[0].payload[0].id);
expect(blocksFound[1].header).toEqual(blocks[1].header);
expect(blocksFound).toHaveLength(2);
});
it('should return blocks by ID', async () => {
const blocksFound = await dataAccess.getBlocksByIDs([
blocks[1].header.id,
blocks[0].header.id,
]);
expect(blocksFound).toHaveLength(2);
expect(blocksFound[0].header).toEqual(blocks[1].header);
expect(blocksFound[1].header).toEqual(blocks[0].header);
expect(blocksFound[1].payload[0]).toBeInstanceOf(Transaction);
expect(blocksFound[1].payload[0].id).toEqual(blocks[0].payload[0].id);
});
});
describe('getBlockHeadersByHeightBetween', () => {
it('should return block headers with in the height order by height', async () => {
const headers = await dataAccess.getBlockHeadersByHeightBetween(
blocks[0].header.height,
blocks[2].header.height,
);
const { header } = blocks[2];
expect(headers).toHaveLength(3);
expect(headers[0]).toEqual(header);
});
});
describe('getBlockHeadersWithHeights', () => {
it('should not throw "not found" error if one of heights does not exist', async () => {
await expect(
dataAccess.getBlockHeadersWithHeights([blocks[1].header.height, 500]),
).resolves.toEqual([blocks[1].header]);
});
it('should return existent blocks if non existent height is specified', async () => {
const headers = await dataAccess.getBlockHeadersWithHeights([
blocks[1].header.height,
blocks[3].header.height,
500,
]);
expect(headers).toEqual([blocks[1].header, blocks[3].header]);
expect(headers).toHaveLength(2);
});
it('should return block headers by height', async () => {
const headers = await dataAccess.getBlockHeadersWithHeights([
blocks[1].header.height,
blocks[3].header.height,
]);
expect(headers[0]).toEqual(blocks[1].header);
expect(headers[1]).toEqual(blocks[3].header);
expect(headers).toHaveLength(2);
});
});
describe('getLastBlockHeader', () => {
it('should return block header with highest height', async () => {
const lastBlockHeader = await dataAccess.getLastBlockHeader();
expect(lastBlockHeader).toEqual(blocks[3].header);
});
});
describe('getLastCommonBlockHeader', () => {
it('should return highest block header which exist in the list and non-existent should not throw', async () => {
const header = await dataAccess.getHighestCommonBlockID([
blocks[3].header.id,
Buffer.from('random-id'),
blocks[1].header.id,
]);
expect(header).toEqual(blocks[3].header.id);
});
});
describe('getBlockByID', () => {
it('should throw not found error if non existent ID is specified', async () => {
expect.assertions(1);
try {
await dataAccess.getBlockByID(Buffer.from('randomId'));
} catch (error) {
// eslint-disable-next-line jest/no-try-expect
expect(error).toBeInstanceOf(NotFoundError);
}
});
it('should return full block by ID', async () => {
const block = await dataAccess.getBlockByID(blocks[0].header.id);
expect(block.header).toStrictEqual(blocks[0].header);
expect(block.payload[0]).toBeInstanceOf(Transaction);
expect(block.payload[0].id).toStrictEqual(blocks[0].payload[0].id);
});
});
describe('getBlockByHeight', () => {
it('should throw not found error if non existent height is specified', async () => {
expect.assertions(1);
try {
await dataAccess.getBlockByHeight(500);
} catch (error) {
// eslint-disable-next-line jest/no-try-expect
expect(error).toBeInstanceOf(NotFoundError);
}
});
it('should return full block by height', async () => {
const block = await dataAccess.getBlockByHeight(blocks[2].header.height);
expect(block.header).toStrictEqual(blocks[2].header);
expect(block.payload[0]).toBeInstanceOf(Transaction);
expect(block.payload[0].id).toStrictEqual(blocks[2].payload[0].id);
});
});
describe('getLastBlock', () => {
it('should return highest height full block', async () => {
const block = await dataAccess.getLastBlock();
expect(block).toStrictEqual(blocks[3]);
});
});
describe('isTempBlockEmpty', () => {
it('should return false if tempBlock exists', async () => {
const empty = await dataAccess.isTempBlockEmpty();
expect(empty).toBeFalse();
});
it('should return true if tempBlock is empty', async () => {
await db.clear();
const empty = await dataAccess.isTempBlockEmpty();
expect(empty).toBeTrue();
});
});
describe('clearTempBlocks', () => {
it('should clean up all temp blocks, but not other data', async () => {
await storage.clearTempBlocks();
expect(await dataAccess.isTempBlockEmpty()).toBeTrue();
const lastBlock = await dataAccess.getLastBlock();
expect(lastBlock.header.height).toEqual(blocks[3].header.height);
});
});
describe('saveBlock', () => {
let block: Block;
// eslint-disable-next-line @typescript-eslint/no-empty-function
const stateStore = { finalize: () => {} };
beforeAll(async () => {
block = await createValidDefaultBlock({
header: { height: 304 },
payload: [getTransaction({ nonce: BigInt(10) }), getTransaction({ nonce: BigInt(20) })],
});
});
it('should create block with all index required', async () => {
await dataAccess.saveBlock(block, stateStore as any, 0);
await expect(
db.exists(`blocks:id:${block.header.id.toString('binary')}`),
).resolves.toBeTrue();
await expect(
db.exists(`blocks:height:${formatInt(block.header.height)}`),
).resolves.toBeTrue();
await expect(
db.exists(`transactions:blockID:${block.header.id.toString('binary')}`),
).resolves.toBeTrue();
await expect(
db.exists(`transactions:id:${block.payload[0].id.toString('binary')}`),
).resolves.toBeTrue();
await expect(
db.exists(`transactions:id:${block.payload[1].id.toString('binary')}`),
).resolves.toBeTrue();
await expect(
db.exists(`tempBlocks:height:${formatInt(block.header.height)}`),
).resolves.toBeTrue();
const createdBlock = await dataAccess.getBlockByID(block.header.id);
expect(createdBlock.header).toStrictEqual(block.header);
expect(createdBlock.payload[0]).toBeInstanceOf(Transaction);
expect(createdBlock.payload[0].id).toStrictEqual(block.payload[0].id);
expect(createdBlock.payload[1]).toBeInstanceOf(Transaction);
expect(createdBlock.payload[1].id).toStrictEqual(block.payload[1].id);
});
it('should create block with all index required and remove the same height block from temp', async () => {
await dataAccess.saveBlock(block, stateStore as any, 0, true);
await expect(
db.exists(`blocks:id:${block.header.id.toString('binary')}`),
).resolves.toBeTrue();
await expect(
db.exists(`blocks:height:${formatInt(block.header.height)}`),
).resolves.toBeTrue();
await expect(
db.exists(`transactions:blockID:${block.header.id.toString('binary')}`),
).resolves.toBeTrue();
await expect(
db.exists(`transactions:id:${block.payload[0].id.toString('binary')}`),
).resolves.toBeTrue();
await expect(
db.exists(`transactions:id:${block.payload[1].id.toString('binary')}`),
).resolves.toBeTrue();
await expect(
db.exists(`tempBlocks:height:${formatInt(block.header.height)}`),
).resolves.toBeFalse();
const createdBlock = await dataAccess.getBlockByID(block.header.id);
expect(createdBlock.header).toStrictEqual(block.header);
expect(createdBlock.payload[0]).toBeInstanceOf(Transaction);
expect(createdBlock.payload[0].id).toStrictEqual(block.payload[0].id);
expect(createdBlock.payload[1]).toBeInstanceOf(Transaction);
expect(createdBlock.payload[1].id).toStrictEqual(block.payload[1].id);
});
it('should delete diff before the finalized height', async () => {
await db.put(`diff:${formatInt(99)}`, Buffer.from('random diff'));
await db.put(`diff:${formatInt(100)}`, Buffer.from('random diff 2'));
await dataAccess.saveBlock(block, stateStore as any, 100, true);
await expect(db.exists(`diff:${formatInt(100)}`)).resolves.toBeTrue();
await expect(db.exists(`diff:${formatInt(99)}`)).resolves.toBeFalse();
});
});
describe('deleteBlock', () => {
// eslint-disable-next-line @typescript-eslint/no-empty-function
const stateStore = { finalize: () => {} };
it('should delete block and all related indexes', async () => {
// Deleting temp blocks to test the saving
await dataAccess.clearTempBlocks();
await dataAccess.deleteBlock(blocks[2], stateStore as any);
await expect(
db.exists(`blocks:id:${blocks[2].header.id.toString('binary')}`),
).resolves.toBeFalse();
await expect(
db.exists(`blocks:height:${formatInt(blocks[2].header.height)}`),
).resolves.toBeFalse();
await expect(
db.exists(`transactions:blockID:${blocks[2].header.id.toString('binary')}`),
).resolves.toBeFalse();
await expect(
db.exists(`transactions:id:${blocks[2].payload[0].id.toString('binary')}`),
).resolves.toBeFalse();
await expect(
db.exists(`transactions:id:${blocks[2].payload[1].id.toString('binary')}`),
).resolves.toBeFalse();
await expect(
db.exists(`tempBlocks:height:${formatInt(blocks[2].header.height)}`),
).resolves.toBeFalse();
});
it('should return all updated accounts', async () => {
// Deleting temp blocks to test the saving
await dataAccess.clearTempBlocks();
const deletedAccount = createFakeDefaultAccount({
token: {
balance: BigInt(200),
},
});
const updatedAccount = createFakeDefaultAccount({
token: {
balance: BigInt(100000000),
},
});
await db.put(
`diff:${formatInt(blocks[2].header.height)}`,
codec.encode(stateDiffSchema, {
created: [],
updated: [
{
key: `${DB_KEY_ACCOUNTS_ADDRESS}:${updatedAccount.address.toString('binary')}`,
value: dataAccess.encodeAccount(updatedAccount),
},
],
deleted: [
{
key: `${DB_KEY_ACCOUNTS_ADDRESS}:${deletedAccount.address.toString('binary')}`,
value: dataAccess.encodeAccount(deletedAccount),
},
],
}),
);
const diffAccounts = await dataAccess.deleteBlock(blocks[2], stateStore as any);
expect(diffAccounts).toHaveLength(2);
expect(
(diffAccounts.find(a => a.address.equals(deletedAccount.address)) as any).token.balance,
).toEqual(BigInt(200));
expect(
(diffAccounts.find(a => a.address.equals(deletedAccount.address)) as any).token.balance,
).toEqual(BigInt(200));
});
it('should throw an error when there is no diff', async () => {
// Deleting temp blocks to test the saving
await db.del(`diff:${formatInt(blocks[2].header.height)}`);
await dataAccess.clearTempBlocks();
await expect(dataAccess.deleteBlock(blocks[2], stateStore as any)).rejects.toThrow(
'Specified key diff:0000012e does not exist',
);
});
it('should delete block and all related indexes and save to temp', async () => {
// Deleting temp blocks to test the saving
await dataAccess.clearTempBlocks();
await dataAccess.deleteBlock(blocks[2], stateStore as any, true);
await expect(
db.exists(`blocks:id:${blocks[2].header.id.toString('binary')}`),
).resolves.toBeFalse();
await expect(
db.exists(`blocks:height:${formatInt(blocks[2].header.height)}`),
).resolves.toBeFalse();
await expect(
db.exists(`transactions:blockID:${blocks[2].header.id.toString('binary')}`),
).resolves.toBeFalse();
await expect(
db.exists(`transactions:id:${blocks[2].payload[0].id.toString('binary')}`),
).resolves.toBeFalse();
await expect(
db.exists(`transactions:id:${blocks[2].payload[1].id.toString('binary')}`),
).resolves.toBeFalse();
await expect(
db.exists(`tempBlocks:height:${formatInt(blocks[2].header.height)}`),
).resolves.toBeTrue();
const tempBlocks = await dataAccess.getTempBlocks();
expect(tempBlocks).toHaveLength(1);
expect(tempBlocks[0].header).toStrictEqual(blocks[2].header);
expect(tempBlocks[0].payload[0]).toBeInstanceOf(Transaction);
expect(tempBlocks[0].payload[0].id).toStrictEqual(blocks[2].payload[0].id);
});
});
}); | the_stack |
type SketchMSFillTypeEnum = 0 | 1 | 4 | 5;
type SketchMSBorderPositionEnum = 0 | 1 | 2 | 3;
interface SketchMSBorder {
_class: 'border';
isEnabled: boolean;
color: SketchMSColor;
fillType: SketchMSFillTypeEnum;
position: SketchMSBorderPositionEnum;
thickness: number;
}
type SketchMSBorderLineCapStyle = 0 | 1 | 2;
type SketchMSBorderLineJoinStyle = 0 | 1 | 2;
interface SketchMSBorderOptions {
_class: 'borderOptions';
isEnabled: boolean;
dashPattern: number[];
lineCapStyle: SketchMSBorderLineCapStyle;
lineJoinStyle: SketchMSBorderLineJoinStyle;
}
interface SketchMSImageDataReference {
_class: 'jSONOriginalDataReference';
_ref: string;
_ref_class: 'imageData';
data: {
_data: string;
};
sha1: {
_data: string;
};
}
type SketchMSPatternFillTypeEnum = 0 | 1 | 2 | 3;
interface SketchMSFill {
_class: 'fill';
isEnabled: boolean;
color?: SketchMSColor;
fillType: SketchMSFillTypeEnum;
image?: SketchMSImageDataReference;
noiseIndex: number;
noiseIntensity: number;
patternFillType: SketchMSPatternFillTypeEnum;
patternTileScale: number;
}
interface SketchMSShadow {
_class: 'shadow' | 'MSInnerShadow';
isEnabled: boolean;
blurRadius: number;
color: SketchMSColor;
contextSettings: SketchMSGraphicsContextSettings;
offsetX: number;
offsetY: number;
spread: number;
}
interface SketchMSStyleBorder {
_class: 'styleBorder';
position: number;
color: SketchMSColor;
gradient: SketchMSGradient;
fillType: number;
thickness: number;
contextSettings: SketchMSGraphicsContextSettings;
isEnabled: number;
}
interface SketchMSGradientStop {
_class: 'gradientStop';
color: SketchMSColor;
position: number;
}
interface SketchMSGradient {
_class: 'gradient';
from: {
x: number;
y: number;
};
shouldSmoothenOpacity: boolean;
gradientType: number;
stops: SketchMSGradientStop[];
to: {
x: number;
y: number;
};
elipseLength: number;
}
interface SketchMSStyleFill {
_class: 'styleFill';
contextSettings: SketchMSGraphicsContextSettings;
color: SketchMSColor;
gradient: SketchMSGradient;
fillType: number;
noiseIntensity: number;
patternFillType: number;
patternTileScale: number;
noiseIndex: number;
isEnabled: number;
}
interface SketchMSStyleShadow {
_class: 'styleShadow';
spread: number;
color: SketchMSColor;
offsetY: number;
offsetX: number;
blurRadius: number;
contextSettings: SketchMSGraphicsContextSettings;
isEnabled: number;
}
interface SketchMSParagraphStyle {
_class: 'paragraphStyle';
alignment: number;
allowsDefaultTighteningForTruncation: number;
}
interface SketchMSStyleBorderOptions {
_class: 'styleBorderOptions';
lineJoinStyle: number;
isEnabled: number;
lineCapStyle: number;
dashPattern: unknown[];
}
interface SketchMSGraphicsContextSettings {
_class: 'graphicsContextSettings';
opacity: number;
blendMode: SketchMSGraphicsContextSettingsBlendMode;
}
type SketchMSGraphicsContextSettingsBlendMode = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15;
interface SketchMSStyleBlur {
_class: 'styleBlur';
radius: number;
motionAngle: number;
isEnabled: number;
type: number;
center: {
x: number;
y: number;
};
}
interface SketchMSStyleReflection {
_class: 'styleReflection';
strength: number;
isEnabled: number;
distance: number;
}
interface SketchMSStyleColorControls {
_class: 'styleColorControls';
hue: number;
brightness: number;
contrast: number;
isEnabled: number;
saturation: number;
}
interface SketchMSFontAttribute {
_class: 'fontDescriptor';
attributes: {
name: string;
size: number;
};
}
interface SketchMSAttributes {
MSAttributedStringColorAttribute: SketchMSColor;
MSAttributedStringFontAttribute: SketchMSFontAttribute;
paragraphStyle: SketchMSParagraphStyle;
kerning: number;
}
interface SketchMSStringAttribute {
_class: 'stringAttribute';
attributes: SketchMSAttributes;
}
interface SketchMSTextStyle {
_class: 'textStyle';
encodedAttributes: SketchMSAttributes;
}
interface SketchMSStyle {
_class: 'style';
do_objectID: string;
endMarkerType: number;
miterLimit: number;
startMarkerType: number;
windingRule: number;
startDecorationType?: number;
borderOptions?: SketchMSStyleBorderOptions;
endDecorationType?: number;
contextSettings?: SketchMSGraphicsContextSettings;
blur?: SketchMSStyleBlur;
textStyle?: SketchMSTextStyle;
reflection?: SketchMSStyleReflection;
colorControls?: SketchMSStyleColorControls;
fills?: SketchMSStyleFill[];
borders?: SketchMSStyleBorder[];
innerShadows?: SketchMSStyleShadow[];
shadows?: SketchMSStyleShadow[];
}
interface SketchMSAttributedString {
_class: 'attributedString';
string: string;
attributes: SketchMSStringAttribute[];
archivedAttributedString?: {
_archive: string;
};
}
interface SketchMSTextLayer extends SketchMSContainerLayer {
_class: 'text';
attributedString: SketchMSAttributedString;
}
interface SketchMSLayoutSimpleGrid {
_class: 'simpleGrid';
thickGridTimes: number;
isEnabled: number;
gridSize: number;
}
interface SketchMSLayoutGrid {
_class: 'layoutGrid';
isEnabled: boolean;
columnWidth: number;
drawHorizontal: boolean;
drawHorizontalLines: boolean;
drawVertical: boolean;
gutterHeight: number;
gutterWidth: number;
guttersOutside: boolean;
horizontalOffset: number;
numberOfColumns: number;
rowHeightMultiplication: number;
totalWidth: number;
}
type SketchMSLayout = SketchMSLayoutGrid | SketchMSLayoutSimpleGrid;
interface SketchMSFlowConnection {
_class: 'immutableFlowConnection';
animationType: number;
destinationArtboardID?: string | 'back';
}
type SketchMSFlow = SketchMSFlowConnection;
interface SketchMSImmutableHotspotLayer extends SketchMSLayer {
_class: 'MSImmutableHotspotLayer';
flow: SketchMSFlow;
}
type SketchMSPointString = string;
type SketchMSCurveMode = 0 | 1 | 2 | 3 | 4;
interface SketchMSCurvePoint {
_class: 'curvePoint';
cornerRadius: number;
curveFrom: SketchMSPointString;
curveMode: SketchMSCurveMode;
curveTo: SketchMSPointString;
hasCurveFrom: boolean;
hasCurveTo: boolean;
point: SketchMSPointString;
}
type SketchMSPoint = SketchMSCurvePoint;
interface SketchMSPathLayer extends SketchMSLayer {
_class: 'path' | 'shapePath' | 'rectangle' | 'oval' | 'triangle';
edited: boolean;
isClosed: boolean;
pointRadiusBehaviour: number;
points: SketchMSPoint[];
}
interface SketchMSColor {
_class: 'color';
red: number;
green: number;
blue: number;
alpha: number;
}
interface SketchMSSymbolMasterLayer extends SketchMSPageLayer {
_class: 'symbolMaster';
backgroundColor: SketchMSColor;
hasBackgroundColor: boolean;
includeBackgroundColorInExport: boolean;
isFlowHome: boolean;
resizesContent: boolean;
includeBackgroundColorInInstance: boolean;
symbolID: string;
changeIdentifier: number;
}
interface SketchMSSymbolInstanceLayer extends SketchMSLayer {
_class: 'symbolInstance';
horizontalSpacing: number;
overrideValues: unknown[];
scale: number;
symbolID: string;
verticalSpacing: number;
}
interface SketchMSRulerData {
_class: 'rulerData';
base: number;
guides: unknown[];
}
interface SketchMSPageLayer extends SketchMSContainerLayer {
_class: 'page' | 'symbolMaster';
hasClickThrough: boolean;
horizontalRulerData: SketchMSRulerData;
includeInCloudUpload: boolean;
verticalRulerData: SketchMSRulerData;
}
interface SketchMSRect {
_class: 'rect';
constrainProportions: boolean;
height: number;
width: number;
x: number;
y: number;
}
type SketchMSLayerBooleanOperation = -1 | 0 | 1 | 2 | 3;
interface SketchMSLayerExportOptions {
_class: 'exportOptions';
exportFormats: unknown[];
includedLayerIds: unknown[];
layerOptions: number;
shouldTrim: boolean;
}
type SketchMSLayerFrame = SketchMSRect;
type SketchMSLayerResizingType = 0 | 1 | 2 | 3;
type SketchMSLayerClippingMaskMode = 0 | 1;
interface SketchMSContainerLayer extends SketchMSLayer {
_class: string;
layers: SketchMSContainerLayer[];
}
interface SketchMSLayer {
_class: string;
do_objectID: string;
booleanOperation: SketchMSLayerBooleanOperation;
exportOptions: SketchMSLayerExportOptions;
frame: SketchMSLayerFrame;
isFixedToViewport: boolean;
isFlippedHorizontal: boolean;
isFlippedVertical: boolean;
isLocked: boolean;
isVisible: boolean;
layerListExpandedType: number;
name: string;
nameIsFixed: boolean;
resizingConstraint: number;
resizingType: SketchMSLayerResizingType;
rotation: number;
shouldBreakMaskChain: boolean;
clippingMaskMode: SketchMSLayerClippingMaskMode;
hasClippingMask: boolean;
style: SketchMSStyle;
layers?: SketchMSLayer[];
// xLayers custom property
css?: string;
}
interface SketchMSSharedStyle {
_class: 'sharedStyle';
value: SketchMSStyle;
name: string;
}
interface SketchMSImageCollection {
_class: 'imageCollection';
images: unknown[];
}
interface SketchMSDocumentAssets {
_class: 'assetCollection';
gradients: unknown[];
colors: unknown[];
imageCollection: SketchMSImageCollection;
images: unknown[];
}
interface SketchMSImmutableForeignSymbol {
_class: 'MSImmutableForeignSymbol';
libraryID: string;
sourceLibraryName: string;
symbolPrivate: boolean;
originalMaster: SketchMSSymbolMasterLayer;
symbolMaster: SketchMSSymbolMasterLayer;
}
interface SketchMSSharedStyleContainer {
_class: 'sharedStyleContainer';
objects: SketchMSSharedStyle[];
}
interface SketchMSSymbolContainers {
_class: 'symbolContainer';
objects: unknown[];
}
interface SketchMSSharedTextStyleContainer {
_class: 'sharedTextStyleContainer';
objects: unknown[];
}
interface SketchMSPageReference {
_class: 'MSJSONFileReference';
_ref_class: 'MSImmutablePage';
_ref: string;
}
interface SketchMSDocument {
_class: 'documentData';
do_objectID: string;
assets: SketchMSDocumentAssets;
colorSpace: number;
currentPageIndex: number;
foreignSymbols: SketchMSImmutableForeignSymbol[];
foreignTextStyles: unknown[];
layerStyles: SketchMSSharedStyleContainer;
layerSymbols: SketchMSSymbolContainers;
layerTextStyles: SketchMSSharedTextStyleContainer;
pages: SketchMSPageReference[];
}
interface SketchMSArtboard {
frame: SketchMSRect;
backgroundColor: SketchMSColor;
hasBackgroundColor: boolean;
horizontalRulerData?: SketchMSRulerData;
verticalRulerData?: SketchMSRulerData;
includeBackgroundColorInExport?: boolean;
includeInCloudUpload?: boolean;
isFlowHome?: boolean;
}
interface SketchMSArtboards {
name: string;
artboards: SketchMSArtboard;
}
interface SketchMSPagesAndArtboards {
[key: string]: SketchMSArtboards;
}
interface SketchMSMeta {
commit: string;
pagesAndArtboards: SketchMSPagesAndArtboards;
version: number;
fonts: string[];
compatibilityVersion: number;
app: string;
autosaved: number;
variant: string;
created: {
commit: string;
appVersion: string;
build: number;
app: string;
compatibilityVersion: number;
version: number;
variant: string;
};
saveHistory: string[];
appVersion: string;
build: number;
}
interface SketchMSUserDocument {
document: {
pageListHeight: number;
pageListCollapsed: number;
};
}
interface SketchMSUserPages {
[key: string]: {
scrollOrigin: SketchMSCurvePoint;
zoomValue: number;
};
}
type SketchMSUser = SketchMSUserPages | SketchMSUserDocument;
interface SketchMSPreview {
source: string;
width: number;
height: number;
}
interface SketchMSData {
pages: SketchMSPageLayer[];
previews: SketchMSPreview[];
document: SketchMSDocument;
user: SketchMSUser;
meta: SketchMSMeta;
} | the_stack |
import { Grid } from '../../../src/grid/base/grid';
import { PredicateModel } from '../../../src/grid/base/grid-model';
import { Filter } from '../../../src/grid/actions/filter';
import { Group } from '../../../src/grid/actions/group';
import { Page } from '../../../src/grid/actions/page';
import { Toolbar } from '../../../src/grid/actions/toolbar';
import { Freeze } from '../../../src/grid/actions/freeze';
import { Selection } from '../../../src/grid/actions/selection';
import { VirtualScroll } from '../../../src/grid/actions/virtual-scroll';
import { filterData, customerData} from '../base/datasource.spec';
import { createGrid, destroy, getKeyUpObj, getClickObj, getKeyActionObj } from '../base/specutil.spec';
import '../../../node_modules/es6-promise/dist/es6-promise';
import { Edit } from '../../../src/grid/actions/edit';
import {profile , inMB, getMemoryProfile} from '../base/common.spec';
import { Query } from '@syncfusion/ej2-data';
import { FilterSearchBeginEventArgs } from '../../../src/grid/base/interface';
import { select } from '@syncfusion/ej2-base';
import { L10n } from '@syncfusion/ej2-base';
import * as events from '../../../src/grid/base/constant';
Grid.Inject(Filter, Page,Toolbar, Selection, Group, Freeze, Edit, Filter, VirtualScroll);
describe('Checkbox Filter module => ', () => {
let checkFilterObj: Function = (obj: PredicateModel, field?: string,
operator?: string, value?: string, predicate?: string, matchCase?: boolean): boolean => {
let isEqual: boolean = true;
if (field) {
isEqual = isEqual && obj.field === field;
}
if (operator) {
isEqual = isEqual && obj.operator === operator;
}
if (value) {
isEqual = isEqual && obj.value === value;
}
if (matchCase) {
isEqual = isEqual && obj.matchCase === matchCase;
}
return isEqual;
};
describe('Checkbox dialog functionalities => ', () => {
let gridObj: Grid;
let actionBegin: () => void;
let checkBoxFilter: Element;
let actionComplete: () => void;
beforeAll((done: Function) => {
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)
}
gridObj = createGrid(
{
dataSource: filterData,
allowFiltering: true,
allowPaging: false,
filterSettings: { type: 'CheckBox', showFilterBarStatus: true },
columns: [{ field: 'OrderID', type: 'number', visible: true },
{ field: 'CustomerID', type: 'string' },
{ field: 'Freight', format: 'C2', type: 'number' },
{ field: 'OrderDate', format: 'yMd'}
],
actionBegin: actionBegin,
actionComplete: actionComplete
}, done);
});
it('dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
expect(checkBoxFilter.querySelectorAll('.e-searchinput').length).toBe(1);
expect(checkBoxFilter.querySelectorAll('.e-selectall').length).toBe(1);
expect(checkBoxFilter.querySelectorAll('.e-chk-hidden').length).toBe(72);
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(72);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(0);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(0);
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('OrderID').querySelector('.e-filtermenudiv')));
});
it('intermediate state testing', () => {
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[1] as any).click();
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(1);
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[2] as any).click();
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(1);
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[1] as any).click();
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[2] as any).click();
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(0);
});
it('search box keyup testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterchoicerequest'){
expect(gridObj.element.querySelector('.e-searchcontainer').querySelectorAll('.e-searchinput').length).toBe(1);
expect(checkBoxFilter.querySelectorAll('.e-selectall').length).toBe(1);
expect(checkBoxFilter.querySelectorAll('.e-chk-hidden').length).toBe(3);
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(3);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(0);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(0);
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
let searchElement : any = gridObj.element.querySelector('.e-searchinput');
searchElement.value = '1024';
(gridObj.filterModule as any).filterModule.checkBoxBase.searchBoxKeyUp(getKeyUpObj(13,searchElement));
});
it('search box keyup repeat testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterchoicerequest'){
expect(checkBoxFilter.querySelectorAll('.e-selectall').length).toBe(1);
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(2);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(0);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(0);
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
let searchElement : any = gridObj.element.querySelector('.e-searchinput');
searchElement.value = '10249';
(gridObj.filterModule as any).filterModule.checkBoxBase.searchBoxKeyUp(getKeyUpObj(13,searchElement));
});
it('search box keyup invalid input testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterchoicerequest'){
expect(checkBoxFilter.querySelectorAll('.e-selectall').length).toBe(0);
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(0);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(0);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(0);
expect(checkBoxFilter.querySelector('.e-checkfltrnmdiv').children[0].innerHTML).toBe('No matches found');
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
let searchElement : any = gridObj.element.querySelector('.e-searchinput');
searchElement.value = '1024923';
(gridObj.filterModule as any).filterModule.checkBoxBase.searchBoxKeyUp(getKeyUpObj(13,searchElement));
});
it('search box keyup invalid - corrected input testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterchoicerequest'){
expect(checkBoxFilter.querySelectorAll('.e-selectall').length).toBe(1);
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(2);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(0);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(0);
expect(checkBoxFilter.children[0].tagName.toLowerCase()).not.toBe('span');
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
let searchElement : any = gridObj.element.querySelector('.e-searchinput');
searchElement.value = '10248';
(gridObj.filterModule as any).filterModule.checkBoxBase.searchBoxKeyUp(getKeyUpObj(13,searchElement));
});
it('clear searchbox testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterchoicerequest'){
expect(checkBoxFilter.querySelectorAll('.e-selectall').length).toBe(1);
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(72);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(0);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(0);
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
let searchElement : any = gridObj.element.querySelector('.e-searchinput');
searchElement.value = '';
(gridObj.filterModule as any).filterModule.checkBoxBase.searchBoxKeyUp(getKeyUpObj(13,searchElement));
});
it('intermediate state with keyup testing', (done: Function) => {
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[1] as any).click();
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[2] as any).click();
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(1);
actionComplete = (args?: any): void => {
if(args.requestType === 'filterchoicerequest'){
expect(checkBoxFilter.querySelectorAll('.e-selectall').length).toBe(1);
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(2);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(0);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(0);
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[1] as any).click();
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
let searchElement : any = gridObj.element.querySelector('.e-searchinput');
searchElement.value = '10255';
(gridObj.filterModule as any).filterModule.checkBoxBase.searchBoxKeyUp(getKeyUpObj(13,searchElement));
});
it('intermediate state with keyup - clear testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterchoicerequest'){
expect(checkBoxFilter.querySelectorAll('.e-selectall').length).toBe(1);
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(72);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(0);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(0);
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
let searchElement : any = gridObj.element.querySelector('.e-searchinput');
searchElement.value = '';
(gridObj.filterModule as any).filterModule.checkBoxBase.searchBoxKeyUp(getKeyUpObj(13,searchElement));
});
it('select all testing', () => {
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[0] as any).click();
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(0);
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(0);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(72);
// filter btn disable testing
expect(checkBoxFilter.querySelectorAll('button')[0].getAttribute('disabled')).not.toBeNull();
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[0] as any).click();
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(0);
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(72);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(0);
// filter btn disable testing
expect(checkBoxFilter.querySelectorAll('button')[0].getAttribute('disabled')).toBeNull();
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[1] as any).click();
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(1);
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(70);
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[1] as any).click();
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(0);
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(72);
//repeat same - faced this issue in rare scenario
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[0] as any).click();
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(0);
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(0);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(72);
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[0] as any).click();
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(0);
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(72);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(0);
});
//scenario1: filter orderid, customerid, freight - 2 items uncheck and then clear filter freight, customerid, orderid
it('Filter orderID testing', (done: Function) => {
actionComplete = (args?: any): void => {
expect(gridObj.filterSettings.columns.length).toBe(2);
expect(checkFilterObj(gridObj.filterSettings.columns[0], 'OrderID', 'notequal', 10248, 'and', false)).toBeTruthy();
expect(gridObj.element.querySelectorAll('.e-row').length).toBe(69);
expect(gridObj.getColumnHeaderByField('OrderID').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeTruthy();
gridObj.actionComplete =null;
done();
};
gridObj.actionComplete = actionComplete;
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[1] as any).click();
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[2] as any).click();
checkBoxFilter.querySelectorAll('button')[0].click();
});
it('orderID dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(69);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(2);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(1);
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('OrderID').querySelector('.e-filtermenudiv')));
});
it('Freight dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(69);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(0);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(0);
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('Freight').querySelector('.e-filtermenudiv')));
});
it('CustomerID dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(43);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(0);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(0);
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('CustomerID').querySelector('.e-filtermenudiv')));
});
it('Filter CustomerID testing', (done: Function) => {
actionComplete = (args?: any): void => {
expect(gridObj.filterSettings.columns.length).toBe(4);
expect(checkFilterObj(gridObj.filterSettings.columns[2], 'CustomerID', 'notequal', 'ANATR', 'and', false)).toBeTruthy();
expect(gridObj.element.querySelectorAll('.e-row').length).toBe(66);
expect(gridObj.getColumnHeaderByField('OrderID').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeTruthy();
expect(gridObj.getColumnHeaderByField('CustomerID').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeTruthy();
gridObj.actionComplete =null;
done();
};
gridObj.actionComplete = actionComplete;
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[1] as any).click();
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[2] as any).click();
checkBoxFilter.querySelectorAll('button')[0].click();
});
it('orderID dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(66);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(2);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(1);
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('OrderID').querySelector('.e-filtermenudiv')));
});
it('CustomerID dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(40);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(2);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(1);
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('CustomerID').querySelector('.e-filtermenudiv')));
});
it('Freight dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(66);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(0);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(0);
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('Freight').querySelector('.e-filtermenudiv')));
});
it('Filter Freight testing', (done: Function) => {
actionComplete = (args?: any): void => {
expect(gridObj.filterSettings.columns.length).toBe(6);
expect(checkFilterObj(gridObj.filterSettings.columns[4], 'Freight', 'notequal', 0.12, 'and', false)).toBeTruthy();
expect(gridObj.element.querySelectorAll('.e-row').length).toBe(64);
expect(gridObj.getColumnHeaderByField('OrderID').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeTruthy();
expect(gridObj.getColumnHeaderByField('CustomerID').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeTruthy();
expect(gridObj.getColumnHeaderByField('Freight').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeTruthy();
gridObj.actionComplete =null;
done();
};
gridObj.actionComplete = actionComplete;
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[1] as any).click();
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[2] as any).click();
checkBoxFilter.querySelectorAll('button')[0].click();
});
it('orderID dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(64);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(2);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(1);
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('OrderID').querySelector('.e-filtermenudiv')));
});
it('CustomerID dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(40);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(2);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(1);
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('CustomerID').querySelector('.e-filtermenudiv')));
});
it('Freight dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(63);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(2);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(1);
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('Freight').querySelector('.e-filtermenudiv')));
});
it('Clear Filter Freight testing', (done: Function) => {
actionComplete = (args?: any): void => {
expect(gridObj.filterSettings.columns.length).toBe(4);
expect(gridObj.element.querySelectorAll('.e-row').length).toBe(66);
expect(gridObj.getColumnHeaderByField('OrderID').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeTruthy();
expect(gridObj.getColumnHeaderByField('CustomerID').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeTruthy();
expect(gridObj.getColumnHeaderByField('Freight').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeFalsy();
gridObj.actionComplete =null;
done();
};
gridObj.actionComplete = actionComplete;
checkBoxFilter.querySelectorAll('button')[1].click();
});
it('Freight dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(66);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(0);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(0);
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('Freight').querySelector('.e-filtermenudiv')));
});
it('CustomerID dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen') {
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('CustomerID').querySelector('.e-filtermenudiv')));
});
it('Clear Filter CustomerID testing', (done: Function) => {
actionComplete = (args?: any): void => {
expect(gridObj.filterSettings.columns.length).toBe(2);
expect(gridObj.element.querySelectorAll('.e-row').length).toBe(69);
expect(gridObj.getColumnHeaderByField('OrderID').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeTruthy();
expect(gridObj.getColumnHeaderByField('CustomerID').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeFalsy();
expect(gridObj.getColumnHeaderByField('Freight').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeFalsy();
gridObj.actionComplete =null;
done();
};
gridObj.actionComplete = actionComplete;
checkBoxFilter.querySelectorAll('button')[1].click();
});
it('CustomerID dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(43);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(0);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(0);
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('CustomerID').querySelector('.e-filtermenudiv')));
});
it('OrderID dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen') {
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('OrderID').querySelector('.e-filtermenudiv')));
});
it('Clear Filter OrderID testing', (done: Function) => {
actionComplete = (args?: any): void => {
expect(gridObj.filterSettings.columns.length).toBe(0);
expect(gridObj.element.querySelectorAll('.e-row').length).toBe(71);
expect(gridObj.getColumnHeaderByField('OrderID').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeFalsy();
expect(gridObj.getColumnHeaderByField('CustomerID').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeFalsy();
expect(gridObj.getColumnHeaderByField('Freight').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeFalsy();
gridObj.actionComplete =null;
done();
};
gridObj.actionComplete = actionComplete;
checkBoxFilter.querySelectorAll('button')[1].click();
});
it('OrderID dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(72);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(0);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(0);
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('OrderID').querySelector('.e-filtermenudiv')));
});
//scenario1 cases completed
//scenario2: filter orderid, customerid, freight - 2 items uncheck and then clear filter orderid, customerid, freight
it('Filter orderID testing', (done: Function) => {
actionComplete = (args?: any): void => {
expect(gridObj.filterSettings.columns.length).toBe(2);
expect(checkFilterObj(gridObj.filterSettings.columns[0], 'OrderID', 'notequal', 10248, 'and', false)).toBeTruthy();
expect(gridObj.element.querySelectorAll('.e-row').length).toBe(69);
expect(gridObj.getColumnHeaderByField('OrderID').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeTruthy();
gridObj.actionComplete =null;
done();
};
gridObj.actionComplete = actionComplete;
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[1] as any).click();
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[2] as any).click();
checkBoxFilter.querySelectorAll('button')[0].click();
});
it('orderID dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(69);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(2);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(1);
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('OrderID').querySelector('.e-filtermenudiv')));
});
it('Freight dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(69);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(0);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(0);
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('Freight').querySelector('.e-filtermenudiv')));
});
it('CustomerID dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(43);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(0);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(0);
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('CustomerID').querySelector('.e-filtermenudiv')));
});
it('Filter CustomerID testing', (done: Function) => {
actionComplete = (args?: any): void => {
expect(gridObj.filterSettings.columns.length).toBe(4);
expect(checkFilterObj(gridObj.filterSettings.columns[2], 'CustomerID', 'notequal', 'ANATR', 'and', false)).toBeTruthy();
expect(gridObj.element.querySelectorAll('.e-row').length).toBe(66);
expect(gridObj.getColumnHeaderByField('OrderID').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeTruthy();
expect(gridObj.getColumnHeaderByField('CustomerID').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeTruthy();
gridObj.actionComplete =null;
done();
};
gridObj.actionComplete = actionComplete;
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[1] as any).click();
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[2] as any).click();
checkBoxFilter.querySelectorAll('button')[0].click();
});
it('orderID dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(66);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(2);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(1);
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('OrderID').querySelector('.e-filtermenudiv')));
});
it('CustomerID dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(40);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(2);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(1);
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('CustomerID').querySelector('.e-filtermenudiv')));
});
it('Freight dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(66);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(0);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(0);
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('Freight').querySelector('.e-filtermenudiv')));
});
it('Filter Freight testing', (done: Function) => {
actionComplete = (args?: any): void => {
expect(gridObj.filterSettings.columns.length).toBe(6);
expect(checkFilterObj(gridObj.filterSettings.columns[4], 'Freight', 'notequal', 0.12, 'and', false)).toBeTruthy();
expect(gridObj.element.querySelectorAll('.e-row').length).toBe(64);
expect(gridObj.getColumnHeaderByField('OrderID').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeTruthy();
expect(gridObj.getColumnHeaderByField('CustomerID').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeTruthy();
expect(gridObj.getColumnHeaderByField('Freight').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeTruthy();
gridObj.actionComplete =null;
done();
};
gridObj.actionComplete = actionComplete;
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[1] as any).click();
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[2] as any).click();
checkBoxFilter.querySelectorAll('button')[0].click();
});
it('orderID dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(64);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(2);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(1);
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('OrderID').querySelector('.e-filtermenudiv')));
});
it('CustomerID dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(40);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(2);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(1);
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('CustomerID').querySelector('.e-filtermenudiv')));
});
it('Freight dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(63);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(2);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(1);
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('Freight').querySelector('.e-filtermenudiv')));
});
it('OrderID dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen') {
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('OrderID').querySelector('.e-filtermenudiv')));
});
it('Clear Filter OrderID testing', (done: Function) => {
actionComplete = (args?: any): void => {
expect(gridObj.filterSettings.columns.length).toBe(4);
expect(gridObj.element.querySelectorAll('.e-row').length).toBe(66);
expect(gridObj.getColumnHeaderByField('OrderID').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeFalsy();
expect(gridObj.getColumnHeaderByField('CustomerID').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeTruthy();
expect(gridObj.getColumnHeaderByField('Freight').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeTruthy();
gridObj.actionComplete =null;
done();
};
gridObj.actionComplete = actionComplete;
checkBoxFilter.querySelectorAll('button')[1].click();
});
it('OrderID dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(67);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(0);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(0);
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('OrderID').querySelector('.e-filtermenudiv')));
});
it('Freight dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(65);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(2);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(1);
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('Freight').querySelector('.e-filtermenudiv')));
});
it('CustomerID dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen') {
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(41);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(2);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(1);
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('CustomerID').querySelector('.e-filtermenudiv')));
});
it('Clear Filter CustomerID testing', (done: Function) => {
actionComplete = (args?: any): void => {
expect(gridObj.filterSettings.columns.length).toBe(2);
expect(gridObj.element.querySelectorAll('.e-row').length).toBe(69);
expect(gridObj.getColumnHeaderByField('OrderID').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeFalsy();
expect(gridObj.getColumnHeaderByField('CustomerID').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeFalsy();
expect(gridObj.getColumnHeaderByField('Freight').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeTruthy();
gridObj.actionComplete =null;
done();
};
gridObj.actionComplete = actionComplete;
checkBoxFilter.querySelectorAll('button')[1].click();
});
it('CustomerID dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(44);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(0);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(0);
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('CustomerID').querySelector('.e-filtermenudiv')));
});
it('OrderID dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen') {
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(70);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(0);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(0);
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('OrderID').querySelector('.e-filtermenudiv')));
});
it('Freight dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(68);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(2);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(1);
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('Freight').querySelector('.e-filtermenudiv')));
});
it('Clear Filter Freight testing', (done: Function) => {
actionComplete = (args?: any): void => {
expect(gridObj.filterSettings.columns.length).toBe(0);
expect(gridObj.element.querySelectorAll('.e-row').length).toBe(71);
expect(gridObj.getColumnHeaderByField('OrderID').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeFalsy();
expect(gridObj.getColumnHeaderByField('CustomerID').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeFalsy();
expect(gridObj.getColumnHeaderByField('Freight').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeFalsy();
gridObj.actionComplete =null;
done();
};
gridObj.actionComplete = actionComplete;
checkBoxFilter.querySelectorAll('button')[1].click();
});
it('OrderID dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(72);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(0);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(0);
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('OrderID').querySelector('.e-filtermenudiv')));
});
//scenario2 cases completed
//scenario3: filter orderid, customerid, freight - 2 to 4 items check and then clear filter freight, customerid, orderid
it('Filter orderID testing', (done: Function) => {
actionComplete = (args?: any): void => {
expect(gridObj.filterSettings.columns.length).toBe(4);
expect(checkFilterObj(gridObj.filterSettings.columns[0], 'OrderID', 'equal', 10248, 'or', false)).toBeTruthy();
expect(gridObj.element.querySelectorAll('.e-row').length).toBe(4);
expect(gridObj.getColumnHeaderByField('OrderID').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeTruthy();
gridObj.actionComplete =null;
done();
};
gridObj.actionComplete = actionComplete;
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[0] as any).click();
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[1] as any).click();
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[2] as any).click();
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[3] as any).click();
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[4] as any).click();
checkBoxFilter.querySelectorAll('button')[0].click();
});
it('orderID dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(4);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(67);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(1);
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('OrderID').querySelector('.e-filtermenudiv')));
});
it('Freight dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(5);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(0);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(0);
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('Freight').querySelector('.e-filtermenudiv')));
});
it('CustomerID dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(5);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(0);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(0);
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('CustomerID').querySelector('.e-filtermenudiv')));
});
it('Filter CustomerID testing', (done: Function) => {
actionComplete = (args?: any): void => {
expect(gridObj.filterSettings.columns.length).toBe(6);
expect(checkFilterObj(gridObj.filterSettings.columns[5], 'CustomerID', 'equal', 'TOMSP', 'or', false)).toBeTruthy();
expect(gridObj.element.querySelectorAll('.e-row').length).toBe(2);
expect(gridObj.getColumnHeaderByField('OrderID').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeTruthy();
expect(gridObj.getColumnHeaderByField('CustomerID').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeTruthy();
gridObj.actionComplete =null;
done();
};
gridObj.actionComplete = actionComplete;
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[0] as any).click();
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[1] as any).click();
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[2] as any).click();
checkBoxFilter.querySelectorAll('button')[0].click();
});
it('orderID dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(2);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(1);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(1);
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('OrderID').querySelector('.e-filtermenudiv')));
});
it('CustomerID dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(2);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(2);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(1);
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('CustomerID').querySelector('.e-filtermenudiv')));
});
it('Freight dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(3);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(0);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(0);
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('Freight').querySelector('.e-filtermenudiv')));
});
it('Filter Freight testing', (done: Function) => {
actionComplete = (args?: any): void => {
expect(gridObj.filterSettings.columns.length).toBe(7);
expect(checkFilterObj(gridObj.filterSettings.columns[6], 'Freight', 'equal', 11.61, 'or', false)).toBeTruthy();
expect(gridObj.element.querySelectorAll('.e-row').length).toBe(1);
expect(gridObj.getColumnHeaderByField('OrderID').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeTruthy();
expect(gridObj.getColumnHeaderByField('CustomerID').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeTruthy();
expect(gridObj.getColumnHeaderByField('Freight').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeTruthy();
gridObj.actionComplete =null;
done();
};
gridObj.actionComplete = actionComplete;
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[0] as any).click();
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[1] as any).click();
checkBoxFilter.querySelectorAll('button')[0].click();
});
it('orderID dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(2);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(0);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(0);
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('OrderID').querySelector('.e-filtermenudiv')));
});
it('CustomerID dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(2);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(0);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(0);
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('CustomerID').querySelector('.e-filtermenudiv')));
});
it('Freight dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(1);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(1);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(1);
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('Freight').querySelector('.e-filtermenudiv')));
});
it('Clear Filter Freight testing', (done: Function) => {
actionComplete = (args?: any): void => {
expect(gridObj.filterSettings.columns.length).toBe(6);
expect(gridObj.element.querySelectorAll('.e-row').length).toBe(2);
expect(gridObj.getColumnHeaderByField('OrderID').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeTruthy();
expect(gridObj.getColumnHeaderByField('CustomerID').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeTruthy();
expect(gridObj.getColumnHeaderByField('Freight').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeFalsy();
gridObj.actionComplete =null;
done();
};
gridObj.actionComplete = actionComplete;
checkBoxFilter.querySelectorAll('button')[1].click();
});
it('Freight dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(3);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(0);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(0);
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('Freight').querySelector('.e-filtermenudiv')));
});
it('CustomerID dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen') {
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('CustomerID').querySelector('.e-filtermenudiv')));
});
it('Clear Filter CustomerID testing', (done: Function) => {
actionComplete = (args?: any): void => {
expect(gridObj.filterSettings.columns.length).toBe(4);
expect(gridObj.element.querySelectorAll('.e-row').length).toBe(4);
expect(gridObj.getColumnHeaderByField('OrderID').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeTruthy();
expect(gridObj.getColumnHeaderByField('CustomerID').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeFalsy();
expect(gridObj.getColumnHeaderByField('Freight').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeFalsy();
gridObj.actionComplete =null;
done();
};
gridObj.actionComplete = actionComplete;
checkBoxFilter.querySelectorAll('button')[1].click();
});
it('CustomerID dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(5);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(0);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(0);
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('CustomerID').querySelector('.e-filtermenudiv')));
});
it('OrderID dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen') {
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('OrderID').querySelector('.e-filtermenudiv')));
});
it('Clear Filter OrderID testing', (done: Function) => {
actionComplete = (args?: any): void => {
expect(gridObj.filterSettings.columns.length).toBe(0);
expect(gridObj.element.querySelectorAll('.e-row').length).toBe(71);
expect(gridObj.getColumnHeaderByField('OrderID').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeFalsy();
expect(gridObj.getColumnHeaderByField('CustomerID').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeFalsy();
expect(gridObj.getColumnHeaderByField('Freight').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeFalsy();
gridObj.actionComplete =null;
done();
};
gridObj.actionComplete = actionComplete;
checkBoxFilter.querySelectorAll('button')[1].click();
});
it('OrderID dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(72);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(0);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(0);
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('OrderID').querySelector('.e-filtermenudiv')));
});
//scenario3 cases completed
//scenario4: filter orderid, customerid, freight - 2 to 4 items check and then clear filter orderid, customerid, freight
it('Filter orderID testing', (done: Function) => {
actionComplete = (args?: any): void => {
expect(gridObj.filterSettings.columns.length).toBe(4);
expect(checkFilterObj(gridObj.filterSettings.columns[0], 'OrderID', 'equal', 10248, 'or', false)).toBeTruthy();
expect(gridObj.element.querySelectorAll('.e-row').length).toBe(4);
expect(gridObj.getColumnHeaderByField('OrderID').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeTruthy();
gridObj.actionComplete =null;
done();
};
gridObj.actionComplete = actionComplete;
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[0] as any).click();
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[1] as any).click();
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[2] as any).click();
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[3] as any).click();
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[4] as any).click();
checkBoxFilter.querySelectorAll('button')[0].click();
});
it('orderID dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(4);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(67);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(1);
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('OrderID').querySelector('.e-filtermenudiv')));
});
it('Freight dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(5);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(0);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(0);
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('Freight').querySelector('.e-filtermenudiv')));
});
it('CustomerID dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(5);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(0);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(0);
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('CustomerID').querySelector('.e-filtermenudiv')));
});
it('Filter CustomerID testing', (done: Function) => {
actionComplete = (args?: any): void => {
expect(gridObj.filterSettings.columns.length).toBe(6);
expect(checkFilterObj(gridObj.filterSettings.columns[5], 'CustomerID', 'equal', 'TOMSP', 'or', false)).toBeTruthy();
expect(gridObj.element.querySelectorAll('.e-row').length).toBe(2);
expect(gridObj.getColumnHeaderByField('OrderID').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeTruthy();
expect(gridObj.getColumnHeaderByField('CustomerID').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeTruthy();
gridObj.actionComplete =null;
done();
};
gridObj.actionComplete = actionComplete;
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[0] as any).click();
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[1] as any).click();
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[2] as any).click();
checkBoxFilter.querySelectorAll('button')[0].click();
});
it('orderID dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(2);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(1);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(1);
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('OrderID').querySelector('.e-filtermenudiv')));
});
it('CustomerID dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(2);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(2);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(1);
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('CustomerID').querySelector('.e-filtermenudiv')));
});
it('Freight dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(3);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(0);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(0);
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('Freight').querySelector('.e-filtermenudiv')));
});
it('Filter Freight testing', (done: Function) => {
actionComplete = (args?: any): void => {
expect(gridObj.filterSettings.columns.length).toBe(7);
expect(checkFilterObj(gridObj.filterSettings.columns[6], 'Freight', 'equal', 11.61, 'or', false)).toBeTruthy();
expect(gridObj.element.querySelectorAll('.e-row').length).toBe(1);
expect(gridObj.getColumnHeaderByField('OrderID').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeTruthy();
expect(gridObj.getColumnHeaderByField('CustomerID').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeTruthy();
expect(gridObj.getColumnHeaderByField('Freight').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeTruthy();
gridObj.actionComplete =null;
done();
};
gridObj.actionComplete = actionComplete;
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[0] as any).click();
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[1] as any).click();
checkBoxFilter.querySelectorAll('button')[0].click();
});
it('orderID dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(2);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(0);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(0);
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('OrderID').querySelector('.e-filtermenudiv')));
});
it('CustomerID dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(2);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(0);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(0);
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('CustomerID').querySelector('.e-filtermenudiv')));
});
it('Freight dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(1);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(1);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(1);
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('Freight').querySelector('.e-filtermenudiv')));
});
it('OrderID dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen') {
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('OrderID').querySelector('.e-filtermenudiv')));
});
it('Clear Filter OrderID testing', (done: Function) => {
actionComplete = (args?: any): void => {
expect(gridObj.filterSettings.columns.length).toBe(3);
expect(gridObj.element.querySelectorAll('.e-row').length).toBe(1);
expect(gridObj.getColumnHeaderByField('OrderID').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeFalsy();
expect(gridObj.getColumnHeaderByField('CustomerID').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeTruthy();
expect(gridObj.getColumnHeaderByField('Freight').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeTruthy();
gridObj.actionComplete =null;
done();
};
gridObj.actionComplete = actionComplete;
checkBoxFilter.querySelectorAll('button')[1].click();
});
it('OrderID dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(2);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(0);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(0);
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('OrderID').querySelector('.e-filtermenudiv')));
});
it('Freight dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(1);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(2);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(1);
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('Freight').querySelector('.e-filtermenudiv')));
});
it('CustomerID dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen') {
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(2);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(0);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(0);
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('CustomerID').querySelector('.e-filtermenudiv')));
});
it('Clear Filter CustomerID testing', (done: Function) => {
actionComplete = (args?: any): void => {
expect(gridObj.filterSettings.columns.length).toBe(1);
expect(gridObj.element.querySelectorAll('.e-row').length).toBe(1);
expect(gridObj.getColumnHeaderByField('OrderID').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeFalsy();
expect(gridObj.getColumnHeaderByField('CustomerID').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeFalsy();
expect(gridObj.getColumnHeaderByField('Freight').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeTruthy();
gridObj.actionComplete =null;
done();
};
gridObj.actionComplete = actionComplete;
checkBoxFilter.querySelectorAll('button')[1].click();
});
it('CustomerID dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(2);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(0);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(0);
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('CustomerID').querySelector('.e-filtermenudiv')));
});
it('OrderID dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen') {
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(2);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(0);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(0);
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('OrderID').querySelector('.e-filtermenudiv')));
});
it('Freight dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(1);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(69);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(1);
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('Freight').querySelector('.e-filtermenudiv')));
});
it('Clear Filter Freight testing', (done: Function) => {
actionComplete = (args?: any): void => {
expect(gridObj.filterSettings.columns.length).toBe(0);
expect(gridObj.element.querySelectorAll('.e-row').length).toBe(71);
expect(gridObj.getColumnHeaderByField('OrderID').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeFalsy();
expect(gridObj.getColumnHeaderByField('CustomerID').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeFalsy();
expect(gridObj.getColumnHeaderByField('Freight').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeFalsy();
gridObj.actionComplete =null;
done();
};
gridObj.actionComplete = actionComplete;
checkBoxFilter.querySelectorAll('button')[1].click();
});
it('OrderID dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(72);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(0);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(0);
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('OrderID').querySelector('.e-filtermenudiv')));
});
//scenario4 cases completed
//scenario5 multiple filter on same column
it('Filter orderID testing', (done: Function) => {
actionComplete = (args?: any): void => {
expect(gridObj.filterSettings.columns.length).toBe(3);
expect(checkFilterObj(gridObj.filterSettings.columns[0], 'OrderID', 'notequal', 10248, 'or', false)).toBeTruthy();
expect(gridObj.element.querySelectorAll('.e-row').length).toBe(68);
expect(gridObj.getColumnHeaderByField('OrderID').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeTruthy();
gridObj.actionComplete =null;
done();
};
gridObj.actionComplete = actionComplete;
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[1] as any).click();
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[2] as any).click();
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[3] as any).click();
checkBoxFilter.querySelectorAll('button')[0].click();
});
it('orderID dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(68);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(3);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(1);
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('OrderID').querySelector('.e-filtermenudiv')));
});
it('Filter orderID testing', (done: Function) => {
actionComplete = (args?: any): void => {
expect(gridObj.filterSettings.columns.length).toBe(2);
expect(checkFilterObj(gridObj.filterSettings.columns[0], 'OrderID', 'equal', 10251, 'or', false)).toBeTruthy();
expect(gridObj.element.querySelectorAll('.e-row').length).toBe(2);
expect(gridObj.getColumnHeaderByField('OrderID').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeTruthy();
gridObj.actionComplete =null;
done();
};
gridObj.actionComplete = actionComplete;
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[0] as any).click();
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[0] as any).click();
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[4] as any).click();
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[5] as any).click();
checkBoxFilter.querySelectorAll('button')[0].click();
});
it('orderID dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(2);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(69);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(1);
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('OrderID').querySelector('.e-filtermenudiv')));
});
it('Clear Filter OrderID testing', (done: Function) => {
actionComplete = (args?: any): void => {
expect(gridObj.filterSettings.columns.length).toBe(0);
expect(gridObj.element.querySelectorAll('.e-row').length).toBe(71);
expect(gridObj.getColumnHeaderByField('OrderID').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeFalsy();
expect(gridObj.getColumnHeaderByField('CustomerID').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeFalsy();
expect(gridObj.getColumnHeaderByField('Freight').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeFalsy();
gridObj.actionComplete =null;
done();
};
gridObj.actionComplete = actionComplete;
checkBoxFilter.querySelectorAll('button')[1].click();
});
it('OrderID dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(72);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(0);
expect(checkBoxFilter.querySelectorAll('.e-stop').length).toBe(0);
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('OrderID').querySelector('.e-filtermenudiv')));
});
it('EJ2-6971-Date filter search checking ', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
expect(gridObj.getColumnByField('OrderDate').type).toBe('datetime');
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
(<any>gridObj.filterModule).filterModule.checkBoxBase.sInput.value = '7/9/1996';
(<any>gridObj.filterModule).filterModule.checkBoxBase.refreshCheckboxes();
expect(checkBoxFilter.querySelector('.e-checkboxlist.e-fields').children.length).toBeGreaterThanOrEqual(2);
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('OrderDate').querySelector('.e-filtermenudiv')));
});
it('EJ2-7690-Search In Filtering Dialog Box Get Closed While Press "Enter Key" ', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
(<any>gridObj.filterModule).filterModule.checkBoxBase.sInput.value = 'Vinet';
(<any>gridObj.filterModule).filterModule.checkBoxBase.btnClick({target: (<any>gridObj.filterModule).filterModule.checkBoxBase.sInput});
}
if (args.requestType === 'filtering') {
expect(gridObj.currentViewData[0]['CustomerID']).toBe('VINET');
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('CustomerID').querySelector('.e-filtermenudiv')));
});
// time - delayed issue
// it('EJ2-7257-Need to hide the filter button in check box filter when no matches found like EJ1 ', (done: Function) => {
// actionComplete = (args?: any): void => {
// if(args.requestType === 'filterafteropen'){
// checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
// (<any>gridObj.filterModule).filterModule.sInput.value = 'edybh';
// (<any>gridObj.filterModule).filterModule.refreshCheckboxes();
// expect(checkBoxFilter.querySelector('.e-footer-content').children[0].hasAttribute('disabled')).toBeTruthy();
// let edit: any = (<any>new Edit(gridObj, gridObj.serviceLocator));
// spyOn(edit, 'deleteRecord');
// edit.keyPressHandler({action: 'delete', target: gridObj.element});
// expect(edit.deleteRecord).not.toHaveBeenCalled();
// gridObj.actionComplete = null;
// done();
// }
// };
// gridObj.actionComplete = actionComplete;
// (gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('CustomerID').querySelector('.e-filtermenudiv')));
// });
// //scenario5 case completed
afterAll(() => {
destroy(gridObj);
gridObj = checkBoxFilter = actionBegin = actionComplete = null;
});
});
describe('EJ2-7408 Checkbox filter for column and filter type menu => ', () => {
let gridObj: Grid;
let actionBegin: () => void;
let checkBoxFilter: Element;
let actionComplete: () => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: filterData,
allowFiltering: true,
allowPaging: false,
filterSettings: { type: 'Menu', showFilterBarStatus: true },
columns: [{ field: 'OrderID', type: 'number', visible: true },
{ field: 'CustomerID', type: 'string', filter: {type: 'CheckBox'} },
{ field: 'Freight', format: 'C2', type: 'number' }
],
actionBegin: actionBegin,
actionComplete: actionComplete
}, done);
});
it('CustomerID dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('CustomerID').querySelector('.e-filtermenudiv')));
});
it('Filter CustomerID testing', (done: Function) => {
actionComplete = (args?: any): void => {
expect(gridObj.filterSettings.columns.length).toBe(2);
expect(gridObj.element.querySelectorAll('.e-row').length).toBe(68);
gridObj.actionComplete =null;
done();
};
gridObj.actionComplete = actionComplete;
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[1] as any).click();
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[2] as any).click();
checkBoxFilter.querySelectorAll('button')[0].click();
});
afterAll(() => {
destroy(gridObj);
gridObj = checkBoxFilter = actionBegin = actionComplete = null;
});
});
describe('EJ2-13031 Batch confirm for checkbox filter => ', () => {
let gridObj: Grid;
let actionBegin: () => void;
let checkBoxFilter: Element;
let actionComplete: () => void;
let cellEdit: () => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: filterData.slice(0),
allowFiltering: true,
editSettings: { allowEditing: true, allowAdding: true, allowDeleting: true, mode: 'Batch', showConfirmDialog: true, showDeleteConfirmDialog: false },
toolbar: ['Add', 'Edit', 'Delete', 'Update', 'Cancel'],
allowPaging: true,
filterSettings: { type: 'CheckBox' },
columns: [{ field: 'OrderID', type: 'number', visible: true },
{ field: 'CustomerID', type: 'string', filter: { type: 'CheckBox' } },
{ field: 'Freight', format: 'C2', type: 'number' }
],
actionBegin: actionBegin,
actionComplete: actionComplete,
cellEdit: cellEdit
}, done);
});
it('edit cell', () => {
gridObj.editModule.editCell(1, 'CustomerID');
});
it('shift tab key', () => {
gridObj.element.querySelector('.e-editedbatchcell').querySelector('input').value = 'updated';
gridObj.editModule.saveCell();
});
it('CustomerID dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if (args.requestType === 'filterafteropen') {
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
gridObj.actionComplete = null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('CustomerID').querySelector('.e-filtermenudiv')));
});
it('Filter CustomerID testing', () => {
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[0] as any).click();
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[1] as any).click();
checkBoxFilter.querySelectorAll('button')[0].click();
});
it('Check confirm dialog', () => {
expect(select('#' + gridObj.element.id + 'EditConfirm', gridObj.element).classList.contains('e-dialog')).toBeTruthy();
});
it('check data are filtered', (done: Function) => {
actionComplete = (args?: any): void => {
if (args.requestType === 'filtering') {
expect(gridObj.currentViewData[0]['CustomerID']).toBe('ANATR');
gridObj.actionComplete = null;
done();
}
};
gridObj.actionComplete = actionComplete;
select('#' + gridObj.element.id + 'EditConfirm', gridObj.element).querySelectorAll('button')[0].click();
});
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);
});
afterAll(() => {
destroy(gridObj);
gridObj = checkBoxFilter = actionBegin = actionComplete = null;
});
});
describe('Filter operation after searching ', () => {
let gridObj: Grid;
let actionBegin: () => void;
let actionComplete: () => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: filterData.slice(0),
allowFiltering: true,
filterSettings: { type: 'Excel' },
toolbar: ['Search'],
columns: [{ field: 'OrderID', type: 'number', visible: true },
{ field: 'CustomerID', type: 'string', filter: { type: 'CheckBox' } },
{ field: 'Freight', format: 'C2', type: 'number' }
],
actionBegin: actionBegin,
actionComplete: actionComplete,
}, done);
});
it('Search', function(done) {
actionComplete = (args?: any): void => {
expect(gridObj.currentViewData.length).toBe(1);
gridObj.actionComplete =null;
done();
};
gridObj.actionComplete = actionComplete;
gridObj.searchModule.search('32.38');
});
it('Filter after search toolbar action', function (done) {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
expect(gridObj.element.querySelectorAll('.e-check').length).toBe(2);
expect(gridObj.element.querySelectorAll('.e-selectall').length).toBe(1);
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('OrderID').querySelector('.e-filtermenudiv')));
});
afterAll(() => {
destroy(gridObj);
gridObj = checkFilterObj = actionBegin = actionComplete = null;
});
});
describe('EJ2-26559 enable case sensitivity check for Checkbox filter', () => {
let gridObj: Grid;
let actionBegin: () => void;
let checkBoxFilter: Element;
let actionComplete: () => void;
let checkFilterObj: Function = (obj: PredicateModel, field?: string,
operator?: string, value?: string, predicate?: string, matchCase?: boolean): boolean => {
let isEqual: boolean = true;
if (field) {
isEqual = isEqual && obj.field === field;
}
if (operator) {
isEqual = isEqual && obj.operator === operator;
}
if (value) {
isEqual = isEqual && obj.value === value;
}
if (matchCase) {
isEqual = isEqual && obj.matchCase === matchCase;
}
return isEqual;
};
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: filterData,
allowFiltering: true,
allowPaging: false,
filterSettings: { type: 'CheckBox', showFilterBarStatus: true },
columns: [{ field: 'OrderID', type: 'number', visible: true },
{ field: 'CustomerID', type: 'string', filter: {type: 'CheckBox'} },
{ field: 'Freight', format: 'C2', type: 'number' }
],
actionBegin: actionBegin,
actionComplete: actionComplete
}, done);
});
it('Filter OrderID dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('OrderID').querySelector('.e-filtermenudiv')));
});
it('Filter OrderID testing for matchcase default value true', (done: Function) => {
actionComplete = (args?: any): void => {
expect(gridObj.filterSettings.columns.length).toBe(2);
expect(checkFilterObj(gridObj.filterSettings.columns[0], 'OrderID', 'equal', 10248, 'or', true)).toBeFalsy();
expect(gridObj.element.querySelectorAll('.e-row').length).toBe(69);
expect(gridObj.getColumnHeaderByField('OrderID').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeTruthy();
gridObj.actionComplete =null;
done();
};
gridObj.actionComplete = actionComplete;
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[1] as any).click();
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[2] as any).click();
checkBoxFilter.querySelectorAll('button')[0].click();
});
it('Filter CustomerID dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('CustomerID').querySelector('.e-filtermenudiv')));
});
it('Filter CustomerID testing for matchcase default value true', (done: Function) => {
actionComplete = (args?: any): void => {
expect(gridObj.filterSettings.columns.length).toBe(4);
expect(checkFilterObj(gridObj.filterSettings.columns[2], 'CustomerID', 'notequal', 'ANATR', 'and', true)).toBeFalsy();
expect(gridObj.element.querySelectorAll('.e-row').length).toBe(66);
expect(gridObj.getColumnHeaderByField('OrderID').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeTruthy();
expect(gridObj.getColumnHeaderByField('CustomerID').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeTruthy();
gridObj.actionComplete =null;
done();
};
gridObj.actionComplete = actionComplete;
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[1] as any).click();
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[2] as any).click();
checkBoxFilter.querySelectorAll('button')[0].click();
});
it('Filter Freight dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('Freight').querySelector('.e-filtermenudiv')));
});
it('Filter Freight testing for matchcase default value true', (done: Function) => {
actionComplete = (args?: any): void => {
expect(gridObj.filterSettings.columns.length).toBe(6);
expect(checkFilterObj(gridObj.filterSettings.columns[4], 'Freight', 'notequal', 0.12, 'and', true)).toBeFalsy();
expect(gridObj.element.querySelectorAll('.e-row').length).toBe(64);
expect(gridObj.getColumnHeaderByField('OrderID').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeTruthy();
expect(gridObj.getColumnHeaderByField('CustomerID').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeTruthy();
expect(gridObj.getColumnHeaderByField('Freight').querySelector('.e-filtermenudiv').classList.contains('e-filtered')).toBeTruthy();
gridObj.actionComplete =null;
done();
};
gridObj.actionComplete = actionComplete;
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[1] as any).click();
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[2] as any).click();
checkBoxFilter.querySelectorAll('button')[0].click();
});
it('Filter Freight dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('Freight').querySelector('.e-filtermenudiv')));
});
it('Filter Freight testing ', (done: Function) => {
actionComplete = (args?: any): void => {
expect(args.requestType).toBe('filtering');
gridObj.actionComplete =null;
done();
};
gridObj.actionComplete = actionComplete;
checkBoxFilter.querySelectorAll('button')[1].click();
});
afterAll(() => {
destroy(gridObj);
gridObj = checkBoxFilter = actionBegin = actionComplete = null;
});
});
describe('EJ2-34831 parent query check for Checkbox filter searchlist ', function () {
let gridObj: Grid;
let actionBegin: () => void;
let checkBoxFilter: Element;
let actionComplete: () => void;
let checkFilterObj: Function = (obj: PredicateModel, field?: string,
operator?: string, value?: string, predicate?: string, matchCase?: boolean): boolean => {
let isEqual: boolean = true;
if (field) {
isEqual = isEqual && obj.field === field;
}
if (operator) {
isEqual = isEqual && obj.operator === operator;
}
if (value) {
isEqual = isEqual && obj.value === value;
}
if (matchCase) {
isEqual = isEqual && obj.matchCase === matchCase;
}
return isEqual;
};
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: filterData,
query: new Query().where("EmployeeID","equal",5),
allowFiltering: true,
allowPaging: false,
filterSettings: { type: 'CheckBox', showFilterBarStatus: true },
columns: [{ field: 'OrderID', type: 'number', visible: true },
{ field: 'CustomerID', type: 'string', filter: {type: 'CheckBox'} },
{ field: 'Freight', format: 'C2', type: 'number' }
],
actionBegin: actionBegin,
actionComplete: actionComplete
}, done);
});
it('Filter OrderID dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('OrderID').querySelector('.e-filtermenudiv')));
});
it('search OrderID testing for searchlist length', function (done) {
actionComplete = (args?: any): void => {
expect(checkBoxFilter.querySelectorAll('.e-selectall').length).toBe(1);
expect(checkBoxFilter.querySelectorAll('.e-chk-hidden').length).toBe(2);
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(2);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(0);
gridObj.actionComplete = null;
done();
};
gridObj.actionComplete = actionComplete;
let searchElement: any = gridObj.element.querySelector('.e-searchinput');
searchElement.value = '10248';
(gridObj.filterModule as any).filterModule.checkBoxBase.searchBoxKeyUp(getKeyUpObj(13, searchElement));
});
it('clear OrderID search testing for searchlist length', function (done) {
actionComplete = (args?: any): void => {
expect(checkBoxFilter.querySelectorAll('.e-selectall').length).toBe(1);
expect(checkBoxFilter.querySelectorAll('.e-chk-hidden').length).toBe(gridObj.currentViewData.length+1);
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(gridObj.currentViewData.length+1);
expect(checkBoxFilter.querySelectorAll('.e-uncheck').length).toBe(0);
gridObj.actionComplete = null;
done();
};
gridObj.actionComplete = actionComplete;
let searchElement: any = gridObj.element.querySelector('.e-searchinput');
searchElement.value = '';
(gridObj.filterModule as any).filterModule.checkBoxBase.searchBoxKeyUp(getKeyUpObj(13, searchElement));
});
afterAll(function () {
destroy(gridObj);
gridObj = checkBoxFilter = actionBegin = actionComplete = null;
});
});
describe('EJ2-36547- Adding value in filterSearchBegin event args ', function () {
let gridObj: Grid;
let actionBegin: () => void;
let checkBoxFilter: Element;
let actionComplete: () => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: filterData,
allowFiltering: true,
allowPaging: false,
filterSettings: { type: 'CheckBox', showFilterBarStatus: true },
columns: [{ field: 'OrderID', type: 'number', visible: true },
{ field: 'CustomerID', type: 'string', filter: {type: 'CheckBox'} },
{ field: 'Freight', format: 'C2', type: 'number' }
],
actionBegin: actionBegin,
actionComplete: actionComplete
}, done);
});
it('Filter OrderID dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('OrderID').querySelector('.e-filtermenudiv')));
});
it('search OrderID testing for search value in search begin event', function (done) {
actionBegin = (args?: FilterSearchBeginEventArgs): void => {
expect(args.value).toBe(10248);
gridObj.actionBegin = null;
done();
};
gridObj.actionBegin = actionBegin;
let searchElement: any = gridObj.element.querySelector('.e-searchinput');
searchElement.value = '10248';
(gridObj.filterModule as any).filterModule.checkBoxBase.searchBoxKeyUp(getKeyUpObj(13, searchElement));
});
afterAll(function () {
destroy(gridObj);
gridObj = checkBoxFilter = actionBegin = actionComplete = null;
});
});
describe('EJ2-36047- Incorrect datetime filter predicates ', function () {
let gridObj: Grid;
let fData: Object[] = [
{ OrderID: 10248, OrderDate: new Date(2019, 8, 28, 18, 33, 36), Freight: 32.38 },
{ OrderID: 10249, OrderDate: new Date(2019, 8, 28, 18, 33, 37), Freight: 11.61 },
{ OrderID: 10250, OrderDate: new Date(2019, 8, 28, 18, 33, 38), Freight: 65.83 },
{ OrderID: 10251, OrderDate: new Date(2019, 8, 28, 18, 35, 53), Freight: 41.34 }];
let actionComplete: () => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: fData,
allowFiltering: true,
allowPaging: false,
filterSettings: { type: 'CheckBox' },
columns: [{ field: 'OrderID', type: 'number', visible: true },
{ field: 'OrderDate', type: 'datetime' },
{ field: 'Freight', format: 'C2', type: 'number' }
],
actionComplete: actionComplete
}, done);
});
it('Filter OrderDate dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
expect(gridObj.currentViewData.length).toBe(4);
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('OrderDate').querySelector('.e-filtermenudiv')));
});
it('OrderDate dialog filter testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filtering'){
expect(gridObj.currentViewData.length).toBe(2);
gridObj.actionComplete =null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.element.querySelectorAll('.e-checkboxlist .e-frame:not(.e-selectall)')[0] as any).click();
(gridObj.element.querySelectorAll('.e-checkboxlist .e-frame:not(.e-selectall)')[1] as any).click();
(gridObj.element.querySelectorAll('.e-checkboxfilter .e-btn')[0] as any).click();
});
afterAll(function () {
destroy(gridObj);
gridObj = actionComplete = null;
});
});
describe('EJ2-37831 checkbox filtering with enter key', () => {
let gridObj: Grid;
let actionBegin: () => void;
let checkBoxFilter: Element;
let actionComplete: () => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: filterData,
allowFiltering: true,
filterSettings: { type: 'CheckBox' },
columns: [{ field: 'OrderID',headerText:'OrderID',visible: true },
{ field: 'CustomerID',headerText:'CustomerName'},
{ field: 'Freight', format: 'C2',headerText:'Freight' },
{ field: 'Verified',headerText:'Verified' }
],
actionBegin: actionBegin,
actionComplete: actionComplete
}, done);
});
it('OrderID filter dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('OrderID').querySelector('.e-filtermenudiv')));
});
it('Filter OrderID testing', () => {
actionComplete = (args?: any): void => {
expect(gridObj.filterSettings.columns.length).toBe(1);
};
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[0] as any).click();
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[1] as any).click();
gridObj.keyboardModule.keyAction({ action: 'enter', target: checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[1] } as any);
});
it('CustomerID filter dialog open testing', (done: Function) => {
actionComplete = (args?: any): void => {
if(args.requestType === 'filterafteropen'){
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('CustomerID').querySelector('.e-filtermenudiv')));
});
it('Filter CustomerID testing', () => {
actionComplete = (args?: any): void => {
expect(gridObj.filterSettings.columns.length).toBe(2);
};
let searchElement : any = gridObj.element.querySelector('.e-searchinput');
searchElement.value = 'ER';
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[0] as any).click();
(checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[1] as any).click();
gridObj.keyboardModule.keyAction({ action: 'enter', target: checkBoxFilter.querySelectorAll('.e-checkbox-wrapper')[1] } as any);
});
afterAll(() => {
destroy(gridObj);
gridObj = checkBoxFilter = actionBegin = actionComplete = null;
});
});
describe('EJ2-37912 - Checkbox selection not maintain properly in overview sample', () => {
let gridObj: Grid;
let chkAll: HTMLElement;
let actionComplete: () => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: filterData,
allowFiltering: true,
enableVirtualization: true,
filterSettings: { type: 'Menu' },
selectionSettings: { persistSelection: true, type: 'Multiple', checkboxOnly: true },
height: 500,
columns: [
{ type: 'checkbox', allowFiltering: false, allowSorting: false, width: '20' },
{ field: 'OrderID', isPrimaryKey: true, headerText: 'Order ID', textAlign: 'Right', width: 40 },
{ field: 'CustomerID', headerText: 'Customer ID', width: 40 },
{ field: 'Freight', headerText: 'Freight', textAlign: 'Right', editType: 'numericedit', width: 30 },
{ field: 'ShipCountry', headerText: 'Ship Country', editType: 'dropdownedit', width: 40 }
],
actionComplete: actionComplete
}, done);
});
it('Checkbox state filtering', (done: Function) => {
actionComplete = (args?: any): void => {
actionComplete = null;
done();
};
gridObj.actionComplete = actionComplete;
chkAll = gridObj.element.querySelector('.e-checkselectall').nextElementSibling as HTMLElement;
chkAll.click();
gridObj.filterByColumn('OrderID', 'equal', '67');
});
it('checkbox state clearing', (done: Function) => {
actionComplete = (args?: any): void => {
expect(chkAll.classList.contains('e-check')).toBeTruthy();
done();
};
gridObj.actionComplete = actionComplete;
gridObj.clearFiltering();
});
afterAll(() => {
destroy(gridObj);
gridObj = actionComplete = null;
});
});
});
describe('EJ2-46285 - Provide support to handle custom filter dataSource in Excel Filter', () => {
let gridObj: Grid;
let actionComplete: () => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: filterData,
allowFiltering: true,
enableVirtualization: true,
filterSettings:{type:'Excel',
columns: [{ field: 'OrderID', matchCase: false, operator: 'equal', value: '10248' }]},
selectionSettings: { persistSelection: true, type: 'Multiple', checkboxOnly: true },
height: 500,
columns: [
{ field: 'OrderID', headerText: 'Order ID', width: 120, textAlign: 'Right', editType: 'numericedit',},
{ field: 'EmployeeID', headerText: 'EmployeeID', width: 150 },
],
actionComplete: actionComplete
}, done);
});
it('assigning custom datasource', () => {
gridObj.on('beforeCheckboxRenderer', function(e: any){
if (e.field === "EmployeeID") {
e.executeQuery = false;
e.dataSource = [
{ EmployeeID: 5 },
{ EmployeeID: 6 },
{ EmployeeID: 4 },
{ EmployeeID: 3 }
]; }
})
});
it('checking the datasource', (done: Function) => {
gridObj.actionComplete = actionComplete = (args?: any): void => {
if(args.requestType === "filterchoicerequest") {
expect(document.getElementsByClassName('e-ftrchk').length).toBe(5);
done();
}
}
gridObj.actionComplete = actionComplete;
(gridObj.element.getElementsByClassName('e-filtermenudiv e-icons e-icon-filter')[1] as any).click();
});
afterAll(() => {
destroy(gridObj);
gridObj = actionComplete = null;
});
describe('EJ2-43845 - Provided the support to set locale texts for Boolean values in checkbox filter', () => {
let gridObj: Grid;
let checkBoxFilter: Element;
let actionComplete: () => void;
beforeAll((done: Function) => {
L10n.load({
'de-DE': {
'grid': {
FilterTrue: 'Wahr',
FilterFalse: 'Falsch',
FilterButton: 'Filter',
ClearButton: 'Lรถschen',
}
}
});
gridObj = createGrid(
{
dataSource: filterData,
locale: 'de-DE',
allowPaging: true,
allowFiltering: true,
filterSettings: { type: 'CheckBox' },
columns: [
{ field: 'OrderID', isPrimaryKey: true, headerText: 'Order ID', textAlign: 'Right', width: 40 },
{ field: 'Verified', headerText: 'Verified', type: 'boolean', width: 100 }
],
actionComplete: actionComplete
}, done);
});
it('checking the locale text', (done: Function) => {
gridObj.actionComplete = actionComplete = (args?: any): void => {
if (args.requestType === "filterchoicerequest") {
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
expect(checkBoxFilter.querySelectorAll('.e-checkboxfiltertext')[1].innerHTML).toBe('Falsch');
expect(checkBoxFilter.querySelectorAll('.e-checkboxfiltertext')[2].innerHTML).toBe('Wahr');
done();
}
}
gridObj.actionComplete = actionComplete;
(gridObj.element.getElementsByClassName('e-filtermenudiv e-icons e-icon-filter')[1] as any).click();
});
afterAll(() => {
destroy(gridObj);
gridObj = actionComplete = null;
});
});
});
describe('EJ2-47692 - Throws script error while using hideSearchbox as true in IFilter.', () => {
let gridObj: Grid;
let actionComplete: () => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: filterData,
allowFiltering: true,
filterSettings: { type: 'Menu' },
height: 500,
columns: [
{ field: 'OrderID', headerText: 'Order ID', width: 120, textAlign: 'Right' },
{ field: 'EmployeeID', headerText: 'EmployeeID', width: 150, filter: {
type: "CheckBox",
hideSearchbox: true,
params: {
showSpinButton: false
}
} },
],
actionComplete: actionComplete
}, done);
});
it('checking the Filter popup open', (done: Function) => {
gridObj.actionComplete = actionComplete = (args?: any): void => {
if (args.requestType === "filterchoicerequest") {
done();
}
}
gridObj.actionComplete = actionComplete;
(gridObj.element.getElementsByClassName('e-filtermenudiv e-icons e-icon-filter')[1] as any).click();
});
afterAll(() => {
destroy(gridObj);
gridObj = actionComplete = null;
});
});
describe('EJ2-49551 - Provide public event to handle queries on custom ExcelFilter dataSource.', () => {
let gridObj: Grid;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: filterData,
allowFiltering: true,
filterSettings: { type: 'Excel' },
height: 500,
columns: [
{ field: 'OrderID', headerText: 'Order ID', width: 120, textAlign: 'Right' },
{ field: 'EmployeeID', headerText: 'EmployeeID', width: 150, },
],
}, done);
});
it('beforeCheckboxRendererQuery internal event check', (done: Function) => {
gridObj.on(events.beforeCheckboxRendererQuery, (args: any) => {
gridObj.off(events.beforeCheckboxRendererQuery);
done();
});
(gridObj.element.getElementsByClassName('e-filtermenudiv e-icons e-icon-filter')[1] as any).click();
});
afterAll(() => {
destroy(gridObj);
gridObj = null;
});
});
describe('EJ2-50998 - Searching blank in filter text box', () => {
let gridObj: Grid;
let actionComplete: () => void;
let checkBoxFilter: Element;
let fltrData: Object[] = [
{ OrderID: 10248, CustomerID: null, ShipCountry: 'France', Freight: 32.38 },
{ OrderID: 10249, CustomerID: 'TOMSP', ShipCountry: 'Germany', Freight: 11.61 },
{ OrderID: 10250, CustomerID: 'HANAR', ShipCountry: 'Brazil', Freight: 65.83 },
{ OrderID: 10251, CustomerID: 'VICTE', ShipCountry: 'France', Freight: 41.34 },
{ OrderID: 10252, CustomerID: 'SUPRD', ShipCountry: 'Belgium', Freight: 51.3 }];
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: fltrData,
allowFiltering: true,
filterSettings: { type: 'CheckBox' },
height: 500,
columns: [
{ field: 'OrderID', headerText: 'Order ID', isPrimaryKey: true, textAlign: 'Right' },
{ field: 'CustomerID', headerText: 'Customer ID' },
{ field: 'Freight', format: 'C2', textAlign: 'Right' },
{ field: 'ShipCountry', headerText: 'Ship Country', },
],
actionComplete: actionComplete
}, done);
});
it('open filter popup', (done: Function) => {
actionComplete = (args?: any): void => {
if (args.requestType === 'filterafteropen') {
checkBoxFilter = gridObj.element.querySelector('.e-checkboxfilter');
gridObj.actionComplete = null;
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj.filterModule as any).filterIconClickHandler(getClickObj(gridObj.getColumnHeaderByField('CustomerID').querySelector('.e-filtermenudiv')));
});
it('Searching blank value', (done: Function) => {
actionComplete = (args?: any): void => {
if (args.requestType === 'filterchoicerequest') {
expect(checkBoxFilter.querySelectorAll('.e-selectall').length).toBe(1);
expect(checkBoxFilter.querySelectorAll('.e-check').length).toBe(2);
expect((checkBoxFilter.querySelector('.e-checkboxlist').children[1] as HTMLElement).innerText).toBe('Blanks');
gridObj.actionComplete = null;
done();
}
};
gridObj.actionComplete = actionComplete;
let searchElement : any = gridObj.element.querySelector('.e-searchinput');
searchElement.value = 'Blanks';
(gridObj.filterModule as any).filterModule.checkBoxBase.searchBoxKeyUp(getKeyUpObj(13,searchElement));
});
it('Check the filter data length', (done: Function) => {
actionComplete = (args?: any): void => {
if (args.requestType === 'filtering') {
expect(gridObj.currentViewData.length).toBe(1);
gridObj.actionComplete = null;
done();
}
};
gridObj.actionComplete = actionComplete;
checkBoxFilter.querySelectorAll('button')[0].click();
});
afterAll(() => {
destroy(gridObj);
gridObj = fltrData = checkBoxFilter = actionComplete = null;
});
}); | the_stack |
import classNames from 'classnames'
import React, { useMemo, useState } from 'react'
import { Omit } from 'utility-types'
import { Form } from '@sourcegraph/branded/src/components/Form'
import { Link } from '@sourcegraph/shared/src/components/Link'
import { Scalars } from '@sourcegraph/shared/src/graphql-operations'
import { Container, PageHeader } from '@sourcegraph/wildcard'
import { AuthenticatedUser } from '../auth'
import { ErrorAlert } from '../components/alerts'
import { Badge } from '../components/Badge'
import { NamespaceProps } from '../namespaces'
import styles from './SavedSearchForm.module.scss'
export interface SavedQueryFields {
id: Scalars['ID']
description: string
query: string
notify: boolean
notifySlack: boolean
slackWebhookURL: string | null
}
export interface SavedSearchFormProps extends NamespaceProps {
authenticatedUser: AuthenticatedUser | null
defaultValues?: Partial<SavedQueryFields>
title?: string
submitLabel: string
onSubmit: (fields: Omit<SavedQueryFields, 'id'>) => void
loading: boolean
error?: any
}
export const SavedSearchForm: React.FunctionComponent<SavedSearchFormProps> = props => {
const [values, setValues] = useState<Omit<SavedQueryFields, 'id'>>(() => ({
description: props.defaultValues?.description || '',
query: props.defaultValues?.query || '',
notify: props.defaultValues?.notify || false,
notifySlack: props.defaultValues?.notifySlack || false,
slackWebhookURL: props.defaultValues?.slackWebhookURL || '',
}))
/**
* Returns an input change handler that updates the SavedQueryFields in the component's state
*
* @param key The key of saved query fields that a change of this input should update
*/
const createInputChangeHandler = (
key: keyof SavedQueryFields
): React.FormEventHandler<HTMLInputElement> => event => {
const { value, checked, type } = event.currentTarget
setValues(values => ({
...values,
[key]: type === 'checkbox' ? checked : value,
}))
}
const handleSubmit = (event: React.FormEvent<HTMLFormElement>): void => {
event.preventDefault()
props.onSubmit(values)
}
/**
* Tells if the query is unsupported for sending notifications.
*/
const isUnsupportedNotifyQuery = useMemo((): boolean => {
const notifying = values.notify || values.notifySlack
return notifying && !values.query.includes('type:diff') && !values.query.includes('type:commit')
}, [values])
const codeMonitoringUrl = useMemo(() => {
const searchParameters = new URLSearchParams()
searchParameters.set('trigger-query', values.query)
searchParameters.set('description', values.description)
return `/code-monitoring/new?${searchParameters.toString()}`
}, [values.query, values.description])
const { query, description, notify, notifySlack, slackWebhookURL } = values
return (
<div className="saved-search-form">
<PageHeader
path={[{ text: props.title }]}
headingElement="h2"
description="Get notifications when there are new results for specific search queries."
className="mb-3"
/>
<Form onSubmit={handleSubmit}>
<Container className="mb-3">
<div className="form-group">
<label className={styles.label} htmlFor="saved-search-form-input-description">
Description
</label>
<input
id="saved-search-form-input-description"
type="text"
name="description"
className="form-control test-saved-search-form-input-description"
placeholder="Description"
required={true}
value={description}
onChange={createInputChangeHandler('description')}
/>
</div>
<div className="form-group">
<label className={styles.label} htmlFor="saved-search-form-input-query">
Query
</label>
<input
id="saved-search-form-input-query"
type="text"
name="query"
className="form-control test-saved-search-form-input-query"
placeholder="Query"
required={true}
value={query}
onChange={createInputChangeHandler('query')}
/>
</div>
{props.defaultValues?.notify && (
<div className="form-group mb-0">
{/* Label is for visual benefit, input has more specific label attached */}
{/* eslint-disable-next-line jsx-a11y/label-has-associated-control */}
<label className={styles.label} id="saved-search-form-email-notifications">
Email notifications
</label>
<div aria-labelledby="saved-search-form-email-notifications">
<label>
<input
type="checkbox"
name="Notify owner"
className={styles.checkbox}
defaultChecked={notify}
onChange={createInputChangeHandler('notify')}
/>{' '}
<span>
{props.namespace.__typename === 'Org'
? 'Send email notifications to all members of this organization'
: props.namespace.__typename === 'User'
? 'Send email notifications to my email'
: 'Email notifications'}
</span>
</label>
</div>
<div className={classNames(styles.codeMonitoringAlert, 'alert alert-primary p-3 mb-0')}>
<div className="mb-2">
<strong>New:</strong> Watch your code for changes with code monitoring to get
notifications.
</div>
<Link to={codeMonitoringUrl} className="btn btn-primary">
Go to code monitoring โ
</Link>
</div>
</div>
)}
{notifySlack && slackWebhookURL && (
<div className="form-group mt-3 mb-0">
<label className={styles.label} htmlFor="saved-search-form-input-slack">
Slack notifications
</label>
<input
id="saved-search-form-input-slack"
type="text"
name="Slack webhook URL"
className="form-control"
value={slackWebhookURL}
disabled={true}
onChange={createInputChangeHandler('slackWebhookURL')}
/>
<small>
Slack webhooks are deprecated and will be removed in a future Sourcegraph version.
</small>
</div>
)}
{isUnsupportedNotifyQuery && (
<div className="alert alert-warning mt-3 mb-0">
<strong>Warning:</strong> non-commit searches do not currently support notifications.
Consider adding <code>type:diff</code> or <code>type:commit</code> to your query.
</div>
)}
{notify && !window.context.emailEnabled && !isUnsupportedNotifyQuery && (
<div className="alert alert-warning mt-3 mb-0">
<strong>Warning:</strong> Sending emails is not currently configured on this Sourcegraph
server.{' '}
{props.authenticatedUser?.siteAdmin
? 'Use the email.smtp site configuration setting to enable sending emails.'
: 'Contact your server admin for more information.'}
</div>
)}
</Container>
<button
type="submit"
disabled={props.loading}
className={classNames(styles.submitButton, 'btn btn-primary test-saved-search-form-submit-button')}
>
{props.submitLabel}
</button>
{props.error && !props.loading && <ErrorAlert className="mb-3" error={props.error} />}
{!props.defaultValues?.notify && (
<Container className="d-flex p-3 align-items-start">
<Badge status="new" className="mr-3">
New
</Badge>
<span>
Watch for changes to your code and trigger email notifications, webhooks, and more with{' '}
<Link to="/code-monitoring">code monitoring โ</Link>
</span>
</Container>
)}
</Form>
</div>
)
} | the_stack |
import { Observable, Subject, fromEvent, race, timer } from 'rxjs';
import { filter, startWith, pairwise, take, takeUntil, map, debounceTime } from 'rxjs/operators';
import { NgZone, ViewContainerRef } from '@angular/core';
import { CollectionViewer, ListRange } from '@angular/cdk/collections';
import { PblDataSource } from '@pebula/ngrid/core';
import { _PblNgridComponent } from '../../../tokens';
import { PblNgridInternalExtensionApi } from '../../../ext/grid-ext-api';
import { PblCdkTableComponent } from '../../pbl-cdk-table/pbl-cdk-table.component';
import { PblCdkVirtualScrollViewportComponent } from './virtual-scroll-viewport.component';
import { splitRange, updateStickyRows, measureRangeSize } from './utils';
import { MetaRowStickyScroll } from './meta-row-sticky-scroll';
function sortByIndex(a: { index: number }, b: { index: number }) { return a.index - b.index };
export interface NgeVirtualTableRowInfo {
readonly headerLength: number;
readonly rowLength: number;
readonly footerLength: number;
}
export class PblVirtualScrollForOf<T> implements CollectionViewer, NgeVirtualTableRowInfo {
viewChange: Observable<ListRange>;
dataStream: Observable<T[] | ReadonlyArray<T>>;
get headerLength(): number { return this.header.rows.length }
get rowLength(): number { return this.vcRefs.data.length }
get footerLength(): number { return this.footer.rows.length }
readonly wheelControl: { wheelListen: () => void; wheelUnListen: () => void; readonly listening: boolean; };
private destroyed = new Subject<void>();
private ds: PblDataSource<T>;
private get vcRefs(): Record<'header' | 'data' | 'footer', ViewContainerRef> {
const value = {
header: this.cdkTable._headerRowOutlet.viewContainer,
data: this.cdkTable._rowOutlet.viewContainer,
footer: this.cdkTable._footerRowOutlet.viewContainer,
};
Object.defineProperty(this, 'vcRefs', { value, configurable: true });
return value;
}
private renderedContentOffset = 0;
/** A tuple containing the last known ranges [header, data, footer] */
private _renderedRanges: [ListRange, ListRange, ListRange];
/** The length of meta rows [0] = header [1] = footer */
private metaRows: [number, number] = [0, 0];
private header = { rows: [] as HTMLElement[], sticky: [] as boolean[], rendered: [] as boolean[] };
private footer = { rows: [] as HTMLElement[], sticky: [] as boolean[], rendered: [] as boolean[] };
private grid: _PblNgridComponent<T>;
private cdkTable: PblCdkTableComponent<T>;
private viewport: PblCdkVirtualScrollViewportComponent;
constructor(extApi: PblNgridInternalExtensionApi<T>, private ngZone: NgZone) {
this.grid = extApi.grid;
this.cdkTable = extApi.cdkTable;
this.viewport = extApi.viewport;
this.viewChange = this.cdkTable.viewChange;
extApi.events
.pipe( takeUntil(this.destroyed) )
.subscribe( event => {
if (event.kind === 'onDataSource') {
this.detachView();
this.attachView(event.curr);
}
});
this.attachView(extApi.grid.ds);
const { metaRowService } = extApi.rowsApi;
metaRowService.sync
.pipe( takeUntil(this.destroyed) )
.subscribe( () => {
const headers = metaRowService.header.row.concat(metaRowService.header.sticky).sort(sortByIndex);
const footers = metaRowService.footer.row.concat(metaRowService.footer.sticky).sort(sortByIndex);
this.header.rows = headers.map( h => h.el );
this.header.sticky = headers.map( h => h.rowDef.type === 'sticky' );
this.footer.rows = footers.map( h => h.el );
this.footer.sticky = footers.map( h => h.rowDef.type === 'sticky' );
updateStickyRows(this.renderedContentOffset, this.header.rows, this.header.sticky, 'top');
updateStickyRows(this.renderedContentOffset, this.footer.rows, this.footer.sticky, 'bottom');
});
this.viewport.offsetChange
.pipe( takeUntil(this.destroyed) )
.subscribe( offset => {
if (this.renderedContentOffset !== offset) {
this.renderedContentOffset = offset;
updateStickyRows(offset, this.header.rows, this.header.sticky, 'top');
updateStickyRows(offset, this.footer.rows, this.footer.sticky, 'bottom');
}
});
this.wheelControl = this.initWheelControl();
}
/**
* Measures the combined size (width for horizontal orientation, height for vertical) of all items
* in the specified range. Throws an error if the range includes items that are not currently
* rendered.
*/
measureRangeSize(range: ListRange, orientation: 'horizontal' | 'vertical'): number {
if (range.start >= range.end) {
return 0;
}
const renderedRanges = this._renderedRanges;
const ranges = splitRange(range, this.metaRows[0], this.ds.length);
const stickyStates = [ this.header.sticky, [], this.footer.sticky ];
const vcRefs = [this.vcRefs.header, this.vcRefs.data, this.vcRefs.footer];
const vcRefSizeReducer = (total: number, vcRef: ViewContainerRef, index: number): number => {
return total + measureRangeSize(vcRef, ranges[index], renderedRanges[index], stickyStates[index]);
};
return vcRefs.reduce(vcRefSizeReducer, 0);
}
destroy(): void {
this.detachView();
this.destroyed.next();
this.destroyed.complete();
}
private initWheelControl() {
let listening = false;
let offset = 0;
const viewPort = this.viewport.element;
const metaRowStickyScroll = new MetaRowStickyScroll(this.viewport, viewPort, { header: this.header, footer: this.footer });
let scrollPosition: number;
const wheelListen = () => {
if (!listening) {
viewPort.addEventListener('wheel', handler, true);
listening = true;
}
};
const wheelUnListen = () => {
if (listening) {
viewPort.removeEventListener('wheel', handler, true);
listening = false;
}
};
const updateScrollPosition = () => scrollPosition = (this.viewport.measureScrollOffset()) / (this.viewport.scrollHeight - this.viewport.getViewportSize());
const scrollEnd$ = this.viewport.scrolling.pipe(filter( s => !s ));
const handler = (event: WheelEvent) => {
if (event.deltaY) {
if ( (scrollPosition === 1 && event.deltaY > 0) || (offset === 0 && event.deltaY < 0)) {
return;
}
let newOffset = offset + event.deltaY;
newOffset = Math.min(this.viewport.scrollHeight, Math.max(0, newOffset));
if (newOffset !== offset) {
offset = newOffset;
if (metaRowStickyScroll.canMove() && metaRowStickyScroll.move(event.deltaY, viewPort.getBoundingClientRect())) {
const restore = () => {
metaRowStickyScroll.restore(this.renderedContentOffset);
updateScrollPosition();
};
switch (this.viewport.wheelMode) {
case 'passive':
wheelUnListen();
this.viewport.scrolling
.pipe(
debounceTime(150),
filter( s => !s ),
take(1)
).subscribe( () => {
restore();
wheelListen();
});
break;
case 'blocking':
scrollEnd$.pipe(take(1)).subscribe(restore);
break;
default:
const threshold = this.viewport.wheelMode;
let removedEvent = false;
this.viewport.scrollFrameRate
.pipe(takeUntil(scrollEnd$.pipe(take(1))))
.subscribe(
{
next: frameRate => {
if (!removedEvent && frameRate < threshold) {
wheelUnListen();
removedEvent = true;
}
},
complete: () => {
const lastWheel$ = fromEvent(viewPort, 'wheel').pipe(debounceTime(50), take(1));
race(lastWheel$, timer(51) as any)
.subscribe( () => {
restore();
if (removedEvent) {
wheelListen();
}
});
// we restore back after 100 ms, for some reason, if it's immediate, we hit a cycle of wheel/scroll/no-scroll and not wheel/scroll/WAIIIIIT/no-scrol
// TODO: maybe we can measure time between no-scrolling and wheel to find this MS value
// OR, register a temp `wheel` listener that will detect wheel end and re-register the original handler.
}
}
);
}
}
}
this.viewport.scrollToOffset(offset);
event.preventDefault();
event.stopPropagation();
return true;
}
};
updateScrollPosition();
// We don't auto enable, the virtual scroll viewport component will decide
// wheelListen();
this.viewport
.scrolling
.subscribe(isScrolling => {
if (!isScrolling) {
offset = this.viewport.measureScrollOffset();
}
});
return { wheelListen, wheelUnListen, get listening() { return listening } };
}
private attachView(ds: PblDataSource<T>): void {
if (ds) {
this.ds = ds;
this._renderedRanges = [ { start: 0, end: 0 }, this.cdkTable.viewChange.value, { start: 0, end: 0 } ];
this.viewport.renderedRangeStream
.pipe( takeUntil(this.destroyed) )
.subscribe( range => {
if (this.headerLength + this.footerLength === 0) { // if no row/sticky meta rows, move on...
this._renderedRanges = [ { start: 0, end: 0 }, range, { start: 0, end: 0 } ];
return this.cdkTable.viewChange.next(range);
}
/* WHAT IS GOING ON HERE? */
/* Table rows are split into 3 sections: Header, Data, Footer.
In the virtual playground only DATA rows are dynamic. Header & Footer rows are fixed.
The `CdkTable` works the same, also have the same sections with a stream API for DATA rows only.
`CdkTable.viewChange.next(RANGE)` will emit to the datasource which will result in a new data section from the datasource.
`CdkTable` alone does not support virtual scrolling, to achieve it we use a virtual scroll viewport which wraps the entire `CdkTable`.
This means that ALL sections are wrapped (hence scrolled over) but only DATA rows are moving...
Each emission of `ListRange` in `renderedRangeStream` is based on size calculation of ALL sections (see `measureRangeSize` above)
and we need to extract the relevant range for DATA rows only and pass it on to the grid.
To make this work we need to extract Header/Footer rows based on the starting position of the range and handle them as well.
Because the grid will only handle the scrolling of DATA rows we need to update HEADER/FOOTER rows to show/hide based on the range.
Because Header/Footer rows are fixed we do this by hiding them with `display: none`, unless they are sticky / pinned.
One exception is the main header row, which we hide virtually because we need it to render and reflect the cell size.
We first extract the actual ranges for each section and update the `CdkTable` with the DATA row range.
We then wait for the rows to render, which is the time for us to also "render" Header/Footer rows...
We don't "render" them per-se, they are already rendered, we just show/hide them based on the range and state (sticky).
This is important, hiding will cause the total height of the scroll container to shrink to the size it should be.
We defer this operation to run AFTER the rows are rendered (not immediately) because an immediate change will trigger
a change in the scroll container size resulting in a scroll event that will bring us back here but this time with
a height that does not fit the range. Immediate change removes rows (Header/Footer) before the new range is applied.
Only after the rows are rendered we can show/hide the Header/Footer rows.
*/
// Extracting actual ranges for each section.
this._renderedRanges = splitRange(range, this.metaRows[0], ds.length);
const [ header, data, footer ] = this._renderedRanges;
this.cdkTable.onRenderRows.pipe(take(1)).subscribe(() => {
// We update the header DOM elements in reverse, skipping the last (first when reversed) DOM element.
// The skipped element is the grid's header row that must keep track of the layout for internal size calculation (e.g. group header rows).
// An hidden row is one that is out of range AND not sticky
if (this.headerLength > 0) {
const htmlRows = this.header.rows;
const renderedRows = this.header.rendered;
const stickyRows = this.header.sticky;
let rowIndex = 0;
for (const len = this.header.sticky.length - 1; rowIndex < len; rowIndex++) {
// assign rendered state + if not rendered and not sticky, set display to "none"
htmlRows[rowIndex].style.display = !(renderedRows[rowIndex] = rowIndex >= header.start) && !stickyRows[rowIndex]
? 'none'
: null
;
}
// Here we update the main header row, when we need to hide it we apply a class that will hide it virtually, i.e. not showing but keeping internal layout.
if (!(renderedRows[rowIndex] = rowIndex >= header.start) && !stickyRows[rowIndex]) {
htmlRows[rowIndex].classList.add('pbl-ngrid-row-visually-hidden');
} else if (this.grid.showHeader && htmlRows[rowIndex]) {
htmlRows[rowIndex].classList.remove('pbl-ngrid-row-visually-hidden');
}
}
if (this.footerLength > 0) {
const htmlRows = this.footer.rows;
const renderedRows = this.footer.rendered;
const stickyRows = this.footer.sticky;
let rowIndex = 0;
for (const len = this.footer.sticky.length; rowIndex < len; rowIndex++) {
// assign rendered state + if not rendered and not sticky, set display to "none"
htmlRows[rowIndex].style.display = !(renderedRows[rowIndex] = rowIndex < footer.end) && !stickyRows[rowIndex]
? 'none'
: null
;
}
}
});
this.cdkTable.viewChange.next(data);
});
// add meta rows to the total row count.
this.dataStream = ds.onRenderDataChanging
.pipe(
takeUntil(this.destroyed),
map( ({data}) => {
const metaRows = this.metaRows = [ this.header.rows.length, this.footer.rows.length ];
return new Array( data.length + metaRows[0] + metaRows[1] );
}),
);
ds.onRenderedDataChanged
.pipe(
takeUntil(this.destroyed),
map( () => ds.length ),
startWith(0),
pairwise(),
filter( ([prev, curr]) => prev !== curr ),
)
.subscribe( ([prev, curr]) => {
this.ngZone.onStable.pipe(take(1)).subscribe( () => this.viewport.onSourceLengthChange(prev, curr) );
});
this.viewport.attach(this as any);
}
}
private detachView(): void {
this.ds = undefined;
this.viewport.detach();
}
} | the_stack |
import SubscriptionClass, { Repositories, Repository, RepositoryData, SyncStatus } from "../models/subscription";
import { RepoSyncState, Subscription } from "../models";
import getJiraClient from "../jira/client";
import { getRepositorySummary } from "./jobs";
import enhanceOctokit from "../config/enhance-octokit";
import statsd from "../config/statsd";
import getPullRequests from "./pull-request";
import getBranches from "./branches";
import getCommits from "./commits";
import { Application, GitHubAPI } from "probot";
import { metricSyncStatus, metricTaskStatus } from "../config/metric-names";
import { booleanFlag, BooleanFlags, isBlocked } from "../config/feature-flags";
import { LoggerWithTarget } from "probot/lib/wrap-logger";
import { Deduplicator, DeduplicatorResult, RedisInProgressStorageWithTimeout } from "./deduplicator";
import Redis from "ioredis";
import getRedisInfo from "../config/redis-info";
import GitHubClient from "../github/client/github-client";
import { BackfillMessagePayload } from "../sqs/backfill";
import { Hub } from "@sentry/types/dist/hub";
import sqsQueues from "../sqs/queues";
import { getCloudInstallationId } from "../github/client/installation-id";
const tasks: TaskProcessors = {
pull: getPullRequests,
branch: getBranches,
commit: getCommits
};
interface TaskProcessors {
[task: string]:
(
logger: LoggerWithTarget,
github: GitHubAPI,
newGithub: GitHubClient,
jiraHost: string,
repository: Repository,
cursor?: string | number,
perPage?: number
) => Promise<{ edges: any[], jiraPayload: any }>;
}
type TaskType = "pull" | "commit" | "branch";
const taskTypes = Object.keys(tasks) as TaskType[];
export const sortedRepos = (repos: Repositories): [string, RepositoryData][] =>
Object.entries(repos).sort(
(a, b) =>
new Date(b[1].repository?.updated_at || 0).getTime() -
new Date(a[1].repository?.updated_at || 0).getTime()
);
const getNextTask = async (subscription: SubscriptionClass): Promise<Task | undefined> => {
const repos = await RepoSyncState.findAllFromSubscription(subscription, { order: [["repoUpdatedAt", "DESC"]] });
const sorted: [string, RepositoryData][] = repos.map(repo => [repo.repoId.toString(), repo.toRepositoryData()]);
for (const [repositoryId, repoData] of sorted) {
const task = taskTypes.find(
(taskType) => repoData[getStatusKey(taskType)] === undefined || repoData[getStatusKey(taskType)] === "pending"
);
if (!task) continue;
const { repository, [getCursorKey(task)]: cursor } = repoData;
return {
task,
repositoryId,
repository: repository as Repository,
cursor: cursor as any
};
}
return undefined;
};
export interface Task {
task: TaskType;
repositoryId: string;
repository: Repository;
cursor?: string | number;
}
const upperFirst = (str: string) =>
str.substring(0, 1).toUpperCase() + str.substring(1);
const getCursorKey = (type: TaskType) => `last${upperFirst(type)}Cursor`;
const getStatusKey = (type: TaskType) => `${type}Status`;
const updateJobStatus = async (
data: BackfillMessagePayload,
edges: any[] | undefined,
task: TaskType,
repositoryId: string,
logger: LoggerWithTarget,
scheduleNextTask: (delay) => void
) => {
const { installationId, jiraHost } = data;
// Get a fresh subscription instance
const subscription = await Subscription.getSingleInstallation(
jiraHost,
installationId
);
// handle promise rejection when an org is removed during a sync
if (!subscription) {
logger.info("Organization has been deleted. Other active syncs will continue.");
return;
}
const status = edges?.length ? "pending" : "complete";
logger.info({ status }, "Updating job status");
await subscription.updateRepoSyncStateItem(repositoryId, getStatusKey(task), status);
if (edges?.length) {
// there's more data to get
await subscription.updateRepoSyncStateItem(repositoryId, getCursorKey(task), edges[edges.length - 1].cursor);
scheduleNextTask(0);
// no more data (last page was processed of this job type)
} else if (!(await getNextTask(subscription))) {
await subscription.update({ syncStatus: SyncStatus.COMPLETE });
const endTime = Date.now();
const startTime = data?.startTime || 0;
const timeDiff = startTime ? endTime - Date.parse(startTime) : 0;
if (startTime) {
// full_sync measures the duration from start to finish of a complete scan and sync of github issues translated to tickets
// startTime will be passed in when this sync job is queued from the discovery
statsd.histogram(metricSyncStatus.fullSyncDuration, timeDiff);
}
logger.info({ startTime, endTime, timeDiff }, "Sync status is complete");
} else {
logger.info("Sync status is pending");
scheduleNextTask(0);
}
};
const getEnhancedGitHub = async (app: Application, installationId) =>
enhanceOctokit(await app.auth(installationId));
/**
* Determines if an an error returned by the GitHub API means that we should retry it
* with a smaller request (i.e. with fewer pages).
* @param err the error thrown by Octokit.
*/
export const isRetryableWithSmallerRequest = (err): boolean => {
if (err.errors) {
const retryableErrors = err.errors.filter(
(error) => {
return "MAX_NODE_LIMIT_EXCEEDED" == error.type
|| error.message?.startsWith("Something went wrong while executing your query");
}
);
return retryableErrors.length;
} else {
return false;
}
};
// Checks if parsed error type is NOT_FOUND / status is 404 which come from 2 different sources
// - GraphqlError: https://github.com/octokit/graphql.js/tree/master#errors
// - RequestError: https://github.com/octokit/request.js/blob/5cef43ea4008728139686b6e542a62df28bb112a/src/fetch-wrapper.ts#L77
export const isNotFoundError = (
err: any,
logger: LoggerWithTarget
): boolean | undefined => {
const isNotFoundErrorType =
err?.errors && err.errors?.filter((error) => error.type === "NOT_FOUND");
const isNotFoundError = isNotFoundErrorType?.length > 0 || err?.status === 404;
isNotFoundError &&
logger.info("Repository deleted after discovery, skipping initial sync");
return isNotFoundError;
};
// TODO: type queues
async function doProcessInstallation(app, data: BackfillMessagePayload, sentry: Hub, installationId: number, jiraHost: string, logger: LoggerWithTarget, scheduleNextTask: (delayMs) => void): Promise<void> {
const subscription = await Subscription.getSingleInstallation(
jiraHost,
installationId
);
// TODO: should this reject instead? it's just ignoring an error
if (!subscription) return;
const jiraClient = await getJiraClient(
subscription.jiraHost,
installationId,
logger
);
const newGithub = new GitHubClient(getCloudInstallationId(installationId), logger);
const github = await getEnhancedGitHub(app, installationId);
const nextTask = await getNextTask(subscription);
if (!nextTask) {
await subscription.update({ syncStatus: "COMPLETE" });
statsd.increment(metricSyncStatus.complete);
logger.info("Sync complete");
return;
}
await subscription.update({ syncStatus: "ACTIVE" });
const { task, repositoryId, cursor } = nextTask;
let { repository } = nextTask;
if (!repository) {
// Old records don't have this info. New ones have it
const { data: repo } = await github.request("GET /repositories/:id", {
id: repositoryId
});
repository = getRepositorySummary(repo);
await subscription.updateSyncState({
repos: {
[repository.id]: {
repository
}
}
});
}
//TODO ARC-582 log task only if detailed logging enabled
logger.info({ task: nextTask }, "Starting task");
const processor = tasks[task];
const execute = async () => {
if (await booleanFlag(BooleanFlags.SIMPLER_PROCESSOR, true)) {
// just try with one page size
return await processor(logger, github, newGithub, jiraHost, repository, cursor, 20);
} else {
for (const perPage of [20, 10, 5, 1]) {
// try for decreasing page sizes in case GitHub returns errors that should be retryable with smaller requests
try {
return await processor(logger, github, newGithub, jiraHost, repository, cursor, perPage);
} catch (err) {
logger.error({
err,
payload: data,
github,
repository,
cursor,
task
}, `Error processing job with page size ${perPage}, retrying with next smallest page size`);
if (isRetryableWithSmallerRequest(err)) {
// error is retryable, retrying with next smaller page size
continue;
} else {
// error is not retryable, re-throwing it
throw err;
}
}
}
}
throw new Error(`Error processing GraphQL query: installationId=${installationId}, repositoryId=${repositoryId}, task=${task}`);
};
try {
const { edges, jiraPayload } = await execute();
if (jiraPayload) {
try {
await jiraClient.devinfo.repository.update(jiraPayload, {
preventTransitions: true
});
} catch (err) {
if (err?.response?.status === 400) {
sentry.setExtra(
"Response body",
err.response.data.errorMessages
);
sentry.setExtra("Jira payload", err.response.data.jiraPayload);
}
if (err.request) {
sentry.setExtra("Request", {
host: err.request.domain,
path: err.request.path,
method: err.request.method
});
}
if (err.response) {
sentry.setExtra("Response", {
status: err.response.status,
statusText: err.response.statusText,
body: err.response.body
});
}
throw err;
}
}
await updateJobStatus(
data,
edges,
task,
repositoryId,
logger,
scheduleNextTask
);
statsd.increment(metricTaskStatus.complete, [`type: ${nextTask.task}`]);
} catch (err) {
const rateLimit = Number(err?.headers?.["x-ratelimit-reset"]);
const delay = Math.max(Date.now() - rateLimit * 1000, 0);
if (delay) {
// if not NaN or 0
logger.info({ delay }, `Delaying job for ${delay}ms`);
scheduleNextTask(delay);
return;
}
if (String(err).includes("connect ETIMEDOUT")) {
// There was a network connection issue.
// Add the job back to the queue with a 5 second delay
logger.warn("ETIMEDOUT error, retrying in 5 seconds");
scheduleNextTask(5_000);
return;
}
if (
String(err.message).includes(
"You have triggered an abuse detection mechanism"
)
) {
// Too much server processing time, wait 60 seconds and try again
logger.warn("Abuse detection triggered. Retrying in 60 seconds");
scheduleNextTask(60_000);
return;
}
// Continue sync when a 404/NOT_FOUND is returned
if (isNotFoundError(err, logger)) {
const edgesLeft = []; // No edges left to process since the repository doesn't exist
await updateJobStatus(data, edgesLeft, task, repositoryId, logger, scheduleNextTask);
return;
}
// TODO: add the jiraHost to the logger with logger.child()
const host = subscription.jiraHost || "none";
logger.warn({ err, jiraHost: host }, "Task failed, continuing with next task");
// marking the current task as failed
await subscription.updateRepoSyncStateItem(nextTask.repositoryId, getStatusKey(nextTask.task as TaskType), "failed");
statsd.increment(metricTaskStatus.failed, [`type: ${nextTask.task}`]);
// queueing the job again to pick up the next task
scheduleNextTask(0);
}
}
// Export for unit testing. TODO: consider improving encapsulation by making this logic as part of Deduplicator, if needed
export async function maybeScheduleNextTask(
jobData: BackfillMessagePayload,
nextTaskDelaysMs: Array<number>,
logger: LoggerWithTarget
) {
if (nextTaskDelaysMs.length > 0) {
nextTaskDelaysMs.sort().reverse();
if (nextTaskDelaysMs.length > 1) {
logger.warn("Multiple next jobs were scheduled, scheduling one with the highest priority");
}
const delayMs = nextTaskDelaysMs.shift()!;
logger.info("Scheduling next job with a delay = " + delayMs);
await sqsQueues.backfill.sendMessage(jobData, (delayMs || 0) / 1000, logger);
}
}
const redis = new Redis(getRedisInfo("installations-in-progress"));
const RETRY_DELAY_BASE_SEC = 60;
export const processInstallation =
(app: Application) => {
const inProgressStorage = new RedisInProgressStorageWithTimeout(redis);
const deduplicator = new Deduplicator(
inProgressStorage, 1_000
);
return async (data: BackfillMessagePayload, sentry: Hub, logger: LoggerWithTarget): Promise<void> => {
const {installationId, jiraHost} = data;
try {
if (await isBlocked(installationId, logger)) {
logger.warn("blocking installation job");
return;
}
sentry.setUser({
gitHubInstallationId: installationId,
jiraHost
});
const nextTaskDelaysMs: Array<number> = [];
const result = await deduplicator.executeWithDeduplication(
"i-" + installationId + "-" + jiraHost,
() => doProcessInstallation(app, data, sentry, installationId, jiraHost, logger, (delay: number) =>
nextTaskDelaysMs.push(delay)
));
switch (result) {
case DeduplicatorResult.E_OK:
logger.info("Job was executed by deduplicator");
maybeScheduleNextTask(data, nextTaskDelaysMs, logger);
break;
case DeduplicatorResult.E_NOT_SURE_TRY_AGAIN_LATER: {
logger.warn("Possible duplicate job was detected, rescheduling");
await sqsQueues.backfill.sendMessage(data, RETRY_DELAY_BASE_SEC, logger);
break;
}
case DeduplicatorResult.E_OTHER_WORKER_DOING_THIS_JOB: {
logger.warn("Duplicate job was detected, rescheduling");
// There could be one case where we might be losing the message even if we are sure that another worker is doing the work:
// Worker A - doing a long-running task
// Redis/SQS - reports that the task execution takes too long and sends it to another worker
// Worker B - checks the status of the task and sees that the Worker A is actually doing work, drops the message
// Worker A dies (e.g. node is rotated).
// In this situation we have a staled job since no message is on the queue an noone is doing the processing.
//
// Always rescheduling should be OK given that only one worker is working on the task right now: even if we
// gather enough messages at the end of the queue, they all will be processed very quickly once the sync
// is finished.
await sqsQueues.backfill.sendMessage(data, RETRY_DELAY_BASE_SEC + RETRY_DELAY_BASE_SEC * Math.random(), logger);
break;
}
}
} catch (err) {
logger.warn({ err }, "Process installation failed");
}
};
}; | the_stack |
import { Store as ReduxStore } from "redux";
export * from "common/types/errors";
export * from "common/types/net";
import {
GameUpdate,
Game,
User,
Collection,
CaveSummary,
DownloadKeySummary,
Download,
DownloadProgress,
Platform,
Profile,
} from "common/butlerd/messages";
import { Endpoint } from "butlerd";
import { modals } from "common/modals";
export interface Store extends ReduxStore<RootState> {}
export interface Dispatch {
(action: Action<any>): void;
}
export interface Action<T extends Object> {
type: string;
payload?: T;
}
interface Watcher {
addSub(sub: Watcher): void;
removeSub(sub: Watcher): void;
}
export interface ChromeStore extends Store {
watcher: Watcher;
}
export interface Dispatch {
(a: Action<any>): void;
}
export type GenerosityLevel = "discreet";
export type ClassificationAction = "launch" | "open";
export interface UserSet {
[id: string]: User;
}
export interface GameSet {
[id: string]: Game;
}
export interface CollectionSet {
[id: string]: Collection;
}
/**
* The entire application state, following the redux philosophy
*/
export interface RootState {
system: SystemState;
setup: SetupState;
profile: ProfileState;
winds: WindsState;
i18n: I18nState;
ui: UIState;
preferences: PreferencesState;
tasks: TasksState;
downloads: DownloadsState;
status: StatusState;
gameUpdates: GameUpdatesState;
/** commonly-needed subset of DB rows available in a compact & performance-friendly format */
commons: CommonsState;
systemTasks: SystemTasksState;
broth: BrothState;
butlerd: ButlerdState;
}
export interface BrothState {
packageNames: string[];
packages: PackagesState;
}
export interface PackagesState {
[key: string]: PackageState;
}
export interface ButlerdState {
startedAt: number;
endpoint?: Endpoint;
}
export interface PackageState {
stage: "assess" | "download" | "install" | "idle" | "need-restart";
version?: string;
versionPrefix?: string;
progressInfo?: ProgressInfo;
availableVersion?: string;
}
export interface CommonsState {
downloadKeys: {
[downloadKeyId: string]: DownloadKeySummary;
};
downloadKeyIdsByGameId: {
[gameId: string]: string[];
};
caves: {
[caveId: string]: CaveSummary;
};
caveIdsByGameId: {
[gameId: string]: string[];
};
/** size on disk (in bytes) of each install location */
locationSizes: {
[id: string]: number;
};
}
export interface GameUpdatesState {
/** pending game updates */
updates: {
[caveId: string]: GameUpdate;
};
/** are we currently checking? */
checking: boolean;
/** check progress */
progress: number;
}
export type ModalAction = Action<any> | Action<any>[];
export interface ModalButton {
/** HTML id for this button */
id?: string;
/** icomoon icon to use for button */
icon?: string;
/** text to show on button */
label: LocalizedString;
/** what should happen when clicking the button */
action?: ModalAction | "widgetResponse";
/** use this to specify custom CSS classes (which is both naughty and nice) */
className?: string;
/** Tags to tack after label */
tags?: ModalButtonTag[];
timeAgo?: {
date: Date | string;
};
left?: boolean;
}
export interface ModalButtonTag {
label?: LocalizedString;
icon?: string;
}
// FIXME: that's naughty - just make static buttons be constants instead, that works.
export type ModalButtonSpec = ModalButton | "ok" | "cancel" | "nevermind";
export interface ModalBase {
/** window this modal belongs to */
wind: string;
/** generated identifier for this modal */
id?: string;
/** title of the modal */
title: LocalizedString;
/** main body of text */
message?: LocalizedString;
/** secondary body of text */
detail?: LocalizedString;
/** an image to show prominently in the modal */
stillCoverUrl?: string;
coverUrl?: string;
/** main buttons (in list format) */
bigButtons?: ModalButtonSpec[];
/** secondary buttons */
buttons?: ModalButtonSpec[];
unclosable?: boolean;
fullscreen?: boolean;
}
export interface Modal extends ModalBase {
/** name of modal widget to render */
widget?: keyof typeof modals;
/** parameters to pass to React component */
widgetParams?: {};
}
export interface ModalUpdate {
/** the modal's unique identifier */
id: string;
/** the parameters for the widget being shown in the modal */
widgetParams: any;
}
export type ModalsState = Modal[];
export interface ItchAppTabs {
/** id of current tab at time of snapshot */
current: string;
/** list of transient tabs when the snapshot was taken */
items: TabDataSave[];
}
export type ProxySource = "os" | "env";
export interface ProxySettings {
/** if non-null, the proxy specified by the OS (as sniffed by Chromium) */
proxy?: string;
/** if non-null, where the proxy settings come from */
proxySource?: ProxySource;
}
export interface SystemState {
/** app name, like 'itch' or 'kitch' */
appName: string;
/** version string, for example '25.0.0' */
appVersion: string;
/** the platform string, in itch format */
platform: Platform;
/** 'ia32' or 'x64' */
arch: string;
/** true if running on macOS */
macos: boolean;
/** true if running on Windows */
windows: boolean;
/** true if running on GNU/Linux */
linux: boolean;
/** 2-letter language code sniffed from user's OS */
sniffedLanguage?: string;
/** path of ~ */
homePath: string;
/** ~/.config/itch, ~/Library/Application Data/itch, %APPDATA%/itch */
userDataPath: string;
/** if non-null, the proxy specified by the OS (as sniffed by Chromium) */
proxy?: string;
/** if non-null, where the proxy settings come from */
proxySource?: ProxySource;
/** true if we're about to quit */
quitting?: boolean;
/** true if we're currently scanning install locations */
locationScanProgress?: number | null;
}
export interface SystemTasksState {
/** timestamp for next components update check (milliseconds since epoch) */
nextComponentsUpdateCheck: number;
/** timestamp for next game update check (milliseconds since epoch) */
nextGameUpdateCheck: number;
}
export interface SetupOperation {
message: LocalizedString;
icon: string;
rawError?: Error;
log?: string;
stage?: string;
progressInfo?: ProgressInfo;
}
export interface SetupState {
done: boolean;
errors: string[];
blockingOperation: SetupOperation;
}
export interface ProfileState {
/** collection freshness information */
profile: Profile;
login: ProfileLoginState;
itchioUris: string[];
}
export interface WindsState {
[wind: string]: WindState;
}
export interface WindState {
navigation: NavigationState;
modals: ModalsState;
tabInstances: TabInstances;
native: NativeWindowState;
properties: WindPropertiesState;
}
export interface NativeWindowState {
/** id of the electron BrowserWindow the window is displayed in */
id: number;
/** true if window has focus */
focused: boolean;
/** true if window is fullscreen */
fullscreen: boolean;
/** true if window is html-fullscreen */
htmlFullscreen: boolean;
/** true if window is maximized */
maximized: boolean;
}
export interface ProfileLoginState {
error?: Error;
blockingOperation: SetupOperation;
lastUsername?: string;
}
export type TabLayout = "grid" | "table";
export interface NavigationState {
/** opened tabs */
openTabs: string[];
/** current tab id */
tab: string;
}
export interface WindPropertiesState {
/** what the window was opened on */
initialURL: string;
/** the window's role */
role: WindRole;
}
export interface I18nResourceSet {
[lang: string]: I18nResources;
}
export interface I18nResources {
[key: string]: string;
}
/** Info about a locale. See locales.json for a list that ships with the app. */
export interface LocaleInfo {
/** 2-letter language code */
value: string;
/** native name of language (English, Franรงais, etc.) */
label: string;
}
export interface I18nState {
/** 2-letter code for the language the app is currently displayed in */
lang: string;
/** all translated strings */
strings: I18nResourceSet;
/** locales we'll download soon */
queued: {
[lang: string]: boolean;
};
/** locales we're downloading now */
downloading: {
[lang: string]: boolean;
};
locales: LocaleInfo[];
}
export interface UIMenuState {
template: MenuTemplate;
}
export interface UIState {
menu: UIMenuState;
search: UISearchState;
}
export interface UISearchState {
open: boolean;
}
interface InstallLocation {
/** path on disk (empty for appdata) */
path: string;
/** set to true when deleted. still keeping the record around in case some caves still exist with it */
deleted?: boolean;
}
export interface PreferencesState {
/** is the app allowed to check for updates to itself? */
downloadSelfUpdates: boolean;
/** do not make any network requests */
offlineMode: boolean;
/**
* DEPRECATED: this is just an import from <v23 itch.
*/
installLocations: {
[id: string]: string;
};
/**
* where to install games by default
*/
defaultInstallLocation: string;
/** use sandbox */
isolateApps: boolean;
/** when closing window, keep running in tray */
closeToTray: boolean;
/** notify when a download has been installed or updated */
readyNotification: boolean;
/** show the advanced section of settings */
showAdvanced: boolean;
/** language picked by the user */
lang: string;
/** if true, user's already seen the 'minimize to tray' notification */
gotMinimizeNotification: boolean;
/** should the itch app start on os startup? */
openAtLogin: boolean;
/** when the itch app starts at login, should it be hidden? */
openAsHidden: boolean;
/** show consent dialog before applying any game updates */
manualGameUpdates: boolean;
/** prevent display sleep while playing */
preventDisplaySleep: boolean;
/** if rediff'd patch is available, use it instead of original patch */
preferOptimizedPatches: boolean;
/** layout to use to show games */
layout: TabLayout;
/** disable all webviews */
disableBrowser: boolean;
/** disable GPU acceleration, see #809 */
disableHardwareAcceleration: boolean;
/** enable tabs - if false, use simple interface */
enableTabs: boolean;
/** the last version of the app we've successfully run a setup of, see https://github.com/itchio/itch/issues/1997 */
lastSuccessfulSetupVersion: string;
/** whether or not we've already imported appdata as an install location */
importedOldInstallLocations: boolean;
}
export interface Task {
/** generated identifier */
id: string;
/** name of the task: install, uninstall, etc. */
name: TaskName;
/** progress in the [0, 1] interval */
progress: number;
/** id of the game this task is for (which game we're launching, etc.) */
gameId: number;
/** id of the cave this task is for */
caveId: string;
/** bytes per second at which task is being processed, if applicable */
bps?: number;
/** estimated time remaining for task, in seconds, if available */
eta?: number;
}
export interface TasksState {
/** all tasks currently going on in the app (installs, uninstalls, etc.) */
tasks: {
[key: string]: Task;
};
/** same as tasks, grouped by gameId - there may be multiple for the same game */
tasksByGameId: {
[gameId: string]: Task[];
};
/** all tasks finished and not cleared yet, since the app started */
finishedTasks: Task[];
}
export interface DownloadsState {
/** All the downloads we know about, indexed by their own id */
items: {
[id: string]: Download;
};
progresses: {
[id: string]: DownloadProgress;
};
/** true if downloads are currently paused */
paused: boolean;
/** Download speeds, in bps, each item represents one second */
speeds: number[];
}
type OpenAtLoginErrorCause = "no_desktop_file" | "error";
/**
* Something went wrong when applying
*/
export interface OpenAtLoginError {
/** why did applying the setting failed */
cause: OpenAtLoginErrorCause;
/** if cause is `error`, this is an error message */
message?: string;
}
export interface StatusState {
messages: LocalizedString[];
openAtLoginError: OpenAtLoginError;
reduxLoggingEnabled: boolean;
}
// i18n
/**
* Localized messages can be just a string, or an Array arranged like so:
* [key: string, params: {[name: string]: string}]
*/
export type LocalizedString = string | any[];
export interface ProgressInfo {
/** progress of the task between [0,1] */
progress: number;
/** current bytes per second */
bps?: number;
/** estimated time remaining, in seconds */
eta?: number;
stage?: string;
doneBytes?: number;
totalBytes?: number;
}
export interface ProgressListener {
(info: ProgressInfo): void;
}
export interface Runtime {
platform: Platform;
}
export interface MenuItem extends Electron.MenuItemConstructorOptions {
localizedLabel?: LocalizedString;
action?: Action<any>;
submenu?: MenuItem[];
id?: string;
}
export type MenuTemplate = MenuItem[];
export interface NavigatePayload {
/** which window initiated the navigation */
wind: string;
/** the url to navigate to */
url: string;
/** if we know this associates with a resource, let it be known here */
resource?: string;
/** whether to open a new tab in the background */
background?: boolean;
/** whether to replace the current history entry */
replace?: boolean;
}
export interface OpenTabPayload extends NavigatePayload {
wind: string;
/** the id of the new tab to open (generated) */
tab?: string;
}
export interface OpenContextMenuBase {
/** which window to open the context menu for */
wind: string;
/** left coordinate, in pixels */
clientX: number;
/** top coordinate, in pixels */
clientY: number;
}
interface EvolveBasePayload {
/** which window the tab belongs to */
wind: string;
/** the tab to evolve */
tab: string;
/** the new URL */
url: string;
/** the new resource if any */
resource?: string;
/** the new label if any */
label?: LocalizedString;
}
export interface EvolveTabPayload extends EvolveBasePayload {
/** if false, that's a new history entry, if true it replaces the current one */
replace: boolean;
/** if true, will only set resource if the url is what we think it is */
onlyIfMatchingURL?: boolean;
fromWebContents?: boolean;
}
export interface NavigateTabPayload extends EvolveBasePayload {
/** whether to open in the background */
background: boolean;
}
export interface TabInstances {
[key: string]: TabInstance;
}
export interface TabPage {
/**
* url of tab, something like:
* - itch://collections/:id
* - itch://games/:id
* - itch://preferences
* - https://google.com/
* - https://leafo.itch.io/x-moon
*/
url: string;
/**
* resource associated with tab, something like
* - `games/:id`
*/
resource?: string;
/**
* label/title for this page
*/
label?: LocalizedString;
/**
* favicon for this page
*/
favicon?: string;
/**
* current scroll value
*/
scrollTop?: number;
/**
* restored scroll value. This only changes when navigating backward/forward
* through the history, and can be safely used by components to implement scroll
* history.
*/
restoredScrollTop?: number;
}
export interface TabInstance {
/** pages visited in this tab */
history: TabPage[];
/** current index of history shown */
currentIndex: number;
/** whether the tab is currently loading */
loading?: boolean;
/** if sleepy, don't load until it's focused */
sleepy?: boolean;
/** label we had when saving the tab */
savedLabel?: LocalizedString;
/** number that increments when we reload a tab */
sequence: number;
/** derived properties related to the current URL */
location?: TabInstanceLocation;
/** derived properties related to the current resource */
resource?: TabInstanceResource;
/** derived properties related to history, etc. */
status?: TabInstanceStatus;
}
export interface TabInstanceLocation {
/** current URL of the tab */
url: string;
/** "https:", "itch:", etc. */
protocol: string;
/** "new-tab", "applog", etc. */
internalPage: string;
/** in "itch://games/3", "3" as string */
firstPathElement: string;
/** in "itch://caves/:caveId/launch", "launch" as string */
secondPathElement: string;
/** in "itch://games/3", 3 as number */
firstPathNumber: number;
/** in "itch://games/3", "games" */
hostname: string;
/** in "itch://games/3", "/3" */
pathname: string;
/** for "https://example.com?a=b&c=d", {"a":"b", "c":"d"} */
query: QueryParams;
/** should the the tab shown in a browser view? */
isBrowser: boolean;
}
export interface QueryParams {
[key: string]: string;
}
export interface TabInstanceResource {
/** for resource "games/3", "games" */
prefix?: string;
/** for resource "games/3", "3" */
suffix?: string;
/** for resource "games/3", "" */
numericId?: number;
/** the entire resource */
value?: string;
}
export interface TabInstanceStatus {
/** true if we can navigate back */
canGoBack: boolean;
/** true if we can navigate forward */
canGoForward: boolean;
/** current favicon of the tab */
favicon: string;
/** current icon of the tab */
icon?: string;
/** current label, maybe empty if we've just navigated */
label?: LocalizedString;
/** if we're loading a new page, this has the previous page's label */
lazyLabel?: LocalizedString;
}
export interface TabDataSave {
/** id of the tab */
id: string;
/** pages visited in this tab */
history: TabPage[];
/** current index of history shown */
currentIndex: number;
}
export type TaskName = "install-queue" | "install" | "uninstall" | "launch";
export type AutoUpdaterStart = () => Promise<boolean>;
export interface ExtendedWindow extends Window {
windSpec: WindSpec;
}
export interface WindSpec {
wind: string;
role: WindRole;
}
export type WindRole = "main" | "secondary";
export type Subtract<T, K> = Omit<T, keyof K>; | the_stack |
module WinJSTests {
"use strict";
var previousTracingOptions;
var step: number;
var iteration: number;
function errorHandler(e) {
// Currently we're just using this to suppress application termination.
}
function testSimpleNotifications(signalTestCaseCompleted, synchronous) {
var dataSource = Helper.ItemsManager.simpleAsynchronousDataSource(0),
handler = Helper.ItemsManager.simpleListNotificationHandler(),
listBinding = dataSource.createListBinding(handler);
if (synchronous) {
dataSource.testDataAdapter.directives.callMethodsSynchronously = true;
} else {
Helper.ItemsManager.ensureAllAsynchronousRequestsFulfilled(dataSource);
}
var state0 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
Helper.ItemsManager.setState(dataSource, state0);
var promises = [];
// Fetch all 10 items
var itemPromise = listBinding.first();
for (var i = 0; i < 10; i++) {
handler.appendItemPromise(itemPromise);
(function (i) {
promises.push(itemPromise.then(function (item) {
handler.updateItem(item);
handler.verifyItem(item, i);
}));
})(i);
itemPromise = listBinding.next();
}
itemPromise.then(function (item) {
LiveUnit.Assert.isNull(item, "Request for item after last item did not return null");
});
WinJS.Promise.join(promises).then(function () {
handler.verifyExpectedNotifications([
"beginNotifications",
"countChanged",
"endNotifications"
]);
handler.verifyState(state0, dataSource);
// Change the state of the data source, as if it had been changed by an external influence
var state1 = [0, 1, 2, 7, 3, 4, 5, 6, 8, 9];
Helper.ItemsManager.setState(dataSource, state1);
// Force a refresh and wait for it to complete
dataSource.invalidateAll().then(function () {
handler.verifyExpectedNotifications([
"beginNotifications",
"moved",
"indexChanged",
"indexChanged",
"indexChanged",
"indexChanged",
"indexChanged",
"endNotifications"
]);
handler.verifyState(state1, dataSource);
// Try three moves and and two insertions
var state2 = [9, 10, 0, 1, 2, 7, 3, 6, 8, 11, 4, 5];
Helper.ItemsManager.setState(dataSource, state2);
// Force a refresh and wait for it to complete
dataSource.invalidateAll().then(function () {
handler.verifyExpectedNotifications([
"beginNotifications",
"moved",
"moved",
"moved",
"inserted",
"inserted",
"indexChanged",
"indexChanged",
"indexChanged",
"indexChanged",
"indexChanged",
"indexChanged",
"indexChanged",
"indexChanged",
"countChanged",
"endNotifications"
]);
handler.verifyState(state2, dataSource);
// Try a move between two insertions and three deletions
var state3 = [10, 0, 1, 7, 3, 12, 2, 13, 8, 11, 4];
Helper.ItemsManager.setState(dataSource, state3);
// Force a refresh and wait for it to complete
dataSource.invalidateAll().then(function () {
handler.verifyExpectedNotifications([
"beginNotifications",
"removed",
"removed",
"removed",
"moved",
"inserted",
"inserted",
"indexChanged",
"indexChanged",
"indexChanged",
"indexChanged",
"indexChanged",
"indexChanged",
"countChanged",
"endNotifications"
]);
handler.verifyState(state3, dataSource);
signalTestCaseCompleted();
});
});
});
});
}
function testInsertAfterClearNotifications(signalTestCaseCompleted, synchronous) {
var dataSource = Helper.ItemsManager.simpleAsynchronousDataSource(5),
handler = Helper.ItemsManager.simpleListNotificationHandler(),
listBinding = dataSource.createListBinding(handler);
if (synchronous) {
dataSource.testDataAdapter.directives.callMethodsSynchronously = true;
} else {
Helper.ItemsManager.ensureAllAsynchronousRequestsFulfilled(dataSource);
}
// Clear the data source
var state0 = [];
Helper.ItemsManager.setState(dataSource, state0);
dataSource.invalidateAll().then(function () {
handler.verifyExpectedNotifications([
"beginNotifications",
"countChanged",
"endNotifications"
]);
handler.verifyState(state0, dataSource);
// Append three items to the empty data source
var state1 = [0, 1, 2];
Helper.ItemsManager.setState(dataSource, state1);
dataSource.invalidateAll().then(function () {
handler.verifyExpectedNotifications([
"beginNotifications",
"countChanged",
"endNotifications"
]);
var promises = [];
// Fetch all the items so that we can verify the state
var itemPromise = listBinding.first();
for (var i = 0; ; i++) {
handler.appendItemPromise(itemPromise);
(function (i) {
promises.push(itemPromise.then(function (item) {
handler.updateItem(item);
handler.verifyItem(item, i);
}));
})(i);
if (i === state1.length - 1) {
break;
}
itemPromise = listBinding.next();
}
WinJS.Promise.join(promises).then(function () {
handler.verifyState(state1, dataSource);
signalTestCaseCompleted();
});
});
});
}
var rand = Helper.ItemsManager.pseudorandom;
function occurs(probability) {
var granularity = 1000;
return rand(granularity) < probability * granularity;
}
function createTestListBinding(dataSource) {
var handler = Helper.ItemsManager.stressListNotificationHandler(),
listBinding = dataSource.createListBinding(handler);
// Add handler as expando on the ListBinding
listBinding.handler = handler;
return listBinding;
}
// Stress tests the VirtualizedDataSource by attempting various random operations
//
// The following behaviors are currently not configurable:
// - Three ListBindings are used to read the data, one by index, one by key/description, and one using index/key
// - Random contiguous ranges of items are read using the ListBindings
// - Some individual items are read directly from the data source
// - Random ranges of items are released
// - countBefore/countAfter are often overridden with a random value
// - Some random edits are made to the data
// - invalidateAll is called periodically
// - Requests of the data source are sometimes completed out of order
//
// The following parameters control the data source behaviors. Each is a probability, so a value of 0.0 means the
// given behavior never occurs, while 1.0 means it always occurs. Values in between specify frequencies that are
// interpreted differently depending on the behavior.
// - indices: Are the index or count parameters returned with FetchResults? (Occasionally switches "modes".)
// - asynchronous: Does a given request completely asynchronously?
// - failures: Is the data source connection lost occasionally?
// - changes: Is the data changing independently?
// - notifications: Does the data source send synchronous change notifications?
function testRandomUsageOnce(indices, asynchronous, failures, changes, notifications, complete) {
var count = 300,
dataSource = Helper.ItemsManager.simpleAsynchronousDataSource(count),
testDataAdapter = dataSource.testDataAdapter,
listBinding1 = createTestListBinding(dataSource),
listBinding2 = createTestListBinding(dataSource),
listBinding3 = createTestListBinding(dataSource);
// Probability constants
var read1 = 0.30,
read2 = 0.10,
read3 = 0.20,
readDirect = 0.03,
resultsCountOverride = 0.40,
edit = 0.05,
refreshDefault = 0.01,
refreshAfterFailure = 0.20,
outOfOrder = 0.1;
// Other constants
var walkMax = 10,
countBeforeAfterMax = 20,
countEditMax = 5,
countToIndicesSwitchMax = 100,
countToCountSwitchMax = 100,
changeCountMax = 10,
changeSizeMax = 30;
function localWalk(listBinding, itemPromise, index?) {
listBinding.handler.requestItem(itemPromise, index);
var handlePrev = itemPromise.handle;
// Walk a small distance in each direction
var j;
var countBefore = rand(walkMax);
for (j = 0; j < countBefore; j++) {
var itemPromisePrevious = listBinding.previous();
listBinding.handler.requestItem(itemPromisePrevious, index - 1 - j, null, handlePrev);
handlePrev = itemPromisePrevious.handle;
}
listBinding.jumpToItem(itemPromise);
handlePrev = itemPromise.handle;
var countAfter = rand(walkMax);
for (j = 0; j < countAfter; j++) {
var itemPromiseNext = listBinding.next();
listBinding.handler.requestItem(itemPromiseNext, index + 1 + j, handlePrev, null);
handlePrev = itemPromiseNext.handle;
}
}
var newItemID = 0;
function newData(change?) {
return "New item " + newItemID++ + (change ? " (change)" : " (edit)");
}
var changedItemID = 0;
function changedData(change?) {
return "Changed item " + changedItemID++ + (change ? " (change)" : " (edit)");
}
function randomIndex(changeSize?) {
return rand(testDataAdapter.currentCount() - (changeSize ? changeSize - 1 : 0));
}
function randomKey() {
return "" + rand(count);
}
var indicesProvided,
countToIndicesSwitch = 0,
countProvided,
countToCountSwitch = 0;
function setBehaviors() {
var directives = testDataAdapter.directives;
// Does the data source return countBefore/countAfter other than those requested?
var override = occurs(resultsCountOverride);
directives.countBeforeOverride = (override ? rand(countBeforeAfterMax) : -1);
directives.countAfterOverride = (override ? rand(countBeforeAfterMax) : -1);
// Periodically switch between providing and not providing indices
if (countToIndicesSwitch-- === 0) {
indicesProvided = occurs(indices);
countToIndicesSwitch = rand(countToIndicesSwitchMax);
}
directives.returnIndices = indicesProvided;
// Periodically switch between providing and not providing the count
if (countToCountSwitch-- === 0) {
countProvided = occurs(indices); // Use the same probability as for indices
countToIndicesSwitch = rand(countToCountSwitchMax);
}
directives.returnCount = countProvided;
// Does the request complete asynchronously?
directives.callMethodsSynchronously = !occurs(asynchronous);
directives.sendChangeNotifications = occurs(notifications);
}
var refresh = refreshDefault;
dataSource.addEventListener("statuschanged", function (ev) {
// In the event of a failure, increase the probability of a refresh until one happens
if (ev.detail === WinJS.UI.DataSourceStatus.failure) {
refresh = refreshAfterFailure;
}
});
// Run a number of simulation "steps" in each of which the data source fulfills one outstanding request (if
// there are any) and the clients make various requests at random times.
var stepCount = 70; //5000;
step = 0;
(function stepOnce() {
var index;
// Does the next request we fulfill time out?
testDataAdapter.directives.communicationFailure = occurs(failures);
// Fulfill one request
if (occurs(outOfOrder)) {
testDataAdapter.fulfillRandomRequest();
} else {
testDataAdapter.fulfillNextRequest();
}
// The first binding reads by index only
if (occurs(read1)) {
index = rand(count);
setBehaviors();
localWalk(listBinding1, listBinding1.fromIndex(index), index);
}
// The second binding reads by key or description
if (occurs(read2)) {
index = rand(count);
setBehaviors();
localWalk(listBinding2, rand(2) ? listBinding2.fromKey("" + index) : listBinding2.fromDescription("" + index));
}
// The third binding reads by index or key
if (occurs(read3)) {
index = rand(count);
setBehaviors();
localWalk(listBinding3, rand(2) ? listBinding3.fromIndex(index) : listBinding3.fromKey("" + index));
}
// Direct reads are by index, key or description
if (occurs(readDirect)) {
index = rand(count);
setBehaviors();
// This test won't pay attention to the results of these fetches
switch (rand(3)) {
case 0:
dataSource.itemFromIndex(index);
break;
case 1:
dataSource.itemFromKey("" + index);
break;
case 2:
dataSource.itemFromDescription("" + index);
break;
}
}
// Release items using the same read probabilities
if (occurs(read1)) {
listBinding1.handler.releaseSomeItems();
}
if (occurs(read2)) {
listBinding2.handler.releaseSomeItems();
}
if (occurs(read3)) {
listBinding3.handler.releaseSomeItems();
}
// Edits can be made to any item, whether or not it has already been requested
if (occurs(edit)) {
var editCount = rand(countEditMax);
// Just use the original keys for the edits; some will have been removed, so some of these edits will
// fail and be undone
for (var i = 0; i < editCount; i++) {
switch (rand(10)) {
case 0:
dataSource.insertAtStart(null, newData()).then(null, errorHandler);
break;
case 1:
dataSource.insertBefore(null, newData(), randomKey()).then(null, errorHandler);
break;
case 2:
dataSource.insertAfter(null, newData(), randomKey()).then(null, errorHandler);
break;
case 3:
dataSource.insertAtEnd(null, newData()).then(null, errorHandler);
break;
case 4:
dataSource.change(randomKey(), changedData()).then(null, errorHandler);
break;
case 5:
dataSource.moveToStart(randomKey()).then(null, errorHandler);
break;
case 6:
dataSource.moveBefore(randomKey(), randomKey()).then(null, errorHandler);
break;
case 7:
dataSource.moveAfter(randomKey(), randomKey()).then(null, errorHandler);
break;
case 8:
dataSource.moveToEnd(randomKey()).then(null, errorHandler);
break;
case 9:
dataSource.remove(randomKey()).then(null, errorHandler);
break;
}
}
}
// Sometimes cause a refresh manually
if (occurs(refresh)) {
dataSource.invalidateAll();
refresh = refreshDefault;
}
// Does the underlying data change?
if (occurs(changes)) {
var changeCount = rand(changeCountMax);
testDataAdapter.directives.sendChangeNotifications = false;
for (var i = 0; i < changeCount; i++) {
// Half the time, a single item is moved
var changeSize = rand(2) ? 1 : rand(changeSizeMax),
indexSource = randomIndex(changeSize),
indexDestination = rand(testDataAdapter.currentCount() + 1),
operation = rand(4);
for (var j = 0; j < changeSize; j++) {
switch (operation) {
case 0:
testDataAdapter.insertAtIndex(newData(true), indexDestination + j);
break;
case 1:
testDataAdapter.changeAtIndex(indexSource + j, changedData(true));
break;
case 2:
testDataAdapter.moveToIndex(indexSource, indexDestination + (indexSource < indexDestination ? 0 : j));
break;
case 3:
testDataAdapter.removeAtIndex(indexSource);
break;
}
}
}
}
listBinding1.handler.verifyIntermediateState();
listBinding2.handler.verifyIntermediateState();
listBinding3.handler.verifyIntermediateState();
var extraIterations = 0;
// See if it's time to wrap up and wait for everything to complete
if (++step < stepCount) {
WinJS.Utilities._setImmediate(stepOnce);
} else {
// Refresh one last time in case there were errors and fetching stopped
dataSource.invalidateAll();
// Rather than adding a then handler to invalidateAll, enter a loop to keep fulfilling requests until
// the requests have clearly stopped.
(function completeAllRequests() {
if (testDataAdapter.requestCount() === 0 && !testDataAdapter.requestFulfilledSynchronously()) {
extraIterations++;
} else {
extraIterations = 0;
}
if (extraIterations === 3) {
var itemArray = testDataAdapter.getItems();
listBinding1.handler.verifyFinalState(itemArray);
listBinding2.handler.verifyFinalState(itemArray);
listBinding3.handler.verifyFinalState(itemArray);
complete();
} else {
testDataAdapter.fulfillAllRequests();
WinJS.Utilities._setImmediate(completeAllRequests);
}
})();
}
})();
// REVIEW: With groups, no edits, and be careful to keep groups contiguous while inserting/removing in underlying data
// (Though GroupDataSource probably needs to tolerate non-contiguous groups, as we can hit that state briefly.)
}
function testRandomUsage(indices, asynchronous, failures, changes, notifications, signalTestCaseCompleted) {
var iterationCount = 5 * Helper.ItemsManager.stressLevel;
iteration = 0;
(function continueTest() {
LiveUnit.LoggingCore.logComment("Test " + iteration + " of " + iterationCount);
Helper.ItemsManager.seedPseudorandom(iteration);
testRandomUsageOnce(indices, asynchronous, failures, changes, notifications, function () {
if (++iteration < iterationCount) {
WinJS.Utilities._setImmediate(continueTest);
} else {
signalTestCaseCompleted();
}
});
})();
}
// verify the newCount and oldCount returned in countChanged handler are correct. No difference is expected in sync/async mode although testing both of them.
function testCountChangedNotificationWithChangingDataSource(signalTestCaseCompleted, synchronous) {
var dataSource = Helper.ItemsManager.simpleAsynchronousDataSource(5),
handler = Helper.ItemsManager.simpleListNotificationHandler(),
listBinding = dataSource.createListBinding(handler);
var newCountValue = 0;
var oldCountValue: any = 0;
var testCount = 2; // number of countChanged should be called. Using this variable to terminate this test.
handler.countChanged = function (newCount, oldCount) {
this.queueNotification("countChanged", arguments);
LiveUnit.Assert.areEqual(newCount, newCountValue, "Expecting: " + newCountValue.toString() + "; Actual: " + newCount.toString());
LiveUnit.Assert.areEqual(oldCount, oldCountValue, "Expecting: " + oldCountValue.toString() + "; Actual: " + oldCount.toString());
testCount--;
if (testCount === 0) {
signalTestCaseCompleted();
}
};
if (synchronous) {
dataSource.testDataAdapter.directives.callMethodsSynchronously = true;
} else {
Helper.ItemsManager.ensureAllAsynchronousRequestsFulfilled(dataSource);
}
var state0 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
Helper.ItemsManager.setState(dataSource, state0);
newCountValue = 10;
oldCountValue = "unknown";
listBinding.first().then(function () {
var state1 = [0, 1, 2, 3, 4];
Helper.ItemsManager.setState(dataSource, state1);
oldCountValue = newCountValue;
newCountValue = 5;
return dataSource.invalidateAll();
})
.then(function () {
var state2 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
Helper.ItemsManager.setState(dataSource, state2);
oldCountValue = newCountValue;
newCountValue = 12;
return dataSource.invalidateAll();
}).done();
}
export class NotificationTests {
setUp() {
previousTracingOptions = VDSLogging.options;
VDSLogging.options = {
log: function (message) { LiveUnit.Assert.fail(message); },
include: /createListBinding|_retainItem|_releaseItem|release/,
handleTracking: true,
logVDS: true,
stackTraceLimit: 0 // set this to 100 to get good stack traces if you run into a failure.
};
VDSLogging.on();
}
tearDown() {
VDSLogging.off();
VDSLogging.options = previousTracingOptions;
}
testEmptyListNotifications(signalTestCaseCompleted) {
var dataSource = Helper.ItemsManager.simpleAsynchronousDataSource(0),
handler = Helper.ItemsManager.simpleListNotificationHandler(),
listBinding = dataSource.createListBinding(handler);
Helper.ItemsManager.ensureAllAsynchronousRequestsFulfilled(dataSource);
// Fetch the first item, which should return a placeholder
var itemPromise = listBinding.first();
handler.appendItemPromise(itemPromise);
// Wait for the fetch to discover that the item doesn't exist
itemPromise.then(function (item) {
LiveUnit.Assert.isNull(item, "First item in list known to be empty not null");
Helper.ItemsManager.verifyRequestCount(dataSource, 0);
// This will actually be called from the refresh - wait for it to complete
Helper.ItemsManager.setImmediate(function () {
Helper.ItemsManager.verifyRequestCount(dataSource, 0);
// The notifications will have been sent after the promise completed, so verify them now
handler.verifyExpectedNotifications([
"beginNotifications",
"removed",
"countChanged",
"endNotifications"
]);
// Fetch the last item, which should return null synchronously
var synchronous = false;
listBinding.last().then(function (item2) {
synchronous = true;
LiveUnit.Assert.isNull(item2, "Last item in list known to be empty not null");
});
LiveUnit.Assert.isTrue(synchronous, "Fetching last item did not complete synchronously");
// Fetch the first item again, which should return null synchronously this time
synchronous = false;
listBinding.first().then(function (item2) {
synchronous = true;
LiveUnit.Assert.isNull(item2, "First item in list known to be empty not null");
});
LiveUnit.Assert.isTrue(synchronous, "Fetching first item did not complete synchronously");
// We don't expect there to be any outstanding requests, or to have received any notifications
Helper.ItemsManager.verifyRequestCount(dataSource, 0);
handler.verifyExpectedNotifications([]);
signalTestCaseCompleted();
});
});
}
testSimpleNotificationsAsynchronous(signalTestCaseCompleted) {
testSimpleNotifications(signalTestCaseCompleted, false);
}
testSimpleNotificationsSynchronous(signalTestCaseCompleted) {
testSimpleNotifications(signalTestCaseCompleted, true);
}
testInsertNotifications(signalTestCaseCompleted) {
var dataSource = Helper.ItemsManager.simpleAsynchronousDataSource(5),
handler = Helper.ItemsManager.simpleListNotificationHandler(),
listBinding = dataSource.createListBinding(handler);
dataSource.testDataAdapter.directives.callMethodsSynchronously = true;
var state0 = [0, 1, 2, 3, 4];
Helper.ItemsManager.setState(dataSource, state0);
var promises = [];
// Fetch just the first three items
var itemPromise = listBinding.first();
for (var i = 0; ; i++) {
handler.appendItemPromise(itemPromise);
(function (i) {
promises.push(itemPromise.then(function (item) {
handler.updateItem(item);
handler.verifyItem(item, i);
}));
})(i);
if (i === 2) {
break;
}
itemPromise = listBinding.next();
}
WinJS.Promise.join(promises).then(function () {
handler.verifyExpectedNotifications([
"beginNotifications",
"countChanged",
"endNotifications"
]);
// Append three items directly to the data source
var state1 = [0, 1, 2, 3, 4, 5, 6, 7];
Helper.ItemsManager.setState(dataSource, state1);
// Force a refresh and wait for it to complete
dataSource.invalidateAll().then(function () {
// We should have received countChanged, but no inserted notifications
handler.verifyExpectedNotifications([
"beginNotifications",
"countChanged",
"endNotifications"
]);
// Don't verify state here, since only a portion of the list has been read
signalTestCaseCompleted();
});
});
}
testInsertAtEndNotifications(signalTestCaseCompleted) {
var dataSource = Helper.ItemsManager.simpleAsynchronousDataSource(5),
handler = Helper.ItemsManager.simpleListNotificationHandler(),
listBinding = dataSource.createListBinding(handler);
dataSource.testDataAdapter.directives.callMethodsSynchronously = true;
var state0 = [0, 1, 2, 3, 4];
Helper.ItemsManager.setState(dataSource, state0);
var promises = [];
// Fetch all the items
var itemPromise = listBinding.first();
for (var i = 0; ; i++) {
handler.appendItemPromise(itemPromise);
(function (i) {
promises.push(itemPromise.then(function (item) {
handler.updateItem(item);
handler.verifyItem(item, i);
}));
})(i);
if (i === state0.length - 1) {
break;
}
itemPromise = listBinding.next();
}
WinJS.Promise.join(promises).then(function () {
handler.verifyExpectedNotifications([
"beginNotifications",
"countChanged",
"endNotifications"
]);
// Append three items directly to the data source
var state1 = [0, 1, 2, 3, 4, 5, 6, 7];
Helper.ItemsManager.setState(dataSource, state1);
// Force a refresh and wait for it to complete
dataSource.invalidateAll().then(function () {
// Because we'd "observed" the end of the list, we should have received three inserted notifications,
// plus countChanged.
handler.verifyExpectedNotifications([
"beginNotifications",
"inserted",
"inserted",
"inserted",
"countChanged",
"endNotifications"
]);
// Don't verify state here, since only a portion of the list has been read
signalTestCaseCompleted();
});
});
}
testInsertAfterClearNotificationsAsynchronous(signalTestCaseCompleted) {
testInsertAfterClearNotifications(signalTestCaseCompleted, false);
}
testInsertAfterClearNotificationsSynchronous(signalTestCaseCompleted) {
testInsertAfterClearNotifications(signalTestCaseCompleted, true);
}
testRefreshWithTwoListBindings(signalTestCaseCompleted) {
var dataSource = Helper.ItemsManager.simpleAsynchronousDataSource(0),
handler1 = Helper.ItemsManager.simpleListNotificationHandler(),
listBinding1 = dataSource.createListBinding(handler1),
handler2 = Helper.ItemsManager.simpleListNotificationHandler(),
listBinding2 = dataSource.createListBinding(handler2);
Helper.ItemsManager.ensureAllAsynchronousRequestsFulfilled(dataSource);
var state0 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
Helper.ItemsManager.setState(dataSource, state0);
var promises = [];
// Fetch the first three items using one ListBinding
var itemPromise = listBinding1.first();
for (var i = 0; ; i++) {
handler1.appendItemPromise(itemPromise);
(function (i) {
promises.push(itemPromise.then(function (item) {
handler1.updateItem(item);
handler1.verifyItem(item, i);
}));
})(i);
if (i === 2) {
break;
}
itemPromise = listBinding1.next();
}
WinJS.Promise.join(promises).then(function () {
handler1.verifyExpectedNotifications([
"beginNotifications",
"countChanged",
"endNotifications"
]);
handler2.verifyExpectedNotifications([
"beginNotifications",
"countChanged",
"endNotifications"
]);
// Now have the other ListBinding request some items by key
handler2.appendItemPromise(listBinding2.fromKey("2"));
handler2.appendItemPromise(listBinding2.fromKey("7"));
// Before the data source gets a chance to respond, cause a refresh
dataSource.invalidateAll().then(function () {
// Since there were no mirages and nothing actually changed in the data, the only notification received
// should be an indexChanged when the index for item "7" was determined.
handler1.verifyExpectedNotifications([]);
handler2.verifyExpectedNotifications([
"beginNotifications",
"indexChanged",
"endNotifications"
]);
signalTestCaseCompleted();
});
});
}
testRandomUsageWithoutIndependentChanges(signalTestCaseCompleted) {
testRandomUsage(
0.30, // indices
0.80, // asynchronous
0.02, // failures
0.00, // changes
0.00, // notifications
signalTestCaseCompleted
);
}
xtestRandomUsageWithoutNotifications(signalTestCaseCompleted) {
testRandomUsage(
0.30, // indices
0.80, // asynchronous
0.02, // failures
0.20, // changes
0.00, // notifications
signalTestCaseCompleted
);
}
xtestRandomUsageWithNotifications(signalTestCaseCompleted) {
testRandomUsage(
0.30, // indices
0.80, // asynchronous
0.02, // failures
0.20, // changes
0.30, // notifications
signalTestCaseCompleted
);
}
testCountChangedNotificationWithChangingDataSourceAsynchronous(signalTestCaseCompleted) {
testCountChangedNotificationWithChangingDataSource(signalTestCaseCompleted, false);
}
testCountChangedNotificationWithChangingDataSourceSynchronous(signalTestCaseCompleted) {
testCountChangedNotificationWithChangingDataSource(signalTestCaseCompleted, true);
}
};
}
// Register the object as a test class by passing in the name
LiveUnit.registerTestClass("WinJSTests.NotificationTests"); | the_stack |
import { AccessLevelList } from "../shared/access-level";
import { PolicyStatement } from "../shared";
/**
* Statement provider for service [cognito-idp](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazoncognitouserpools.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
export class CognitoIdp extends PolicyStatement {
public servicePrefix = 'cognito-idp';
/**
* Statement provider for service [cognito-idp](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazoncognitouserpools.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
constructor (sid?: string) {
super(sid);
}
/**
* Adds additional user attributes to the user pool schema.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AddCustomAttributes.html
*/
public toAddCustomAttributes() {
return this.to('AddCustomAttributes');
}
/**
* Adds the specified user to the specified group.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminAddUserToGroup.html
*/
public toAdminAddUserToGroup() {
return this.to('AdminAddUserToGroup');
}
/**
* Confirms user registration as an admin without using a confirmation code. Works on any user.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminConfirmSignUp.html
*/
public toAdminConfirmSignUp() {
return this.to('AdminConfirmSignUp');
}
/**
* Creates a new user in the specified user pool and sends a welcome message via email or phone (SMS).
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminCreateUser.html
*/
public toAdminCreateUser() {
return this.to('AdminCreateUser');
}
/**
* Deletes a user as an administrator. Works on any user.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminDeleteUser.html
*/
public toAdminDeleteUser() {
return this.to('AdminDeleteUser');
}
/**
* Deletes the user attributes in a user pool as an administrator. Works on any user.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminDeleteUserAttributes.html
*/
public toAdminDeleteUserAttributes() {
return this.to('AdminDeleteUserAttributes');
}
/**
* Disables the user from signing in with the specified external (SAML or social) identity provider.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminDisableProviderForUser.html
*/
public toAdminDisableProviderForUser() {
return this.to('AdminDisableProviderForUser');
}
/**
* Disables the specified user as an administrator. Works on any user.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminDisableUser.html
*/
public toAdminDisableUser() {
return this.to('AdminDisableUser');
}
/**
* Enables the specified user as an administrator. Works on any user.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminEnableUser.html
*/
public toAdminEnableUser() {
return this.to('AdminEnableUser');
}
/**
* Forgets the device, as an administrator.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminForgetDevice.html
*/
public toAdminForgetDevice() {
return this.to('AdminForgetDevice');
}
/**
* Gets the device, as an administrator.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminGetDevice.html
*/
public toAdminGetDevice() {
return this.to('AdminGetDevice');
}
/**
* Gets the specified user by user name in a user pool as an administrator. Works on any user.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminGetUser.html
*/
public toAdminGetUser() {
return this.to('AdminGetUser');
}
/**
* Authenticates a user in a user pool as an administrator. Works on any user.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminInitiateAuth.html
*/
public toAdminInitiateAuth() {
return this.to('AdminInitiateAuth');
}
/**
* Links an existing user account in a user pool (DestinationUser) to an identity from an external identity provider (SourceUser) based on a specified attribute name and value from the external identity provider.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminLinkProviderForUser.html
*/
public toAdminLinkProviderForUser() {
return this.to('AdminLinkProviderForUser');
}
/**
* Lists devices, as an administrator.
*
* Access Level: List
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminListDevices.html
*/
public toAdminListDevices() {
return this.to('AdminListDevices');
}
/**
* Lists the groups that the user belongs to.
*
* Access Level: List
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminInitiateAuth.html
*/
public toAdminListGroupsForUser() {
return this.to('AdminListGroupsForUser');
}
/**
* Lists the authentication events for the user.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminListUserAuthEvents.html
*/
public toAdminListUserAuthEvents() {
return this.to('AdminListUserAuthEvents');
}
/**
* Removes the specified user from the specified group.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminRemoveUserFromGroup.html
*/
public toAdminRemoveUserFromGroup() {
return this.to('AdminRemoveUserFromGroup');
}
/**
* Resets the specified user's password in a user pool as an administrator. Works on any user.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminResetUserPassword.html
*/
public toAdminResetUserPassword() {
return this.to('AdminResetUserPassword');
}
/**
* Responds to an authentication challenge, as an administrator.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminRespondToAuthChallenge.html
*/
public toAdminRespondToAuthChallenge() {
return this.to('AdminRespondToAuthChallenge');
}
/**
* Sets MFA preference for the user in the userpool
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminSetUserMFAPreference.html
*/
public toAdminSetUserMFAPreference() {
return this.to('AdminSetUserMFAPreference');
}
/**
* Sets the specified user's password in a user pool as an administrator. Works on any user.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminSetUserPassword.html
*/
public toAdminSetUserPassword() {
return this.to('AdminSetUserPassword');
}
/**
* Sets all the user settings for a specified user name. Works on any user.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminSetUserSettings.html
*/
public toAdminSetUserSettings() {
return this.to('AdminSetUserSettings');
}
/**
* Updates the feedback for the user authentication event
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminUpdateAuthEventFeedback.html
*/
public toAdminUpdateAuthEventFeedback() {
return this.to('AdminUpdateAuthEventFeedback');
}
/**
* Updates the device status as an administrator.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminUpdateDeviceStatus.html
*/
public toAdminUpdateDeviceStatus() {
return this.to('AdminUpdateDeviceStatus');
}
/**
* Updates the specified user's attributes, including developer attributes, as an administrator.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminUpdateUserAttributes.html
*/
public toAdminUpdateUserAttributes() {
return this.to('AdminUpdateUserAttributes');
}
/**
* Signs out users from all devices, as an administrator.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminUserGlobalSignOut.html
*/
public toAdminUserGlobalSignOut() {
return this.to('AdminUserGlobalSignOut');
}
/**
* Returns a unique generated shared secret key code for the user account.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AssociateSoftwareToken.html
*/
public toAssociateSoftwareToken() {
return this.to('AssociateSoftwareToken');
}
/**
* Changes the password for a specified user in a user pool.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ChangePassword.html
*/
public toChangePassword() {
return this.to('ChangePassword');
}
/**
* Confirms tracking of the device. This API call is the call that begins device tracking.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ConfirmDevice.html
*/
public toConfirmDevice() {
return this.to('ConfirmDevice');
}
/**
* Allows a user to enter a confirmation code to reset a forgotten password.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ConfirmForgotPassword.html
*/
public toConfirmForgotPassword() {
return this.to('ConfirmForgotPassword');
}
/**
* Confirms registration of a user and handles the existing alias from a previous user.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ConfirmSignUp.html
*/
public toConfirmSignUp() {
return this.to('ConfirmSignUp');
}
/**
* Creates a new group in the specified user pool.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateGroup.html
*/
public toCreateGroup() {
return this.to('CreateGroup');
}
/**
* Creates an identity provider for a user pool.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateIdentityProvider.html
*/
public toCreateIdentityProvider() {
return this.to('CreateIdentityProvider');
}
/**
* Creates a new OAuth2.0 resource server and defines custom scopes in it.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateResourceServer.html
*/
public toCreateResourceServer() {
return this.to('CreateResourceServer');
}
/**
* Creates the user import job.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserImportJob.html
*/
public toCreateUserImportJob() {
return this.to('CreateUserImportJob');
}
/**
* Creates a new Amazon Cognito user pool and sets the password policy for the pool.
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
* - .ifAwsResourceTag()
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPool.html
*/
public toCreateUserPool() {
return this.to('CreateUserPool');
}
/**
* Creates the user pool client.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPoolClient.html
*/
public toCreateUserPoolClient() {
return this.to('CreateUserPoolClient');
}
/**
* Creates a new domain for a user pool.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPoolDomain.html
*/
public toCreateUserPoolDomain() {
return this.to('CreateUserPoolDomain');
}
/**
* Deletes a group. Currently only groups with no members can be deleted.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_DeleteGroup.html
*/
public toDeleteGroup() {
return this.to('DeleteGroup');
}
/**
* Deletes an identity provider for a user pool.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_DeleteIdentityProvider.html
*/
public toDeleteIdentityProvider() {
return this.to('DeleteIdentityProvider');
}
/**
* Deletes a resource server.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_DeleteResourceServer.html
*/
public toDeleteResourceServer() {
return this.to('DeleteResourceServer');
}
/**
* Allows a user to delete one's self.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_DeleteUser.html
*/
public toDeleteUser() {
return this.to('DeleteUser');
}
/**
* Deletes the attributes for a user.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_DeleteUserAttributes.html
*/
public toDeleteUserAttributes() {
return this.to('DeleteUserAttributes');
}
/**
* Deletes the specified Amazon Cognito user pool.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_DeleteUserPool.html
*/
public toDeleteUserPool() {
return this.to('DeleteUserPool');
}
/**
* Allows the developer to delete the user pool client.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_DeleteUserPoolClient.html
*/
public toDeleteUserPoolClient() {
return this.to('DeleteUserPoolClient');
}
/**
* Deletes a domain for a user pool.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_DeleteUserPoolDomain.html
*/
public toDeleteUserPoolDomain() {
return this.to('DeleteUserPoolDomain');
}
/**
* Gets information about a specific identity provider.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_DescribeIdentityProvider.html
*/
public toDescribeIdentityProvider() {
return this.to('DescribeIdentityProvider');
}
/**
* Describes a resource server.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_DescribeResourceServer.html
*/
public toDescribeResourceServer() {
return this.to('DescribeResourceServer');
}
/**
* Describes the risk configuration setting for the userpool / userpool client
*
* Access Level: Read
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_DescribeRiskConfiguration.html
*/
public toDescribeRiskConfiguration() {
return this.to('DescribeRiskConfiguration');
}
/**
* Describes the user import job.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_DescribeUserImportJob.html
*/
public toDescribeUserImportJob() {
return this.to('DescribeUserImportJob');
}
/**
* Returns the configuration information and metadata of the specified user pool.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_DescribeUserPool.html
*/
public toDescribeUserPool() {
return this.to('DescribeUserPool');
}
/**
* Client method for returning the configuration information and metadata of the specified user pool client.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_DescribeUserPoolClient.html
*/
public toDescribeUserPoolClient() {
return this.to('DescribeUserPoolClient');
}
/**
* Gets information about a domain.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_DescribeUserPoolDomain.html
*/
public toDescribeUserPoolDomain() {
return this.to('DescribeUserPoolDomain');
}
/**
* Forgets the specified device.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ForgetDevice.html
*/
public toForgetDevice() {
return this.to('ForgetDevice');
}
/**
* Calling this API causes a message to be sent to the end user with a confirmation code that is required to change the user's password.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ForgotPassword.html
*/
public toForgotPassword() {
return this.to('ForgotPassword');
}
/**
* Gets the header information for the .csv file to be used as input for the user import job.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_GetCSVHeader.html
*/
public toGetCSVHeader() {
return this.to('GetCSVHeader');
}
/**
* Gets the device.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_GetDevice.html
*/
public toGetDevice() {
return this.to('GetDevice');
}
/**
* Gets a group.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_GetGroup.html
*/
public toGetGroup() {
return this.to('GetGroup');
}
/**
* Gets the specified identity provider.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_GetIdentityProviderByIdentifier.html
*/
public toGetIdentityProviderByIdentifier() {
return this.to('GetIdentityProviderByIdentifier');
}
/**
* Returns the signing certificate.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_GetSigningCertificate.html
*/
public toGetSigningCertificate() {
return this.to('GetSigningCertificate');
}
/**
* Gets the UI Customization information for a particular app client's app UI, if there is something set.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_GetUICustomization.html
*/
public toGetUICustomization() {
return this.to('GetUICustomization');
}
/**
* Gets the user attributes and metadata for a user.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_GetUser.html
*/
public toGetUser() {
return this.to('GetUser');
}
/**
* Gets the user attribute verification code for the specified attribute name.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_GetUserAttributeVerificationCode.html
*/
public toGetUserAttributeVerificationCode() {
return this.to('GetUserAttributeVerificationCode');
}
/**
* Gets the MFA configuration for the userpool
*
* Access Level: Read
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_GetUserPoolMfaConfig.html
*/
public toGetUserPoolMfaConfig() {
return this.to('GetUserPoolMfaConfig');
}
/**
* Signs out users from all devices.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_GlobalSignOut.html
*/
public toGlobalSignOut() {
return this.to('GlobalSignOut');
}
/**
* Initiates the authentication flow.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html
*/
public toInitiateAuth() {
return this.to('InitiateAuth');
}
/**
* Lists the devices.
*
* Access Level: List
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ListDevices.html
*/
public toListDevices() {
return this.to('ListDevices');
}
/**
* Lists the groups associated with a user pool.
*
* Access Level: List
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ListGroups.html
*/
public toListGroups() {
return this.to('ListGroups');
}
/**
* Lists information about all identity providers for a user pool.
*
* Access Level: List
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ListIdentityProviders.html
*/
public toListIdentityProviders() {
return this.to('ListIdentityProviders');
}
/**
* Lists the resource servers for a user pool.
*
* Access Level: List
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ListResourceServers.html
*/
public toListResourceServers() {
return this.to('ListResourceServers');
}
/**
* Lists the tags that are assigned to an Amazon Cognito user pool.
*
* Access Level: List
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ListTagsForResource.html
*/
public toListTagsForResource() {
return this.to('ListTagsForResource');
}
/**
* Lists the user import jobs..
*
* Access Level: List
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ListUserImportJobs.html
*/
public toListUserImportJobs() {
return this.to('ListUserImportJobs');
}
/**
* Lists the clients that have been created for the specified user pool.
*
* Access Level: List
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ListUserPoolClients.html
*/
public toListUserPoolClients() {
return this.to('ListUserPoolClients');
}
/**
* Lists the user pools associated with an AWS account.
*
* Access Level: List
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ListUserPools.html
*/
public toListUserPools() {
return this.to('ListUserPools');
}
/**
* Lists the users in the Amazon Cognito user pool.
*
* Access Level: List
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ListUsers.html
*/
public toListUsers() {
return this.to('ListUsers');
}
/**
* Lists the users in the specified group.
*
* Access Level: List
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ListUsersInGroup.html
*/
public toListUsersInGroup() {
return this.to('ListUsersInGroup');
}
/**
* Resends the confirmation (for confirmation of registration) to a specific user in the user pool.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ResendConfirmationCode.html
*/
public toResendConfirmationCode() {
return this.to('ResendConfirmationCode');
}
/**
* Responds to the authentication challenge.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_RespondToAuthChallenge.html
*/
public toRespondToAuthChallenge() {
return this.to('RespondToAuthChallenge');
}
/**
* sets the risk configuration setting for the userpool / userpool client
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SetRiskConfiguration.html
*/
public toSetRiskConfiguration() {
return this.to('SetRiskConfiguration');
}
/**
* Sets the UI customization information for a user pool's built-in app UI.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SetUICustomization.html
*/
public toSetUICustomization() {
return this.to('SetUICustomization');
}
/**
* Sets MFA preference for the user in the userpool
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SetUserMFAPreference.html
*/
public toSetUserMFAPreference() {
return this.to('SetUserMFAPreference');
}
/**
* Sets the MFA configuration for the userpool
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SetUserPoolMfaConfig.html
*/
public toSetUserPoolMfaConfig() {
return this.to('SetUserPoolMfaConfig');
}
/**
* Sets the user settings like multi-factor authentication (MFA).
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SetUserSettings.html
*/
public toSetUserSettings() {
return this.to('SetUserSettings');
}
/**
* Registers the user in the specified user pool and creates a user name, password, and user attributes.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SignUp.html
*/
public toSignUp() {
return this.to('SignUp');
}
/**
* Starts the user import.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_StartUserImportJob.html
*/
public toStartUserImportJob() {
return this.to('StartUserImportJob');
}
/**
* Stops the user import job.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_StopUserImportJob.html
*/
public toStopUserImportJob() {
return this.to('StopUserImportJob');
}
/**
* Assigns a set of tags to an Amazon Cognito user pool.
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_TagResource.html
*/
public toTagResource() {
return this.to('TagResource');
}
/**
* Removes the specified tags from an Amazon Cognito user pool.
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UntagResource.html
*/
public toUntagResource() {
return this.to('UntagResource');
}
/**
* Updates the feedback for the user authentication event
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateAuthEventFeedback.html
*/
public toUpdateAuthEventFeedback() {
return this.to('UpdateAuthEventFeedback');
}
/**
* Updates the device status.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateDeviceStatus.html
*/
public toUpdateDeviceStatus() {
return this.to('UpdateDeviceStatus');
}
/**
* Updates the specified group with the specified attributes.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateGroup.html
*/
public toUpdateGroup() {
return this.to('UpdateGroup');
}
/**
* Updates identity provider information for a user pool.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateIdentityProvider.html
*/
public toUpdateIdentityProvider() {
return this.to('UpdateIdentityProvider');
}
/**
* Updates the name and scopes of resource server.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateResourceServer.html
*/
public toUpdateResourceServer() {
return this.to('UpdateResourceServer');
}
/**
* Allows a user to update a specific attribute (one at a time).
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserAttributes.html
*/
public toUpdateUserAttributes() {
return this.to('UpdateUserAttributes');
}
/**
* Updates the specified user pool with the specified attributes.
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserPool.html
*/
public toUpdateUserPool() {
return this.to('UpdateUserPool');
}
/**
* Allows the developer to update the specified user pool client and password policy.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserPoolClient.html
*/
public toUpdateUserPoolClient() {
return this.to('UpdateUserPoolClient');
}
/**
* Updates the Secure Sockets Layer (SSL) certificate for the custom domain for your user pool.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserPoolDomain.html
*/
public toUpdateUserPoolDomain() {
return this.to('UpdateUserPoolDomain');
}
/**
* Registers a user's entered TOTP code and mark the user's software token MFA status as verified if successful.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_VerifySoftwareToken.html
*/
public toVerifySoftwareToken() {
return this.to('VerifySoftwareToken');
}
/**
* Verifies a user attribute using a one time verification code.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_VerifyUserAttribute.html
*/
public toVerifyUserAttribute() {
return this.to('VerifyUserAttribute');
}
protected accessLevelList: AccessLevelList = {
"Write": [
"AddCustomAttributes",
"AdminAddUserToGroup",
"AdminConfirmSignUp",
"AdminCreateUser",
"AdminDeleteUser",
"AdminDeleteUserAttributes",
"AdminDisableProviderForUser",
"AdminDisableUser",
"AdminEnableUser",
"AdminForgetDevice",
"AdminInitiateAuth",
"AdminLinkProviderForUser",
"AdminRemoveUserFromGroup",
"AdminResetUserPassword",
"AdminRespondToAuthChallenge",
"AdminSetUserMFAPreference",
"AdminSetUserPassword",
"AdminSetUserSettings",
"AdminUpdateAuthEventFeedback",
"AdminUpdateDeviceStatus",
"AdminUpdateUserAttributes",
"AdminUserGlobalSignOut",
"AssociateSoftwareToken",
"ChangePassword",
"ConfirmDevice",
"ConfirmForgotPassword",
"ConfirmSignUp",
"CreateGroup",
"CreateIdentityProvider",
"CreateResourceServer",
"CreateUserImportJob",
"CreateUserPool",
"CreateUserPoolClient",
"CreateUserPoolDomain",
"DeleteGroup",
"DeleteIdentityProvider",
"DeleteResourceServer",
"DeleteUser",
"DeleteUserAttributes",
"DeleteUserPool",
"DeleteUserPoolClient",
"DeleteUserPoolDomain",
"ForgetDevice",
"ForgotPassword",
"GlobalSignOut",
"InitiateAuth",
"ResendConfirmationCode",
"RespondToAuthChallenge",
"SetRiskConfiguration",
"SetUICustomization",
"SetUserMFAPreference",
"SetUserPoolMfaConfig",
"SetUserSettings",
"SignUp",
"StartUserImportJob",
"StopUserImportJob",
"UpdateAuthEventFeedback",
"UpdateDeviceStatus",
"UpdateGroup",
"UpdateIdentityProvider",
"UpdateResourceServer",
"UpdateUserAttributes",
"UpdateUserPool",
"UpdateUserPoolClient",
"UpdateUserPoolDomain",
"VerifySoftwareToken",
"VerifyUserAttribute"
],
"Read": [
"AdminGetDevice",
"AdminGetUser",
"AdminListUserAuthEvents",
"DescribeIdentityProvider",
"DescribeResourceServer",
"DescribeRiskConfiguration",
"DescribeUserImportJob",
"DescribeUserPool",
"DescribeUserPoolClient",
"DescribeUserPoolDomain",
"GetCSVHeader",
"GetDevice",
"GetGroup",
"GetIdentityProviderByIdentifier",
"GetSigningCertificate",
"GetUICustomization",
"GetUser",
"GetUserAttributeVerificationCode",
"GetUserPoolMfaConfig"
],
"List": [
"AdminListDevices",
"AdminListGroupsForUser",
"ListDevices",
"ListGroups",
"ListIdentityProviders",
"ListResourceServers",
"ListTagsForResource",
"ListUserImportJobs",
"ListUserPoolClients",
"ListUserPools",
"ListUsers",
"ListUsersInGroup"
],
"Tagging": [
"TagResource",
"UntagResource"
]
};
/**
* Adds a resource of type userpool to the statement
*
* https://docs.aws.amazon.com/cognito/latest/developerguide/resource-permissions.html#amazon-cognito-amazon-resource-names
*
* @param userPoolId - Identifier for the userPoolId.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onUserpool(userPoolId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:cognito-idp:${Region}:${Account}:userpool/${UserPoolId}';
arn = arn.replace('${UserPoolId}', userPoolId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
} | the_stack |
import { Colors, Types } from "./types";
import themes from '../themes';
import { warn } from './log';
import isEqual from 'lodash/isEqual';
import isEqualWith from 'lodash/isEqualWith';
import merge from 'lodash/merge';
export { isEqual, isEqualWith, merge };
export const requestAnimationFrame = window && window.requestAnimationFrame;
export const propertyMap = {
axis: [
'type', 'showLast', 'alias', 'sync', 'mask', 'base', 'exponent', 'values',
'range', 'min', 'max', 'minLimit', 'maxLimit', 'nice',
'ticks', 'tickMethod', 'tickCount', 'maxTickCount', 'tickInterval', 'minTickInterval', 'formatter',
],
};
const keyType: Types.LooseObject = {
min: 'number',
max: 'number',
minLimit: 'number',
maxLimit: 'number',
tickCount: 'number',
};
/**
* ๅ็ฎๆ ๅฏน่ฑกๆท่ดๆๅฎ็key็ๅผ
*
* @param {string[]} keys ๅคๆญ็key
* @param {Object} target ็ฎๆ ๅฏน่ฑก
* @param {Object} source ๆบๅฏน่ฑก
*
* @return {Object} ็ฎๆ ๅฏน่ฑก
* */
export function propertyAssign(keys: string[], target: Types.LooseObject, source: Types.LooseObject | false) {
if (!source) {
return target;
}
keys.forEach((key) => {
// ไป
ๅคๆญundefined็ๆ
ๅต
if (source[key] === undefined) {
return;
}
// ๅฟฝ็ฅ tickCount: 'auto'
if (key === 'tickCount' && source[key] === 'auto') {
warn('config.axis', `tickCount: 'auto' ่ขซๆฟๆขไธบ Axis.autoHide: true`);
return;
}
// ๅฐ้จๅ้ๅถไบ็ฑปๅ็keyๅฑๆง่ฝฌๆขไธบ้่ฆ็็ฑปๅ
if (keyType[key] !== 'number') {
target[key] = source[key];
} else if (source[key] === null) {
// ่ฎพ็ฝฎnullๅ็ดๆฅ่ตๅผ
target[key] = null;
} else if (!isInvalidNumber(source[key])) {
// ๆฏๆฐๅญๆถๆ่ตๅผ๏ผๅฆๅ็ดๆฅ่ทณ่ฟ
target[key] = Number(source[key]);
}
// if (keyType[key] === 'number') {
// if (!isInvalidNumber(source[key])) {
// target[key] = Number(source[key]);
// }
// } else {
// target[key] = source[key];
// }
});
return target;
}
/**
* ๆพๅฐๅฏนๅบๅ
็ด ็็ถๅ
็ด ็ๅคงๅฐ
*
* @param {element} element Htmlๅ
็ด
* @param {number | string} width propsไธญไผ ้็widthๅฑๆง
* @param {number | string} height propsไธญไผ ้็heightๅฑๆง
*
* @return {number[]} ๅฎฝๅ้ซ็ๆฐ็ป
* */
export function getParentSize(element: HTMLElement, width: number | string, height: number | string) {
let w = width || '';
let h = height || '';
const parent = element && element.parentElement;
if (parent) {
const parentStyle = window.getComputedStyle(parent);
const paddingTop = pxToNumber(parentStyle.getPropertyValue('padding-top'));
const paddingRight = pxToNumber(parentStyle.getPropertyValue('padding-right'));
const paddingBottom = pxToNumber(parentStyle.getPropertyValue('padding-bottom'));
const paddingLeft = pxToNumber(parentStyle.getPropertyValue('padding-left'));
if (!width) {
w = parent.clientWidth - paddingLeft - paddingRight;
}
if (!height) {
h = parent.clientHeight - paddingTop - paddingBottom;
}
}
return [Number(w), Number(h)];
}
/**
* ๅฐๅ็ด ๅญ็ฌฆไธฒ่ฝฌไธบๆฐๅผ
*
* @param {string} px ๅ็ด ๅญ็ฌฆไธฒ
*
* @return {number} ๆฐๅผ
* */
export function pxToNumber(px: string) {
return Number(px.replace('px', ''));
}
/**
* ไปHighchartsๆ ผๅผๆฐๆฎไธญๆพๅฐๅฏนๅบindex็้ข่ฒ
*
* @param {array} colors ้ข่ฒๆฐ็ป
* @param {array} rawData Highcharts ๆ ผๅผ็ๆฐๆฎ
* @param {number} dataIndex y่ฝดๅฏนๅบ็index
* */
export function getDataIndexColor(colors: Colors, rawData: any[], dataIndex: number): string | void {
if (typeof colors === 'string') {
return colors;
}
let colorIndex = null;
// ๆพๅฐ็ฌฌไธไธช้กบๅบๅผๅๆฐๆฎไธญyAxisๅผๅน้
็index
rawData.some((d, i) => {
const dataYAxisIndex = d.yAxis || 0;
if (dataYAxisIndex === dataIndex) {
colorIndex = i;
return true;
}
return false;
});
if (typeof colorIndex === 'number') {
if (Array.isArray(colors)) {
return colors[colorIndex];
}
if (typeof colors === 'function') {
return colors(rawData[colorIndex].name);
}
}
}
/**
* ๆ นๆฎ็ถๆ่ทๅพ้ข่ฒๅผ
*
* @param {string} status ็ถๆๅญ็ฌฆไธฒ
*
* @return {string} ้ข่ฒๅผ
* */
export function getStatusColor(status: string) {
// map ๆพๅ
ฅๅฝๆฐๅ
๏ผไปฅๅๅบ theme ็ๅจๆๅๅ
const statusMap: Types.LooseObject = {
error: themes['widgets-color-red'],
red: themes['widgets-color-red'],
warning: themes['widgets-color-orange'],
orange: themes['widgets-color-orange'],
normal: themes['widgets-color-blue'],
blue: themes['widgets-color-blue'],
success: themes['widgets-color-green'],
green: themes['widgets-color-green'],
none: themes['widgets-color-gray'],
gray: themes['widgets-color-gray'],
};
return statusMap[status] || status || statusMap.normal;
}
const statusColorMap: { [key: string]: string } = {
error: 'red',
warning: 'orange',
normal: 'blue',
success: 'green',
none: 'gray',
};
/**
* ๆ นๆฎ็ถๆ่ทๅพ้ข่ฒๅ็งฐ
*
* @param {string} status ็ถๆๅญ็ฌฆไธฒ
*
* @return {string} ้ข่ฒๅ็งฐ
* */
export function getStatusColorName(status: string) {
return statusColorMap[status] || status || statusColorMap.normal;
}
/**
* ๅคๆญๆฏๅฆๆฏๆๆๆฐๅญ
*
* @param v ่พๅ
ฅๅผ
*
* @return {boolean} ๆฏๅฆๆๆๆฐๅญ
* */
export function isInvalidNumber(v: any) {
return isNaN(v) || !isFinite(v) || v === '' || typeof v === 'object';
}
/**
* ๆฐๅญๆ ผๅผๅๅฐๆฐไฝ
*
* @param {number} num ่พๅ
ฅๆฐๅญ
* @param {number} decimal ๅฐๆฐไฝๆฐ๏ผ้ป่ฎคไธคไฝ
*
* @return {string|number} ๅฆๆไธๆฏๆฐๅญ๏ผ่ฟๅๆจชๆ ๅญ็ฌฆไธฒใๅฆๆๆฏๆฐๅญ๏ผ่ฟๅ่ฎพๅฎๅฐๆฐไฝ็ๅญ็ฌฆไธฒใ
* */
export function numberDecimal(num: any, decimal = 2) {
if (isInvalidNumber(num) || isInvalidNumber(decimal)) {
return num;
}
// ๅฐๆฐไฝ่ขซ่ฝฌๆขไธบๆดๆฐไธไธๅฐไบ0
let d = Math.max(0, Math.round(decimal));
return Math.round(Number(num) * Math.pow(10, d)) / Math.pow(10, d);
}
/**
* ๆฐๅญๆ ผๅผๅๅๅไฝ
*
* @param {number} num ่พๅ
ฅๆฐๅญ
* @param {number} char ๅ้็ฌฆ๏ผ้ป่ฎคไธบ้ๅท
*
* @return {string|number} ๅฆๆไธๆฏๆฐๅญ๏ผ่ฟๅๆจชๆ ๅญ็ฌฆไธฒใๅฆๆๆฏๆฐๅญ๏ผ่ฟๅๅๅไฝ็ๅญ็ฌฆไธฒใ
* */
export function beautifyNumber(num: any, char = ',') {
if (isInvalidNumber(num)) {
return num;
}
const isNegative = num < 0;
const numberArr = num.toString().split('.');
let number = numberArr[0].replace('-', '');
let result = '';
while (number.length > 3) {
result = char + number.slice(-3) + result;
number = number.slice(0, number.length - 3);
}
if (number) {
result = number + result;
}
// fix ไฟ็ไบๅฐๆฐไฝๆฐๅญ
if (numberArr[1]) {
result = `${result}.${numberArr[1]}`;
}
// ๅค็่ดๆฐ
if (isNegative) {
result = `-${result}`;
}
return result;
}
/**
* ็ฉบๅฝๆฐ
* */
export function noop() {}
/**
* tooltip item ่ทๅๅๅงๆฐๆฎ
*
* @param {object} config ๅพ่กจ้
็ฝฎ้กน
* @param {array} rawData ๆ่ฝฝไบ this.rawData ไธ็ๅๅงๆฐๆฎ
* @param {number} item tooltipๆ ผๅผๅๅฝๆฐ็ๅฝๅๆฐๆฎ้กน
*
* @return {object} ๅฏปๆพๅพๅฐ็ๅๅงๆฐๆฎ๏ผๆฒกๆๆพๅฐๅ่ฟๅ็ฉบๅฏน่ฑกใ
* */
export function getRawData(config: { dataType?: string }, rawData: any[], item: any) {
if (!rawData) {
return {};
}
let originData = item.data || {};
if (config.dataType !== 'g2' && Array.isArray(rawData)) {
rawData.some((r) => {
if (r.name === originData.type) {
// ๅฆๆๅๆฐๆฎไธญๅฎไนไบ facet๏ผ้่ฆ้ขๅคๅคๅฎ facet ๅญๆฎต
if (r.facet && originData.facet !== r.facet) {
return false;
}
originData = r;
return true;
}
return false;
});
}
return originData;
}
/**
* ่ฟๆปคๅฏน่ฑกไธญ็key๏ผๅธธ็จไบ่ฟๆปคไผ ้็ปdiv็props๏ผ้ฒๆญขreact invalid attribute warning
*
* @param {object} obj ่ฟๆปค็ๅฏน่ฑก
* @param {array} keys ่ฟๆปค็้ฎๅ่กจ
*
* @return {object} ่ฟๆปคๅ็็ปๆ
* */
export function filterKey(obj: Types.LooseObject, keys: string[]) {
const result: Types.LooseObject = {};
Object.keys(obj).forEach((key) => {
if (keys.indexOf(key) === -1) {
result[key] = obj[key];
}
});
return result;
}
/**
* ๅค็ๅพ่กจๅบไธญ็้ป่ฎคpaddingๅผ็้็จๅฝๆฐ
*
* @param {padding} padding ็จๆท้
็ฝฎ็paddingๅผ
* @param {object} config ๅๅนถไบ้ป่ฎค้
็ฝฎๅ็ๆ็ป้
็ฝฎ้กน
* ไปฅไธๅๆฐ้ๅฟ
้
* @param {number} [defaultTop] ้ป่ฎคtop padding
* @param {number} [defaultRight] ้ป่ฎคright padding
* @param {number} [defaultBottom] ้ป่ฎคbottom padding
* @param {number} [defaultLeft] ้ป่ฎคleft padding
*
* @return
* */
// export function defaultPadding(padding, config, defaultTop, defaultRight, defaultBottom, defaultLeft) {
// if (padding) {
// return padding;
// }
//
// // ๅ้ป่ฎค้
็ฝฎไธญ็padding
// let top = defaultTop;
// let right = defaultRight;
// let bottom = defaultBottom;
// let left = defaultLeft;
//
// if (right !== 'auto' && Array.isArray(config.yAxis)) {
// right = 45;
// }
//
// if (top !== 'auto' && (config.legend === false || (config.legend && config.legend.visible === false))) {
// top = 16;
// }
// if (config.legend !== false && !(config.legend && config.legend.visible === false)) {
// const { position = 'top' } = config.legend || {};
// if (top !== 'auto' && position === 'bottom') {
// top = 10;
// }
// if (position === 'bottom') {
// bottom = 48;
// }
// }
//
// // X่ฝดๆ ้ข
// if (config.xAxis && config.xAxis.visible !== false && config.xAxis.alias && bottom !== 'auto') {
// bottom += 14;
// }
//
// // Y่ฝดๆ ้ข
// if (Array.isArray(config.yAxis)) {
// config.yAxis.forEach((axis, yIndex) => {
// if (yIndex === 0 && axis && axis.visible !== false && axis.alias && left !== 'auto') {
// left += 20;
// }
// if (yIndex !== 0 && axis && axis.visible !== false && axis.alias && right !== 'auto') {
// right += 20;
// }
// });
// } else if (config.yAxis && config.yAxis.visible !== false && config.yAxis.alias && left !== 'auto') {
// left += 20;
// }
//
// return [top, right, bottom, left];
// }
export interface customFormatterConfig {
unit?: string;
decimal?: number;
grouping?: boolean | string;
}
/**
* ่ชๅฎไนๆ ผๅผๅๅฝๆฐ๏ผๆฏๆ ๅไฝใๅฐๆฐไฝใๅๅไฝ ๅค็
* */
export function customFormatter(config: customFormatterConfig) {
const { unit, decimal = 6, grouping } = config;
if (!unit && (decimal === undefined || decimal === null) && !grouping) {
return null;
}
return function (v: any) {
let result = v;
let newUnit = unit || '';
if (isInvalidNumber(v)) {
return `${v}${newUnit}`;
}
// ๅฐๆฐไฝ
result = numberDecimal(result, decimal);
// ๅๅไฝ
if (grouping) {
result = beautifyNumber(result, typeof grouping === 'boolean' ? ',' : grouping);
}
return `${result}${newUnit}`;
}
} | the_stack |
import { MessengerTypes } from 'bottender';
export { FacebookConnectorOptions } from './FacebookConnector';
export { FacebookContextOptions } from './FacebookContext';
export type CamelCaseUnion<KM, U extends keyof KM> = U extends string
? KM[U]
: never;
export type FeedStatus = {
from: {
id: string;
name: string;
};
item: 'status';
postId: string;
verb: 'add' | 'edited';
published: number;
createdTime: number;
message: string;
};
export type FeedPost = {
recipientId: string;
from: {
id: string;
};
item: 'post';
postId: string;
verb: 'add' | 'edited' | 'remove';
createdTime: number;
};
export type FeedComment = {
from: {
/**
* The ID of the sender
*/
id: string;
/**
* The name of the sender
*/
name?: string;
};
item: 'comment';
/**
* The comment ID
*/
commentId: string;
/**
* The post ID
*/
postId: string;
/**
* The parent ID
*/
parentId: string;
/**
* The timestamp of when the object was created
*/
createdTime: number;
/**
* Provide additional content about a post
*/
post?: {
/**
* The ID of the post
*/
id: string;
/**
* The type of the post
*/
type: 'photo' | 'video' | string;
/**
* Description of the type of a status update.
*/
statusType: 'added_photos' | 'added_videos' | string;
/**
* The time the post was last updated, which occurs when a user comments on the post.
*/
updatedTime: string;
/**
* Status of the promotion, if the post was promoted
*/
promotionStatus: 'inactive' | 'extendable' | string;
/**
* The permanent static URL to the post on www.facebook.com.
*/
permalinkUrl: string;
/**
* Indicates whether a scheduled post was published (applies to scheduled Page Post only, for users post and instanlty published posts this value is always true)
*/
isPublished: boolean;
};
} & (
| {
verb: 'add' | 'edited';
/**
* The message that is part of the content
*/
message: string;
}
| { verb: 'remove' }
);
export type FeedReaction = {
reactionType: 'like' | 'love' | 'haha' | 'wow' | 'sad' | 'angry' | 'care';
from: {
id: string;
};
parentId: string;
commentId?: string;
postId: string;
verb: 'add' | 'edit' | 'remove';
item: 'reaction';
createdTime: number;
};
export type FeedEvent = {
item: 'event';
message?: string;
postId: string;
story?: string;
eventId: string;
verb: 'add';
createdTime: number;
};
export type FeedPhoto = {
item: 'photo';
from: {
id: string;
name?: string;
};
link?: string;
message?: string;
postId: string;
createdTime: number;
photoId: string;
published: 0 | 1;
verb: 'add' | 'edited';
};
export type FeedVideo =
| {
item: 'video';
from: {
id: string;
name?: string;
};
link?: string;
message?: string;
postId: string;
createdTime: number;
published: 0 | 1;
verb: 'add' | 'edited';
videoId: string;
}
| {
item: 'video';
from: {
id: string;
name?: string;
};
postId: string;
createdTime: number;
verb: 'remove';
recipientId: string;
}
| {
item: 'video';
link: string;
message?: string;
videoFlagReason: 1;
verb: 'mute';
videoId: string;
}
| {
item: 'video';
message?: string;
videoFlagReason: 1;
verb: 'block';
videoId: string;
}
| {
item: 'video';
link: string;
message?: string;
videoFlagReason: 1;
verb: 'unblock';
videoId: string;
};
export type FeedShare = {
item: 'share';
from: {
id: string;
name?: string;
};
link?: string;
message?: string;
postId: string;
createdTime: number;
published: 0 | 1;
verb: 'add' | 'edited';
shareId: string;
};
export type FeedPageLike = {
item: 'like';
verb: 'add';
};
/**
* item: album, address, comment, connection, coupon, event, experience, group, group_message, interest, like, link, mention, milestone, note, page, picture, platform-story, photo, photo-album, post, profile, question, rating, reaction, relationship-status, share, status, story, timeline cover, tag, video
*/
export type FacebookRawEvent = {
field: 'feed';
value:
| FeedStatus
| FeedPost
| FeedComment
| FeedReaction
| FeedEvent
| FeedPhoto
| FeedVideo
| FeedShare
| FeedPageLike;
};
export type ChangesEntry = {
id: string;
time: number;
changes: FacebookRawEvent[];
};
type FacebookRequestBody = {
object: 'page';
entry: ChangesEntry[];
};
export type FacebookWebhookRequestBody =
| MessengerTypes.MessengerRequestBody
| FacebookRequestBody;
/**
* https://developers.facebook.com/docs/graph-api/reference/v6.0/comment
*/
export type CommentField =
| 'id'
| 'attachment'
| 'can_comment'
| 'can_remove'
| 'can_hide'
| 'can_like'
| 'can_reply_privately'
| 'comment_count'
| 'created_time'
| 'from'
| 'like_count'
| 'message'
| 'message_tags'
| 'object'
| 'parent'
| 'private_reply_conversation'
| 'user_likes';
export type CommentKeyMap = {
id: 'id';
attachment: 'attachment';
can_comment: 'canComment';
can_remove: 'canRemove';
can_hide: 'canHide';
can_like: 'canLike';
can_reply_privately: 'canReplyPrivately';
comment_count: 'commentCount';
created_time: 'createdTime';
from: 'from';
like_count: 'likeCount';
message: 'message';
message_tags: 'messageTags';
object: 'object';
parent: 'parent';
private_reply_conversation: 'privateReplyConversation';
user_likes: 'userLikes';
};
export type InputComment =
| {
/**
* An optional ID of a unpublished photo (see no_story field in `/{user-id}/photos`) uploaded to Facebook to include as a photo comment.
*/
attachmentId?: string;
}
| {
/**
* The URL of a GIF to include as a animated GIF comment.
*/
attachmentShareUrl?: string;
}
| {
/**
* The URL of an image to include as a photo comment.
*/
attachmentUrl?: string;
}
| {
/**
* The comment text.
*/
message?: string;
};
export type Comment = {
/**
* The comment ID
*/
id: string;
/**
* Link, video, sticker, or photo attached to the comment
*/
attachment: StoryAttachment;
/**
* Whether the viewer can reply to this comment
*/
canComment: boolean;
/**
* Whether the viewer can remove this comment
*/
canRemove: boolean;
/**
* Whether the viewer can hide this comment. Only visible to a page admin
*/
canHide: boolean;
/**
* Whether the viewer can like this comment
*/
canLike: boolean;
/**
* Whether the viewer can send a private reply to this comment (Page viewers only)
*/
canReplyPrivately: boolean;
/**
* Number of replies to this comment
*/
commentCount: number;
/**
* The time this comment was made
*/
createdTime: string;
/**
* The person that made this comment
*/
from: User;
/**
* Number of times this comment was liked
*/
likeCount: number;
/**
* The comment text
*/
message: string;
/**
* An array of Profiles tagged in message.
*/
messageTags: MessageTag[];
/**
* For comments on a photo or video, this is that object. Otherwise, this is empty.
*/
object: any;
/**
* For comment replies, this the comment that this is a reply to.
*/
parent: Comment;
/**
* For comments with private replies, gets conversation between the Page and author of the comment (Page viewers only)
*/
privateReplyConversation: Conversation;
/**
* Whether the viewer has liked this comment.
*/
userLikes: boolean;
};
/**
* https://developers.facebook.com/docs/graph-api/reference/v6.0/conversation
*/
export type Conversation = {
/**
* The ID of a conversation, in a format similar to t_000000000000000
*/
id: string;
/**
* The url to the thread
*/
link: string;
/**
* The snippet of the most recent message in a conversation
*/
snippet: string;
/**
* Last update time
*/
updatedTime: string;
/**
* An estimate of the number of messages
*/
messageCount: number;
/**
* An estimate of the number of unread messages
*/
unreadCount: number;
/**
* People and Pages who are on this conversation
*/
participants: {
name: string;
email: string;
id: string;
}[];
/**
* People who have sent a message
*/
senders: {
name: string;
email: string;
id: string;
}[];
/**
* Whether the Page is able to reply
*/
canReply: boolean;
/**
* Whether the Page is subscribed to the conversation
*/
isSubscribed: boolean;
};
export type MessageTag = {
/**
* ID of the profile that was tagged.
*/
id: string;
/**
* The text used in the tag.
*/
name: string;
/**
* Indicates which type of profile is tagged.
*/
type: 'user' | 'page' | 'group';
/**
* Where the first character of the tagged text is in the message, measured in unicode code points.
*/
offset: number;
/**
* How many unicode code points this tag consists of, after the offset.
*/
length: number;
};
export type StoryAttachment = {
/**
* Text accompanying the attachment
*/
description: string;
/**
* Profiles tagged in the text accompanying the attachment
*/
descriptionTags: EntityAtTextRange[];
/**
* Media object (photo, link etc.) contained in the attachment
*/
media: StoryAttachmentMedia;
/**
* Type of the media such as (photo, video, link etc)
*/
mediaType?: string;
/**
* Object that the attachment links to
*/
target: StoryAttachmentTarget;
/**
* Title of the attachment
*/
title: string;
/**
* Type of the attachment.
*/
type:
| 'album'
| 'animated_image_autoplay'
| 'checkin'
| 'cover_photo'
| 'event'
| 'link'
| 'multiple'
| 'music'
| 'note'
| 'offer'
| 'photo'
| 'profile_media'
| 'status'
| 'video'
| 'video_autoplay';
/**
* Unshimmed URL of the attachment
*/
unshimmedUrl?: string;
/**
* URL of the attachment
*/
url: string;
};
/**
* Location and identity of an object in some source text
*
* https://developers.facebook.com/docs/graph-api/reference/entity-at-text-range/
*/
type EntityAtTextRange = {
/**
* ID of the profile
*/
id: string;
/**
* Number of characters in the text indicating the object
*/
length: number;
/**
* Name of the object
*/
name: string;
/**
* The object itself
*/
object: any;
/**
* The character offset in the source text of the text indicating the object
*/
offset: number;
} & (
| {
/**
* Type of the object
*/
type: 'user';
/**
* The object itself
*/
object: User;
}
| {
type: 'page';
object: Page;
}
| {
type: 'event';
object: Event;
}
| {
type: 'group';
object: Group;
}
| {
type: 'application';
object: Application;
}
);
/**
* https://developers.facebook.com/docs/graph-api/reference/user
*/
type User = {
/**
* The ID of this person's user account. This ID is unique to each app and cannot be used across different apps.
*/
id: string;
/**
* The User's address.
*/
address?: Location;
/**
* Notes added by viewing page on this User.
*/
adminNotes?: PageAdminNote[];
/**
* The age segment for this person expressed as a minimum and maximum age. For example, more than 18, less than 21.
*/
ageRange: AgeRange;
/**
* The authentication method a Workplace User has configured for their account.
*/
authMethod?: 'password' | 'sso';
/**
* The person's birthday. This is a fixed format string, like MM/DD/YYYY.
*/
birthday: string;
/**
* Can the person review brand polls
*/
canReviewMeasurementRequest: boolean;
/**
* The User's primary email address listed on their profile. This field will not be returned if no valid email address is available.
*/
email?: string;
/**
* Athletes the User likes.
*/
favoriteAthletes?: Experience[];
/**
* Sports teams the User likes.
*/
favoriteTeams?: Experience[];
/**
* The person's first name
*/
firstName: string;
/**
* The gender selected by this person, male or female. If the gender is set to a custom value, this value will be based off of the preferred pronoun; it will be omitted if the preferred pronoun is neutral
*/
gender: string;
/**
* The person's hometown
*/
hometown: Page;
/**
* The person's inspirational people
*/
inspirationalPeople: Experience[];
/**
* Install type
*/
installType?: string;
/**
* Is the app making the request installed
*/
installed?: boolean;
/**
* if the current user is a guest user. should always return false.
*/
isGuestUser?: false;
/**
* Is this a shared login (e.g. a gray user)
*/
isSharedLogin?: boolean;
/**
* Facebook Pages representing the languages this person knows
*/
languages?: Experience[];
/**
* The person's last name
*/
lastName: string;
/**
* A link to the person's Timeline. The link will only resolve if the person clicking the link is logged into Facebook and is a friend of the person whose profile is being viewed.
*/
link: string;
/**
* The person's current location as entered by them on their profile. This field requires the user_location permission.
*/
location: Page;
/**
* What the person is interested in meeting for
*/
meetingFor?: string[];
/**
* The person's middle name
*/
middleName?: string;
/**
* The person's full name
*/
name: string;
/**
* The person's name formatted to correctly handle Chinese, Japanese, or Korean ordering
*/
nameFormat?: string;
/**
* The person's payment pricepoints
*/
paymentPricepoints?: PaymentPricepoints;
/**
* The profile picture URL of the Messenger user. The URL will expire.
*/
profilePic?: string;
/**
* The person's PGP public key
*/
publicKey?: string;
/**
* The person's favorite quotes
*/
quotes?: string;
/**
* Security settings
*/
securitySettings: SecuritySettings;
/**
* The time that the shared login needs to be upgraded to Business Manager by
*/
sharedLoginUpgradeRequiredBy: string;
/**
* Shortened, locale-aware name for the person
*/
shortName?: string;
/**
* The person's significant other
*/
significantOther?: User;
/**
* Sports played by the person
*/
sports?: Experience[];
/**
* Whether the user can add a Donate Button to their Live Videos
*/
supportsDonateButtonInLiveVideo?: boolean;
/**
* Platform test group
*/
testGroup?: number;
/**
* A token that is the same across a business's apps. Access to this token requires that the person be logged into your app or have a role on your app. This token will change if the business owning the app changes
*/
tokenForBusiness?: string;
/**
* Video upload limits
*/
videoUploadLimits: VideoUploadLimits;
/**
* Can the viewer send a gift to this person?
*/
viewerCanSendGift?: boolean;
};
/**
* https://developers.facebook.com/docs/graph-api/reference/location/
*/
type Location = {
city: string;
cityId?: number;
country: string;
countryCode?: string;
latitude: number;
locatedIn: string;
longitude: number;
name: string;
region?: string;
regionId?: number;
state: string;
street: string;
zip: string;
};
type PageAdminNote = any;
/**
* https://developers.facebook.com/docs/graph-api/reference/age-range/
*/
type AgeRange = {
/**
* The upper bounds of the range for this person's age. `enum{17, 20, or empty}`.
*/
max: number;
/**
* The lower bounds of the range for this person's age. `enum{13, 18, 21}`
*/
min: number;
};
/**
* https://developers.facebook.com/docs/graph-api/reference/experience/
*/
type Experience = {
id: string;
description: string;
from: User;
name: string;
with: User[];
};
/**
* https://developers.facebook.com/docs/graph-api/reference/payment-pricepoints/
*/
type PaymentPricepoints = {
mobile: PaymentPricepoint[];
};
/**
* https://developers.facebook.com/docs/graph-api/reference/payment-pricepoint/
*/
type PaymentPricepoint = {
credits: number;
localCurrency: string;
userPrice: string;
};
/**
* https://developers.facebook.com/docs/graph-api/reference/security-settings/
*/
type SecuritySettings = {
secureBrowsing: SecureBrowsing;
};
/**
* https://developers.facebook.com/docs/graph-api/reference/secure-browsing/
*/
type SecureBrowsing = {
enabled: boolean;
};
/**
* https://developers.facebook.com/docs/graph-api/reference/video-upload-limits/
*/
type VideoUploadLimits = {
length: number;
size: number;
};
/**
* https://developers.facebook.com/docs/graph-api/reference/page
*/
type Page = Record<string, any>;
/**
* https://developers.facebook.com/docs/graph-api/reference/event
*/
type Event = Record<string, any>;
/**
* https://developers.facebook.com/docs/graph-api/reference/v6.0/group
*/
type Group = {
/**
* The Group ID
*/
id: string;
/**
* Information about the Group's cover photo.
*/
cover: CoverPhoto;
/**
* A brief description of the Group.
*/
description: string;
/**
* The email address to upload content to the Group. Only current members of the Group can use this.
*/
email: string;
/**
* The URL for the Group's icon.
*/
icon: string;
/**
* The number of members in the Group.
*/
memberCount: number;
/**
* The number of pending member requests. Requires an access token of an Admin of the Group.we The count is only returned when the number of pending member requests is over 50.
*/
memberRequestCount: number;
/**
* The name of the Group.
*/
name: string;
/**
* The parent of this Group, if it exists.
*/
parent: Group | Page;
/**
* The permissions a User has granted for an app installed in the Group.
*/
permissions: string;
/**
* The privacy setting of the Group. Requires an access token of an Admin of the Group.
*/
privacy: 'CLOSED' | 'OPEN' | 'SECRET';
/**
* The last time the Group was updated (includes changes Group properties, Posts, and Comments). Requires an access token of an Admin of the Group.
*/
updatedTime: string;
};
type CoverPhoto = {
/**
* ID of the Photo that represents this cover photo.
*/
id: string;
/**
* URL to the Photo that represents this cover photo.
*/
source: string;
/**
* The vertical offset in pixels of the photo from the bottom.
*/
offsetY: number;
/**
* The horizontal offset in pixels of the photo from the left.
*/
offsetX: number;
};
/**
* https://developers.facebook.com/docs/graph-api/reference/application
*/
type Application = Record<string, any>;
/**
* https://developers.facebook.com/docs/graph-api/reference/story-attachment-media/
*/
type StoryAttachmentMedia = {
image: any;
source: string;
};
/**
* https://developers.facebook.com/docs/graph-api/reference/story-attachment-target/
*/
type StoryAttachmentTarget = {
id: string;
unshimmedUrl?: string;
url: string;
};
/**
* https://developers.facebook.com/docs/graph-api/reference/v6.0/object/likes
*/
export type Likes = {
data: Like[];
paging: {
cursors: {
before: string;
after: string;
};
next: string;
};
summary?: {
totalCount: number;
};
};
export type Like = {
name: string;
id: string;
createdTime: string;
};
export type CommonPaginationOptions = {
limit?: number;
};
export type CursorBasedPaginationOptions = CommonPaginationOptions & {
before?: string;
after?: string;
};
export type TimeBasedPaginationOptions = CommonPaginationOptions & {
until?: string;
since?: string;
};
export type OffsetBasedPaginationOptions = CommonPaginationOptions & {
offset?: number;
};
export type PaginationOptions =
| CursorBasedPaginationOptions
| TimeBasedPaginationOptions
| OffsetBasedPaginationOptions;
export type PagingData<T extends object> = {
data: T;
paging: {
previous?: string;
next?: string;
};
};
export type GetCommentOptions<T extends CommentField> = {
fields?: T[];
};
export type GetCommentsOptions<
T extends CommentField,
U extends boolean
> = PaginationOptions & {
summary?: U;
filter?: 'toplevel' | 'stream';
order?: 'chronological' | 'reverse_chronological';
fields?: T[];
};
export type GetLikesOptions = {
summary?: boolean;
};
/**
* https://developers.facebook.com/docs/graph-api/reference/v7.0/insights
*/
export type DatePreset =
| 'today'
| 'yesterday'
| 'this_month'
| 'last_month'
| 'this_quarter'
| 'lifetime'
| 'last_3d'
| 'last_7d'
| 'last_14d'
| 'last_28d'
| 'last_30d'
| 'last_90d'
| 'last_week_mon_sun'
| 'last_week_sun_sat'
| 'last_quarter'
| 'last_year'
| 'this_week_mon_today'
| 'this_week_sun_today'
| 'this_year';
export type PageInsightsMetricDay =
| 'page_tab_views_login_top_unique'
| 'page_tab_views_login_top'
| 'page_tab_views_logout_top'
| 'page_total_actions'
| 'page_cta_clicks_logged_in_total'
| 'page_cta_clicks_logged_in_unique'
| 'page_cta_clicks_by_site_logged_in_unique'
| 'page_cta_clicks_by_age_gender_logged_in_unique'
| 'page_cta_clicks_logged_in_by_country_unique'
| 'page_cta_clicks_logged_in_by_city_unique'
| 'page_call_phone_clicks_logged_in_unique'
| 'page_call_phone_clicks_by_age_gender_logged_in_unique'
| 'page_call_phone_clicks_logged_in_by_country_unique'
| 'page_call_phone_clicks_logged_in_by_city_unique'
| 'page_call_phone_clicks_by_site_logged_in_unique'
| 'page_get_directions_clicks_logged_in_unique'
| 'page_get_directions_clicks_by_age_gender_logged_in_unique'
| 'page_get_directions_clicks_logged_in_by_country_unique'
| 'page_get_directions_clicks_logged_in_by_city_unique'
| 'page_get_directions_clicks_by_site_logged_in_unique'
| 'page_website_clicks_logged_in_unique'
| 'page_website_clicks_by_age_gender_logged_in_unique'
| 'page_website_clicks_logged_in_by_country_unique'
| 'page_website_clicks_logged_in_by_city_unique'
| 'page_website_clicks_by_site_logged_in_unique'
| 'page_engaged_users'
| 'page_post_engagements'
| 'page_consumptions'
| 'page_consumptions_unique'
| 'page_consumptions_by_consumption_type'
| 'page_consumptions_by_consumption_type_unique'
| 'page_places_checkin_total'
| 'page_places_checkin_total_unique'
| 'page_places_checkin_mobile'
| 'page_places_checkin_mobile_unique'
| 'page_places_checkins_by_age_gender'
| 'page_places_checkins_by_locale'
| 'page_places_checkins_by_country'
| 'page_negative_feedback'
| 'page_negative_feedback_unique'
| 'page_negative_feedback_by_type'
| 'page_negative_feedback_by_type_unique'
| 'page_positive_feedback_by_type'
| 'page_positive_feedback_by_type_unique'
| 'page_fans_online'
| 'page_fans_online_per_day'
| 'page_fan_adds_by_paid_non_paid_unique'
| 'page_impressions'
| 'page_impressions_unique'
| 'page_impressions_paid'
| 'page_impressions_paid_unique'
| 'page_impressions_organic'
| 'page_impressions_organic_unique'
| 'page_impressions_viral'
| 'page_impressions_viral_unique'
| 'page_impressions_nonviral'
| 'page_impressions_nonviral_unique'
| 'page_impressions_by_story_type'
| 'page_impressions_by_story_type_unique'
| 'page_impressions_by_city_unique'
| 'page_impressions_by_country_unique'
| 'page_impressions_by_locale_unique'
| 'page_impressions_by_age_gender_unique'
| 'page_impressions_frequency_distribution'
| 'page_impressions_viral_frequency_distribution'
| 'page_posts_impressions'
| 'page_posts_impressions_unique'
| 'page_posts_impressions_paid'
| 'page_posts_impressions_paid_unique'
| 'page_posts_impressions_organic'
| 'page_posts_impressions_organic_unique'
| 'page_posts_served_impressions_organic_unique'
| 'page_posts_impressions_viral'
| 'page_posts_impressions_viral_unique'
| 'page_posts_impressions_nonviral'
| 'page_posts_impressions_nonviral_unique'
| 'page_posts_impressions_frequency_distribution'
| 'page_actions_post_reactions_like_total'
| 'page_actions_post_reactions_love_total'
| 'page_actions_post_reactions_wow_total'
| 'page_actions_post_reactions_haha_total'
| 'page_actions_post_reactions_sorry_total'
| 'page_actions_post_reactions_anger_total'
| 'page_actions_post_reactions_total'
| 'page_fans'
| 'page_fans_locale'
| 'page_fans_city'
| 'page_fans_country'
| 'page_fans_gender_age'
| 'page_fan_adds'
| 'page_fan_adds_unique'
| 'page_fans_by_like_source'
| 'page_fans_by_like_source_unique'
| 'page_fan_removes'
| 'page_fan_removes_unique'
| 'page_fans_by_unlike_source'
| 'page_fans_by_unlike_source_unique'
| 'page_video_views'
| 'page_video_views_paid'
| 'page_video_views_organic'
| 'page_video_views_by_paid_non_paid'
| 'page_video_views_autoplayed'
| 'page_video_views_click_to_play'
| 'page_video_views_unique'
| 'page_video_repeat_views'
| 'page_video_complete_views_30s'
| 'page_video_complete_views_30s_paid'
| 'page_video_complete_views_30s_organic'
| 'page_video_complete_views_30s_autoplayed'
| 'page_video_complete_views_30s_click_to_play'
| 'page_video_complete_views_30s_unique'
| 'page_video_complete_views_30s_repeat_views'
| 'page_video_views_10s'
| 'page_video_views_10s_paid'
| 'page_video_views_10s_organic'
| 'page_video_views_10s_autoplayed'
| 'page_video_views_10s_click_to_play'
| 'page_video_views_10s_unique'
| 'page_video_views_10s_repeat'
| 'page_video_view_time'
| 'page_views_total'
| 'page_views_logout'
| 'page_views_logged_in_total'
| 'page_views_logged_in_unique'
| 'page_views_external_referrals'
| 'page_views_by_profile_tab_total'
| 'page_views_by_profile_tab_logged_in_unique'
| 'page_views_by_internal_referer_logged_in_unique'
| 'page_views_by_site_logged_in_unique'
| 'page_views_by_age_gender_logged_in_unique'
| 'page_views_by_referers_logged_in_unique'
| 'page_content_activity_by_action_type_unique'
| 'page_content_activity_by_age_gender_unique'
| 'page_content_activity_by_city_unique'
| 'page_content_activity_by_country_unique'
| 'page_content_activity_by_locale_unique'
| 'page_content_activity'
| 'page_content_activity_by_action_type'
| 'page_daily_video_ad_break_ad_impressions_by_crosspost_status'
| 'page_daily_video_ad_break_cpm_by_crosspost_status'
| 'page_daily_video_ad_break_earnings_by_crosspost_status';
export type PageInsightsMetricWeek =
| 'page_tab_views_login_top_unique'
| 'page_tab_views_login_top'
| 'page_total_actions'
| 'page_cta_clicks_logged_in_total'
| 'page_cta_clicks_logged_in_unique'
| 'page_cta_clicks_by_site_logged_in_unique'
| 'page_cta_clicks_by_age_gender_logged_in_unique'
| 'page_cta_clicks_logged_in_by_country_unique'
| 'page_cta_clicks_logged_in_by_city_unique'
| 'page_call_phone_clicks_logged_in_unique'
| 'page_call_phone_clicks_by_age_gender_logged_in_unique'
| 'page_call_phone_clicks_logged_in_by_country_unique'
| 'page_call_phone_clicks_logged_in_by_city_unique'
| 'page_call_phone_clicks_by_site_logged_in_unique'
| 'page_get_directions_clicks_logged_in_unique'
| 'page_get_directions_clicks_by_age_gender_logged_in_unique'
| 'page_get_directions_clicks_logged_in_by_country_unique'
| 'page_get_directions_clicks_logged_in_by_city_unique'
| 'page_get_directions_clicks_by_site_logged_in_unique'
| 'page_website_clicks_logged_in_unique'
| 'page_website_clicks_by_age_gender_logged_in_unique'
| 'page_website_clicks_logged_in_by_country_unique'
| 'page_website_clicks_logged_in_by_city_unique'
| 'page_website_clicks_by_site_logged_in_unique'
| 'page_engaged_users'
| 'page_post_engagements'
| 'page_consumptions'
| 'page_consumptions_unique'
| 'page_consumptions_by_consumption_type'
| 'page_consumptions_by_consumption_type_unique'
| 'page_places_checkin_total'
| 'page_places_checkin_total_unique'
| 'page_places_checkin_mobile'
| 'page_places_checkin_mobile_unique'
| 'page_negative_feedback'
| 'page_negative_feedback_unique'
| 'page_negative_feedback_by_type'
| 'page_negative_feedback_by_type_unique'
| 'page_positive_feedback_by_type'
| 'page_positive_feedback_by_type_unique'
| 'page_impressions'
| 'page_impressions_unique'
| 'page_impressions_paid'
| 'page_impressions_paid_unique'
| 'page_impressions_organic'
| 'page_impressions_organic_unique'
| 'page_impressions_viral'
| 'page_impressions_viral_unique'
| 'page_impressions_nonviral'
| 'page_impressions_nonviral_unique'
| 'page_impressions_by_story_type'
| 'page_impressions_by_story_type_unique'
| 'page_impressions_by_city_unique'
| 'page_impressions_by_country_unique'
| 'page_impressions_by_locale_unique'
| 'page_impressions_by_age_gender_unique'
| 'page_impressions_frequency_distribution'
| 'page_impressions_viral_frequency_distribution'
| 'page_posts_impressions'
| 'page_posts_impressions_unique'
| 'page_posts_impressions_paid'
| 'page_posts_impressions_paid_unique'
| 'page_posts_impressions_organic'
| 'page_posts_impressions_organic_unique'
| 'page_posts_served_impressions_organic_unique'
| 'page_posts_impressions_viral'
| 'page_posts_impressions_viral_unique'
| 'page_posts_impressions_nonviral'
| 'page_posts_impressions_nonviral_unique'
| 'page_posts_impressions_frequency_distribution'
| 'page_actions_post_reactions_like_total'
| 'page_actions_post_reactions_love_total'
| 'page_actions_post_reactions_wow_total'
| 'page_actions_post_reactions_haha_total'
| 'page_actions_post_reactions_sorry_total'
| 'page_actions_post_reactions_anger_total'
| 'page_actions_post_reactions_total'
| 'page_fan_adds_unique'
| 'page_fan_removes_unique'
| 'page_fans_by_unlike_source'
| 'page_fans_by_unlike_source_unique'
| 'page_video_views'
| 'page_video_views_paid'
| 'page_video_views_organic'
| 'page_video_views_by_paid_non_paid'
| 'page_video_views_autoplayed'
| 'page_video_views_click_to_play'
| 'page_video_views_unique'
| 'page_video_repeat_views'
| 'page_video_complete_views_30s'
| 'page_video_complete_views_30s_paid'
| 'page_video_complete_views_30s_organic'
| 'page_video_complete_views_30s_autoplayed'
| 'page_video_complete_views_30s_click_to_play'
| 'page_video_complete_views_30s_unique'
| 'page_video_complete_views_30s_repeat_views'
| 'page_video_views_10s'
| 'page_video_views_10s_paid'
| 'page_video_views_10s_organic'
| 'page_video_views_10s_autoplayed'
| 'page_video_views_10s_click_to_play'
| 'page_video_views_10s_unique'
| 'page_video_views_10s_repeat'
| 'page_views_total'
| 'page_views_logged_in_total'
| 'page_views_logged_in_unique'
| 'page_views_external_referrals'
| 'page_views_by_profile_tab_total'
| 'page_views_by_profile_tab_logged_in_unique'
| 'page_views_by_internal_referer_logged_in_unique'
| 'page_views_by_site_logged_in_unique'
| 'page_views_by_age_gender_logged_in_unique'
| 'page_views_by_referers_logged_in_unique'
| 'page_content_activity_by_action_type_unique'
| 'page_content_activity_by_age_gender_unique'
| 'page_content_activity_by_city_unique'
| 'page_content_activity_by_country_unique'
| 'page_content_activity_by_locale_unique'
| 'page_content_activity'
| 'page_content_activity_by_action_type';
export type PageInsightsMetricDays28 =
| 'page_total_actions'
| 'page_cta_clicks_logged_in_total'
| 'page_cta_clicks_logged_in_unique'
| 'page_cta_clicks_by_site_logged_in_unique'
| 'page_cta_clicks_by_age_gender_logged_in_unique'
| 'page_call_phone_clicks_logged_in_unique'
| 'page_call_phone_clicks_by_age_gender_logged_in_unique'
| 'page_call_phone_clicks_by_site_logged_in_unique'
| 'page_get_directions_clicks_logged_in_unique'
| 'page_get_directions_clicks_by_age_gender_logged_in_unique'
| 'page_get_directions_clicks_by_site_logged_in_unique'
| 'page_website_clicks_logged_in_unique'
| 'page_website_clicks_by_age_gender_logged_in_unique'
| 'page_website_clicks_by_site_logged_in_unique'
| 'page_engaged_users'
| 'page_post_engagements'
| 'page_consumptions'
| 'page_consumptions_unique'
| 'page_consumptions_by_consumption_type'
| 'page_consumptions_by_consumption_type_unique'
| 'page_places_checkin_total'
| 'page_places_checkin_total_unique'
| 'page_places_checkin_mobile'
| 'page_places_checkin_mobile_unique'
| 'page_negative_feedback'
| 'page_negative_feedback_unique'
| 'page_negative_feedback_by_type'
| 'page_negative_feedback_by_type_unique'
| 'page_positive_feedback_by_type'
| 'page_positive_feedback_by_type_unique'
| 'page_impressions'
| 'page_impressions_unique'
| 'page_impressions_paid'
| 'page_impressions_paid_unique'
| 'page_impressions_organic'
| 'page_impressions_organic_unique'
| 'page_impressions_viral'
| 'page_impressions_viral_unique'
| 'page_impressions_nonviral'
| 'page_impressions_nonviral_unique'
| 'page_impressions_by_story_type'
| 'page_impressions_by_story_type_unique'
| 'page_impressions_by_city_unique'
| 'page_impressions_by_country_unique'
| 'page_impressions_by_locale_unique'
| 'page_impressions_by_age_gender_unique'
| 'page_impressions_frequency_distribution'
| 'page_impressions_viral_frequency_distribution'
| 'page_posts_impressions'
| 'page_posts_impressions_unique'
| 'page_posts_impressions_paid'
| 'page_posts_impressions_paid_unique'
| 'page_posts_impressions_organic'
| 'page_posts_impressions_organic_unique'
| 'page_posts_served_impressions_organic_unique'
| 'page_posts_impressions_viral'
| 'page_posts_impressions_viral_unique'
| 'page_posts_impressions_nonviral'
| 'page_posts_impressions_nonviral_unique'
| 'page_posts_impressions_frequency_distribution'
| 'page_actions_post_reactions_like_total'
| 'page_actions_post_reactions_love_total'
| 'page_actions_post_reactions_wow_total'
| 'page_actions_post_reactions_haha_total'
| 'page_actions_post_reactions_sorry_total'
| 'page_actions_post_reactions_anger_total'
| 'page_actions_post_reactions_total'
| 'page_fan_adds_unique'
| 'page_fan_removes_unique'
| 'page_fans_by_unlike_source'
| 'page_fans_by_unlike_source_unique'
| 'page_video_views'
| 'page_video_views_paid'
| 'page_video_views_organic'
| 'page_video_views_by_paid_non_paid'
| 'page_video_views_autoplayed'
| 'page_video_views_click_to_play'
| 'page_video_views_unique'
| 'page_video_repeat_views'
| 'page_video_complete_views_30s'
| 'page_video_complete_views_30s_paid'
| 'page_video_complete_views_30s_organic'
| 'page_video_complete_views_30s_autoplayed'
| 'page_video_complete_views_30s_click_to_play'
| 'page_video_complete_views_30s_unique'
| 'page_video_complete_views_30s_repeat_views'
| 'page_video_views_10s'
| 'page_video_views_10s_paid'
| 'page_video_views_10s_organic'
| 'page_video_views_10s_autoplayed'
| 'page_video_views_10s_click_to_play'
| 'page_video_views_10s_unique'
| 'page_video_views_10s_repeat'
| 'page_views_total'
| 'page_views_logged_in_total'
| 'page_views_logged_in_unique'
| 'page_views_external_referrals'
| 'page_views_by_profile_tab_total'
| 'page_views_by_profile_tab_logged_in_unique'
| 'page_views_by_internal_referer_logged_in_unique'
| 'page_views_by_site_logged_in_unique'
| 'page_views_by_age_gender_logged_in_unique'
| 'page_content_activity_by_action_type_unique'
| 'page_content_activity_by_age_gender_unique'
| 'page_content_activity_by_city_unique'
| 'page_content_activity_by_country_unique'
| 'page_content_activity_by_locale_unique'
| 'page_content_activity'
| 'page_content_activity_by_action_type';
export type PostInsightsMetricDay =
| 'post_video_views_organic'
| 'post_video_views_paid'
| 'post_video_views'
| 'post_video_views_unique'
| 'post_video_views_10s'
| 'post_video_views_10s_paid'
| 'post_video_view_time'
| 'post_video_view_time_organic'
| 'post_video_view_time_by_region_id'
| 'post_video_ad_break_ad_impressions'
| 'post_video_ad_break_earnings'
| 'post_video_ad_break_ad_cpm';
export type PostInsightsMetricLifetime =
| 'post_engaged_users'
| 'post_negative_feedback'
| 'post_negative_feedback_unique'
| 'post_negative_feedback_by_type'
| 'post_negative_feedback_by_type_unique'
| 'post_engaged_fan'
| 'post_clicks'
| 'post_clicks_unique'
| 'post_clicks_by_type'
| 'post_clicks_by_type_unique'
| 'post_impressions'
| 'post_impressions_unique'
| 'post_impressions_paid'
| 'post_impressions_paid_unique'
| 'post_impressions_fan'
| 'post_impressions_fan_unique'
| 'post_impressions_fan_paid'
| 'post_impressions_fan_paid_unique'
| 'post_impressions_organic'
| 'post_impressions_organic_unique'
| 'post_impressions_viral'
| 'post_impressions_viral_unique'
| 'post_impressions_nonviral'
| 'post_impressions_nonviral_unique'
| 'post_impressions_by_story_type'
| 'post_impressions_by_story_type_unique'
| 'post_reactions_like_total'
| 'post_reactions_love_total'
| 'post_reactions_wow_total'
| 'post_reactions_haha_total'
| 'post_reactions_sorry_total'
| 'post_reactions_anger_total'
| 'post_reactions_by_type_total'
| 'post_video_complete_views_30s_autoplayed'
| 'post_video_complete_views_30s_clicked_to_play'
| 'post_video_complete_views_30s_organic'
| 'post_video_complete_views_30s_paid'
| 'post_video_complete_views_30s_unique'
| 'post_video_avg_time_watched'
| 'post_video_complete_views_organic'
| 'post_video_complete_views_organic_unique'
| 'post_video_complete_views_paid'
| 'post_video_complete_views_paid_unique'
| 'post_video_retention_graph'
| 'post_video_retention_graph_clicked_to_play'
| 'post_video_retention_graph_autoplayed'
| 'post_video_views_organic'
| 'post_video_views_organic_unique'
| 'post_video_views_paid'
| 'post_video_views_paid_unique'
| 'post_video_length'
| 'post_video_views'
| 'post_video_views_unique'
| 'post_video_views_autoplayed'
| 'post_video_views_clicked_to_play'
| 'post_video_views_10s'
| 'post_video_views_10s_unique'
| 'post_video_views_10s_autoplayed'
| 'post_video_views_10s_clicked_to_play'
| 'post_video_views_10s_organic'
| 'post_video_views_10s_paid'
| 'post_video_views_10s_sound_on'
| 'post_video_views_sound_on'
| 'post_video_view_time'
| 'post_video_view_time_organic'
| 'post_video_view_time_by_age_bucket_and_gender'
| 'post_video_view_time_by_region_id'
| 'post_video_views_by_distribution_type'
| 'post_video_view_time_by_distribution_type'
| 'post_video_view_time_by_country_id'
| 'post_activity'
| 'post_activity_unique'
| 'post_activity_by_action_type'
| 'post_activity_by_action_type_unique'
| 'post_video_ad_break_ad_impressions'
| 'post_video_ad_break_earnings'
| 'post_video_ad_break_ad_cpm'; | the_stack |
import { Comp, createPlugin, PluginViewCtx, ProdoPlugin } from "@prodo/core";
import * as firebase from "firebase/app";
import "firebase/firestore";
import * as _ from "lodash";
import { createFirestoreQuery, createQueryName } from "./query";
import {
ActionCtx,
Collection,
Config,
DBQuery,
Doc,
DocChange,
FetchAll,
Fetching,
Query,
QueryRefs,
Universe,
ViewCtx,
} from "./types";
export { Collection };
(window as any).counter = 0;
let firestore: firebase.firestore.Firestore;
const cannotUseInAction = "Cannot use this method in an action";
const cannotUseInComponent = "Cannot use this method in a React component";
const addIdToDoc = <T>(
doc: firebase.firestore.DocumentSnapshot,
): T & { id: string } => ({
id: doc.id,
...(doc.data() as T),
});
const getSnapshotDocs = <T>(
docs: firebase.firestore.QueryDocumentSnapshot[],
): Array<T & { id: string }> => docs.map(doc => addIdToDoc(doc));
const firestorePlugin = <DB>(): ProdoPlugin<
Config<DB>,
Universe,
ActionCtx<DB>,
ViewCtx<DB>
> => {
const plugin = createPlugin<Config<DB>, Universe, ActionCtx<DB>, ViewCtx<DB>>(
"firestore",
);
const queryRefs: QueryRefs = {};
const updateDocs = plugin.action(
ctx => (collectionName: string, docChanges: DocChange[]) => {
docChanges.forEach(({ id, changeType, data }) => {
const path = [collectionName, id];
const existingDoc: Doc = _.get(ctx.db_cache.docs, path) || {
// default,
watchers: 0,
};
if (changeType === "added") {
_.set(ctx.db_cache.docs, path, {
...existingDoc,
watchers: existingDoc.watchers + 1,
data,
});
} else if (changeType === "modified") {
_.set(ctx.db_cache.docs, path, {
...existingDoc,
data,
});
} else if (changeType === "removed") {
_.set(ctx.db_cache.docs, path, {
...existingDoc,
watchers: existingDoc.watchers - 1,
});
const doc = _.get(ctx.db_cache.docs, path);
if (doc.watchers <= 0) {
_.unset(ctx.db_cache.docs, path);
}
}
});
},
"updateDocs",
);
const removeQuery = plugin.action(
ctx => (collectionName: string, queryName: string) => {
const dbQuery = ctx.db_cache.queries[collectionName][queryName];
delete ctx.db_cache.queries[collectionName][queryName];
const docChanges: DocChange[] = dbQuery.ids.map(id => ({
id,
changeType: "removed",
}));
updateDocs(ctx)(collectionName, docChanges);
},
"removeQuery",
);
const updateQuery = plugin.action(
ctx => (
collectionName: string,
queryName: string,
dbQuery: Partial<DBQuery>,
) => {
const existingDbQuery: DBQuery = _.get(ctx.db_cache.queries, [
collectionName,
queryName,
]) || {
// deafult db query
ids: [],
query: {},
state: "fetching",
};
_.set(ctx.db_cache.queries, [collectionName, queryName], {
...existingDbQuery,
...dbQuery,
});
},
"updateQuery",
);
const createActionCollection = <T extends { id: string }>(
_ctx: ActionCtx<DB>,
collectionName: string,
): Collection<T> => {
return {
getAll: async (): Promise<T[]> => {
const snapshot = await firestore.collection(collectionName).get();
const data = getSnapshotDocs<T>(snapshot.docs);
return data;
},
get: async (id: string): Promise<T> => {
const doc = await firestore
.collection(collectionName)
.doc(id)
.get();
const data = addIdToDoc<T>(doc);
return data;
},
set: async (id: string, value: Omit<T, "id">): Promise<void> => {
await firestore
.collection(collectionName)
.doc(id)
.set(value);
},
update: async (
id: string,
value: Partial<Omit<T, "id">>,
): Promise<void> => {
await firestore
.collection(collectionName)
.doc(id)
.set(value, { merge: true });
},
delete: async (id: string): Promise<void> => {
await firestore
.collection(collectionName)
.doc(id)
.delete();
},
query: async (query: Query<T>): Promise<T[]> => {
const ref = createFirestoreQuery(
firestore.collection(collectionName),
query,
);
const snapshot = await ref.get();
const data = getSnapshotDocs<T>(snapshot.docs);
return data;
},
insert: async (
value: Pick<T, Exclude<keyof T, "id">>,
): Promise<string> => {
const ref = await firestore.collection(collectionName).add(value);
return ref.id;
},
watch: () => {
throw new Error(cannotUseInAction);
},
watchAll: () => {
throw new Error(cannotUseInAction);
},
ref: (): firebase.firestore.CollectionReference => {
return firestore.collection(name);
},
};
};
// subscribe component to query and every id in the query
// when component is unsubscribed, cleanup queries and docs in universe
const subscribeComponent = ({
queryRefs,
ctx,
collectionName,
queryName,
comp,
dbQuery,
}: {
queryRefs: QueryRefs;
ctx: ViewCtx<DB> & PluginViewCtx<ActionCtx<DB>, Universe>;
collectionName: string;
queryName: string;
comp: Comp;
dbQuery: DBQuery;
}) => {
if (!queryRefs[queryName].watchers.has(comp.name)) {
queryRefs[queryName].watchers.add(comp.name);
}
// subscribe component to query ids and each individual id
ctx.subscribe(
["db_cache", "queries", collectionName, queryName, "ids"],
(comp: Comp) => {
if (queryRefs[queryName]) {
queryRefs[queryName].watchers.delete(comp.name);
if (queryRefs[queryName].watchers.size === 0) {
ctx.dispatch(removeQuery)(collectionName, queryName);
queryRefs[queryName].unsubscribe();
delete queryRefs[queryName];
}
}
},
);
if (dbQuery != null) {
dbQuery.ids.forEach(id =>
ctx.subscribe(["db_cache", "docs", collectionName, id]),
);
}
};
// try to get all docs for a query from the universe
const getDocsFromUniverse = <T>({
dbQuery,
universe,
collectionName,
}: {
dbQuery: DBQuery;
universe: Universe;
collectionName: string;
}): FetchAll<T> => {
if (dbQuery == null || dbQuery.state === "fetching") {
return {
_fetching: true,
};
} else {
// query error
if (dbQuery.state === "error") {
return {
_notFound: true,
};
}
// get all docs from docs cache
const data: T[] = dbQuery.ids
.map(id => _.get(universe.db_cache.docs, [collectionName, id]))
.filter(doc => doc != null)
.map(doc => doc.data);
return {
_fetching: false,
_notFound: false,
data,
};
}
};
const createViewCollection = <T extends { id: string }>(
queryRefs: QueryRefs,
ctx: ViewCtx<DB> & PluginViewCtx<ActionCtx<DB>, Universe>,
collectionName: string,
universe: Universe,
comp: Comp,
): Collection<T> => {
return {
get: () => {
throw new Error(cannotUseInComponent);
},
getAll: async () => {
throw new Error(cannotUseInComponent);
},
insert: () => {
throw new Error(cannotUseInComponent);
},
set: () => {
throw new Error(cannotUseInComponent);
},
update: () => {
throw new Error(cannotUseInComponent);
},
delete: () => {
throw new Error(cannotUseInComponent);
},
query: () => {
throw new Error(cannotUseInComponent);
},
watch: (id: string): Fetching<T> => {
const queryName = `${collectionName}-${id}`;
const dbQuery = _.get(universe.db_cache.queries, [
collectionName,
queryName,
]);
const queryExists = dbQuery != null;
// setup firestore watcher if it does not already exist
if (!queryExists && !queryRefs[queryName]) {
(window as any).counter += 1;
let firstTime = true;
const unsubscribe = firestore
.collection(collectionName)
.doc(id)
.onSnapshot(
snapshot => {
const ids = [id];
if (snapshot.exists) {
const docChanges: DocChange[] = [
{
id,
data: addIdToDoc(snapshot),
changeType: firstTime ? "added" : "modified",
},
];
firstTime = false;
ctx.dispatch(updateDocs)(collectionName, docChanges);
ctx.dispatch(updateQuery)(collectionName, queryName, {
ids,
state: "success",
});
} else {
firstTime = true;
// document does not exist
const docChanges: DocChange[] = [
{
id,
data: addIdToDoc(snapshot),
changeType: "removed",
},
];
ctx.dispatch(updateDocs)(collectionName, docChanges);
ctx.dispatch(updateQuery)(collectionName, queryName, {
ids,
state: "error",
});
}
},
error => {
// tslint:disable-next-line:no-console
console.error("onSnapshot Error", error);
ctx.dispatch(updateQuery)(collectionName, queryName, {
state: "error",
});
},
);
ctx.dispatch(updateQuery)(collectionName, queryName, {
state: "fetching",
});
queryRefs[queryName] = { unsubscribe, watchers: new Set() };
}
subscribeComponent({
queryRefs,
ctx,
collectionName,
queryName,
comp,
dbQuery,
});
// get all data for the query
const data = getDocsFromUniverse<T>({
dbQuery,
universe,
collectionName,
});
// convert array of data to single item, if it exists
if (data._fetching) {
return {
_fetching: true,
};
}
if (data._notFound) {
return {
_notFound: true,
};
}
const element = data.data[0];
return {
_fetching: false,
_notFound: false,
data: element,
};
},
watchAll: (query?: Query<T>): FetchAll<T> => {
const queryName = createQueryName(collectionName, query);
const dbQuery = _.get(universe.db_cache.queries, [
collectionName,
queryName,
]);
const queryExists = dbQuery != null;
// setup firestore watcher if it does not already exist
if (!queryExists && !queryRefs[queryName]) {
const ref = createFirestoreQuery(
firestore.collection(collectionName),
query,
);
(window as any).counter += 1;
const unsubscribe = ref.onSnapshot(
snapshot => {
const ids = snapshot.docs.map(doc => doc.id);
const docChanges: DocChange[] = snapshot
.docChanges()
.map(change => ({
id: change.doc.id,
changeType: change.type,
data: addIdToDoc(change.doc),
}));
ctx.dispatch(updateDocs)(collectionName, docChanges);
ctx.dispatch(updateQuery)(collectionName, queryName, {
ids,
state: "success",
});
},
error => {
// tslint:disable-next-line:no-console
console.error("onSnapshot Error", error);
ctx.dispatch(updateQuery)(collectionName, queryName, {
state: "error",
});
},
);
ctx.dispatch(updateQuery)(collectionName, queryName, {
state: "fetching",
});
queryRefs[queryName] = { unsubscribe, watchers: new Set() };
}
subscribeComponent({
queryRefs,
ctx,
collectionName,
queryName,
comp,
dbQuery,
});
const data = getDocsFromUniverse<T>({
dbQuery,
universe,
collectionName,
});
return data;
},
ref: (): firebase.firestore.CollectionReference => {
return firestore.collection(name);
},
};
};
plugin.init((config, universe) => {
if (!config.firestoreMock) {
firebase.initializeApp(config.firebaseConfig);
firestore = firebase.firestore();
}
universe.db_cache = {
docs: {},
queries: {},
};
});
plugin.prepareActionCtx(({ ctx, universe }) => {
ctx.db_cache = universe.db_cache;
ctx.db = new Proxy(
{},
{
get(_target, key) {
return createActionCollection(ctx, key.toString());
},
},
) as DB;
});
plugin.prepareViewCtx(({ ctx, universe, comp }) => {
ctx.db = new Proxy(
{},
{
get(_target, key) {
return createViewCollection(
queryRefs,
ctx,
key.toString(),
universe,
comp,
);
},
},
) as DB;
});
return plugin;
};
export default firestorePlugin; | the_stack |
declare module BABYLON {
/** @hidden */
export var brickProceduralTexturePixelShader: {
name: string;
shader: string;
};
}
declare module BABYLON {
export class BrickProceduralTexture extends BABYLON.ProceduralTexture {
private _numberOfBricksHeight;
private _numberOfBricksWidth;
private _jointColor;
private _brickColor;
constructor(name: string, size: number, scene: BABYLON.Scene, fallbackTexture?: BABYLON.Texture, generateMipMaps?: boolean);
updateShaderUniforms(): void;
numberOfBricksHeight: number;
numberOfBricksWidth: number;
jointColor: BABYLON.Color3;
brickColor: BABYLON.Color3;
/**
* Serializes this brick procedural texture
* @returns a serialized brick procedural texture object
*/
serialize(): any;
/**
* Creates a Brick Procedural BABYLON.Texture from parsed brick procedural texture data
* @param parsedTexture defines parsed texture data
* @param scene defines the current scene
* @param rootUrl defines the root URL containing brick procedural texture information
* @returns a parsed Brick Procedural BABYLON.Texture
*/
static Parse(parsedTexture: any, scene: BABYLON.Scene, rootUrl: string): BrickProceduralTexture;
}
}
declare module BABYLON {
/** @hidden */
export var cloudProceduralTexturePixelShader: {
name: string;
shader: string;
};
}
declare module BABYLON {
export class CloudProceduralTexture extends BABYLON.ProceduralTexture {
private _skyColor;
private _cloudColor;
constructor(name: string, size: number, scene: BABYLON.Scene, fallbackTexture?: BABYLON.Texture, generateMipMaps?: boolean);
updateShaderUniforms(): void;
skyColor: BABYLON.Color4;
cloudColor: BABYLON.Color4;
/**
* Serializes this cloud procedural texture
* @returns a serialized cloud procedural texture object
*/
serialize(): any;
/**
* Creates a Cloud Procedural BABYLON.Texture from parsed cloud procedural texture data
* @param parsedTexture defines parsed texture data
* @param scene defines the current scene
* @param rootUrl defines the root URL containing cloud procedural texture information
* @returns a parsed Cloud Procedural BABYLON.Texture
*/
static Parse(parsedTexture: any, scene: BABYLON.Scene, rootUrl: string): CloudProceduralTexture;
}
}
declare module BABYLON {
/** @hidden */
export var fireProceduralTexturePixelShader: {
name: string;
shader: string;
};
}
declare module BABYLON {
export class FireProceduralTexture extends BABYLON.ProceduralTexture {
private _time;
private _speed;
private _autoGenerateTime;
private _fireColors;
private _alphaThreshold;
constructor(name: string, size: number, scene: BABYLON.Scene, fallbackTexture?: BABYLON.Texture, generateMipMaps?: boolean);
updateShaderUniforms(): void;
render(useCameraPostProcess?: boolean): void;
static readonly PurpleFireColors: BABYLON.Color3[];
static readonly GreenFireColors: BABYLON.Color3[];
static readonly RedFireColors: BABYLON.Color3[];
static readonly BlueFireColors: BABYLON.Color3[];
autoGenerateTime: boolean;
fireColors: BABYLON.Color3[];
time: number;
speed: BABYLON.Vector2;
alphaThreshold: number;
/**
* Serializes this fire procedural texture
* @returns a serialized fire procedural texture object
*/
serialize(): any;
/**
* Creates a Fire Procedural BABYLON.Texture from parsed fire procedural texture data
* @param parsedTexture defines parsed texture data
* @param scene defines the current scene
* @param rootUrl defines the root URL containing fire procedural texture information
* @returns a parsed Fire Procedural BABYLON.Texture
*/
static Parse(parsedTexture: any, scene: BABYLON.Scene, rootUrl: string): FireProceduralTexture;
}
}
declare module BABYLON {
/** @hidden */
export var grassProceduralTexturePixelShader: {
name: string;
shader: string;
};
}
declare module BABYLON {
export class GrassProceduralTexture extends BABYLON.ProceduralTexture {
private _grassColors;
private _groundColor;
constructor(name: string, size: number, scene: BABYLON.Scene, fallbackTexture?: BABYLON.Texture, generateMipMaps?: boolean);
updateShaderUniforms(): void;
grassColors: BABYLON.Color3[];
groundColor: BABYLON.Color3;
/**
* Serializes this grass procedural texture
* @returns a serialized grass procedural texture object
*/
serialize(): any;
/**
* Creates a Grass Procedural BABYLON.Texture from parsed grass procedural texture data
* @param parsedTexture defines parsed texture data
* @param scene defines the current scene
* @param rootUrl defines the root URL containing grass procedural texture information
* @returns a parsed Grass Procedural BABYLON.Texture
*/
static Parse(parsedTexture: any, scene: BABYLON.Scene, rootUrl: string): GrassProceduralTexture;
}
}
declare module BABYLON {
/** @hidden */
export var marbleProceduralTexturePixelShader: {
name: string;
shader: string;
};
}
declare module BABYLON {
export class MarbleProceduralTexture extends BABYLON.ProceduralTexture {
private _numberOfTilesHeight;
private _numberOfTilesWidth;
private _amplitude;
private _jointColor;
constructor(name: string, size: number, scene: BABYLON.Scene, fallbackTexture?: BABYLON.Texture, generateMipMaps?: boolean);
updateShaderUniforms(): void;
numberOfTilesHeight: number;
amplitude: number;
numberOfTilesWidth: number;
jointColor: BABYLON.Color3;
/**
* Serializes this marble procedural texture
* @returns a serialized marble procedural texture object
*/
serialize(): any;
/**
* Creates a Marble Procedural BABYLON.Texture from parsed marble procedural texture data
* @param parsedTexture defines parsed texture data
* @param scene defines the current scene
* @param rootUrl defines the root URL containing marble procedural texture information
* @returns a parsed Marble Procedural BABYLON.Texture
*/
static Parse(parsedTexture: any, scene: BABYLON.Scene, rootUrl: string): MarbleProceduralTexture;
}
}
declare module BABYLON {
/** @hidden */
export var normalMapProceduralTexturePixelShader: {
name: string;
shader: string;
};
}
declare module BABYLON {
export class NormalMapProceduralTexture extends BABYLON.ProceduralTexture {
private _baseTexture;
constructor(name: string, size: number, scene: BABYLON.Scene, fallbackTexture?: BABYLON.Texture, generateMipMaps?: boolean);
updateShaderUniforms(): void;
render(useCameraPostProcess?: boolean): void;
resize(size: any, generateMipMaps: any): void;
baseTexture: BABYLON.Texture;
/**
* Serializes this normal map procedural texture
* @returns a serialized normal map procedural texture object
*/
serialize(): any;
/**
* Creates a Normal Map Procedural BABYLON.Texture from parsed normal map procedural texture data
* @param parsedTexture defines parsed texture data
* @param scene defines the current scene
* @param rootUrl defines the root URL containing normal map procedural texture information
* @returns a parsed Normal Map Procedural BABYLON.Texture
*/
static Parse(parsedTexture: any, scene: BABYLON.Scene, rootUrl: string): NormalMapProceduralTexture;
}
}
declare module BABYLON {
/** @hidden */
export var perlinNoiseProceduralTexturePixelShader: {
name: string;
shader: string;
};
}
declare module BABYLON {
export class PerlinNoiseProceduralTexture extends BABYLON.ProceduralTexture {
time: number;
timeScale: number;
translationSpeed: number;
private _currentTranslation;
constructor(name: string, size: number, scene: BABYLON.Scene, fallbackTexture?: BABYLON.Texture, generateMipMaps?: boolean);
updateShaderUniforms(): void;
render(useCameraPostProcess?: boolean): void;
resize(size: any, generateMipMaps: any): void;
/**
* Serializes this perlin noise procedural texture
* @returns a serialized perlin noise procedural texture object
*/
serialize(): any;
/**
* Creates a Perlin Noise Procedural BABYLON.Texture from parsed perlin noise procedural texture data
* @param parsedTexture defines parsed texture data
* @param scene defines the current scene
* @param rootUrl defines the root URL containing perlin noise procedural texture information
* @returns a parsed Perlin Noise Procedural BABYLON.Texture
*/
static Parse(parsedTexture: any, scene: BABYLON.Scene, rootUrl: string): PerlinNoiseProceduralTexture;
}
}
declare module BABYLON {
/** @hidden */
export var roadProceduralTexturePixelShader: {
name: string;
shader: string;
};
}
declare module BABYLON {
export class RoadProceduralTexture extends BABYLON.ProceduralTexture {
private _roadColor;
constructor(name: string, size: number, scene: BABYLON.Scene, fallbackTexture?: BABYLON.Texture, generateMipMaps?: boolean);
updateShaderUniforms(): void;
roadColor: BABYLON.Color3;
/**
* Serializes this road procedural texture
* @returns a serialized road procedural texture object
*/
serialize(): any;
/**
* Creates a Road Procedural BABYLON.Texture from parsed road procedural texture data
* @param parsedTexture defines parsed texture data
* @param scene defines the current scene
* @param rootUrl defines the root URL containing road procedural texture information
* @returns a parsed Road Procedural BABYLON.Texture
*/
static Parse(parsedTexture: any, scene: BABYLON.Scene, rootUrl: string): RoadProceduralTexture;
}
}
declare module BABYLON {
/** @hidden */
export var starfieldProceduralTexturePixelShader: {
name: string;
shader: string;
};
}
declare module BABYLON {
export class StarfieldProceduralTexture extends BABYLON.ProceduralTexture {
private _time;
private _alpha;
private _beta;
private _zoom;
private _formuparam;
private _stepsize;
private _tile;
private _brightness;
private _darkmatter;
private _distfading;
private _saturation;
constructor(name: string, size: number, scene: BABYLON.Scene, fallbackTexture?: BABYLON.Texture, generateMipMaps?: boolean);
updateShaderUniforms(): void;
time: number;
alpha: number;
beta: number;
formuparam: number;
stepsize: number;
zoom: number;
tile: number;
brightness: number;
darkmatter: number;
distfading: number;
saturation: number;
/**
* Serializes this starfield procedural texture
* @returns a serialized starfield procedural texture object
*/
serialize(): any;
/**
* Creates a Starfield Procedural BABYLON.Texture from parsed startfield procedural texture data
* @param parsedTexture defines parsed texture data
* @param scene defines the current scene
* @param rootUrl defines the root URL containing startfield procedural texture information
* @returns a parsed Starfield Procedural BABYLON.Texture
*/
static Parse(parsedTexture: any, scene: BABYLON.Scene, rootUrl: string): StarfieldProceduralTexture;
}
}
declare module BABYLON {
/** @hidden */
export var woodProceduralTexturePixelShader: {
name: string;
shader: string;
};
}
declare module BABYLON {
export class WoodProceduralTexture extends BABYLON.ProceduralTexture {
private _ampScale;
private _woodColor;
constructor(name: string, size: number, scene: BABYLON.Scene, fallbackTexture?: BABYLON.Texture, generateMipMaps?: boolean);
updateShaderUniforms(): void;
ampScale: number;
woodColor: BABYLON.Color3;
/**
* Serializes this wood procedural texture
* @returns a serialized wood procedural texture object
*/
serialize(): any;
/**
* Creates a Wood Procedural BABYLON.Texture from parsed wood procedural texture data
* @param parsedTexture defines parsed texture data
* @param scene defines the current scene
* @param rootUrl defines the root URL containing wood procedural texture information
* @returns a parsed Wood Procedural BABYLON.Texture
*/
static Parse(parsedTexture: any, scene: BABYLON.Scene, rootUrl: string): WoodProceduralTexture;
}
} | the_stack |
'use strict'
// **Github:** https://github.com/fidm/quic
//
// **License:** MIT
import { debuglog } from 'util'
import { EventEmitter } from 'events'
import {
PingFrameDelay,
DefaultIdleTimeout,
MaxStreamWaitingTimeout,
DefaultMaxIncomingStreams,
ReceiveConnectionWindow,
DefaultMaxReceiveConnectionWindowClient,
DefaultMaxReceiveConnectionWindowServer,
// DefaultMaxIncomingStreams,
} from './internal/constant'
import {
Offset,
SessionType,
StreamID,
PacketNumber,
ConnectionID,
SocketAddress,
Tag,
QuicTags,
} from './internal/protocol'
import {
kID,
kFC,
kHS,
kRTT,
kStreams,
kSocket,
kState,
kType,
kVersion,
kACKHandler,
kNextStreamID,
kNextPacketNumber,
kIntervalCheck,
kUnackedPackets,
} from './internal/symbol'
import {
Frame,
PingFrame,
StreamFrame,
RstStreamFrame,
AckRange,
AckFrame,
GoAwayFrame,
ConnectionCloseFrame,
WindowUpdateFrame,
StopWaitingFrame,
BlockedFrame,
} from './internal/frame'
import { Packet, ResetPacket, RegularPacket } from './internal/packet'
import { QuicError, StreamError, QUICError } from './internal/error'
import { ConnectionFlowController } from './internal/flowcontrol'
import { RTTStats } from './internal/congestion'
import { BufferVisitor, toBuffer, Queue } from './internal/common'
import { Socket } from './socket'
import { Stream, SessionRef } from './stream'
import { HandShake } from './handshake'
const debug = debuglog('quic:session')
export declare interface Session {
addListener (event: "error", listener: (err: Error) => void): this
addListener (event: "goaway", listener: (err: QUICError) => void): this
addListener (event: "close", listener: (err?: Error) => void): this
addListener (event: "timeout", listener: () => void): this
addListener (event: "stream", listener: (stream: Stream) => void): this
emit (event: "error", err: Error): boolean
emit (event: "goaway", err: QUICError): boolean
emit (event: "close", err?: Error): boolean
emit (event: "timeout"): boolean
emit (event: "stream", stream: Stream): boolean
on (event: "error", listener: (err: Error) => void): this
on (event: "goaway", listener: (err: QUICError) => void): this
on (event: "close", listener: (err?: Error) => void): this
on (event: "timeout", listener: () => void): this
on (event: "stream", listener: (stream: Stream) => void): this
once (event: "error", listener: (err: Error) => void): this
once (event: "goaway", listener: (err: QUICError) => void): this
once (event: "close", listener: (err?: Error) => void): this
once (event: "timeout", listener: () => void): this
once (event: "stream", listener: (stream: Stream) => void): this
}
//
// *************** Session ***************
//
export class Session extends EventEmitter implements SessionRef {
// Event: 'timeout'
// Event: 'close'
// Event: 'error'
// Event: 'stream'
// Event: 'version'
// Event: 'goaway'
[kID]: ConnectionID
[kType]: SessionType
[kIntervalCheck]: NodeJS.Timer | null
[kStreams]: Map<number, Stream>
[kNextStreamID]: StreamID
[kState]: SessionState
[kACKHandler]: ACKHandler
[kSocket]: Socket<Session> | null
[kVersion]: string
[kNextPacketNumber]: PacketNumber
[kUnackedPackets]: Queue<RegularPacket>
[kRTT]: RTTStats
[kFC]: ConnectionFlowController
[kHS]: HandShake
constructor (id: ConnectionID, type: SessionType) {
super()
this[kID] = id
this[kType] = type
this[kStreams] = new Map()
this[kNextStreamID] = new StreamID(type === SessionType.SERVER ? 2 : 1)
this[kState] = new SessionState()
this[kACKHandler] = new ACKHandler()
this[kHS] = new HandShake(this) // will be overwrite
this[kSocket] = null
this[kVersion] = ''
this[kIntervalCheck] = null
this[kNextPacketNumber] = new PacketNumber(1)
this[kUnackedPackets] = new Queue() // up to 1000
this[kRTT] = new RTTStats()
this[kFC] = this.isClient ? // TODO
new ConnectionFlowController(ReceiveConnectionWindow, DefaultMaxReceiveConnectionWindowClient) :
new ConnectionFlowController(ReceiveConnectionWindow, DefaultMaxReceiveConnectionWindowServer)
}
get id (): string {
return this[kID].valueOf()
}
get version (): string {
return this[kVersion]
}
get isClient (): boolean {
return this[kType] === SessionType.CLIENT
}
get destroyed (): boolean {
return this[kState].destroyed
}
get localAddr () {
return {
address: this[kState].localAddress,
family: this[kState].localFamily,
port: this[kState].localPort,
socketAddress: this[kState].localAddr,
}
}
get remoteAddr () {
return {
address: this[kState].remoteAddress,
family: this[kState].remoteFamily,
port: this[kState].remotePort,
socketAddress: this[kState].remoteAddr,
}
}
get _stateMaxPacketSize (): number {
return this[kState].maxPacketSize
}
_stateDecreaseStreamCount () {
this[kState].liveStreamCount -= 1
}
_newRegularPacket (): RegularPacket {
const packetNumber = this[kNextPacketNumber]
this[kNextPacketNumber] = packetNumber.nextNumber()
return new RegularPacket(this[kID], packetNumber)
}
_sendFrame (frame: Frame, callback?: (...args: any[]) => void) {
const regularPacket = this._newRegularPacket()
regularPacket.addFrames(frame)
regularPacket.isRetransmittable = frame.isRetransmittable()
this._sendPacket(regularPacket, callback)
}
_sendStopWaitingFrame (leastUnacked: number) {
const regularPacket = this._newRegularPacket()
const frame = new StopWaitingFrame(regularPacket.packetNumber, leastUnacked)
regularPacket.addFrames(frame)
regularPacket.isRetransmittable = false
debug(`%s session %s - write StopWaitingFrame, packetNumber: %d, leastUnacked: %d`,
SessionType[this[kType]], this.id, frame.packetNumber.valueOf(), leastUnacked)
this._sendPacket(regularPacket)
}
_retransmit (frame: AckFrame, rcvTime: number): number {
const unackedPackets = this[kUnackedPackets]
debug(`%s session %s - start retransmit, count: %d, ackFrame: %j`,
SessionType[this[kType]], this.id, unackedPackets.length, frame.valueOf())
let count = 0
let packet = unackedPackets.first()
while (packet != null) {
const packetNumber = packet.packetNumber.valueOf()
if (packetNumber > frame.largestAcked) {
break // wait for newest ack
} else if (packetNumber === frame.largestAcked) {
this[kRTT].updateRTT(packet.sentTime, rcvTime, frame.delayTime)
}
if (frame.acksPacket(packetNumber)) {
unackedPackets.shift()
packet = unackedPackets.first()
continue
}
unackedPackets.shift()
packet.setPacketNumber(this[kNextPacketNumber])
this[kNextPacketNumber] = packet.packetNumber.nextNumber()
this._sendPacket(packet)
count += 1
packet = unackedPackets.first()
}
debug(`%s session %s - finish retransmit, count: %d`, SessionType[this[kType]], this.id, count)
return count
}
_sendPacket (packet: Packet, callback?: (...args: any[]) => void) {
const socket = this[kSocket]
if (callback == null) {
callback = (err) => {
if (err != null) {
this.destroy(err)
}
}
}
if (socket == null) {
return callback(QuicError.fromError(QuicError.QUIC_PACKET_WRITE_ERROR))
}
if (socket[kState].destroyed) {
return callback(QuicError.fromError(QuicError.QUIC_PACKET_WRITE_ERROR))
}
if (packet.isRegular()) {
const _packet = packet as RegularPacket
if (this.isClient && !this[kState].versionNegotiated) {
_packet.setVersion(this[kVersion])
}
if (_packet.isRetransmittable) {
this[kUnackedPackets].push(packet as RegularPacket)
if (this[kUnackedPackets].length > 4096) {
return callback(QuicError.fromError(QuicError.QUIC_TOO_MANY_OUTSTANDING_SENT_PACKETS))
}
}
debug(`%s session %s - write RegularPacket, packetNumber: %d, frames: %j`,
SessionType[this[kType]], this.id, _packet.packetNumber.valueOf(), _packet.frames.map((frame) => frame.name))
}
socket.sendPacket(packet, this[kState].remotePort, this[kState].remoteAddress, callback)
// debug(`%s session %s - write packet: %j`, this.id, packet.valueOf())
}
_sendWindowUpdate (offset: Offset, streamID?: StreamID) {
if (streamID == null) {
// update for session
streamID = new StreamID(0)
}
debug(`%s session %s - write WindowUpdateFrame, streamID: %d, offset: %d`,
SessionType[this[kType]], this.id, streamID.valueOf(), offset)
this._sendFrame(new WindowUpdateFrame(streamID, offset), (err: any) => {
if (err != null) {
this.emit('error', err)
}
})
}
_trySendAckFrame () {
const frame = this[kACKHandler].toFrame()
if (frame == null) {
return
}
debug(`%s session %s - write AckFrame, lowestAcked: %d, largestAcked: %d, ackRanges: %j`,
SessionType[this[kType]], this.id, frame.lowestAcked, frame.largestAcked, frame.ackRanges)
frame.setDelay()
this._sendFrame(frame, (err) => {
if (err != null) {
this.destroy(err)
}
})
}
_handleRegularPacket (packet: RegularPacket, rcvTime: number, bufv: BufferVisitor) {
const packetNumber = packet.packetNumber.valueOf()
this[kState].lastNetworkActivityTime = rcvTime
// if (!this[kHS].completed) {
// this[kHS].handlePacket(packet, rcvTime, bufv)
// if (this[kACKHandler].ack(packetNumber, rcvTime, packet.needAck())) {
// this._trySendAckFrame()
// }
// return
// }
packet.parseFrames(bufv)
if (this[kACKHandler].ack(packetNumber, rcvTime, packet.needAck())) {
this._trySendAckFrame()
}
debug(`%s session %s - received RegularPacket, packetNumber: %d, frames: %j`,
SessionType[this[kType]], this.id, packetNumber, packet.frames.map((frame) => frame.name))
for (const frame of packet.frames) {
switch (frame.name) {
case 'STREAM':
this._handleStreamFrame(frame as StreamFrame, rcvTime)
break
case 'ACK':
this._handleACKFrame(frame as AckFrame, rcvTime)
break
case 'STOP_WAITING':
// The STOP_WAITING frame is sent to inform the peer that it should not continue to
// wait for packets with packet numbers lower than a specified value.
// The resulting least unacked is the smallest packet number of any packet for which the sender is still awaiting an ack.
// If the receiver is missing any packets smaller than this value,
// the receiver should consider those packets to be irrecoverably lost.
this._handleStopWaitingFrame(frame as StopWaitingFrame)
break
case 'WINDOW_UPDATE':
this._handleWindowUpdateFrame(frame as WindowUpdateFrame)
break
case 'BLOCKED':
// The BLOCKED frame is used to indicate to the remote endpoint that this endpoint is
// ready to send data (and has data to send), but is currently flow control blocked.
// It is a purely informational frame.
this._handleBlockedFrame(frame as RstStreamFrame, rcvTime)
break
case 'CONGESTION_FEEDBACK':
// The CONGESTION_FEEDBACK frame is an experimental frame currently not used.
break
case 'PADDING':
// When this frame is encountered, the rest of the packet is expected to be padding bytes.
return
case 'RST_STREAM':
this._handleRstStreamFrame(frame as RstStreamFrame, rcvTime)
break
case 'PING':
// The PING frame contains no payload.
// The receiver of a PING frame simply needs to ACK the packet containing this frame.
break
case 'CONNECTION_CLOSE':
this.destroy((frame as ConnectionCloseFrame).error)
break
case 'GOAWAY':
this[kState].shuttingDown = true
this.emit('goaway', (frame as GoAwayFrame).error)
break
}
}
}
_handleStreamFrame (frame: StreamFrame, rcvTime: number) {
const streamID = frame.streamID.valueOf()
let stream = this[kStreams].get(streamID)
if (stream == null) {
if (this[kState].shuttingDown) {
return
}
stream = new Stream(frame.streamID, this, {})
if (this[kState].liveStreamCount >= DefaultMaxIncomingStreams) {
stream.close(QuicError.fromError(QuicError.QUIC_TOO_MANY_AVAILABLE_STREAMS))
return
}
this[kStreams].set(streamID, stream)
this[kState].liveStreamCount += 1
this.emit('stream', stream)
} else if (stream.destroyed) {
return
}
stream._handleFrame(frame, rcvTime)
}
_handleRstStreamFrame (frame: RstStreamFrame, rcvTime: number) {
const streamID = frame.streamID.valueOf()
const stream = this[kStreams].get(streamID)
if (stream == null || stream.destroyed) {
return
}
stream._handleRstFrame(frame, rcvTime)
}
_handleACKFrame (frame: AckFrame, rcvTime: number) {
// The sender must always close the connection if an unsent packet number is acked,
// so this mechanism automatically defeats any potential attackers.
if (frame.largestAcked >= this[kNextPacketNumber].valueOf()) {
this.destroy(QuicError.fromError(QuicError.QUIC_INTERNAL_ERROR))
return
}
// It is recommended for the sender to send the most recent largest acked packet
// it has received in an ack as the stop waiting frameโs least unacked value.
if (frame.hasMissingRanges()) {
this._sendStopWaitingFrame(frame.largestAcked)
}
this._retransmit(frame, rcvTime)
}
_handleStopWaitingFrame (frame: StopWaitingFrame) {
this[kACKHandler].lowest(frame.leastUnacked.valueOf())
}
_handleWindowUpdateFrame (frame: WindowUpdateFrame) {
// The stream ID can be 0, indicating this WINDOW_UPDATE applies to the connection level flow control window,
// or > 0 indicating that the specified stream should increase its flow control window.
const streamID = frame.streamID.valueOf()
const offset = frame.offset.valueOf()
debug(`%s session %s - received WindowUpdateFrame, streamID: %d, offset: %d`,
SessionType[this[kType]], this.id, streamID, offset)
if (streamID === 0) {
this[kFC].updateMaxSendOffset(offset)
} else {
const stream = this[kStreams].get(streamID)
if (stream != null && !stream.destroyed) {
if (stream[kFC].updateMaxSendOffset(offset)) {
stream._tryFlushCallbacks()
}
}
}
}
_handleBlockedFrame (frame: BlockedFrame, rcvTime: number) {
this[kFC].updateBlockedFrame(frame.streamID.valueOf(), rcvTime)
}
_intervalCheck (time: number) {
if (this.destroyed) {
return
}
// The PING frame should be used to keep a connection alive when a stream is open.
if (this[kState].keepAlivePingSent && this[kStreams].size > 0 && (time - this[kState].lastNetworkActivityTime >= PingFrameDelay)) {
this.ping().catch((err) => this.emit('error', err))
}
for (const stream of this[kStreams].values()) {
if (stream.destroyed) {
// clearup idle stream
if (time - stream[kState].lastActivityTime > this[kState].idleTimeout) {
this[kStreams].delete(stream.id)
}
} else if (time - stream[kState].lastActivityTime > MaxStreamWaitingTimeout) {
stream.emit('timeout')
}
}
this._trySendAckFrame()
return
}
request (options?: any): Stream {
if (this[kState].shuttingDown) {
throw StreamError.fromError(StreamError.QUIC_STREAM_PEER_GOING_AWAY)
}
if (this[kState].liveStreamCount >= DefaultMaxIncomingStreams) {
throw QuicError.fromError(QuicError.QUIC_TOO_MANY_OPEN_STREAMS)
}
const streamID = this[kNextStreamID]
this[kNextStreamID] = streamID.nextID()
const stream = new Stream(streamID, this, (options == null ? {} : options))
this[kStreams].set(streamID.valueOf(), stream)
this[kState].liveStreamCount += 1
return stream
}
goaway (err: any): Promise<void> {
return new Promise((resolve) => {
if (this[kState].shuttingDown) {
return resolve()
}
this[kState].shuttingDown = true
const frame = new GoAwayFrame(this[kNextStreamID].prevID(), QuicError.fromError(err))
debug(`%s session %s - write GoAwayFrame, streamID: %d, error: %j`,
SessionType[this[kType]], this.id, frame.streamID.valueOf(), frame.error)
this._sendFrame(frame, (_e: any) => {
resolve()
})
})
}
ping (): Promise<void> {
return new Promise((resolve, reject) => {
debug(`%s session %s - write PingFrame`, SessionType[this[kType]], this.id)
this._sendFrame(new PingFrame(), (err: any) => {
if (err != null) {
reject(err)
} else {
resolve()
}
})
})
}
setTimeout (_msecs: number) {
return
}
close (err?: any): Promise<void> {
return new Promise((resolve) => {
if (this[kState].destroyed) {
return resolve()
}
const frame = new ConnectionCloseFrame(QuicError.fromError(err))
debug(`%s session %s - write ConnectionCloseFrame, error: %j`, SessionType[this[kType]], this.id, frame.error)
this._sendFrame(frame, (e: any) => {
this.destroy(e)
resolve()
})
})
}
reset (_err: any): Promise<void> {
return new Promise((resolve) => {
if (this[kState].destroyed) {
return resolve()
}
const tags = new QuicTags(Tag.PRST)
tags.set(Tag.RNON, Buffer.allocUnsafe(8)) // TODO
tags.set(Tag.RSEQ, toBuffer(this[kNextPacketNumber].prevNumber()))
const localAddr = this[kState].localAddr
if (localAddr != null) {
tags.set(Tag.CADR, toBuffer(localAddr))
}
const packet = new ResetPacket(this[kID], tags)
debug(`%s session %s - write ResetPacket, packet: %j`, SessionType[this[kType]], this.id, packet)
this._sendPacket(packet, (e: any) => {
this.destroy(e)
resolve()
})
})
}
destroy (err: any) {
if (this[kState].destroyed) {
return
}
debug(`%s session %s - session destroyed, error: %j`, SessionType[this[kType]], this.id, err)
err = QuicError.checkAny(err)
if (err != null && err.isNoError) {
err = null
}
const socket = this[kSocket]
if (socket != null) {
socket[kState].conns.delete(this.id)
if (this.isClient && !socket[kState].destroyed && (socket[kState].exclusive || socket[kState].conns.size === 0)) {
socket.close()
socket[kState].destroyed = true
}
this[kSocket] = null
}
for (const stream of this[kStreams].values()) {
stream.destroy(err)
}
const timer = this[kIntervalCheck]
if (timer != null) {
clearInterval(timer)
}
this[kStreams].clear()
this[kUnackedPackets].reset()
if (err != null) {
this.emit('error', err)
}
if (!this[kState].destroyed) {
this[kState].destroyed = true
process.nextTick(() => this.emit('close'))
}
return
}
}
export class SessionState {
localFamily: string
localAddress: string
localPort: number
localAddr: SocketAddress | null // SocketAddress
remoteFamily: string
remoteAddress: string
remotePort: number
remoteAddr: SocketAddress | null // SocketAddress
maxPacketSize: number
bytesRead: number
bytesWritten: number
idleTimeout: number
liveStreamCount: number
lastNetworkActivityTime: number
destroyed: boolean
shutdown: boolean
shuttingDown: boolean
versionNegotiated: boolean
keepAlivePingSent: boolean
constructor () {
this.localFamily = ''
this.localAddress = ''
this.localPort = 0
this.localAddr = null // SocketAddress
this.remoteFamily = ''
this.remoteAddress = ''
this.remotePort = 0
this.remoteAddr = null // SocketAddress
this.maxPacketSize = 0
this.bytesRead = 0
this.bytesWritten = 0
this.idleTimeout = DefaultIdleTimeout
this.liveStreamCount = 0
this.lastNetworkActivityTime = Date.now()
this.destroyed = false
this.shutdown = false
this.shuttingDown = false // send or receive GOAWAY
this.versionNegotiated = false
this.keepAlivePingSent = false
}
}
export class ACKHandler {
misshit: number
lowestAcked: number
largestAcked: number
numbersAcked: number[]
largestAckedTime: number // timestamp
lastAckedTime: number // timestamp
constructor () {
this.misshit = 0
this.lowestAcked = 0
this.largestAcked = 0
this.numbersAcked = []
this.largestAckedTime = 0
this.lastAckedTime = Date.now()
}
lowest (packetNumber: number) {
if (packetNumber > this.lowestAcked) {
this.lowestAcked = packetNumber
}
}
ack (packetNumber: number, rcvTime: number, needAck: boolean): boolean {
if (packetNumber < this.lowestAcked) {
return false // ignore
}
if (packetNumber > this.largestAcked) {
if (packetNumber - this.largestAcked > 1) {
this.misshit += 1
}
this.largestAcked = packetNumber
this.largestAckedTime = rcvTime
} else if (Math.abs(packetNumber - this.numbersAcked[0]) > 1) {
this.misshit += 1
}
let shouldAck = this.numbersAcked.unshift(packetNumber) >= 511 // 256 blocks + 255 gaps, too many packets, should ack
if (!needAck && this.largestAcked - this.lowestAcked <= 1) {
// ACK frame
this.lowestAcked = this.largestAcked
this.numbersAcked.length = 1
return false
}
if (this.misshit > 16) {
shouldAck = true
}
const timeSpan = rcvTime - this.lastAckedTime
if (timeSpan >= 512) {
shouldAck = true
}
if (shouldAck) {
debug(`should ACK, largestAcked: %d, lowestAcked: %d, misshit: %d, numbersAcked: %d, timeSpan: %d`,
this.largestAcked, this.lowestAcked, this.misshit, this.numbersAcked.length, timeSpan)
this.lastAckedTime = rcvTime
}
return shouldAck
}
toFrame (): AckFrame | null {
const numbersAcked = this.numbersAcked
if (numbersAcked.length === 0) {
return null
}
numbersAcked.sort((a, b) => b - a)
if (numbersAcked[0] <= this.lowestAcked) {
numbersAcked.length = 0
this.largestAcked = this.lowestAcked
return null
}
const frame = new AckFrame()
frame.largestAcked = this.largestAcked
frame.largestAckedTime = this.largestAckedTime
let range = new AckRange(this.largestAcked, this.largestAcked)
// numbersAcked should include largestAcked and lowestAcked for this AGL
for (let i = 1, l = numbersAcked.length; i < l; i++) {
const num = numbersAcked[i]
if (num < this.lowestAcked) {
numbersAcked.length = i // drop smaller numbers
break
}
const ret = numbersAcked[i - 1] - num
if (ret === 1) {
range.first = num
} else if (ret > 1) {
frame.ackRanges.push(range)
range = new AckRange(num, num)
} // else ingnore
}
frame.lowestAcked = range.first
if (range.last < frame.largestAcked) {
frame.ackRanges.push(range)
}
if (frame.ackRanges.length === 0) {
this.lowestAcked = this.largestAcked
numbersAcked.length = 1
} else if (frame.ackRanges.length > 256) {
// if ackRanges.length > 256, ignore some ranges between
frame.ackRanges[255] = frame.ackRanges[frame.ackRanges.length - 1]
frame.ackRanges.length = 256
}
debug(`after build AckFrame, largestAcked: %d, lowestAcked: %d, numbersAcked: %j`,
this.largestAcked, this.lowestAcked, numbersAcked)
this.misshit = 0
return frame
}
} | the_stack |
import { Dictionary } from "./internal/Dictionary";
import { XMLList } from "./XMLList";
import { IPair } from "tstl/utility/IPair";
import { Pair } from "tstl/utility/Pair";
import { HashMap } from "tstl/container/HashMap";
import { DomainError } from "tstl/exception/DomainError";
import { OutOfRange } from "tstl/exception/OutOfRange";
/**
* The XML parser
*
* @author Jeongho Nam - https://github.com/samchon
*/
export class XML
extends Dictionary<XMLList>
implements Omit<HashMap<string, XMLList>, "toJSON">
{
/**
* @hidden
*/
private tag_!: string;
/**
* @hidden
*/
private value_!: string;
/**
* @hidden
*/
private property_map_!: HashMap<string, string>;
/* =============================================================
CONSTRUCTORS
- BASIC CONSTRUCTORS
- PARSERS
================================================================
BASIC CONSTRUCTORS
------------------------------------------------------------- */
public constructor();
public constructor(str: string);
public constructor(xml: XML);
public constructor(obj?: string | XML)
{
super();
if (obj instanceof XML)
this._Copy_constructor(obj);
else
{
this.property_map_ = new HashMap<string, string>();
this.value_ = "";
if (obj !== undefined && typeof obj === "string")
this._Parser_constructor(obj);
}
}
/**
* @hidden
*/
private _Copy_constructor(obj: XML): void
{
// COPY MEMBERS
this.tag_ = obj.tag_;
this.value_ = obj.value_;
this.property_map_ = new HashMap(obj.property_map_);
// COPY CHILDREN
for (const entry of obj)
{
const xml_list: XMLList = new XMLList();
for (const child of entry.second)
xml_list.push_back(new XML(child));
this.emplace(entry.first, xml_list);
}
}
/**
* @hidden
*/
private _Parser_constructor(str: string): void
{
if (str.indexOf("<") === -1)
return;
let start: number;
let end!: number;
//ERASE HEADER OF XML
if ((start = str.indexOf("<?xml")) !== -1)
{
end = str.indexOf("?>", start);
if (end !== -1)
str = str.substr(end + 2);
}
//ERASE COMMENTS
while ((start = str.indexOf("<!--")) !== -1)
{
end = str.indexOf("-->", start);
if (end === -1)
break;
str = str.substr(0, start) + str.substr(end + 3);
}
// ERASE !DOCTYPE
start = str.indexOf("<!DOCTYPE");
if (start !== -1)
{
let open_cnt: number = 1;
let close_cnt: number = 0;
for (let i: number = start + 1; i < str.length; ++i)
{
let ch: string = str.charAt(i);
if (ch === "<")
++open_cnt;
else if (ch === ">")
{
++close_cnt;
end = i;
if (open_cnt === close_cnt)
break;
}
}
if (open_cnt !== close_cnt)
throw new DomainError("Error on XML.constructor(): invalid XML format was found on the <!DOCTYPE />");
str = str.substr(0, start) + str.substr(end + 1);
}
//BEGIN PARSING
this._Parse(str);
}
/* -------------------------------------------------------------
PARSERS
------------------------------------------------------------- */
/**
* @hidden
*/
private _Parse(str: string): void
{
this._Parse_tag(str);
this._Parse_properties(str);
const res = this._Parse_value(str);
if (res.second === true)
this._Parse_children(res.first);
}
/**
* @hidden
*/
private _Parse_tag(str: string): void
{
const start: number = str.indexOf("<") + 1;
const end: number =
XML._Compute_min_index
(
str.indexOf(" ", start),
str.indexOf("\r\n", start),
str.indexOf("\n", start),
str.indexOf("\t", start),
str.indexOf(">", start),
str.indexOf("/", start)
);
if (start === 0 || end === -1)
throw new DomainError("Error on XML.constructor(): invalid XML format, unable to parse tag.");
this.tag_ = str.substring(start, end);
}
/**
* @hidden
*/
private _Parse_properties(str: string): void
{
let start: number = str.indexOf("<" + this.tag_) + this.tag_.length + 1;
const end: number = XML._Compute_min_index(str.lastIndexOf("/"), str.indexOf(">", start));
if (start === -1 || end === -1 || start >= end)
return;
//<comp label='ABCD' /> : " label='ABCD' "
const line: string = str.substring(start, end);
if (line.indexOf("=") === -1)
return;
let label: string;
let value: string;
let helpers: IQuote[] = [];
let inQuote: boolean = false;
let quoteType!: number;
let equal: number;
//INDEXING
for (let i: number = 0; i < line.length; ++i)
{
//Start of quote
if (inQuote === false && (line.charAt(i) === "'" || line.charAt(i) === "\""))
{
inQuote = true;
start = i;
if (line.charAt(i) === "'")
quoteType = 1;
else if (line.charAt(i) === "\"")
quoteType = 2;
}
else if
(
inQuote === true &&
(
(quoteType === 1 && line.charAt(i) === "'") ||
(quoteType === 2 && line.charAt(i) === "\"")
)
)
{
helpers.push({ type: quoteType, start: start, end: i });
inQuote = false;
}
}
//CONSTRUCTING
for (let i: number = 0; i < helpers.length; ++i)
{
if (i === 0)
{
equal = line.indexOf("=");
label = line.substring(0, equal).trim();
}
else
{
equal = line.indexOf("=", helpers[i - 1].end + 1);
label = line.substring(helpers[i - 1].end + 1, equal).trim();
}
value = line.substring(helpers[i].start + 1, helpers[i].end);
this.setProperty(label, XML.decode_property(value));
}
}
/**
* @hidden
*/
private _Parse_value(str: string): Pair<string, boolean>
{
const end_slash: number = str.lastIndexOf("/");
const end_block: number = str.indexOf(">");
if (end_slash < end_block || end_slash + 1 === str.lastIndexOf("<"))
{
//STATEMENT1: <TAG />
//STATEMENT2: <TAG></TAG> -> SAME WITH STATEMENT1: <TAG />
this.value_ = "";
return new Pair<string, boolean>(str, false);
}
const start: number = end_block + 1;
const end: number = str.lastIndexOf("<");
str = str.substring(start, end); //REDEFINE WEAK_STRING -> IN TO THE TAG
if (str.indexOf("<") === -1)
this.value_ = XML.decode_value(str.trim());
else
this.value_ = "";
return new Pair<string, boolean>(str, true);
}
/**
* @hidden
*/
private _Parse_children(str: string): void
{
if (str.indexOf("<") === -1)
return;
let start: number = str.indexOf("<");
let end: number = str.lastIndexOf(">") + 1;
str = str.substring(start, end);
let blockStart: number = 0;
let blockEnd: number = 0;
start = 0;
for (let i: number = 0; i < str.length; ++i)
{
if (str.charAt(i) === "<" && str.substr(i, 2) !== "</")
++blockStart;
else if (str.substr(i, 2) === "/>" || str.substr(i, 2) === "</")
++blockEnd;
if (blockStart >= 1 && blockStart === blockEnd)
{
end = str.indexOf(">", i);
const xml: XML = new XML();
xml._Parse(str.substring(start, end + 1));
let xmlList: XMLList;
if (this.has(xml.tag_) === true)
xmlList = this.get(xml.tag_);
else
{
xmlList = new XMLList();
this.set(xml.tag_, xmlList);
}
xmlList.push(xml);
i = end;
start = end + 1;
blockStart = 0;
blockEnd = 0;
}
}
}
/* =============================================================
ACCESSORS
- GETTERS
- SETTERS
- ELEMENTS I/O
================================================================
GETTERS
------------------------------------------------------------- */
public getTag(): string
{
return this.tag_;
}
public getValue(): string
{
return this.value_;
}
public findProperty(key: string): HashMap.Iterator<string, string>
{
return this.property_map_.find(key);
}
public hasProperty(key: string): boolean
{
return this.property_map_.has(key);
}
public getProperty(key: string): string
{
return this.property_map_.get(key);
}
public getPropertyMap(): HashMap<string, string>
{
return this.property_map_;
}
/* -------------------------------------------------------------
SETTERS
------------------------------------------------------------- */
public setTag(val: string): void
{
this.tag_ = val;
}
public setValue(val: string): void
{
this.value_ = val;
}
public insertValue(tag: string, value: string): XML
{
const xml = new XML();
xml.setTag(tag);
xml.setValue(value);
this.push(xml);
return xml;
}
public setProperty(key: string, value: string): void
{
this.property_map_.set(key, value);
}
public eraseProperty(key: string): void
{
const it = this.property_map_.find(key);
if (it.equals(this.property_map_.end()) === true)
throw new OutOfRange("Error on XML.eraseProperty(): unable to find the matched key.");
this.property_map_.erase(it);
}
/* -------------------------------------------------------------
ELEMENTS I/O
------------------------------------------------------------- */
public push(...args: IPair<string, XMLList>[]): number;
public push(...xmls: XML[]): number;
public push(...xmlLists: XMLList[]): number;
public push(...items: any[]): number
{
for (const elem of items)
if (elem instanceof XML)
if (this.has(elem.tag_) === true)
this.get(elem.tag_).push(elem);
else
{
const xmlList: XMLList = new XMLList();
xmlList.push(elem);
this.set(elem.tag_, xmlList);
}
else if (elem instanceof XMLList)
if (elem.empty() === true)
continue;
else if (this.has(elem.getTag()) === true)
{
const xmlList: XMLList = this.get(elem.getTag());
xmlList.insert(xmlList.end(), elem.begin(), elem.end());
}
else
this.set(elem.getTag(), elem);
else
super.push(elem);
return this.size();
}
/**
* @hidden
*/
protected _Handle_insert(first: HashMap.Iterator<string, XMLList>, last: HashMap.Iterator<string, XMLList>): void
{
for (let it = first; !it.equals(last); it = it.next())
{
const tag: string = it.first;
const xmlList: XMLList = it.second;
for (const xml of xmlList)
if (xml.getTag() !== tag)
xml.setTag(tag);
}
super._Handle_insert(first, last);
}
/* -------------------------------------------------------------
STRING UTILS
------------------------------------------------------------- */
public toJSON(): string
{
return this.toString();
}
public toString(): string;
/**
* @internal
*/
public toString(level: number): string;
public toString(tab: number = 0): string
{
let str: string = XML._Repeat("\t", tab) + "<" + this.tag_;
//PROPERTIES
for (const entry of this.property_map_)
str += " " + entry.first + "=\"" + XML.encode_property(entry.second) + "\"";
if (this.size() === 0)
{
// VALUE
if (this.value_ !== "")
str += ">" + XML.encode_value(this.value_) + "</" + this.tag_ + ">";
else
str += " />";
}
else
{
// CHILDREN
str += ">\n";
for (const entry of this)
str += entry.second.toString(tab + 1);
str += XML._Repeat("\t", tab) + "</" + this.tag_ + ">";
}
return str;
}
/**
* @hidden
*/
private static _Compute_min_index(...args: number[]): number
{
let min: number = -1;
for (const elem of args)
if (elem === -1)
continue;
else if (min === -1 || elem < min)
min = elem;
return min;
}
/**
* @hidden
*/
private static _Repeat(str: string, n: number): string
{
let ret: string = "";
for (let i: number = 0; i < n; ++i)
ret += str;
return ret;
}
}
export namespace XML
{
export type Iterator = HashMap.Iterator<string, XMLList>;
export type ReverseIterator = HashMap.ReverseIterator<string, XMLList>;
export function head(encoding: string = "utf-8"): string
{
return `<?xml version="1.0" encoding="${encoding}" ?>`;
}
export function encode_value(str: string): string
{
for (const p of VALUE_CODES)
str = str.split(p.first).join(p.second);
return str;
}
export function encode_property(str: string): string
{
for (const p of PROPERTY_CODES)
str = str.split(p.first).join(p.second);
return str;
}
export function decode_value(str: string): string
{
for (const p of VALUE_CODES)
str = str.split(p.second).join(p.first);
return str;
}
export function decode_property(str: string): string
{
for (const p of PROPERTY_CODES)
str = str.split(p.second).join(p.first);
return str;
}
/**
* @hidden
*/
const VALUE_CODES: Pair<string, string>[] =
[
new Pair("&", "&"),
new Pair("<", "<"),
new Pair(">", ">")
];
/**
* @hidden
*/
const PROPERTY_CODES: Pair<string, string>[] =
[
...VALUE_CODES,
new Pair("\"", """),
new Pair("'", "'"),
new Pair("\t", "	"),
new Pair("\n", "
"),
new Pair("\r", "
")
];
}
/**
* @hidden
*/
interface IQuote
{
type: number;
start: number;
end: number;
} | the_stack |
import { PagedAsyncIterableIterator } from "@azure/core-paging";
import { PollerLike, PollOperationState } from "@azure/core-lro";
import {
CassandraKeyspaceGetResults,
CassandraResourcesListCassandraKeyspacesOptionalParams,
CassandraTableGetResults,
CassandraResourcesListCassandraTablesOptionalParams,
CassandraResourcesGetCassandraKeyspaceOptionalParams,
CassandraResourcesGetCassandraKeyspaceResponse,
CassandraKeyspaceCreateUpdateParameters,
CassandraResourcesCreateUpdateCassandraKeyspaceOptionalParams,
CassandraResourcesCreateUpdateCassandraKeyspaceResponse,
CassandraResourcesDeleteCassandraKeyspaceOptionalParams,
CassandraResourcesGetCassandraKeyspaceThroughputOptionalParams,
CassandraResourcesGetCassandraKeyspaceThroughputResponse,
ThroughputSettingsUpdateParameters,
CassandraResourcesUpdateCassandraKeyspaceThroughputOptionalParams,
CassandraResourcesUpdateCassandraKeyspaceThroughputResponse,
CassandraResourcesGetCassandraTableOptionalParams,
CassandraResourcesGetCassandraTableResponse,
CassandraTableCreateUpdateParameters,
CassandraResourcesCreateUpdateCassandraTableOptionalParams,
CassandraResourcesCreateUpdateCassandraTableResponse,
CassandraResourcesDeleteCassandraTableOptionalParams,
CassandraResourcesGetCassandraTableThroughputOptionalParams,
CassandraResourcesGetCassandraTableThroughputResponse,
CassandraResourcesUpdateCassandraTableThroughputOptionalParams,
CassandraResourcesUpdateCassandraTableThroughputResponse
} from "../models";
/// <reference lib="esnext.asynciterable" />
/** Interface representing a CassandraResources. */
export interface CassandraResources {
/**
* Lists the Cassandra keyspaces under an existing Azure Cosmos DB database account.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param options The options parameters.
*/
listCassandraKeyspaces(
resourceGroupName: string,
accountName: string,
options?: CassandraResourcesListCassandraKeyspacesOptionalParams
): PagedAsyncIterableIterator<CassandraKeyspaceGetResults>;
/**
* Lists the Cassandra table under an existing Azure Cosmos DB database account.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param keyspaceName Cosmos DB keyspace name.
* @param options The options parameters.
*/
listCassandraTables(
resourceGroupName: string,
accountName: string,
keyspaceName: string,
options?: CassandraResourcesListCassandraTablesOptionalParams
): PagedAsyncIterableIterator<CassandraTableGetResults>;
/**
* Gets the Cassandra keyspaces under an existing Azure Cosmos DB database account with the provided
* name.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param keyspaceName Cosmos DB keyspace name.
* @param options The options parameters.
*/
getCassandraKeyspace(
resourceGroupName: string,
accountName: string,
keyspaceName: string,
options?: CassandraResourcesGetCassandraKeyspaceOptionalParams
): Promise<CassandraResourcesGetCassandraKeyspaceResponse>;
/**
* Create or update an Azure Cosmos DB Cassandra keyspace
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param keyspaceName Cosmos DB keyspace name.
* @param createUpdateCassandraKeyspaceParameters The parameters to provide for the current Cassandra
* keyspace.
* @param options The options parameters.
*/
beginCreateUpdateCassandraKeyspace(
resourceGroupName: string,
accountName: string,
keyspaceName: string,
createUpdateCassandraKeyspaceParameters: CassandraKeyspaceCreateUpdateParameters,
options?: CassandraResourcesCreateUpdateCassandraKeyspaceOptionalParams
): Promise<
PollerLike<
PollOperationState<
CassandraResourcesCreateUpdateCassandraKeyspaceResponse
>,
CassandraResourcesCreateUpdateCassandraKeyspaceResponse
>
>;
/**
* Create or update an Azure Cosmos DB Cassandra keyspace
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param keyspaceName Cosmos DB keyspace name.
* @param createUpdateCassandraKeyspaceParameters The parameters to provide for the current Cassandra
* keyspace.
* @param options The options parameters.
*/
beginCreateUpdateCassandraKeyspaceAndWait(
resourceGroupName: string,
accountName: string,
keyspaceName: string,
createUpdateCassandraKeyspaceParameters: CassandraKeyspaceCreateUpdateParameters,
options?: CassandraResourcesCreateUpdateCassandraKeyspaceOptionalParams
): Promise<CassandraResourcesCreateUpdateCassandraKeyspaceResponse>;
/**
* Deletes an existing Azure Cosmos DB Cassandra keyspace.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param keyspaceName Cosmos DB keyspace name.
* @param options The options parameters.
*/
beginDeleteCassandraKeyspace(
resourceGroupName: string,
accountName: string,
keyspaceName: string,
options?: CassandraResourcesDeleteCassandraKeyspaceOptionalParams
): Promise<PollerLike<PollOperationState<void>, void>>;
/**
* Deletes an existing Azure Cosmos DB Cassandra keyspace.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param keyspaceName Cosmos DB keyspace name.
* @param options The options parameters.
*/
beginDeleteCassandraKeyspaceAndWait(
resourceGroupName: string,
accountName: string,
keyspaceName: string,
options?: CassandraResourcesDeleteCassandraKeyspaceOptionalParams
): Promise<void>;
/**
* Gets the RUs per second of the Cassandra Keyspace under an existing Azure Cosmos DB database account
* with the provided name.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param keyspaceName Cosmos DB keyspace name.
* @param options The options parameters.
*/
getCassandraKeyspaceThroughput(
resourceGroupName: string,
accountName: string,
keyspaceName: string,
options?: CassandraResourcesGetCassandraKeyspaceThroughputOptionalParams
): Promise<CassandraResourcesGetCassandraKeyspaceThroughputResponse>;
/**
* Update RUs per second of an Azure Cosmos DB Cassandra Keyspace
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param keyspaceName Cosmos DB keyspace name.
* @param updateThroughputParameters The RUs per second of the parameters to provide for the current
* Cassandra Keyspace.
* @param options The options parameters.
*/
beginUpdateCassandraKeyspaceThroughput(
resourceGroupName: string,
accountName: string,
keyspaceName: string,
updateThroughputParameters: ThroughputSettingsUpdateParameters,
options?: CassandraResourcesUpdateCassandraKeyspaceThroughputOptionalParams
): Promise<
PollerLike<
PollOperationState<
CassandraResourcesUpdateCassandraKeyspaceThroughputResponse
>,
CassandraResourcesUpdateCassandraKeyspaceThroughputResponse
>
>;
/**
* Update RUs per second of an Azure Cosmos DB Cassandra Keyspace
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param keyspaceName Cosmos DB keyspace name.
* @param updateThroughputParameters The RUs per second of the parameters to provide for the current
* Cassandra Keyspace.
* @param options The options parameters.
*/
beginUpdateCassandraKeyspaceThroughputAndWait(
resourceGroupName: string,
accountName: string,
keyspaceName: string,
updateThroughputParameters: ThroughputSettingsUpdateParameters,
options?: CassandraResourcesUpdateCassandraKeyspaceThroughputOptionalParams
): Promise<CassandraResourcesUpdateCassandraKeyspaceThroughputResponse>;
/**
* Gets the Cassandra table under an existing Azure Cosmos DB database account.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param keyspaceName Cosmos DB keyspace name.
* @param tableName Cosmos DB table name.
* @param options The options parameters.
*/
getCassandraTable(
resourceGroupName: string,
accountName: string,
keyspaceName: string,
tableName: string,
options?: CassandraResourcesGetCassandraTableOptionalParams
): Promise<CassandraResourcesGetCassandraTableResponse>;
/**
* Create or update an Azure Cosmos DB Cassandra Table
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param keyspaceName Cosmos DB keyspace name.
* @param tableName Cosmos DB table name.
* @param createUpdateCassandraTableParameters The parameters to provide for the current Cassandra
* Table.
* @param options The options parameters.
*/
beginCreateUpdateCassandraTable(
resourceGroupName: string,
accountName: string,
keyspaceName: string,
tableName: string,
createUpdateCassandraTableParameters: CassandraTableCreateUpdateParameters,
options?: CassandraResourcesCreateUpdateCassandraTableOptionalParams
): Promise<
PollerLike<
PollOperationState<CassandraResourcesCreateUpdateCassandraTableResponse>,
CassandraResourcesCreateUpdateCassandraTableResponse
>
>;
/**
* Create or update an Azure Cosmos DB Cassandra Table
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param keyspaceName Cosmos DB keyspace name.
* @param tableName Cosmos DB table name.
* @param createUpdateCassandraTableParameters The parameters to provide for the current Cassandra
* Table.
* @param options The options parameters.
*/
beginCreateUpdateCassandraTableAndWait(
resourceGroupName: string,
accountName: string,
keyspaceName: string,
tableName: string,
createUpdateCassandraTableParameters: CassandraTableCreateUpdateParameters,
options?: CassandraResourcesCreateUpdateCassandraTableOptionalParams
): Promise<CassandraResourcesCreateUpdateCassandraTableResponse>;
/**
* Deletes an existing Azure Cosmos DB Cassandra table.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param keyspaceName Cosmos DB keyspace name.
* @param tableName Cosmos DB table name.
* @param options The options parameters.
*/
beginDeleteCassandraTable(
resourceGroupName: string,
accountName: string,
keyspaceName: string,
tableName: string,
options?: CassandraResourcesDeleteCassandraTableOptionalParams
): Promise<PollerLike<PollOperationState<void>, void>>;
/**
* Deletes an existing Azure Cosmos DB Cassandra table.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param keyspaceName Cosmos DB keyspace name.
* @param tableName Cosmos DB table name.
* @param options The options parameters.
*/
beginDeleteCassandraTableAndWait(
resourceGroupName: string,
accountName: string,
keyspaceName: string,
tableName: string,
options?: CassandraResourcesDeleteCassandraTableOptionalParams
): Promise<void>;
/**
* Gets the RUs per second of the Cassandra table under an existing Azure Cosmos DB database account
* with the provided name.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param keyspaceName Cosmos DB keyspace name.
* @param tableName Cosmos DB table name.
* @param options The options parameters.
*/
getCassandraTableThroughput(
resourceGroupName: string,
accountName: string,
keyspaceName: string,
tableName: string,
options?: CassandraResourcesGetCassandraTableThroughputOptionalParams
): Promise<CassandraResourcesGetCassandraTableThroughputResponse>;
/**
* Update RUs per second of an Azure Cosmos DB Cassandra table
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param keyspaceName Cosmos DB keyspace name.
* @param tableName Cosmos DB table name.
* @param updateThroughputParameters The RUs per second of the parameters to provide for the current
* Cassandra table.
* @param options The options parameters.
*/
beginUpdateCassandraTableThroughput(
resourceGroupName: string,
accountName: string,
keyspaceName: string,
tableName: string,
updateThroughputParameters: ThroughputSettingsUpdateParameters,
options?: CassandraResourcesUpdateCassandraTableThroughputOptionalParams
): Promise<
PollerLike<
PollOperationState<
CassandraResourcesUpdateCassandraTableThroughputResponse
>,
CassandraResourcesUpdateCassandraTableThroughputResponse
>
>;
/**
* Update RUs per second of an Azure Cosmos DB Cassandra table
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param keyspaceName Cosmos DB keyspace name.
* @param tableName Cosmos DB table name.
* @param updateThroughputParameters The RUs per second of the parameters to provide for the current
* Cassandra table.
* @param options The options parameters.
*/
beginUpdateCassandraTableThroughputAndWait(
resourceGroupName: string,
accountName: string,
keyspaceName: string,
tableName: string,
updateThroughputParameters: ThroughputSettingsUpdateParameters,
options?: CassandraResourcesUpdateCassandraTableThroughputOptionalParams
): Promise<CassandraResourcesUpdateCassandraTableThroughputResponse>;
} | the_stack |
export enum ServiceError {
/**
* NoError. Indicates that an error has not occurred.
*/
NoError = 0,
/**
* Access is denied. Check credentials and try again.
*/
ErrorAccessDenied,
/**
* The impersonation authentication header should not be included.
*/
ErrorAccessModeSpecified,
/**
* Account is disabled. Contact the account administrator.
*/
ErrorAccountDisabled,
/**
* Failed to add one or more delegates.
*/
ErrorAddDelegatesFailed,
/**
* ErrorAddressSpaceNotFound
*/
ErrorAddressSpaceNotFound,
/**
* Active Directory operation did not succeed. Try again later.
*/
ErrorADOperation,
/**
* Invalid search criteria.
*/
ErrorADSessionFilter,
/**
* Active Directory is unavailable. Try again later.
*/
ErrorADUnavailable,
/**
* AffectedTaskOccurrences attribute is required for Task items.
*/
ErrorAffectedTaskOccurrencesRequired,
/**
* The conversation action alwayscategorize or alwaysmove or alwaysdelete has failed.
*/
ErrorApplyConversationActionFailed,
/**
* Archive mailbox not enabled
*/
ErrorArchiveMailboxNotEnabled,
/**
* Unable to create the folder in archive mailbox to which the items will be archived
*/
ErrorArchiveFolderPathCreation,
/**
* Unable to discover archive mailbox
*/
ErrorArchiveMailboxServiceDiscoveryFailed,
/**
* The item has attachment at more than the maximum supported nest level.
*/
ErrorAttachmentNestLevelLimitExceeded,
/**
* The file attachment exceeds the maximum supported size.
*/
ErrorAttachmentSizeLimitExceeded,
/**
* ErrorAutoDiscoverFailed
*/
ErrorAutoDiscoverFailed,
/**
* ErrorAvailabilityConfigNotFound
*/
ErrorAvailabilityConfigNotFound,
/**
* Item was not processed as a result of a previous error.
*/
ErrorBatchProcessingStopped,
/**
* Can not move or copy a calendar occurrence.
*/
ErrorCalendarCannotMoveOrCopyOccurrence,
/**
* Cannot update calendar item that has already been deleted.
*/
ErrorCalendarCannotUpdateDeletedItem,
/**
* The Id specified does not represent an occurrence.
*/
ErrorCalendarCannotUseIdForOccurrenceId,
/**
* The specified Id does not represent a recurring master item.
*/
ErrorCalendarCannotUseIdForRecurringMasterId,
/**
* Calendar item duration is too long.
*/
ErrorCalendarDurationIsTooLong,
/**
* EndDate is earlier than StartDate
*/
ErrorCalendarEndDateIsEarlierThanStartDate,
/**
* Cannot request CalendarView for the folder.
*/
ErrorCalendarFolderIsInvalidForCalendarView,
/**
* Attribute has an invalid value.
*/
ErrorCalendarInvalidAttributeValue,
/**
* The value of the DaysOfWeek property is not valid for time change pattern of time zone.
*/
ErrorCalendarInvalidDayForTimeChangePattern,
/**
* The value of the DaysOfWeek property is invalid for a weekly recurrence.
*/
ErrorCalendarInvalidDayForWeeklyRecurrence,
/**
* The property has invalid state.
*/
ErrorCalendarInvalidPropertyState,
/**
* The property has an invalid value.
*/
ErrorCalendarInvalidPropertyValue,
/**
* The recurrence is invalid.
*/
ErrorCalendarInvalidRecurrence,
/**
* TimeZone is invalid.
*/
ErrorCalendarInvalidTimeZone,
/**
* A meeting that's been canceled can't be accepted.
*/
ErrorCalendarIsCancelledForAccept,
/**
* A canceled meeting can't be declined.
*/
ErrorCalendarIsCancelledForDecline,
/**
* A canceled meeting can't be removed.
*/
ErrorCalendarIsCancelledForRemove,
/**
* A canceled meeting can't be accepted tentatively.
*/
ErrorCalendarIsCancelledForTentative,
/**
* AcceptItem action is invalid for a delegated meeting message.
*/
ErrorCalendarIsDelegatedForAccept,
/**
* DeclineItem operation is invalid for a delegated meeting message.
*/
ErrorCalendarIsDelegatedForDecline,
/**
* RemoveItem action is invalid for a delegated meeting message.
*/
ErrorCalendarIsDelegatedForRemove,
/**
* The TentativelyAcceptItem action isn't valid for a delegated meeting message.
*/
ErrorCalendarIsDelegatedForTentative,
/**
* User must be an organizer for CancelCalendarItem action.
*/
ErrorCalendarIsNotOrganizer,
/**
* The user is the organizer of this meeting, and cannot, therefore, accept it.
*/
ErrorCalendarIsOrganizerForAccept,
/**
* The user is the organizer of this meeting, and cannot, therefore, decline it.
*/
ErrorCalendarIsOrganizerForDecline,
/**
* The user is the organizer of this meeting, and cannot, therefore, remove it.
*/
ErrorCalendarIsOrganizerForRemove,
/**
* The user is the organizer of this meeting, and therefore can't tentatively accept it.
*/
ErrorCalendarIsOrganizerForTentative,
/**
* The meeting request is out of date. The calendar couldn't be updated.
*/
ErrorCalendarMeetingRequestIsOutOfDate,
/**
* Occurrence index is out of recurrence range.
*/
ErrorCalendarOccurrenceIndexIsOutOfRecurrenceRange,
/**
* Occurrence with this index was previously deleted from the recurrence.
*/
ErrorCalendarOccurrenceIsDeletedFromRecurrence,
/**
* The calendar property falls out of valid range.
*/
ErrorCalendarOutOfRange,
/**
* The specified view range exceeds the maximum range of two years.
*/
ErrorCalendarViewRangeTooBig,
/**
* Failed to get valid Active Directory information for the calling account. Confirm that it
* is a valid Active Directory account.
*/
ErrorCallerIsInvalidADAccount,
/**
* Cannot archive items in Calendar, contact to task folders
*/
ErrorCannotArchiveCalendarContactTaskFolderException,
/**
* Cannot archive items in archive mailboxes
*/
ErrorCannotArchiveItemsInArchiveMailbox,
/**
* Cannot archive items in public folders
*/
ErrorCannotArchiveItemsInPublicFolders,
/**
* Cannot create a calendar item in a non-calendar folder.
*/
ErrorCannotCreateCalendarItemInNonCalendarFolder,
/**
* Cannot create a contact in a non-contact folder.
*/
ErrorCannotCreateContactInNonContactFolder,
/**
* Cannot create a post item in a folder that is not a mail folder.
*/
ErrorCannotCreatePostItemInNonMailFolder,
/**
* Cannot create a task in a non-task Folder.
*/
ErrorCannotCreateTaskInNonTaskFolder,
/**
* Object cannot be deleted.
*/
ErrorCannotDeleteObject,
/**
* Deleting a task occurrence is not permitted on non-recurring tasks, on the last
* occurrence of a recurring task or on a regenerating task.
*/
ErrorCannotDeleteTaskOccurrence,
/**
* Mandatory extensions cannot be disabled by end users
*/
ErrorCannotDisableMandatoryExtension,
/**
* Folder cannot be emptied.
*/
ErrorCannotEmptyFolder,
/**
* Cannot get external ECP URL. This might happen if external ECP URL isn't configured
*/
ErrorCannotGetExternalEcpUrl,
/**
* Unable to read the folder path for the source folder while archiving items
*/
ErrorCannotGetSourceFolderPath,
/**
* The attachment could not be opened.
*/
ErrorCannotOpenFileAttachment,
/**
* Expected a PermissionSet but received a CalendarPermissionSet.
*/
ErrorCannotSetCalendarPermissionOnNonCalendarFolder,
/**
* Expected a CalendarPermissionSet but received a PermissionSet.
*/
ErrorCannotSetNonCalendarPermissionOnCalendarFolder,
/**
* Cannot set UnknownEntries on a PermissionSet or CalendarPermissionSet.
*/
ErrorCannotSetPermissionUnknownEntries,
/**
* Cannot specify search folders as source folders while archiving items
*/
ErrorCannotSpecifySearchFolderAsSourceFolder,
/**
* Expected an item Id but received a folder Id.
*/
ErrorCannotUseFolderIdForItemId,
/**
* Expected a folder Id but received an item Id.
*/
ErrorCannotUseItemIdForFolderId,
/**
* ChangeKey is required if overriding automatic conflict resolution.
*/
ErrorChangeKeyRequired,
/**
* ChangeKey is required for this operation.
*/
ErrorChangeKeyRequiredForWriteOperations,
/**
* ErrorClientDisconnected
*/
ErrorClientDisconnected,
/**
* Connection did not succeed. Try again later.
*/
ErrorConnectionFailed,
/**
* The Contains filter can only be used for string properties.
*/
ErrorContainsFilterWrongType,
/**
* Content conversion failed.
*/
ErrorContentConversionFailed,
/**
* Data is corrupt.
*/
ErrorCorruptData,
/**
* Unable to create item. The user account does not have the right to create items.
*/
ErrorCreateItemAccessDenied,
/**
* Failed to create one or more of the specified managed folders.
*/
ErrorCreateManagedFolderPartialCompletion,
/**
* Unable to create subfolder. The user account does not have the right to create
* subfolders.
*/
ErrorCreateSubfolderAccessDenied,
/**
* Move and Copy operations across mailbox boundaries are not permitted.
*/
ErrorCrossMailboxMoveCopy,
/**
* This request isn't allowed because the Client Access server that's servicing the request
* is in a different site than the requested resource. Use Autodiscover to find the correct
* URL for accessing the specified resource.
*/
ErrorCrossSiteRequest,
/**
* Property exceeds the maximum supported size.
*/
ErrorDataSizeLimitExceeded,
/**
* Invalid data source operation.
*/
ErrorDataSourceOperation,
/**
* The user is already a delegate for the mailbox.
*/
ErrorDelegateAlreadyExists,
/**
* This is an invalid operation. Cannot add owner as delegate.
*/
ErrorDelegateCannotAddOwner,
/**
* Delegate is not configured properly.
*/
ErrorDelegateMissingConfiguration,
/**
* The delegate does not map to a user in the Active Directory.
*/
ErrorDelegateNoUser,
/**
* Cannot add the delegate user. Failed to validate the changes.
*/
ErrorDelegateValidationFailed,
/**
* Distinguished folders cannot be deleted.
*/
ErrorDeleteDistinguishedFolder,
/**
* The deletion failed.
*/
ErrorDeleteItemsFailed,
/**
* DistinguishedUser should not be specified for a Delegate User.
*/
ErrorDistinguishedUserNotSupported,
/**
* The group member doesn't exist.
*/
ErrorDistributionListMemberNotExist,
/**
* The specified list of managed folder names contains duplicate entries.
*/
ErrorDuplicateInputFolderNames,
/**
* A duplicate exchange legacy DN.
*/
ErrorDuplicateLegacyDistinguishedName,
/**
* A duplicate SOAP header was received.
*/
ErrorDuplicateSOAPHeader,
/**
* The specified permission set contains duplicate UserIds.
*/
ErrorDuplicateUserIdsSpecified,
/**
* The email address associated with a folder Id does not match the mailbox you are
* operating on.
*/
ErrorEmailAddressMismatch,
/**
* The watermark used for creating this subscription was not found.
*/
ErrorEventNotFound,
/**
* You have exceeded the available concurrent connections for your account. Try again once
* your other requests have completed.
*/
ErrorExceededConnectionCount,
/**
* You have exceeded the maximum number of objects that can be returned for the find
* operation. Use paging to reduce the result size and try your request again.
*/
ErrorExceededFindCountLimit,
/**
* You have exceeded the available subscriptions for your account. Remove unnecessary
* subscriptions and try your request again.
*/
ErrorExceededSubscriptionCount,
/**
* Subscription information is not available. Subscription is expired.
*/
ErrorExpiredSubscription,
/**
* Extension with id specified was not found
*/
ErrorExtensionNotFound,
/**
* The folder is corrupt.
*/
ErrorFolderCorrupt,
/**
* A folder with the specified name already exists.
*/
ErrorFolderExists,
/**
* The specified folder could not be found in the store.
*/
ErrorFolderNotFound,
/**
* ErrorFolderPropertRequestFailed
*/
ErrorFolderPropertRequestFailed,
/**
* The folder save operation did not succeed.
*/
ErrorFolderSave,
/**
* The save operation failed or partially succeeded.
*/
ErrorFolderSaveFailed,
/**
* The folder save operation failed due to invalid property values.
*/
ErrorFolderSavePropertyError,
/**
* ErrorFreeBusyDLLimitReached
*/
ErrorFreeBusyDLLimitReached,
/**
* ErrorFreeBusyGenerationFailed
*/
ErrorFreeBusyGenerationFailed,
/**
* ErrorGetServerSecurityDescriptorFailed
*/
ErrorGetServerSecurityDescriptorFailed,
/**
* ErrorImContactLimitReached
*/
ErrorImContactLimitReached,
/**
* ErrorImGroupDisplayNameAlreadyExists
*/
ErrorImGroupDisplayNameAlreadyExists,
/**
* ErrorImGroupLimitReached
*/
ErrorImGroupLimitReached,
/**
* The account does not have permission to impersonate the requested user.
*/
ErrorImpersonateUserDenied,
/**
* ErrorImpersonationDenied
*/
ErrorImpersonationDenied,
/**
* Impersonation failed.
*/
ErrorImpersonationFailed,
/**
* ErrorInboxRulesValidationError
*/
ErrorInboxRulesValidationError,
/**
* The request is valid but does not specify the correct server version in the
* RequestServerVersion SOAP header. Ensure that the RequestServerVersion SOAP header is
* set with the correct RequestServerVersionValue.
*/
ErrorIncorrectSchemaVersion,
/**
* An object within a change description must contain one and only one property to modify.
*/
ErrorIncorrectUpdatePropertyCount,
/**
* ErrorIndividualMailboxLimitReached
*/
ErrorIndividualMailboxLimitReached,
/**
* Resources are unavailable. Try again later.
*/
ErrorInsufficientResources,
/**
* An internal server error occurred. The operation failed.
*/
ErrorInternalServerError,
/**
* An internal server error occurred. Try again later.
*/
ErrorInternalServerTransientError,
/**
* ErrorInvalidAccessLevel
*/
ErrorInvalidAccessLevel,
/**
* ErrorInvalidArgument
*/
ErrorInvalidArgument,
/**
* The specified attachment Id is invalid.
*/
ErrorInvalidAttachmentId,
/**
* Attachment subfilters must have a single TextFilter therein.
*/
ErrorInvalidAttachmentSubfilter,
/**
* Attachment subfilters must have a single TextFilter on the display name only.
*/
ErrorInvalidAttachmentSubfilterTextFilter,
/**
* ErrorInvalidAuthorizationContext
*/
ErrorInvalidAuthorizationContext,
/**
* The change key is invalid.
*/
ErrorInvalidChangeKey,
/**
* ErrorInvalidClientSecurityContext
*/
ErrorInvalidClientSecurityContext,
/**
* CompleteDate cannot be set to a date in the future.
*/
ErrorInvalidCompleteDate,
/**
* The e-mail address that was supplied isn't valid.
*/
ErrorInvalidContactEmailAddress,
/**
* The e-mail index supplied isn't valid.
*/
ErrorInvalidContactEmailIndex,
/**
* ErrorInvalidCrossForestCredentials
*/
ErrorInvalidCrossForestCredentials,
/**
* Invalid Delegate Folder Permission.
*/
ErrorInvalidDelegatePermission,
/**
* One or more UserId parameters are invalid. Make sure that the PrimarySmtpAddress, Sid and
* DisplayName properties refer to the same user when specified.
*/
ErrorInvalidDelegateUserId,
/**
* An ExchangeImpersonation SOAP header must contain a user principal name, user SID, or
* primary SMTP address.
*/
ErrorInvalidExchangeImpersonationHeaderData,
/**
* Second operand in Excludes expression must be uint compatible.
*/
ErrorInvalidExcludesRestriction,
/**
* FieldURI can only be used in Contains expressions.
*/
ErrorInvalidExpressionTypeForSubFilter,
/**
* The extended property attribute combination is invalid.
*/
ErrorInvalidExtendedProperty,
/**
* The extended property value is inconsistent with its type.
*/
ErrorInvalidExtendedPropertyValue,
/**
* The original sender of the message (initiator field in the sharing metadata) is not
* valid.
*/
ErrorInvalidExternalSharingInitiator,
/**
* The sharing message is not intended for this caller.
*/
ErrorInvalidExternalSharingSubscriber,
/**
* The organization is either not federated, or it's configured incorrectly.
*/
ErrorInvalidFederatedOrganizationId,
/**
* Folder Id is invalid.
*/
ErrorInvalidFolderId,
/**
* ErrorInvalidFolderTypeForOperation
*/
ErrorInvalidFolderTypeForOperation,
/**
* Invalid fractional paging offset values.
*/
ErrorInvalidFractionalPagingParameters,
/**
* ErrorInvalidFreeBusyViewType
*/
ErrorInvalidFreeBusyViewType,
/**
* Either DataType or SharedFolderId must be specified, but not both.
*/
ErrorInvalidGetSharingFolderRequest,
/**
* The Id is invalid.
*/
ErrorInvalidId,
/**
* The Im Contact id was invalid.
*/
ErrorInvalidImContactId,
/**
* The Im Distribution Group Smtp Address was invalid.
*/
ErrorInvalidImDistributionGroupSmtpAddress,
/**
* The Im Contact id was invalid.
*/
ErrorInvalidImGroupId,
/**
* Id must be non-empty.
*/
ErrorInvalidIdEmpty,
/**
* Id is malformed.
*/
ErrorInvalidIdMalformed,
/**
* The EWS Id is in EwsLegacyId format which is not supported by the Exchange version
* specified by your request. Please use the ConvertId method to convert from EwsLegacyId
* to EwsId format.
*/
ErrorInvalidIdMalformedEwsLegacyIdFormat,
/**
* Moniker exceeded allowable length.
*/
ErrorInvalidIdMonikerTooLong,
/**
* The Id does not represent an item attachment.
*/
ErrorInvalidIdNotAnItemAttachmentId,
/**
* ResolveNames returned an invalid Id.
*/
ErrorInvalidIdReturnedByResolveNames,
/**
* Id exceeded allowable length.
*/
ErrorInvalidIdStoreObjectIdTooLong,
/**
* Too many attachment levels.
*/
ErrorInvalidIdTooManyAttachmentLevels,
/**
* The Id Xml is invalid.
*/
ErrorInvalidIdXml,
/**
* The specified indexed paging values are invalid.
*/
ErrorInvalidIndexedPagingParameters,
/**
* Only one child node is allowed when setting an Internet Message Header.
*/
ErrorInvalidInternetHeaderChildNodes,
/**
* Item type is invalid for AcceptItem action.
*/
ErrorInvalidItemForOperationAcceptItem,
/**
* Item type is invalid for ArchiveItem action.
*/
ErrorInvalidItemForOperationArchiveItem,
/**
* Item type is invalid for CancelCalendarItem action.
*/
ErrorInvalidItemForOperationCancelItem,
/**
* Item type is invalid for CreateItem operation.
*/
ErrorInvalidItemForOperationCreateItem,
/**
* Item type is invalid for CreateItemAttachment operation.
*/
ErrorInvalidItemForOperationCreateItemAttachment,
/**
* Item type is invalid for DeclineItem operation.
*/
ErrorInvalidItemForOperationDeclineItem,
/**
* ExpandDL operation does not support this item type.
*/
ErrorInvalidItemForOperationExpandDL,
/**
* Item type is invalid for RemoveItem operation.
*/
ErrorInvalidItemForOperationRemoveItem,
/**
* Item type is invalid for SendItem operation.
*/
ErrorInvalidItemForOperationSendItem,
/**
* The item of this type is invalid for TentativelyAcceptItem action.
*/
ErrorInvalidItemForOperationTentative,
/**
* The logon type isn't valid.
*/
ErrorInvalidLogonType,
/**
* Mailbox is invalid. Verify the specified Mailbox property.
*/
ErrorInvalidMailbox,
/**
* The Managed Folder property is corrupt or otherwise invalid.
*/
ErrorInvalidManagedFolderProperty,
/**
* The managed folder has an invalid quota.
*/
ErrorInvalidManagedFolderQuota,
/**
* The managed folder has an invalid storage limit value.
*/
ErrorInvalidManagedFolderSize,
/**
* ErrorInvalidMergedFreeBusyInterval
*/
ErrorInvalidMergedFreeBusyInterval,
/**
* The specified value is not a valid name for name resolution.
*/
ErrorInvalidNameForNameResolution,
/**
* ErrorInvalidNetworkServiceContext
*/
ErrorInvalidNetworkServiceContext,
/**
* ErrorInvalidOofParameter
*/
ErrorInvalidOofParameter,
/**
* ErrorInvalidOperation
*/
ErrorInvalidOperation,
/**
* ErrorInvalidOrganizationRelationshipForFreeBusy
*/
ErrorInvalidOrganizationRelationshipForFreeBusy,
/**
* MaxEntriesReturned must be greater than zero.
*/
ErrorInvalidPagingMaxRows,
/**
* Cannot create a subfolder within a SearchFolder.
*/
ErrorInvalidParentFolder,
/**
* PercentComplete must be an integer between 0 and 100.
*/
ErrorInvalidPercentCompleteValue,
/**
* The permission settings were not valid.
*/
ErrorInvalidPermissionSettings,
/**
* The phone call ID isn't valid.
*/
ErrorInvalidPhoneCallId,
/**
* The phone number isn't valid.
*/
ErrorInvalidPhoneNumber,
/**
* The append action is not supported for this property.
*/
ErrorInvalidPropertyAppend,
/**
* The delete action is not supported for this property.
*/
ErrorInvalidPropertyDelete,
/**
* Property cannot be used in Exists expression. Use IsEqualTo instead.
*/
ErrorInvalidPropertyForExists,
/**
* Property is not valid for this operation.
*/
ErrorInvalidPropertyForOperation,
/**
* Property is not valid for this object type.
*/
ErrorInvalidPropertyRequest,
/**
* Set action is invalid for property.
*/
ErrorInvalidPropertySet,
/**
* Update operation is invalid for property of a sent message.
*/
ErrorInvalidPropertyUpdateSentMessage,
/**
* The proxy security context is invalid.
*/
ErrorInvalidProxySecurityContext,
/**
* SubscriptionId is invalid. Subscription is not a pull subscription.
*/
ErrorInvalidPullSubscriptionId,
/**
* URL specified for push subscription is invalid.
*/
ErrorInvalidPushSubscriptionUrl,
/**
* One or more recipients are invalid.
*/
ErrorInvalidRecipients,
/**
* Recipient subfilters are only supported when there are two expressions within a single
* AND filter.
*/
ErrorInvalidRecipientSubfilter,
/**
* Recipient subfilter must have a comparison filter that tests equality to recipient type
* or attendee type.
*/
ErrorInvalidRecipientSubfilterComparison,
/**
* Recipient subfilters must have a text filter and a comparison filter in that order.
*/
ErrorInvalidRecipientSubfilterOrder,
/**
* Recipient subfilter must have a TextFilter on the SMTP address only.
*/
ErrorInvalidRecipientSubfilterTextFilter,
/**
* The reference item does not support the requested operation.
*/
ErrorInvalidReferenceItem,
/**
* The request is invalid.
*/
ErrorInvalidRequest,
/**
* The restriction is invalid.
*/
ErrorInvalidRestriction,
/**
* ErrorInvalidRetentionIdTagTypeMismatch.
*/
ErrorInvalidRetentionTagTypeMismatch,
/**
* ErrorInvalidRetentionTagInvisible.
*/
ErrorInvalidRetentionTagInvisible,
/**
* ErrorInvalidRetentionTagInheritance.
*/
ErrorInvalidRetentionTagInheritance,
/**
* ErrorInvalidRetentionTagIdGuid.
*/
ErrorInvalidRetentionTagIdGuid,
/**
* The routing type format is invalid.
*/
ErrorInvalidRoutingType,
/**
* ErrorInvalidScheduledOofDuration
*/
ErrorInvalidScheduledOofDuration,
/**
* The mailbox that was requested doesn't support the specified RequestServerVersion.
*/
ErrorInvalidSchemaVersionForMailboxVersion,
/**
* ErrorInvalidSecurityDescriptor
*/
ErrorInvalidSecurityDescriptor,
/**
* Invalid combination of SaveItemToFolder attribute and SavedItemFolderId element.
*/
ErrorInvalidSendItemSaveSettings,
/**
* Invalid serialized access token.
*/
ErrorInvalidSerializedAccessToken,
/**
* The specified server version is invalid.
*/
ErrorInvalidServerVersion,
/**
* The sharing message metadata is not valid.
*/
ErrorInvalidSharingData,
/**
* The sharing message is not valid.
*/
ErrorInvalidSharingMessage,
/**
* A SID with an invalid format was encountered.
*/
ErrorInvalidSid,
/**
* The SIP address isn't valid.
*/
ErrorInvalidSIPUri,
/**
* The SMTP address format is invalid.
*/
ErrorInvalidSmtpAddress,
/**
* Invalid subFilterType.
*/
ErrorInvalidSubfilterType,
/**
* SubFilterType is not attendee type.
*/
ErrorInvalidSubfilterTypeNotAttendeeType,
/**
* SubFilterType is not recipient type.
*/
ErrorInvalidSubfilterTypeNotRecipientType,
/**
* Subscription is invalid.
*/
ErrorInvalidSubscription,
/**
* A subscription can only be established on a single public folder or on folders from a
* single mailbox.
*/
ErrorInvalidSubscriptionRequest,
/**
* Synchronization state data is corrupt or otherwise invalid.
*/
ErrorInvalidSyncStateData,
/**
* ErrorInvalidTimeInterval
*/
ErrorInvalidTimeInterval,
/**
* A UserId was not valid.
*/
ErrorInvalidUserInfo,
/**
* ErrorInvalidUserOofSettings
*/
ErrorInvalidUserOofSettings,
/**
* The impersonation principal name is invalid.
*/
ErrorInvalidUserPrincipalName,
/**
* The user SID is invalid or does not map to a user in the Active Directory.
*/
ErrorInvalidUserSid,
/**
* ErrorInvalidUserSidMissingUPN
*/
ErrorInvalidUserSidMissingUPN,
/**
* The specified value is invalid for property.
*/
ErrorInvalidValueForProperty,
/**
* The watermark is invalid.
*/
ErrorInvalidWatermark,
/**
* A valid IP gateway couldn't be found.
*/
ErrorIPGatewayNotFound,
/**
* The send or update operation could not be performed because the change key passed in the
* request does not match the current change key for the item.
*/
ErrorIrresolvableConflict,
/**
* The item is corrupt.
*/
ErrorItemCorrupt,
/**
* The specified object was not found in the store.
*/
ErrorItemNotFound,
/**
* One or more of the properties requested for this item could not be retrieved.
*/
ErrorItemPropertyRequestFailed,
/**
* The item save operation did not succeed.
*/
ErrorItemSave,
/**
* Item save operation did not succeed.
*/
ErrorItemSavePropertyError,
/**
* ErrorLegacyMailboxFreeBusyViewTypeNotMerged
*/
ErrorLegacyMailboxFreeBusyViewTypeNotMerged,
/**
* ErrorLocalServerObjectNotFound
*/
ErrorLocalServerObjectNotFound,
/**
* ErrorLogonAsNetworkServiceFailed
*/
ErrorLogonAsNetworkServiceFailed,
/**
* Unable to access an account or mailbox.
*/
ErrorMailboxConfiguration,
/**
* ErrorMailboxDataArrayEmpty
*/
ErrorMailboxDataArrayEmpty,
/**
* ErrorMailboxDataArrayTooBig
*/
ErrorMailboxDataArrayTooBig,
/**
* ErrorMailboxFailover
*/
ErrorMailboxFailover,
/**
* The specific mailbox hold is not found.
*/
ErrorMailboxHoldNotFound,
/**
* ErrorMailboxLogonFailed
*/
ErrorMailboxLogonFailed,
/**
* Mailbox move in progress. Try again later.
*/
ErrorMailboxMoveInProgress,
/**
* The mailbox database is temporarily unavailable.
*/
ErrorMailboxStoreUnavailable,
/**
* ErrorMailRecipientNotFound
*/
ErrorMailRecipientNotFound,
/**
* MailTips aren't available for your organization.
*/
ErrorMailTipsDisabled,
/**
* The specified Managed Folder already exists in the mailbox.
*/
ErrorManagedFolderAlreadyExists,
/**
* Unable to find the specified managed folder in the Active Directory.
*/
ErrorManagedFolderNotFound,
/**
* Failed to create or bind to the folder: Managed Folders
*/
ErrorManagedFoldersRootFailure,
/**
* ErrorMeetingSuggestionGenerationFailed
*/
ErrorMeetingSuggestionGenerationFailed,
/**
* MessageDisposition attribute is required.
*/
ErrorMessageDispositionRequired,
/**
* The message exceeds the maximum supported size.
*/
ErrorMessageSizeExceeded,
/**
* The domain specified in the tracking request doesn't exist.
*/
ErrorMessageTrackingNoSuchDomain,
/**
* The log search service can't track this message.
*/
ErrorMessageTrackingPermanentError,
/**
* The log search service isn't currently available. Please try again later.
*/
ErrorMessageTrackingTransientError,
/**
* MIME content conversion failed.
*/
ErrorMimeContentConversionFailed,
/**
* Invalid MIME content.
*/
ErrorMimeContentInvalid,
/**
* Invalid base64 string for MIME content.
*/
ErrorMimeContentInvalidBase64String,
/**
* The subscription has missed events, but will continue service on this connection.
*/
ErrorMissedNotificationEvents,
/**
* ErrorMissingArgument
*/
ErrorMissingArgument,
/**
* When making a request as an account that does not have a mailbox, you must specify the
* mailbox primary SMTP address for any distinguished folder Ids.
*/
ErrorMissingEmailAddress,
/**
* When making a request with an account that does not have a mailbox, you must specify the
* primary SMTP address for an existing mailbox.
*/
ErrorMissingEmailAddressForManagedFolder,
/**
* EmailAddress or ItemId must be included in the request.
*/
ErrorMissingInformationEmailAddress,
/**
* ReferenceItemId must be included in the request.
*/
ErrorMissingInformationReferenceItemId,
/**
* SharingFolderId must be included in the request.
*/
ErrorMissingInformationSharingFolderId,
/**
* An item must be specified when creating an item attachment.
*/
ErrorMissingItemForCreateItemAttachment,
/**
* The managed folder Id is missing.
*/
ErrorMissingManagedFolderId,
/**
* A message needs to have at least one recipient.
*/
ErrorMissingRecipients,
/**
* Missing information for delegate user. You must either specify a valid SMTP address or
* SID.
*/
ErrorMissingUserIdInformation,
/**
* Only one access mode header may be specified.
*/
ErrorMoreThanOneAccessModeSpecified,
/**
* The move or copy operation failed.
*/
ErrorMoveCopyFailed,
/**
* Cannot move distinguished folder.
*/
ErrorMoveDistinguishedFolder,
/**
* ErrorMultiLegacyMailboxAccess
*/
ErrorMultiLegacyMailboxAccess,
/**
* Multiple results were found.
*/
ErrorNameResolutionMultipleResults,
/**
* User must have a mailbox for name resolution operations.
*/
ErrorNameResolutionNoMailbox,
/**
* No results were found.
*/
ErrorNameResolutionNoResults,
/**
* Another connection was opened against this subscription.
*/
ErrorNewEventStreamConnectionOpened,
/**
* Exchange Web Services are not currently available for this request because there are no
* available Client Access Services Servers in the target AD Site.
*/
ErrorNoApplicableProxyCASServersAvailable,
/**
* ErrorNoCalendar
*/
ErrorNoCalendar,
/**
* Exchange Web Services aren't available for this request because there is no Client Access
* server with the necessary configuration in the Active Directory site where the mailbox is
* stored. If the problem continues, click Help.
*/
ErrorNoDestinationCASDueToKerberosRequirements,
/**
* Exchange Web Services aren't currently available for this request because an SSL
* connection couldn't be established to the Client Access server that should be used for
* mailbox access. If the problem continues, click Help.
*/
ErrorNoDestinationCASDueToSSLRequirements,
/**
* Exchange Web Services aren't currently available for this request because the Client
* Access server used for proxying has an older version of Exchange installed than the
* Client Access server in the mailbox Active Directory site.
*/
ErrorNoDestinationCASDueToVersionMismatch,
/**
* You cannot specify the FolderClass when creating a non-generic folder.
*/
ErrorNoFolderClassOverride,
/**
* ErrorNoFreeBusyAccess
*/
ErrorNoFreeBusyAccess,
/**
* Mailbox does not exist.
*/
ErrorNonExistentMailbox,
/**
* The primary SMTP address must be specified when referencing a mailbox.
*/
ErrorNonPrimarySmtpAddress,
/**
* Custom properties cannot be specified using property tags. The GUID and Id/Name
* combination must be used instead.
*/
ErrorNoPropertyTagForCustomProperties,
/**
* ErrorNoPublicFolderReplicaAvailable
*/
ErrorNoPublicFolderReplicaAvailable,
/**
* There are no public folder servers available.
*/
ErrorNoPublicFolderServerAvailable,
/**
* Exchange Web Services are not currently available for this request because none of the
* Client Access Servers in the destination site could process the request.
*/
ErrorNoRespondingCASInDestinationSite,
/**
* Policy does not allow granting of permissions to external users.
*/
ErrorNotAllowedExternalSharingByPolicy,
/**
* The user is not a delegate for the mailbox.
*/
ErrorNotDelegate,
/**
* There was not enough memory to complete the request.
*/
ErrorNotEnoughMemory,
/**
* The sharing message is not supported.
*/
ErrorNotSupportedSharingMessage,
/**
* Operation would change object type, which is not permitted.
*/
ErrorObjectTypeChanged,
/**
* Modified occurrence is crossing or overlapping adjacent occurrence.
*/
ErrorOccurrenceCrossingBoundary,
/**
* One occurrence of the recurring calendar item overlaps with another occurrence of the
* same calendar item.
*/
ErrorOccurrenceTimeSpanTooBig,
/**
* Operation not allowed with public folder root.
*/
ErrorOperationNotAllowedWithPublicFolderRoot,
/**
* Organization is not federated.
*/
ErrorOrganizationNotFederated,
/**
* ErrorOutlookRuleBlobExists
*/
ErrorOutlookRuleBlobExists,
/**
* You must specify the parent folder Id for this operation.
*/
ErrorParentFolderIdRequired,
/**
* The specified parent folder could not be found.
*/
ErrorParentFolderNotFound,
/**
* Password change is required.
*/
ErrorPasswordChangeRequired,
/**
* Password has expired. Change password.
*/
ErrorPasswordExpired,
/**
* Policy does not allow granting permission level to user.
*/
ErrorPermissionNotAllowedByPolicy,
/**
* Dialing restrictions are preventing the phone number that was entered from being dialed.
*/
ErrorPhoneNumberNotDialable,
/**
* Property update did not succeed.
*/
ErrorPropertyUpdate,
/**
* At least one property failed validation.
*/
ErrorPropertyValidationFailure,
/**
* Subscription related request failed because EWS could not contact the appropriate CAS
* server for this request. If this problem persists, recreate the subscription.
*/
ErrorProxiedSubscriptionCallFailure,
/**
* Request failed because EWS could not contact the appropriate CAS server for this request.
*/
ErrorProxyCallFailed,
/**
* Exchange Web Services (EWS) is not available for this mailbox because the user account
* associated with the mailbox is a member of too many groups. EWS limits the group
* membership it can proxy between Client Access Service Servers to 3000.
*/
ErrorProxyGroupSidLimitExceeded,
/**
* ErrorProxyRequestNotAllowed
*/
ErrorProxyRequestNotAllowed,
/**
* ErrorProxyRequestProcessingFailed
*/
ErrorProxyRequestProcessingFailed,
/**
* Exchange Web Services are not currently available for this mailbox because it could not
* determine the Client Access Services Server to use for the mailbox.
*/
ErrorProxyServiceDiscoveryFailed,
/**
* Proxy token has expired.
*/
ErrorProxyTokenExpired,
/**
* ErrorPublicFolderRequestProcessingFailed
*/
ErrorPublicFolderRequestProcessingFailed,
/**
* ErrorPublicFolderServerNotFound
*/
ErrorPublicFolderServerNotFound,
/**
* The search folder has a restriction that is too long to return.
*/
ErrorQueryFilterTooLong,
/**
* Mailbox has exceeded maximum mailbox size.
*/
ErrorQuotaExceeded,
/**
* Unable to retrieve events for this subscription. The subscription must be recreated.
*/
ErrorReadEventsFailed,
/**
* Unable to suppress read receipt. Read receipts are not pending.
*/
ErrorReadReceiptNotPending,
/**
* Recurrence end date can not exceed Sep 1, 4500 00:00:00.
*/
ErrorRecurrenceEndDateTooBig,
/**
* Recurrence has no occurrences in the specified range.
*/
ErrorRecurrenceHasNoOccurrence,
/**
* Failed to remove one or more delegates.
*/
ErrorRemoveDelegatesFailed,
/**
* ErrorRequestAborted
*/
ErrorRequestAborted,
/**
* ErrorRequestStreamTooBig
*/
ErrorRequestStreamTooBig,
/**
* Required property is missing.
*/
ErrorRequiredPropertyMissing,
/**
* Cannot perform ResolveNames for non-contact folder.
*/
ErrorResolveNamesInvalidFolderType,
/**
* Only one contacts folder can be specified in request.
*/
ErrorResolveNamesOnlyOneContactsFolderAllowed,
/**
* The response failed schema validation.
*/
ErrorResponseSchemaValidation,
/**
* The restriction or sort order is too complex for this operation.
*/
ErrorRestrictionTooComplex,
/**
* Restriction contained too many elements.
*/
ErrorRestrictionTooLong,
/**
* ErrorResultSetTooBig
*/
ErrorResultSetTooBig,
/**
* ErrorRulesOverQuota
*/
ErrorRulesOverQuota,
/**
* The folder in which items were to be saved could not be found.
*/
ErrorSavedItemFolderNotFound,
/**
* The request failed schema validation.
*/
ErrorSchemaValidation,
/**
* The search folder is not initialized.
*/
ErrorSearchFolderNotInitialized,
/**
* The user account which was used to submit this request does not have the right to send
* mail on behalf of the specified sending account.
*/
ErrorSendAsDenied,
/**
* SendMeetingCancellations attribute is required for Calendar items.
*/
ErrorSendMeetingCancellationsRequired,
/**
* The SendMeetingInvitationsOrCancellations attribute is required for calendar items.
*/
ErrorSendMeetingInvitationsOrCancellationsRequired,
/**
* The SendMeetingInvitations attribute is required for calendar items.
*/
ErrorSendMeetingInvitationsRequired,
/**
* The meeting request has already been sent and might not be updated.
*/
ErrorSentMeetingRequestUpdate,
/**
* The task request has already been sent and may not be updated.
*/
ErrorSentTaskRequestUpdate,
/**
* The server cannot service this request right now. Try again later.
*/
ErrorServerBusy,
/**
* ErrorServiceDiscoveryFailed
*/
ErrorServiceDiscoveryFailed,
/**
* No external Exchange Web Service URL available.
*/
ErrorSharingNoExternalEwsAvailable,
/**
* Failed to synchronize the sharing folder.
*/
ErrorSharingSynchronizationFailed,
/**
* The current ChangeKey is required for this operation.
*/
ErrorStaleObject,
/**
* The message couldn't be sent because the sender's submission quota was exceeded. Please
* try again later.
*/
ErrorSubmissionQuotaExceeded,
/**
* Access is denied. Only the subscription owner may access the subscription.
*/
ErrorSubscriptionAccessDenied,
/**
* Subscriptions are not supported for delegate user access.
*/
ErrorSubscriptionDelegateAccessNotSupported,
/**
* The specified subscription was not found.
*/
ErrorSubscriptionNotFound,
/**
* The StreamingSubscription was unsubscribed while the current connection was servicing it.
*/
ErrorSubscriptionUnsubscribed,
/**
* The folder to be synchronized could not be found.
*/
ErrorSyncFolderNotFound,
/**
* ErrorTeamMailboxNotFound
*/
ErrorTeamMailboxNotFound,
/**
* ErrorTeamMailboxNotLinkedToSharePoint
*/
ErrorTeamMailboxNotLinkedToSharePoint,
/**
* ErrorTeamMailboxUrlValidationFailed
*/
ErrorTeamMailboxUrlValidationFailed,
/**
* ErrorTeamMailboxNotAuthorizedOwner
*/
ErrorTeamMailboxNotAuthorizedOwner,
/**
* ErrorTeamMailboxActiveToPendingDelete
*/
ErrorTeamMailboxActiveToPendingDelete,
/**
* ErrorTeamMailboxFailedSendingNotifications
*/
ErrorTeamMailboxFailedSendingNotifications,
/**
* ErrorTeamMailboxErrorUnknown
*/
ErrorTeamMailboxErrorUnknown,
/**
* ErrorTimeIntervalTooBig
*/
ErrorTimeIntervalTooBig,
/**
* ErrorTimeoutExpired
*/
ErrorTimeoutExpired,
/**
* The time zone isn't valid.
*/
ErrorTimeZone,
/**
* The specified target folder could not be found.
*/
ErrorToFolderNotFound,
/**
* The requesting account does not have permission to serialize tokens.
*/
ErrorTokenSerializationDenied,
/**
* ErrorUnableToGetUserOofSettings
*/
ErrorUnableToGetUserOofSettings,
/**
* ErrorUnableToRemoveImContactFromGroup
*/
ErrorUnableToRemoveImContactFromGroup,
/**
* A dial plan could not be found.
*/
ErrorUnifiedMessagingDialPlanNotFound,
/**
* The UnifiedMessaging request failed.
*/
ErrorUnifiedMessagingRequestFailed,
/**
* A connection couldn't be made to the Unified Messaging server.
*/
ErrorUnifiedMessagingServerNotFound,
/**
* The specified item culture is not supported on this server.
*/
ErrorUnsupportedCulture,
/**
* The MAPI property type is not supported.
*/
ErrorUnsupportedMapiPropertyType,
/**
* MIME conversion is not supported for this item type.
*/
ErrorUnsupportedMimeConversion,
/**
* The property can not be used with this type of restriction.
*/
ErrorUnsupportedPathForQuery,
/**
* The property can not be used for sorting or grouping results.
*/
ErrorUnsupportedPathForSortGroup,
/**
* PropertyDefinition is not supported in searches.
*/
ErrorUnsupportedPropertyDefinition,
/**
* QueryFilter type is not supported.
*/
ErrorUnsupportedQueryFilter,
/**
* The specified recurrence is not supported.
*/
ErrorUnsupportedRecurrence,
/**
* Unsupported subfilter type.
*/
ErrorUnsupportedSubFilter,
/**
* Unsupported type for restriction conversion.
*/
ErrorUnsupportedTypeForConversion,
/**
* Failed to update one or more delegates.
*/
ErrorUpdateDelegatesFailed,
/**
* Property for update does not match property in object.
*/
ErrorUpdatePropertyMismatch,
/**
* Policy does not allow granting permissions to user.
*/
ErrorUserNotAllowedByPolicy,
/**
* The user isn't enabled for Unified Messaging
*/
ErrorUserNotUnifiedMessagingEnabled,
/**
* The user doesn't have an SMTP proxy address from a federated domain.
*/
ErrorUserWithoutFederatedProxyAddress,
/**
* The value is out of range.
*/
ErrorValueOutOfRange,
/**
* Virus detected in the message.
*/
ErrorVirusDetected,
/**
* The item has been deleted as a result of a virus scan.
*/
ErrorVirusMessageDeleted,
/**
* The Voice Mail distinguished folder is not implemented.
*/
ErrorVoiceMailNotImplemented,
/**
* ErrorWebRequestInInvalidState
*/
ErrorWebRequestInInvalidState,
/**
* ErrorWin32InteropError
*/
ErrorWin32InteropError,
/**
* ErrorWorkingHoursSaveFailed
*/
ErrorWorkingHoursSaveFailed,
/**
* ErrorWorkingHoursXmlMalformed
*/
ErrorWorkingHoursXmlMalformed,
/**
* The Client Access server version doesn't match the Mailbox server version of the resource
* that was being accessed. To determine the correct URL to use to access the resource, use
* Autodiscover with the address of the resource.
*/
ErrorWrongServerVersion,
/**
* The mailbox of the authenticating user and the mailbox of the resource being accessed
* must have the same Mailbox server version.
*/
ErrorWrongServerVersionDelegate,
/**
* The client access token request is invalid.
*/
ErrorInvalidClientAccessTokenRequest,
/**
* invalid managementrole header value or usage.
*/
ErrorInvalidManagementRoleHeader,
/**
* SearchMailboxes query has too many keywords.
*/
ErrorSearchQueryHasTooManyKeywords,
/**
* SearchMailboxes on too many mailboxes.
*/
ErrorSearchTooManyMailboxes,
/**
* There are no retention tags.
*/
ErrorInvalidRetentionTagNone,
/**
* Discovery Searches are disabled.
*/
ErrorDiscoverySearchesDisabled,
/**
* SeekToConditionPageView not supported for calendar items.
*/
ErrorCalendarSeekToConditionNotSupported,
/**
* Archive mailbox search operation failed.
*/
ErrorArchiveMailboxSearchFailed,
/**
* Get remote archive mailbox folder failed.
*/
ErrorGetRemoteArchiveFolderFailed,
/**
* Find remote archive mailbox folder failed.
*/
ErrorFindRemoteArchiveFolderFailed,
/**
* Get remote archive mailbox item failed.
*/
ErrorGetRemoteArchiveItemFailed,
/**
* Export remote archive mailbox items failed.
*/
ErrorExportRemoteArchiveItemsFailed,
/**
* Invalid state definition.
*/
ErrorClientIntentInvalidStateDefinition,
/**
* Client intent not found.
*/
ErrorClientIntentNotFound,
/**
* The Content Indexing service is required to perform this search, but it's not enabled.
*/
ErrorContentIndexingNotEnabled,
/**
* The custom prompt files you specified couldn't be removed.
*/
ErrorDeleteUnifiedMessagingPromptFailed,
/**
* The location service is disabled.
*/
ErrorLocationServicesDisabled,
/**
* Invalid location service request.
*/
ErrorLocationServicesInvalidRequest,
/**
* The request for location information failed.
*/
ErrorLocationServicesRequestFailed,
/**
* The request for location information timed out.
*/
ErrorLocationServicesRequestTimedOut,
/**
* Weather service is disabled.
*/
ErrorWeatherServiceDisabled,
/**
* Mailbox scope not allowed without a query string.
*/
ErrorMailboxScopeNotAllowedWithoutQueryString,
/**
* No speech detected.
*/
ErrorNoSpeechDetected,
/**
* An error occurred while accessing the custom prompt publishing point.
*/
ErrorPromptPublishingOperationFailed,
/**
* Unable to discover the URL of the public folder mailbox.
*/
ErrorPublicFolderMailboxDiscoveryFailed,
/**
* Public folder operation failed.
*/
ErrorPublicFolderOperationFailed,
/**
* The operation succeeded on the primary public folder mailbox, but failed to sync to the secondary public folder mailbox.
*/
ErrorPublicFolderSyncException,
/**
* Discovery Searches are disabled.
*/
ErrorRecipientNotFound,
/**
* Recognizer not installed.
*/
ErrorRecognizerNotInstalled,
/**
* Speech grammar error.
*/
ErrorSpeechGrammarError,
/**
* Too many concurrent connections opened.
*/
ErrorTooManyObjectsOpened,
/**
* Unified Messaging server unavailable.
*/
ErrorUMServerUnavailable,
/**
* The Unified Messaging custom prompt file you specified couldn't be found.
*/
ErrorUnifiedMessagingPromptNotFound,
/**
* Report data for the UM call summary couldn't be found.
*/
ErrorUnifiedMessagingReportDataNotFound,
/**
* The requested size is invalid.
*/
ErrorInvalidPhotoSize,
/**
* AcceptItem action is invalid for a meeting message in group mailbox.
*/
ErrorCalendarIsGroupMailboxForAccept,
/**
* DeclineItem operation is invalid for a meeting message in group mailbox.
*/
ErrorCalendarIsGroupMailboxForDecline,
/**
* TentativelyAcceptItem action isn't valid for a meeting message in group mailbox.
*/
ErrorCalendarIsGroupMailboxForTentative,
/**
* SuppressReadReceipt action isn't valid for a meeting message in group mailbox.
*/
ErrorCalendarIsGroupMailboxForSuppressReadReceipt,
/**
* The Organization is marked for removal.
*/
ErrorOrganizationAccessBlocked,
/**
* User doesn't have a valid license.
*/
ErrorInvalidLicense,
/**
* Receive quota message per folder is exceeded.
*/
ErrorMessagePerFolderCountReceiveQuotaExceeded,
/**
* Unified group was not found.
*/
ErrorUnifiedGroupMailboxNotFound,
/**
* Invalid channel id.
*/
ErrorInvalidChannelId,
/**
* Another connection is opened on the same channel.
*/
ErrorNewChannelConnectionOpened,
/**
* The channel subscription cannot be found.
*/
ErrorChannelSubscriptionNotFound,
/**
* The channel contains too many subscriptions.
*/
ErrorExceededChannelSubscriptionCount,
/**
* The channel subscription already exists.
*/
ErrorChannelSubscriptionAlreadyExists,
/**
* The given channel subscription id is invalid.
*/
ErrorInvalidChannelSubscriptionId,
/* #region Error codes to map WASCL errors */
/**
* Error indicating that message submission blocked by WASCL for a consumer mailboxes
*/
ErrorMessageSubmissionBlocked,
/**
* Error indicating that number of submitted messages exceeded the limit and message submission is blocked by WASCL
*/
ErrorExceededMessageLimit,
/**
* Error indicating that recipients number for a consumer mailbox has exceeded the limit defined by WASCL
*/
ErrorExceededMaxRecipientLimitBlock,
/**
* Error indicating that access to the consumer mailbox is suspended by WASCL
*/
ErrorAccountSuspend,
/**
* Error indicating that recipients number for a consumer mailbox has exceeded the limit defined by WASCL
*/
ErrorExceededMaxRecipientLimit,
/**
* Error indicating that particular message cannot be sent for a consumer mailbox as it is considered as SPAM by WASCL
*/
ErrorMessageBlocked,
/**
* Error indicating that access to the consumer mailbox is suspended by WASCL
*/
ErrorAccountSuspendShowTierUpgrade,
/**
* Error indicating that message sent from a consumer mailbox has exceeded the limit defined by WASCL
*/
ErrorExceededMessageLimitShowTierUpgrade,
/**
* Error indicating that recipients number for a consumer mailbox has exceeded the limit defined by WASCL
*/
ErrorExceededMaxRecipientLimitShowTierUpgrade,
/* #endregion */
} | the_stack |
import { Plane, Quaternion, Vector3, Vector4, Viewport } from '.';
import { MathTmp } from './tmp';
/**
* Class used to store matrix data (4x4)
*/
export class Matrix {
private static updateFlagSeed = 0;
private static identityReadOnly = Matrix.Identity();
private _isIdentity = false;
private _isIdentityDirty = true;
private _isIdentity3x2 = true;
private _isIdentity3x2Dirty = true;
/**
* Gets the update flag of the matrix which is an unique number for the matrix.
* It will be incremented every time the matrix data change.
* You can use it to speed the comparison between two versions of the same matrix.
*/
public updateFlag: number;
private readonly _m: Float32Array = new Float32Array(16);
/**
* Gets the internal data of the matrix
*/
public get m(): Readonly<Float32Array> { return this._m; }
/**
* @hidden
*/
public _markAsUpdated() {
this.updateFlag = Matrix.updateFlagSeed++;
this._isIdentity = false;
this._isIdentity3x2 = false;
this._isIdentityDirty = true;
this._isIdentity3x2Dirty = true;
}
/**
* @hidden
*/
private _updateIdentityStatus(
isIdentity: boolean,
isIdentityDirty = false,
isIdentity3x2 = false,
isIdentity3x2Dirty = true) {
this.updateFlag = Matrix.updateFlagSeed++;
this._isIdentity = isIdentity;
this._isIdentity3x2 = isIdentity || isIdentity3x2;
this._isIdentityDirty = this._isIdentity ? false : isIdentityDirty;
this._isIdentity3x2Dirty = this._isIdentity3x2 ? false : isIdentity3x2Dirty;
}
/**
* Creates an empty matrix (filled with zeros)
*/
constructor() {
this._updateIdentityStatus(false);
}
// Properties
/**
* Check if the current matrix is identity
* @returns true is the matrix is the identity matrix
*/
public isIdentity(): boolean {
if (this._isIdentityDirty) {
this._isIdentityDirty = false;
const m = this._m;
this._isIdentity = (
m[0] === 1.0 && m[1] === 0.0 && m[2] === 0.0 && m[3] === 0.0 &&
m[4] === 0.0 && m[5] === 1.0 && m[6] === 0.0 && m[7] === 0.0 &&
m[8] === 0.0 && m[9] === 0.0 && m[10] === 1.0 && m[11] === 0.0 &&
m[12] === 0.0 && m[13] === 0.0 && m[14] === 0.0 && m[15] === 1.0
);
}
return this._isIdentity;
}
/**
* Check if the current matrix is identity as a texture matrix (3x2 store in 4x4)
* @returns true is the matrix is the identity matrix
*/
public isIdentityAs3x2(): boolean {
if (this._isIdentity3x2Dirty) {
this._isIdentity3x2Dirty = false;
if (this._m[0] !== 1.0 || this._m[5] !== 1.0 || this._m[15] !== 1.0) {
this._isIdentity3x2 = false;
} else if (this._m[1] !== 0.0 || this._m[2] !== 0.0 || this._m[3] !== 0.0 ||
this._m[4] !== 0.0 || this._m[6] !== 0.0 || this._m[7] !== 0.0 ||
this._m[8] !== 0.0 || this._m[9] !== 0.0 || this._m[10] !== 0.0 || this._m[11] !== 0.0 ||
this._m[12] !== 0.0 || this._m[13] !== 0.0 || this._m[14] !== 0.0) {
this._isIdentity3x2 = false;
} else {
this._isIdentity3x2 = true;
}
}
return this._isIdentity3x2;
}
/**
* Gets the determinant of the matrix
* @returns the matrix determinant
*/
public determinant(): number {
if (this._isIdentity === true) {
return 1;
}
const m = this._m;
const m00 = m[0], m01 = m[1], m02 = m[2], m03 = m[3];
const m10 = m[4], m11 = m[5], m12 = m[6], m13 = m[7];
const m20 = m[8], m21 = m[9], m22 = m[10], m23 = m[11];
const m30 = m[12], m31 = m[13], m32 = m[14], m33 = m[15];
// https://en.wikipedia.org/wiki/Laplace_expansion
// to compute the deterrminant of a 4x4 Matrix we compute the cofactors of any row or column,
// then we multiply each Cofactor by its corresponding matrix value and sum them all to get the determinant
// Cofactor(i, j) = sign(i,j) * det(Minor(i, j))
// where
// - sign(i,j) = (i+j) % 2 === 0 ? 1 : -1
// - Minor(i, j) is the 3x3 matrix we get by removing row i and column j from current Matrix
//
// Here we do that for the 1st row.
const det_22_33 = m22 * m33 - m32 * m23;
const det_21_33 = m21 * m33 - m31 * m23;
const det_21_32 = m21 * m32 - m31 * m22;
const det_20_33 = m20 * m33 - m30 * m23;
const det_20_32 = m20 * m32 - m22 * m30;
const det_20_31 = m20 * m31 - m30 * m21;
const cofact_00 = +(m11 * det_22_33 - m12 * det_21_33 + m13 * det_21_32);
const cofact_01 = -(m10 * det_22_33 - m12 * det_20_33 + m13 * det_20_32);
const cofact_02 = +(m10 * det_21_33 - m11 * det_20_33 + m13 * det_20_31);
const cofact_03 = -(m10 * det_21_32 - m11 * det_20_32 + m12 * det_20_31);
return m00 * cofact_00 + m01 * cofact_01 + m02 * cofact_02 + m03 * cofact_03;
}
// Methods
/**
* Returns the matrix as a Float32Array
* @returns the matrix underlying array
*/
public toArray(): Readonly<Float32Array> {
return this._m;
}
/**
* Returns the matrix as a Float32Array
* @returns the matrix underlying array.
*/
public asArray(): Readonly<Float32Array> {
return this._m;
}
/**
* Inverts the current matrix in place
* @returns the current inverted matrix
*/
public invert(): Matrix {
this.invertToRef(this);
return this;
}
/**
* Sets all the matrix elements to zero
* @returns the current matrix
*/
public reset(): Matrix {
Matrix.FromValuesToRef(
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
this,
);
this._updateIdentityStatus(false);
return this;
}
/**
* Adds the current matrix with a second one
* @param other defines the matrix to add
* @returns a new matrix as the addition of the current matrix and the given one
*/
public add(other: Matrix): Matrix {
const result = new Matrix();
this.addToRef(other, result);
return result;
}
/**
* Sets the given matrix "result" to the addition of the current matrix and the given one
* @param other defines the matrix to add
* @param result defines the target matrix
* @returns the current matrix
*/
public addToRef(other: Matrix, result: Matrix): Matrix {
for (let index = 0; index < 16; index++) {
result._m[index] = this._m[index] + other._m[index];
}
result._markAsUpdated();
return this;
}
/**
* Adds in place the given matrix to the current matrix
* @param other defines the second operand
* @returns the current updated matrix
*/
public addToSelf(other: Matrix): Matrix {
for (let index = 0; index < 16; index++) {
this._m[index] += other._m[index];
}
this._markAsUpdated();
return this;
}
/**
* Sets the given matrix to the current inverted Matrix
* @param other defines the target matrix
* @returns the unmodified current matrix
*/
public invertToRef(other: Matrix): Matrix {
if (this._isIdentity === true) {
Matrix.IdentityToRef(other);
return this;
}
// the inverse of a Matrix is the transpose of cofactor matrix divided by the determinant
const m = this._m;
const m00 = m[0], m01 = m[1], m02 = m[2], m03 = m[3];
const m10 = m[4], m11 = m[5], m12 = m[6], m13 = m[7];
const m20 = m[8], m21 = m[9], m22 = m[10], m23 = m[11];
const m30 = m[12], m31 = m[13], m32 = m[14], m33 = m[15];
const det_22_33 = m22 * m33 - m32 * m23;
const det_21_33 = m21 * m33 - m31 * m23;
const det_21_32 = m21 * m32 - m31 * m22;
const det_20_33 = m20 * m33 - m30 * m23;
const det_20_32 = m20 * m32 - m22 * m30;
const det_20_31 = m20 * m31 - m30 * m21;
const cofact_00 = +(m11 * det_22_33 - m12 * det_21_33 + m13 * det_21_32);
const cofact_01 = -(m10 * det_22_33 - m12 * det_20_33 + m13 * det_20_32);
const cofact_02 = +(m10 * det_21_33 - m11 * det_20_33 + m13 * det_20_31);
const cofact_03 = -(m10 * det_21_32 - m11 * det_20_32 + m12 * det_20_31);
const det = m00 * cofact_00 + m01 * cofact_01 + m02 * cofact_02 + m03 * cofact_03;
if (det === 0) {
// not invertible
other.copyFrom(this);
return this;
}
const detInv = 1 / det;
const det_12_33 = m12 * m33 - m32 * m13;
const det_11_33 = m11 * m33 - m31 * m13;
const det_11_32 = m11 * m32 - m31 * m12;
const det_10_33 = m10 * m33 - m30 * m13;
const det_10_32 = m10 * m32 - m30 * m12;
const det_10_31 = m10 * m31 - m30 * m11;
const det_12_23 = m12 * m23 - m22 * m13;
const det_11_23 = m11 * m23 - m21 * m13;
const det_11_22 = m11 * m22 - m21 * m12;
const det_10_23 = m10 * m23 - m20 * m13;
const det_10_22 = m10 * m22 - m20 * m12;
const det_10_21 = m10 * m21 - m20 * m11;
const cofact_10 = -(m01 * det_22_33 - m02 * det_21_33 + m03 * det_21_32);
const cofact_11 = +(m00 * det_22_33 - m02 * det_20_33 + m03 * det_20_32);
const cofact_12 = -(m00 * det_21_33 - m01 * det_20_33 + m03 * det_20_31);
const cofact_13 = +(m00 * det_21_32 - m01 * det_20_32 + m02 * det_20_31);
const cofact_20 = +(m01 * det_12_33 - m02 * det_11_33 + m03 * det_11_32);
const cofact_21 = -(m00 * det_12_33 - m02 * det_10_33 + m03 * det_10_32);
const cofact_22 = +(m00 * det_11_33 - m01 * det_10_33 + m03 * det_10_31);
const cofact_23 = -(m00 * det_11_32 - m01 * det_10_32 + m02 * det_10_31);
const cofact_30 = -(m01 * det_12_23 - m02 * det_11_23 + m03 * det_11_22);
const cofact_31 = +(m00 * det_12_23 - m02 * det_10_23 + m03 * det_10_22);
const cofact_32 = -(m00 * det_11_23 - m01 * det_10_23 + m03 * det_10_21);
const cofact_33 = +(m00 * det_11_22 - m01 * det_10_22 + m02 * det_10_21);
Matrix.FromValuesToRef(
cofact_00 * detInv, cofact_10 * detInv, cofact_20 * detInv, cofact_30 * detInv,
cofact_01 * detInv, cofact_11 * detInv, cofact_21 * detInv, cofact_31 * detInv,
cofact_02 * detInv, cofact_12 * detInv, cofact_22 * detInv, cofact_32 * detInv,
cofact_03 * detInv, cofact_13 * detInv, cofact_23 * detInv, cofact_33 * detInv,
other
);
return this;
}
/**
* add a value at the specified position in the current Matrix
* @param index the index of the value within the matrix. between 0 and 15.
* @param value the value to be added
* @returns the current updated matrix
*/
public addAtIndex(index: number, value: number): Matrix {
this._m[index] += value;
this._markAsUpdated();
return this;
}
/**
* mutiply the specified position in the current Matrix by a value
* @param index the index of the value within the matrix. between 0 and 15.
* @param value the value to be added
* @returns the current updated matrix
*/
public multiplyAtIndex(index: number, value: number): Matrix {
this._m[index] *= value;
this._markAsUpdated();
return this;
}
/**
* Inserts the translation vector (using 3 floats) in the current matrix
* @param x defines the 1st component of the translation
* @param y defines the 2nd component of the translation
* @param z defines the 3rd component of the translation
* @returns the current updated matrix
*/
public setTranslationFromFloats(x: number, y: number, z: number): Matrix {
this._m[12] = x;
this._m[13] = y;
this._m[14] = z;
this._markAsUpdated();
return this;
}
/**
* Inserts the translation vector in the current matrix
* @param vector3 defines the translation to insert
* @returns the current updated matrix
*/
public setTranslation(vector3: Vector3): Matrix {
return this.setTranslationFromFloats(vector3.x, vector3.y, vector3.z);
}
/**
* Gets the translation value of the current matrix
* @returns a new Vector3 as the extracted translation from the matrix
*/
public getTranslation(): Vector3 {
return new Vector3(this._m[12], this._m[13], this._m[14]);
}
/**
* Fill a Vector3 with the extracted translation from the matrix
* @param result defines the Vector3 where to store the translation
* @returns the current matrix
*/
public getTranslationToRef(result: Vector3): Matrix {
result.x = this._m[12];
result.y = this._m[13];
result.z = this._m[14];
return this;
}
/**
* Remove rotation and scaling part from the matrix
* @returns the updated matrix
*/
public removeRotationAndScaling(): Matrix {
const m = this.m;
Matrix.FromValuesToRef(
1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
m[12], m[13], m[14], m[15],
this
);
this._updateIdentityStatus(m[12] === 0 && m[13] === 0 && m[14] === 0 && m[15] === 1);
return this;
}
/**
* Multiply two matrices
* @param other defines the second operand
* @returns a new matrix set with the multiplication result of the current Matrix and the given one
*/
public multiply(other: Readonly<Matrix>): Matrix {
const result = new Matrix();
this.multiplyToRef(other, result);
return result;
}
/**
* Copy the current matrix from the given one
* @param other defines the source matrix
* @returns the current updated matrix
*/
public copyFrom(other: Readonly<Matrix>): Matrix {
other.copyToArray(this._m);
const o = (other as Matrix);
this._updateIdentityStatus(o._isIdentity, o._isIdentityDirty, o._isIdentity3x2, o._isIdentity3x2Dirty);
return this;
}
/**
* Populates the given array from the starting index with the current matrix values
* @param array defines the target array
* @param offset defines the offset in the target array where to start storing values
* @returns the current matrix
*/
public copyToArray(array: Float32Array, offset = 0): Matrix {
for (let index = 0; index < 16; index++) {
array[offset + index] = this._m[index];
}
return this;
}
/**
* Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
* @param other defines the second operand
* @param result defines the matrix where to store the multiplication
* @returns the current matrix
*/
public multiplyToRef(other: Readonly<Matrix>, result: Matrix): Matrix {
if (this._isIdentity) {
result.copyFrom(other);
return this;
}
if ((other as Matrix)._isIdentity) {
result.copyFrom(this);
return this;
}
this.multiplyToArray(other, result._m, 0);
result._markAsUpdated();
return this;
}
/**
* Sets the Float32Array "result" from the given index "offset" with the multiplication of the
* current matrix and the given one
* @param other defines the second operand
* @param result defines the array where to store the multiplication
* @param offset defines the offset in the target array where to start storing values
* @returns the current matrix
*/
public multiplyToArray(other: Readonly<Matrix>, result: Float32Array, offset: number): Matrix {
const m = this._m;
const otherM = other.m;
const tm0 = m[0], tm1 = m[1], tm2 = m[2], tm3 = m[3];
const tm4 = m[4], tm5 = m[5], tm6 = m[6], tm7 = m[7];
const tm8 = m[8], tm9 = m[9], tm10 = m[10], tm11 = m[11];
const tm12 = m[12], tm13 = m[13], tm14 = m[14], tm15 = m[15];
const om0 = otherM[0], om1 = otherM[1], om2 = otherM[2], om3 = otherM[3];
const om4 = otherM[4], om5 = otherM[5], om6 = otherM[6], om7 = otherM[7];
const om8 = otherM[8], om9 = otherM[9], om10 = otherM[10], om11 = otherM[11];
const om12 = otherM[12], om13 = otherM[13], om14 = otherM[14], om15 = otherM[15];
result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
return this;
}
/**
* Check equality between this matrix and a second one
* @param value defines the second matrix to compare
* @returns true is the current matrix and the given one values are strictly equal
*/
public equals(value: Matrix): boolean {
const other = (value as Matrix);
if (!other) {
return false;
}
if (this._isIdentity || other._isIdentity) {
if (!this._isIdentityDirty && !other._isIdentityDirty) {
return this._isIdentity && other._isIdentity;
}
}
const m = this.m;
const om = other.m;
return (
m[0] === om[0] && m[1] === om[1] && m[2] === om[2] && m[3] === om[3] &&
m[4] === om[4] && m[5] === om[5] && m[6] === om[6] && m[7] === om[7] &&
m[8] === om[8] && m[9] === om[9] && m[10] === om[10] && m[11] === om[11] &&
m[12] === om[12] && m[13] === om[13] && m[14] === om[14] && m[15] === om[15]
);
}
/**
* Clone the current matrix
* @returns a new matrix from the current matrix
*/
public clone(): Matrix {
const matrix = new Matrix();
matrix.copyFrom(this);
return matrix;
}
/**
* Returns the name of the current matrix class
* @returns the string "Matrix"
*/
public getClassName(): string {
return "Matrix";
}
/**
* Gets the hash code of the current matrix
* @returns the hash code
*/
public getHashCode(): number {
let hash = this._m[0] || 0;
for (let i = 1; i < 16; i++) {
hash = (hash * 397) ^ (this._m[i] || 0);
}
return hash;
}
/**
* Decomposes the current Matrix into a translation, rotation and scaling components
* @param scale defines the scale vector3 given as a reference to update
* @param rotation defines the rotation quaternion given as a reference to update
* @param translation defines the translation vector3 given as a reference to update
* @returns true if operation was successful
*/
public decompose(scale?: Vector3, rotation?: Quaternion, translation?: Vector3): boolean {
if (this._isIdentity) {
if (translation) {
translation.setAll(0);
}
if (scale) {
scale.setAll(1);
}
if (rotation) {
rotation.copyFromFloats(0, 0, 0, 1);
}
return true;
}
const m = this._m;
if (translation) {
translation.copyFromFloats(m[12], m[13], m[14]);
}
scale = scale || MathTmp.Vector3[0];
scale.x = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
scale.y = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
scale.z = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
if (this.determinant() <= 0) {
scale.y *= -1;
}
if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
if (rotation) {
rotation.copyFromFloats(0.0, 0.0, 0.0, 1.0);
}
return false;
}
if (rotation) {
const sx = 1 / scale.x, sy = 1 / scale.y, sz = 1 / scale.z;
Matrix.FromValuesToRef(
m[0] * sx, m[1] * sx, m[2] * sx, 0.0,
m[4] * sy, m[5] * sy, m[6] * sy, 0.0,
m[8] * sz, m[9] * sz, m[10] * sz, 0.0,
0.0, 0.0, 0.0, 1.0,
MathTmp.Matrix[0]
);
Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
}
return true;
}
/**
* Gets specific row of the matrix
* @param index defines the number of the row to get
* @returns the index-th row of the current matrix as a new Vector4
*/
public getRow(index: number): Vector4 {
if (index < 0 || index > 3) {
return null;
}
const i = index * 4;
return new Vector4(this._m[i + 0], this._m[i + 1], this._m[i + 2], this._m[i + 3]);
}
/**
* Sets the index-th row of the current matrix to the vector4 values
* @param index defines the number of the row to set
* @param row defines the target vector4
* @returns the updated current matrix
*/
public setRow(index: number, row: Vector4): Matrix {
return this.setRowFromFloats(index, row.x, row.y, row.z, row.w);
}
/**
* Compute the transpose of the matrix
* @returns the new transposed matrix
*/
public transpose(): Matrix {
return Matrix.Transpose(this);
}
/**
* Compute the transpose of the matrix and store it in a given matrix
* @param result defines the target matrix
* @returns the current matrix
*/
public transposeToRef(result: Matrix): Matrix {
Matrix.TransposeToRef(this, result);
return this;
}
/**
* Sets the index-th row of the current matrix with the given 4 x float values
* @param index defines the row index
* @param x defines the x component to set
* @param y defines the y component to set
* @param z defines the z component to set
* @param w defines the w component to set
* @returns the updated current matrix
*/
public setRowFromFloats(index: number, x: number, y: number, z: number, w: number): Matrix {
if (index < 0 || index > 3) {
return this;
}
const i = index * 4;
this._m[i + 0] = x;
this._m[i + 1] = y;
this._m[i + 2] = z;
this._m[i + 3] = w;
this._markAsUpdated();
return this;
}
/**
* Compute a new matrix set with the current matrix values multiplied by scale (float)
* @param scale defines the scale factor
* @returns a new matrix
*/
public scale(scale: number): Matrix {
const result = new Matrix();
this.scaleToRef(scale, result);
return result;
}
/**
* Scale the current matrix values by a factor to a given result matrix
* @param scale defines the scale factor
* @param result defines the matrix to store the result
* @returns the current matrix
*/
public scaleToRef(scale: number, result: Matrix): Matrix {
for (let index = 0; index < 16; index++) {
result._m[index] = this._m[index] * scale;
}
result._markAsUpdated();
return this;
}
/**
* Scale the current matrix values by a factor and add the result to a given matrix
* @param scale defines the scale factor
* @param result defines the Matrix to store the result
* @returns the current matrix
*/
public scaleAndAddToRef(scale: number, result: Matrix): Matrix {
for (let index = 0; index < 16; index++) {
result._m[index] += this._m[index] * scale;
}
result._markAsUpdated();
return this;
}
/**
* Writes to the given matrix a normal matrix, computed from this one (using values from
* identity matrix for fourth row and column).
* @param ref matrix to store the result
*/
public toNormalMatrix(ref: Matrix): void {
const tmp = MathTmp.Matrix[0];
this.invertToRef(tmp);
tmp.transposeToRef(ref);
const m = ref._m;
Matrix.FromValuesToRef(
m[0], m[1], m[2], 0.0,
m[4], m[5], m[6], 0.0,
m[8], m[9], m[10], 0.0,
0.0, 0.0, 0.0, 1.0,
ref
);
}
/**
* Gets only rotation part of the current matrix
* @returns a new matrix sets to the extracted rotation matrix from the current one
*/
public getRotationMatrix(): Matrix {
const result = new Matrix();
this.getRotationMatrixToRef(result);
return result;
}
/**
* Extracts the rotation matrix from the current one and sets it as the given "result"
* @param result defines the target matrix to store data to
* @returns the current matrix
*/
public getRotationMatrixToRef(result: Matrix): Matrix {
const scale = MathTmp.Vector3[0];
if (!this.decompose(scale)) {
Matrix.IdentityToRef(result);
return this;
}
const m = this._m;
const sx = 1 / scale.x, sy = 1 / scale.y, sz = 1 / scale.z;
Matrix.FromValuesToRef(
m[0] * sx, m[1] * sx, m[2] * sx, 0.0,
m[4] * sy, m[5] * sy, m[6] * sy, 0.0,
m[8] * sz, m[9] * sz, m[10] * sz, 0.0,
0.0, 0.0, 0.0, 1.0,
result
);
return this;
}
/**
* Toggles model matrix from being right handed to left handed in place and vice versa
*/
public toggleModelMatrixHandInPlace() {
const m = this._m;
m[2] *= -1;
m[6] *= -1;
m[8] *= -1;
m[9] *= -1;
m[14] *= -1;
this._markAsUpdated();
}
/**
* Toggles projection matrix from being right handed to left handed in place and vice versa
*/
public toggleProjectionMatrixHandInPlace() {
const m = this._m;
m[8] *= -1;
m[9] *= -1;
m[10] *= -1;
m[11] *= -1;
this._markAsUpdated();
}
// Statics
/**
* Creates a matrix from an array
* @param array defines the source array
* @param offset defines an offset in the source array
* @returns a new Matrix set from the starting index of the given array
*/
public static FromArray(array: ArrayLike<number>, offset = 0): Matrix {
const result = new Matrix();
Matrix.FromArrayToRef(array, offset, result);
return result;
}
/**
* Copy the content of an array into a given matrix
* @param array defines the source array
* @param offset defines an offset in the source array
* @param result defines the target matrix
*/
public static FromArrayToRef(array: ArrayLike<number>, offset: number, result: Matrix) {
for (let index = 0; index < 16; index++) {
result._m[index] = array[index + offset];
}
result._markAsUpdated();
}
/**
* Stores an array into a matrix after having multiplied each component by a given factor
* @param array defines the source array
* @param offset defines the offset in the source array
* @param scale defines the scaling factor
* @param result defines the target matrix
*/
public static FromFloat32ArrayToRefScaled(array: Float32Array, offset: number, scale: number, result: Matrix) {
for (let index = 0; index < 16; index++) {
result._m[index] = array[index + offset] * scale;
}
result._markAsUpdated();
}
/**
* Gets an identity matrix that must not be updated
*/
public static get IdentityReadOnly(): Readonly<Matrix> {
return Matrix.identityReadOnly;
}
/**
* Stores a list of values (16) inside a given matrix
* @param initialM11 defines 1st value of 1st row
* @param initialM12 defines 2nd value of 1st row
* @param initialM13 defines 3rd value of 1st row
* @param initialM14 defines 4th value of 1st row
* @param initialM21 defines 1st value of 2nd row
* @param initialM22 defines 2nd value of 2nd row
* @param initialM23 defines 3rd value of 2nd row
* @param initialM24 defines 4th value of 2nd row
* @param initialM31 defines 1st value of 3rd row
* @param initialM32 defines 2nd value of 3rd row
* @param initialM33 defines 3rd value of 3rd row
* @param initialM34 defines 4th value of 3rd row
* @param initialM41 defines 1st value of 4th row
* @param initialM42 defines 2nd value of 4th row
* @param initialM43 defines 3rd value of 4th row
* @param initialM44 defines 4th value of 4th row
* @param result defines the target matrix
*/
public static FromValuesToRef(
initialM11: number, initialM12: number, initialM13: number, initialM14: number,
initialM21: number, initialM22: number, initialM23: number, initialM24: number,
initialM31: number, initialM32: number, initialM33: number, initialM34: number,
initialM41: number, initialM42: number, initialM43: number, initialM44: number, result: Matrix): void {
const m = result._m;
m[0] = initialM11; m[1] = initialM12; m[2] = initialM13; m[3] = initialM14;
m[4] = initialM21; m[5] = initialM22; m[6] = initialM23; m[7] = initialM24;
m[8] = initialM31; m[9] = initialM32; m[10] = initialM33; m[11] = initialM34;
m[12] = initialM41; m[13] = initialM42; m[14] = initialM43; m[15] = initialM44;
result._markAsUpdated();
}
/**
* Creates new matrix from a list of values (16)
* @param initialM11 defines 1st value of 1st row
* @param initialM12 defines 2nd value of 1st row
* @param initialM13 defines 3rd value of 1st row
* @param initialM14 defines 4th value of 1st row
* @param initialM21 defines 1st value of 2nd row
* @param initialM22 defines 2nd value of 2nd row
* @param initialM23 defines 3rd value of 2nd row
* @param initialM24 defines 4th value of 2nd row
* @param initialM31 defines 1st value of 3rd row
* @param initialM32 defines 2nd value of 3rd row
* @param initialM33 defines 3rd value of 3rd row
* @param initialM34 defines 4th value of 3rd row
* @param initialM41 defines 1st value of 4th row
* @param initialM42 defines 2nd value of 4th row
* @param initialM43 defines 3rd value of 4th row
* @param initialM44 defines 4th value of 4th row
* @returns the new matrix
*/
public static FromValues(
initialM11: number, initialM12: number, initialM13: number, initialM14: number,
initialM21: number, initialM22: number, initialM23: number, initialM24: number,
initialM31: number, initialM32: number, initialM33: number, initialM34: number,
initialM41: number, initialM42: number, initialM43: number, initialM44: number): Matrix {
const result = new Matrix();
const m = result._m;
m[0] = initialM11; m[1] = initialM12; m[2] = initialM13; m[3] = initialM14;
m[4] = initialM21; m[5] = initialM22; m[6] = initialM23; m[7] = initialM24;
m[8] = initialM31; m[9] = initialM32; m[10] = initialM33; m[11] = initialM34;
m[12] = initialM41; m[13] = initialM42; m[14] = initialM43; m[15] = initialM44;
result._markAsUpdated();
return result;
}
/**
* Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
* @param scale defines the scale vector3
* @param rotation defines the rotation quaternion
* @param translation defines the translation vector3
* @returns a new matrix
*/
public static Compose(scale: Vector3, rotation: Quaternion, translation: Vector3): Matrix {
const result = new Matrix();
Matrix.ComposeToRef(scale, rotation, translation, result);
return result;
}
/**
* Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
* @param scale defines the scale vector3
* @param rotation defines the rotation quaternion
* @param translation defines the translation vector3
* @param result defines the target matrix
*/
public static ComposeToRef(scale: Vector3, rotation: Quaternion, translation: Vector3, result: Matrix): void {
Matrix.ScalingToRef(scale.x, scale.y, scale.z, MathTmp.Matrix[1]);
rotation.toRotationMatrix(MathTmp.Matrix[0]);
MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
result.setTranslation(translation);
}
/**
* Creates a new identity matrix
* @returns a new identity matrix
*/
public static Identity(): Matrix {
const identity = Matrix.FromValues(
1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0);
identity._updateIdentityStatus(true);
return identity;
}
/**
* Creates a new identity matrix and stores the result in a given matrix
* @param result defines the target matrix
*/
public static IdentityToRef(result: Matrix): void {
Matrix.FromValuesToRef(
1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0,
result
);
result._updateIdentityStatus(true);
}
/**
* Creates a new zero matrix
* @returns a new zero matrix
*/
public static Zero(): Matrix {
const zero = Matrix.FromValues(
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0);
zero._updateIdentityStatus(false);
return zero;
}
/**
* Creates a new rotation matrix for "angle" radians around the X axis
* @param angle defines the angle (in radians) to use
* @return the new matrix
*/
public static RotationX(angle: number): Matrix {
const result = new Matrix();
Matrix.RotationXToRef(angle, result);
return result;
}
/**
* Creates a new matrix as the invert of a given matrix
* @param source defines the source matrix
* @returns the new matrix
*/
public static Invert(source: Matrix): Matrix {
const result = new Matrix();
source.invertToRef(result);
return result;
}
/**
* Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
* @param angle defines the angle (in radians) to use
* @param result defines the target matrix
*/
public static RotationXToRef(angle: number, result: Matrix): void {
const s = Math.sin(angle);
const c = Math.cos(angle);
Matrix.FromValuesToRef(
1.0, 0.0, 0.0, 0.0,
0.0, c, s, 0.0,
0.0, -s, c, 0.0,
0.0, 0.0, 0.0, 1.0,
result
);
result._updateIdentityStatus(c === 1 && s === 0);
}
/**
* Creates a new rotation matrix for "angle" radians around the Y axis
* @param angle defines the angle (in radians) to use
* @return the new matrix
*/
public static RotationY(angle: number): Matrix {
const result = new Matrix();
Matrix.RotationYToRef(angle, result);
return result;
}
/**
* Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
* @param angle defines the angle (in radians) to use
* @param result defines the target matrix
*/
public static RotationYToRef(angle: number, result: Matrix): void {
const s = Math.sin(angle);
const c = Math.cos(angle);
Matrix.FromValuesToRef(
c, 0.0, -s, 0.0,
0.0, 1.0, 0.0, 0.0,
s, 0.0, c, 0.0,
0.0, 0.0, 0.0, 1.0,
result
);
result._updateIdentityStatus(c === 1 && s === 0);
}
/**
* Creates a new rotation matrix for "angle" radians around the Z axis
* @param angle defines the angle (in radians) to use
* @return the new matrix
*/
public static RotationZ(angle: number): Matrix {
const result = new Matrix();
Matrix.RotationZToRef(angle, result);
return result;
}
/**
* Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
* @param angle defines the angle (in radians) to use
* @param result defines the target matrix
*/
public static RotationZToRef(angle: number, result: Matrix): void {
const s = Math.sin(angle);
const c = Math.cos(angle);
Matrix.FromValuesToRef(
c, s, 0.0, 0.0,
-s, c, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0,
result
);
result._updateIdentityStatus(c === 1 && s === 0);
}
/**
* Creates a new rotation matrix for "angle" radians around the given axis
* @param axis defines the axis to use
* @param angle defines the angle (in radians) to use
* @return the new matrix
*/
public static RotationAxis(axis: Vector3, angle: number): Matrix {
const result = new Matrix();
Matrix.RotationAxisToRef(axis, angle, result);
return result;
}
/**
* Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
* @param axis defines the axis to use
* @param angle defines the angle (in radians) to use
* @param result defines the target matrix
*/
public static RotationAxisToRef(axis: Vector3, angle: number, result: Matrix): void {
const s = Math.sin(-angle);
const c = Math.cos(-angle);
const c1 = 1 - c;
axis.normalize();
const m = result._m;
m[0] = (axis.x * axis.x) * c1 + c;
m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
m[3] = 0.0;
m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
m[5] = (axis.y * axis.y) * c1 + c;
m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
m[7] = 0.0;
m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
m[10] = (axis.z * axis.z) * c1 + c;
m[11] = 0.0;
m[12] = 0.0;
m[13] = 0.0;
m[14] = 0.0;
m[15] = 1.0;
result._markAsUpdated();
}
/**
* Creates a rotation matrix
* @param yaw defines the yaw angle in radians (Y axis)
* @param pitch defines the pitch angle in radians (X axis)
* @param roll defines the roll angle in radians (X axis)
* @returns the new rotation matrix
*/
public static RotationYawPitchRoll(yaw: number, pitch: number, roll: number): Matrix {
const result = new Matrix();
Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
return result;
}
/**
* Creates a rotation matrix and stores it in a given matrix
* @param yaw defines the yaw angle in radians (Y axis)
* @param pitch defines the pitch angle in radians (X axis)
* @param roll defines the roll angle in radians (X axis)
* @param result defines the target matrix
*/
public static RotationYawPitchRollToRef(yaw: number, pitch: number, roll: number, result: Matrix): void {
Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, MathTmp.Quaternion[0]);
MathTmp.Quaternion[0].toRotationMatrix(result);
}
/**
* Creates a scaling matrix
* @param x defines the scale factor on X axis
* @param y defines the scale factor on Y axis
* @param z defines the scale factor on Z axis
* @returns the new matrix
*/
public static Scaling(x: number, y: number, z: number): Matrix {
const result = new Matrix();
Matrix.ScalingToRef(x, y, z, result);
return result;
}
/**
* Creates a scaling matrix and stores it in a given matrix
* @param x defines the scale factor on X axis
* @param y defines the scale factor on Y axis
* @param z defines the scale factor on Z axis
* @param result defines the target matrix
*/
public static ScalingToRef(x: number, y: number, z: number, result: Matrix): void {
Matrix.FromValuesToRef(
x, 0.0, 0.0, 0.0,
0.0, y, 0.0, 0.0,
0.0, 0.0, z, 0.0,
0.0, 0.0, 0.0, 1.0,
result
);
result._updateIdentityStatus(x === 1 && y === 1 && z === 1);
}
/**
* Creates a translation matrix
* @param x defines the translation on X axis
* @param y defines the translation on Y axis
* @param z defines the translationon Z axis
* @returns the new matrix
*/
public static Translation(x: number, y: number, z: number): Matrix {
const result = new Matrix();
Matrix.TranslationToRef(x, y, z, result);
return result;
}
/**
* Creates a translation matrix and stores it in a given matrix
* @param x defines the translation on X axis
* @param y defines the translation on Y axis
* @param z defines the translationon Z axis
* @param result defines the target matrix
*/
public static TranslationToRef(x: number, y: number, z: number, result: Matrix): void {
Matrix.FromValuesToRef(
1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
x, y, z, 1.0,
result
);
result._updateIdentityStatus(x === 0 && y === 0 && z === 0);
}
/**
* Returns a new Matrix whose values are the interpolated values for "gradient" (float)
* between the ones of the matrices "startValue" and "endValue".
* @param startValue defines the start value
* @param endValue defines the end value
* @param gradient defines the gradient factor
* @returns the new matrix
*/
public static Lerp(startValue: Matrix, endValue: Matrix, gradient: number): Matrix {
const result = new Matrix();
Matrix.LerpToRef(startValue, endValue, gradient, result);
return result;
}
/**
* Set the given matrix "result" as the interpolated values for "gradient" (float)
* between the ones of the matrices "startValue" and "endValue".
* @param startValue defines the start value
* @param endValue defines the end value
* @param gradient defines the gradient factor
* @param result defines the Matrix object where to store data
*/
public static LerpToRef(startValue: Matrix, endValue: Matrix, gradient: number, result: Matrix): void {
for (let index = 0; index < 16; index++) {
result._m[index] = startValue._m[index] * (1.0 - gradient) + endValue._m[index] * gradient;
}
result._markAsUpdated();
}
/**
* Builds a new matrix whose values are computed by:
* * decomposing the the "startValue" and "endValue" matrices into their
* respective scale, rotation and translation matrices
* * interpolating for "gradient" (float) the values between each of these decomposed
* matrices between the start and the end
* * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
* @param startValue defines the first matrix
* @param endValue defines the second matrix
* @param gradient defines the gradient between the two matrices
* @returns the new matrix
*/
public static DecomposeLerp(startValue: Matrix, endValue: Matrix, gradient: number): Matrix {
const result = new Matrix();
Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
return result;
}
/**
* Update a matrix to values which are computed by:
* * decomposing the the "startValue" and "endValue" matrices into their respective
* scale, rotation and translation matrices
* * interpolating for "gradient" (float) the values between each of these decomposed
* matrices between the start and the end
* * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
* @param startValue defines the first matrix
* @param endValue defines the second matrix
* @param gradient defines the gradient between the two matrices
* @param result defines the target matrix
*/
public static DecomposeLerpToRef(startValue: Matrix, endValue: Matrix, gradient: number, result: Matrix) {
const startScale = MathTmp.Vector3[0];
const startRotation = MathTmp.Quaternion[0];
const startTranslation = MathTmp.Vector3[1];
startValue.decompose(startScale, startRotation, startTranslation);
const endScale = MathTmp.Vector3[2];
const endRotation = MathTmp.Quaternion[1];
const endTranslation = MathTmp.Vector3[3];
endValue.decompose(endScale, endRotation, endTranslation);
const resultScale = MathTmp.Vector3[4];
Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
const resultRotation = MathTmp.Quaternion[2];
Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
const resultTranslation = MathTmp.Vector3[5];
Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
}
/**
* Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3,
* from the eye vector3 position, the up vector3 being oriented like "up"
* This function works in left handed mode
* @param eye defines the final position of the entity
* @param target defines where the entity should look at
* @param up defines the up vector for the entity
* @returns the new matrix
*/
public static LookAtLH(eye: Vector3, target: Vector3, up: Vector3): Matrix {
const result = new Matrix();
Matrix.LookAtLHToRef(eye, target, up, result);
return result;
}
/**
* Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks
* at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
* This function works in left handed mode
* @param eye defines the final position of the entity
* @param target defines where the entity should look at
* @param up defines the up vector for the entity
* @param result defines the target matrix
*/
public static LookAtLHToRef(eye: Vector3, target: Vector3, up: Vector3, result: Matrix): void {
const xAxis = MathTmp.Vector3[0];
const yAxis = MathTmp.Vector3[1];
const zAxis = MathTmp.Vector3[2];
// Z axis
target.subtractToRef(eye, zAxis);
zAxis.normalize();
// X axis
Vector3.CrossToRef(up, zAxis, xAxis);
const xSquareLength = xAxis.lengthSquared();
if (xSquareLength === 0) {
xAxis.x = 1.0;
} else {
xAxis.normalizeFromLength(Math.sqrt(xSquareLength));
}
// Y axis
Vector3.CrossToRef(zAxis, xAxis, yAxis);
yAxis.normalize();
// Eye angles
const ex = -Vector3.Dot(xAxis, eye);
const ey = -Vector3.Dot(yAxis, eye);
const ez = -Vector3.Dot(zAxis, eye);
Matrix.FromValuesToRef(
xAxis.x, yAxis.x, zAxis.x, 0.0,
xAxis.y, yAxis.y, zAxis.y, 0.0,
xAxis.z, yAxis.z, zAxis.z, 0.0,
ex, ey, ez, 1.0,
result
);
}
/**
* Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3,
* from the eye vector3 position, the up vector3 being oriented like "up"
* This function works in right handed mode
* @param eye defines the final position of the entity
* @param target defines where the entity should look at
* @param up defines the up vector for the entity
* @returns the new matrix
*/
public static LookAtRH(eye: Vector3, target: Vector3, up: Vector3): Matrix {
const result = new Matrix();
Matrix.LookAtRHToRef(eye, target, up, result);
return result;
}
/**
* Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks
* at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
* This function works in right handed mode
* @param eye defines the final position of the entity
* @param target defines where the entity should look at
* @param up defines the up vector for the entity
* @param result defines the target matrix
*/
public static LookAtRHToRef(eye: Vector3, target: Vector3, up: Vector3, result: Matrix): void {
const xAxis = MathTmp.Vector3[0];
const yAxis = MathTmp.Vector3[1];
const zAxis = MathTmp.Vector3[2];
// Z axis
eye.subtractToRef(target, zAxis);
zAxis.normalize();
// X axis
Vector3.CrossToRef(up, zAxis, xAxis);
const xSquareLength = xAxis.lengthSquared();
if (xSquareLength === 0) {
xAxis.x = 1.0;
} else {
xAxis.normalizeFromLength(Math.sqrt(xSquareLength));
}
// Y axis
Vector3.CrossToRef(zAxis, xAxis, yAxis);
yAxis.normalize();
// Eye angles
const ex = -Vector3.Dot(xAxis, eye);
const ey = -Vector3.Dot(yAxis, eye);
const ez = -Vector3.Dot(zAxis, eye);
Matrix.FromValuesToRef(
xAxis.x, yAxis.x, zAxis.x, 0.0,
xAxis.y, yAxis.y, zAxis.y, 0.0,
xAxis.z, yAxis.z, zAxis.z, 0.0,
ex, ey, ez, 1.0,
result
);
}
/**
* Create a left-handed orthographic projection matrix
* @param width defines the viewport width
* @param height defines the viewport height
* @param znear defines the near clip plane
* @param zfar defines the far clip plane
* @returns a new matrix as a left-handed orthographic projection matrix
*/
public static OrthoLH(width: number, height: number, znear: number, zfar: number): Matrix {
const matrix = new Matrix();
Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
return matrix;
}
/**
* Store a left-handed orthographic projection to a given matrix
* @param width defines the viewport width
* @param height defines the viewport height
* @param znear defines the near clip plane
* @param zfar defines the far clip plane
* @param result defines the target matrix
*/
public static OrthoLHToRef(width: number, height: number, znear: number, zfar: number, result: Matrix): void {
const n = znear;
const f = zfar;
const a = 2.0 / width;
const b = 2.0 / height;
const c = 2.0 / (f - n);
const d = -(f + n) / (f - n);
Matrix.FromValuesToRef(
a, 0.0, 0.0, 0.0,
0.0, b, 0.0, 0.0,
0.0, 0.0, c, 0.0,
0.0, 0.0, d, 1.0,
result
);
result._updateIdentityStatus(a === 1 && b === 1 && c === 1 && d === 0);
}
/**
* Create a left-handed orthographic projection matrix
* @param left defines the viewport left coordinate
* @param right defines the viewport right coordinate
* @param bottom defines the viewport bottom coordinate
* @param top defines the viewport top coordinate
* @param znear defines the near clip plane
* @param zfar defines the far clip plane
* @returns a new matrix as a left-handed orthographic projection matrix
*/
public static OrthoOffCenterLH(
left: number, right: number,
bottom: number, top: number,
znear: number, zfar: number): Matrix {
const matrix = new Matrix();
Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
return matrix;
}
/**
* Stores a left-handed orthographic projection into a given matrix
* @param left defines the viewport left coordinate
* @param right defines the viewport right coordinate
* @param bottom defines the viewport bottom coordinate
* @param top defines the viewport top coordinate
* @param znear defines the near clip plane
* @param zfar defines the far clip plane
* @param result defines the target matrix
*/
public static OrthoOffCenterLHToRef(
left: number, right: number,
bottom: number, top: number,
znear: number, zfar: number,
result: Matrix): void {
const n = znear;
const f = zfar;
const a = 2.0 / (right - left);
const b = 2.0 / (top - bottom);
const c = 2.0 / (f - n);
const d = -(f + n) / (f - n);
const i0 = (left + right) / (left - right);
const i1 = (top + bottom) / (bottom - top);
Matrix.FromValuesToRef(
a, 0.0, 0.0, 0.0,
0.0, b, 0.0, 0.0,
0.0, 0.0, c, 0.0,
i0, i1, d, 1.0,
result
);
result._markAsUpdated();
}
/**
* Creates a right-handed orthographic projection matrix
* @param left defines the viewport left coordinate
* @param right defines the viewport right coordinate
* @param bottom defines the viewport bottom coordinate
* @param top defines the viewport top coordinate
* @param znear defines the near clip plane
* @param zfar defines the far clip plane
* @returns a new matrix as a right-handed orthographic projection matrix
*/
public static OrthoOffCenterRH(
left: number, right: number,
bottom: number, top: number,
znear: number, zfar: number): Matrix {
const matrix = new Matrix();
Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
return matrix;
}
/**
* Stores a right-handed orthographic projection into a given matrix
* @param left defines the viewport left coordinate
* @param right defines the viewport right coordinate
* @param bottom defines the viewport bottom coordinate
* @param top defines the viewport top coordinate
* @param znear defines the near clip plane
* @param zfar defines the far clip plane
* @param result defines the target matrix
*/
public static OrthoOffCenterRHToRef(
left: number, right: number,
bottom: number, top: number,
znear: number, zfar: number,
result: Matrix): void {
Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
// No need to call _markAsUpdated as previous function already called it and let _isIdentityDirty to true
result._m[10] *= -1;
}
/**
* Creates a left-handed perspective projection matrix
* @param width defines the viewport width
* @param height defines the viewport height
* @param znear defines the near clip plane
* @param zfar defines the far clip plane
* @returns a new matrix as a left-handed perspective projection matrix
*/
public static PerspectiveLH(width: number, height: number, znear: number, zfar: number): Matrix {
const matrix = new Matrix();
const n = znear;
const f = zfar;
const a = 2.0 * n / width;
const b = 2.0 * n / height;
const c = (f + n) / (f - n);
const d = -2.0 * f * n / (f - n);
Matrix.FromValuesToRef(
a, 0.0, 0.0, 0.0,
0.0, b, 0.0, 0.0,
0.0, 0.0, c, 1.0,
0.0, 0.0, d, 0.0,
matrix
);
matrix._updateIdentityStatus(false);
return matrix;
}
/**
* Creates a left-handed perspective projection matrix
* @param fov defines the horizontal field of view
* @param aspect defines the aspect ratio
* @param znear defines the near clip plane
* @param zfar defines the far clip plane
* @returns a new matrix as a left-handed perspective projection matrix
*/
public static PerspectiveFovLH(fov: number, aspect: number, znear: number, zfar: number): Matrix {
const matrix = new Matrix();
Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
return matrix;
}
/**
* Stores a left-handed perspective projection into a given matrix
* @param fov defines the horizontal field of view
* @param aspect defines the aspect ratio
* @param znear defines the near clip plane
* @param zfar defines the far clip plane
* @param result defines the target matrix
* @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
*/
public static PerspectiveFovLHToRef(
fov: number, aspect: number,
znear: number, zfar: number,
result: Matrix, isVerticalFovFixed = true): void {
const n = znear;
const f = zfar;
const t = 1.0 / (Math.tan(fov * 0.5));
const a = isVerticalFovFixed ? (t / aspect) : t;
const b = isVerticalFovFixed ? t : (t * aspect);
const c = (f + n) / (f - n);
const d = -2.0 * f * n / (f - n);
Matrix.FromValuesToRef(
a, 0.0, 0.0, 0.0,
0.0, b, 0.0, 0.0,
0.0, 0.0, c, 1.0,
0.0, 0.0, d, 0.0,
result
);
result._updateIdentityStatus(false);
}
/**
* Creates a right-handed perspective projection matrix
* @param fov defines the horizontal field of view
* @param aspect defines the aspect ratio
* @param znear defines the near clip plane
* @param zfar defines the far clip plane
* @returns a new matrix as a right-handed perspective projection matrix
*/
public static PerspectiveFovRH(fov: number, aspect: number, znear: number, zfar: number): Matrix {
const matrix = new Matrix();
Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
return matrix;
}
/**
* Stores a right-handed perspective projection into a given matrix
* @param fov defines the horizontal field of view
* @param aspect defines the aspect ratio
* @param znear defines the near clip plane
* @param zfar defines the far clip plane
* @param result defines the target matrix
* @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
*/
public static PerspectiveFovRHToRef(
fov: number, aspect: number,
znear: number, zfar: number,
result: Matrix, isVerticalFovFixed = true): void {
// alternatively this could be expressed as:
// m = PerspectiveFovLHToRef
// m[10] *= -1.0;
// m[11] *= -1.0;
const n = znear;
const f = zfar;
const t = 1.0 / (Math.tan(fov * 0.5));
const a = isVerticalFovFixed ? (t / aspect) : t;
const b = isVerticalFovFixed ? t : (t * aspect);
const c = -(f + n) / (f - n);
const d = -2 * f * n / (f - n);
Matrix.FromValuesToRef(
a, 0.0, 0.0, 0.0,
0.0, b, 0.0, 0.0,
0.0, 0.0, c, -1.0,
0.0, 0.0, d, 0.0,
result
);
result._updateIdentityStatus(false);
}
/**
* Stores a perspective projection for WebVR info a given matrix
* @param fov defines the field of view
* @param znear defines the near clip plane
* @param zfar defines the far clip plane
* @param result defines the target matrix
* @param rightHanded defines if the matrix must be in right-handed mode (false by default)
*/
public static PerspectiveFovWebVRToRef(
fov: {
upDegrees: number, downDegrees: number,
leftDegrees: number, rightDegrees: number
},
znear: number, zfar: number,
result: Matrix, rightHanded = false): void {
const rightHandedFactor = rightHanded ? -1 : 1;
const upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
const downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
const leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
const rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
const xScale = 2.0 / (leftTan + rightTan);
const yScale = 2.0 / (upTan + downTan);
const m = result._m;
m[0] = xScale;
m[1] = m[2] = m[3] = m[4] = 0.0;
m[5] = yScale;
m[6] = m[7] = 0.0;
m[8] = ((leftTan - rightTan) * xScale * 0.5);
m[9] = -((upTan - downTan) * yScale * 0.5);
m[10] = -zfar / (znear - zfar);
m[11] = 1.0 * rightHandedFactor;
m[12] = m[13] = m[15] = 0.0;
m[14] = -(2.0 * zfar * znear) / (zfar - znear);
result._markAsUpdated();
}
/**
* Computes a complete transformation matrix
* @param viewport defines the viewport to use
* @param world defines the world matrix
* @param view defines the view matrix
* @param projection defines the projection matrix
* @param zmin defines the near clip plane
* @param zmax defines the far clip plane
* @returns the transformation matrix
*/
public static GetFinalMatrix(
viewport: Viewport, world: Matrix, view: Matrix, projection: Matrix,
zmin: number, zmax: number): Matrix {
const cw = viewport.width;
const ch = viewport.height;
const cx = viewport.x;
const cy = viewport.y;
const viewportMatrix = Matrix.FromValues(
cw / 2.0, 0.0, 0.0, 0.0,
0.0, -ch / 2.0, 0.0, 0.0,
0.0, 0.0, zmax - zmin, 0.0,
cx + cw / 2.0, ch / 2.0 + cy, zmin, 1.0);
const matrix = MathTmp.Matrix[0];
world.multiplyToRef(view, matrix);
matrix.multiplyToRef(projection, matrix);
return matrix.multiply(viewportMatrix);
}
/**
* Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
* @param matrix defines the matrix to use
* @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
*/
public static GetAsMatrix2x2(matrix: Matrix): Float32Array {
return new Float32Array([
matrix._m[0], matrix._m[1],
matrix._m[4], matrix._m[5]
]);
}
/**
* Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
* @param matrix defines the matrix to use
* @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
*/
public static GetAsMatrix3x3(matrix: Matrix): Float32Array {
return new Float32Array([
matrix._m[0], matrix._m[1], matrix._m[2],
matrix._m[4], matrix._m[5], matrix._m[6],
matrix._m[8], matrix._m[9], matrix._m[10]
]);
}
/**
* Compute the transpose of a given matrix
* @param matrix defines the matrix to transpose
* @returns the new matrix
*/
public static Transpose(matrix: Matrix): Matrix {
const result = new Matrix();
Matrix.TransposeToRef(matrix, result);
return result;
}
/**
* Compute the transpose of a matrix and store it in a target matrix
* @param matrix defines the matrix to transpose
* @param result defines the target matrix
*/
public static TransposeToRef(matrix: Matrix, result: Matrix): void {
const rm = result._m;
const mm = matrix._m;
rm[0] = mm[0];
rm[1] = mm[4];
rm[2] = mm[8];
rm[3] = mm[12];
rm[4] = mm[1];
rm[5] = mm[5];
rm[6] = mm[9];
rm[7] = mm[13];
rm[8] = mm[2];
rm[9] = mm[6];
rm[10] = mm[10];
rm[11] = mm[14];
rm[12] = mm[3];
rm[13] = mm[7];
rm[14] = mm[11];
rm[15] = mm[15];
// identity-ness does not change when transposing
result._updateIdentityStatus(matrix._isIdentity, matrix._isIdentityDirty);
}
/**
* Computes a reflection matrix from a plane
* @param plane defines the reflection plane
* @returns a new matrix
*/
public static Reflection(plane: Plane): Matrix {
const matrix = new Matrix();
Matrix.ReflectionToRef(plane, matrix);
return matrix;
}
/**
* Computes a reflection matrix from a plane
* @param plane defines the reflection plane
* @param result defines the target matrix
*/
public static ReflectionToRef(plane: Plane, result: Matrix): void {
plane.normalize();
const x = plane.normal.x;
const y = plane.normal.y;
const z = plane.normal.z;
const temp = -2 * x;
const temp2 = -2 * y;
const temp3 = -2 * z;
Matrix.FromValuesToRef(
temp * x + 1, temp2 * x, temp3 * x, 0.0,
temp * y, temp2 * y + 1, temp3 * y, 0.0,
temp * z, temp2 * z, temp3 * z + 1, 0.0,
temp * plane.d, temp2 * plane.d, temp3 * plane.d, 1.0,
result
);
}
/**
* Sets the given matrix as a rotation matrix composed from the 3 left handed axes
* @param xaxis defines the value of the 1st axis
* @param yaxis defines the value of the 2nd axis
* @param zaxis defines the value of the 3rd axis
* @param result defines the target matrix
*/
public static FromXYZAxesToRef(xaxis: Vector3, yaxis: Vector3, zaxis: Vector3, result: Matrix) {
Matrix.FromValuesToRef(
xaxis.x, xaxis.y, xaxis.z, 0.0,
yaxis.x, yaxis.y, yaxis.z, 0.0,
zaxis.x, zaxis.y, zaxis.z, 0.0,
0.0, 0.0, 0.0, 1.0,
result
);
}
/**
* Creates a rotation matrix from a quaternion and stores it in a target matrix
* @param quat defines the quaternion to use
* @param result defines the target matrix
*/
public static FromQuaternionToRef(quat: Quaternion, result: Matrix) {
const xx = quat.x * quat.x;
const yy = quat.y * quat.y;
const zz = quat.z * quat.z;
const xy = quat.x * quat.y;
const zw = quat.z * quat.w;
const zx = quat.z * quat.x;
const yw = quat.y * quat.w;
const yz = quat.y * quat.z;
const xw = quat.x * quat.w;
result._m[0] = 1.0 - (2.0 * (yy + zz));
result._m[1] = 2.0 * (xy + zw);
result._m[2] = 2.0 * (zx - yw);
result._m[3] = 0.0;
result._m[4] = 2.0 * (xy - zw);
result._m[5] = 1.0 - (2.0 * (zz + xx));
result._m[6] = 2.0 * (yz + xw);
result._m[7] = 0.0;
result._m[8] = 2.0 * (zx + yw);
result._m[9] = 2.0 * (yz - xw);
result._m[10] = 1.0 - (2.0 * (yy + xx));
result._m[11] = 0.0;
result._m[12] = 0.0;
result._m[13] = 0.0;
result._m[14] = 0.0;
result._m[15] = 1.0;
result._markAsUpdated();
}
} | the_stack |
let state: string
let timer: number
let gesturesRunning: boolean
let wasShake: boolean
let wasLogoUp: boolean
let wasLogoDown: boolean
let wasScreenUp: boolean
let wasScreenDown: boolean
while (true) {
splashScreen()
if (input.buttonIsPressed(Button.B)) {
// animate: add pancake
basic.showAnimation(`
# # # # # # . . . # . . . . . . . . . . . . . . .
. . . . . . # # # . . # # # . . . . . . . . . . .
. . . . . . . . . . # . . . # # . . . # . . . . .
. . . . . . . . . . . . . . . . # # # . . # # # .
. . . . . . . . . . . . . . . . . . . . # . . . #
`, 250)
runGameOnce()
// animate: pancake done
basic.showAnimation(`
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # # # . # # # # # . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . # . . . # # # # # # # . . . # . . . . . . . . . . . # . # . . . . . . . # . # . . . . . .
. . . . . . . . . . . # # # . # # # # # . # # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
# . . . # # # # # # # . . . # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. # # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
`, 250)
} else if (input.buttonIsPressed(Button.A)) {
testShake()
}
}
/**
* Runs one complete game from start to end
*/
function runGameOnce() {
let score = 0
let cooks = 0
let target_time = 0
// make sure no gestures are outstanding from last game
wasShake = false
wasLogoUp = false
wasLogoDown = false
wasScreenUp = false
wasScreenDown = false
state = "NEWSIDE"
while (true) {
// Handle any gestures that can happen at any time
let gesture = getGesture()
if (gesture == "FLOOR") {
state = "DROPPED"
}
// Run code appropriate to the present state of the game
if (state == "NEWSIDE") {
target_time = 5 + Math.randomInt(5)
state = "COOKING"
startTimer()
} else if (state == "COOKING") {
// animate: cooking
basic.showAnimation(`
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . # . . . . . . . . . . . . . #
# # # # # . # # # # # # # # # # # # # .
`, 100)
if (gesture == "FLIP") {
state = "FLIPPING"
} else if (getTimerSec() >= target_time) {
state = "READY"
score = score + 1
startTimer()
}
} else if (state == "READY") {
// animate: ready
basic.showAnimation(`
. . . . .
. . . . .
. . . . .
# . . . #
. # # # .
`, 100)
if (getTimerSec() > 2) {
state = "BURNING"
score = score - 1
startTimer()
} else if (gesture == "FLIP") {
state = "FLIPPING"
}
} else if (state == "BURNING") {
// animate: burning
basic.showAnimation(`
. . . . . . . . . . . . . # . . . . # .
. . . . . . . . # . . # . # . . # . . .
. . . . . . # . # . . # . . . . . . . .
. . . . . . # . . . . . . . . . . . . .
# # # # # # # # # # # # # # # # # # # #
`, 100)
if (gesture == "SKY") {
state = "NEWSIDE"
} else if (getTimerSec() > 2) {
state = "BURNT"
}
} else if (state == "FLIPPING") {
// animate: flipping
basic.showAnimation(`
. . . . . . . . . . . . . . . . . . . . # . . . . . . . . . . . . . # . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . # # # # # . # # . . . # # # . . . # # . # # # # # . . . . . . . . . .
. . . . . . . . . . # # # # # . . . . . . . . # # . # # # . # # . . . . . . . . # # # # # . . . . .
. . . . . # # # # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # # # # #
# # # # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
`, 100)
// Prevent a spurious double-flip from happening
wasShake = false
cooks = cooks + 1
if (cooks == 5) {
state = "GAMEOVER"
} else {
state = "NEWSIDE"
}
} else if (state == "DROPPED") {
// animate: dropped
basic.showAnimation(`
# . . . # . . . . . # . . . # . . . . .
. # . # . . . . . . . # . # . . . . . .
. . # . . . . . . . . . # . . . . . . .
. # . # . . . . . . . # . # . . . . . .
# . . . # . . . . . # . . . # . . . . .
`, 250)
score = 0
state = "GAMEOVER"
} else if (state == "BURNT") {
// animate: burnt
basic.showAnimation(`
. . . . . . . . . . . . . . . . . . . . . . # . . . . . . . . # . # . . . . . . . # # # .
. . . . . . . . . . . . . . . . . # . . . . . . . . # . # . . . . . . . # # # . . . . . .
. . . . . . . . . . . . . . . . . . . . . # . # . . . . . . . # # # . . . . . . . . . . .
. . . . . . # . # . . # # # . . # . # . . . . . . . # # # . . . . . . . . . . . . . . . .
# # # # # . # # # . . # # # . . # # # . . # # # . . . . . . . . . . . . . . . . . . . . .
`, 250)
score = 0
state = "GAMEOVER"
} else if (state == "GAMEOVER") {
animateScore(score)
state = "WAITEJECT"
} else if (state == "WAITEJECT") {
if (gesture == "UPSIDEDOWN") {
return
}
}
}
}
/**
* show score (0..9) flashing
* @param score TODO
*/
function animateScore(score: number) {
score = Math.clamp(0, 9, score)
for (let i = 0; i < 5; i++) {
basic.showNumber(score, 0)
basic.pause(500)
basic.clearScreen()
basic.pause(500)
}
basic.showNumber(score, 0)
}
/**
* NOTE: Eventually this will move into a gesture library
* It hides all the nasty detail of detecting gestures
*/
function getGesture(): string {
if (!gesturesRunning) {
input.onShake(() => {
wasShake = true
})
input.onLogoUp(() => {
wasLogoUp = true
})
input.onLogoDown(() => {
wasLogoDown = true
})
input.onScreenUp(() => {
wasScreenUp = true
})
input.onScreenDown(() => {
wasScreenDown = true
})
gesturesRunning = true
}
// work out which of a possible set of gestures has occurred:
// Button gestures and movement gestures both handled
// This is so that it is easy to also use this on the simulator too
// Generally, B is used for normal OK, A is used for abnormal RECOVERY
// (flip is a normal action, touch sky to turn off smoke alarm is recovery)
let a = input.buttonIsPressed(Button.A)
let b = input.buttonIsPressed(Button.B)
if (state == "COOKING" || state == "READY") {
if (b || wasShake) {
wasShake = false
return "FLIP"
}
} else if (state == "FLIPPING") {
if (a || wasLogoDown) {
wasLogoDown = false
return "FLOOR"
}
} else if (state == "BURNING") {
if (a || wasLogoUp) {
wasLogoUp = false
return "SKY"
}
} else if (state == "GAMEOVER" || state == "WAITEJECT") {
if (b || wasScreenDown) {
wasScreenDown = false
return "UPSIDEDOWN"
}
}
return "NONE"
}
/**
* start timer by sampling runningtime and storing into starttime
*/
function startTimer() {
timer = input.runningTime()
}
/**
* get the elapsed time from the global starttime with ref to running time
* in seconds.
*/
function getTimerSec(): number {
let t = (input.runningTime() - timer) / 1000
return t
}
/**
* Show a splash screen "Perfect Pancakes >>>"
* Splash screen "PP" with little arrow pointing to the start button
*/
function splashScreen() {
let splash = images.createImage(`
# # # # . . . . . . # # # # . . . . . . . . . . . . . . . . . . . . .
# . . . # . . . . . # . . . # # . . . . . # . . . . . # . . . . . # .
# # # # . . . . . . # # # # . . # . . . . . # . . . . . # . . . . . #
# . . . . . . . . . # . . . . # . . . . . # . . . . . # . . . . . # .
# . . . . . . . . . # . . . . . . . . . . . . . . . . . . . . . . . .
`)
// use show image (not show animation) so that button press is more responsive
let index = 0
// Any button press finishes the splash screen
while (!input.buttonIsPressed(Button.B) && !input.buttonIsPressed(Button.A)) {
splash.showImage(index * 5)
index = index + 1
if (index > splash.width() / 5) {
index = 0
}
basic.pause(250)
}
}
function testShake() { } | the_stack |
import {BooleanInput, coerceBooleanProperty} from '@angular/cdk/coercion';
import {TAB} from '@angular/cdk/keycodes';
import {
AfterContentInit,
ChangeDetectionStrategy,
Component,
ContentChildren,
EventEmitter,
forwardRef,
Input,
OnDestroy,
Output,
QueryList,
ViewEncapsulation,
} from '@angular/core';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms';
import {Observable} from 'rxjs';
import {startWith, takeUntil} from 'rxjs/operators';
import {MatChip, MatChipEvent} from './chip';
import {MatChipOption, MatChipSelectionChange} from './chip-option';
import {MatChipSet} from './chip-set';
/** Change event object that is emitted when the chip listbox value has changed. */
export class MatChipListboxChange {
constructor(
/** Chip listbox that emitted the event. */
public source: MatChipListbox,
/** Value of the chip listbox when the event was emitted. */
public value: any,
) {}
}
/**
* Provider Expression that allows mat-chip-listbox to register as a ControlValueAccessor.
* This allows it to support [(ngModel)].
* @docs-private
*/
export const MAT_CHIP_LISTBOX_CONTROL_VALUE_ACCESSOR: any = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => MatChipListbox),
multi: true,
};
/**
* An extension of the MatChipSet component that supports chip selection.
* Used with MatChipOption chips.
*/
@Component({
selector: 'mat-chip-listbox',
template: `
<span class="mdc-evolution-chip-set__chips" role="presentation">
<ng-content></ng-content>
</span>
`,
styleUrls: ['chip-set.css'],
inputs: ['tabIndex'],
host: {
'class': 'mdc-evolution-chip-set mat-mdc-chip-listbox',
'[attr.role]': 'role',
'[tabIndex]': 'empty ? -1 : tabIndex',
// TODO: replace this binding with use of AriaDescriber
'[attr.aria-describedby]': '_ariaDescribedby || null',
'[attr.aria-required]': 'role ? required : null',
'[attr.aria-disabled]': 'disabled.toString()',
'[attr.aria-multiselectable]': 'multiple',
'[attr.aria-orientation]': 'ariaOrientation',
'[class.mat-mdc-chip-list-disabled]': 'disabled',
'[class.mat-mdc-chip-list-required]': 'required',
'(focus)': 'focus()',
'(blur)': '_blur()',
'(keydown)': '_keydown($event)',
},
providers: [MAT_CHIP_LISTBOX_CONTROL_VALUE_ACCESSOR],
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class MatChipListbox
extends MatChipSet
implements AfterContentInit, OnDestroy, ControlValueAccessor
{
/**
* Function when touched. Set as part of ControlValueAccessor implementation.
* @docs-private
*/
_onTouched = () => {};
/**
* Function when changed. Set as part of ControlValueAccessor implementation.
* @docs-private
*/
_onChange: (value: any) => void = () => {};
// TODO: MDC uses `grid` here
protected override _defaultRole = 'listbox';
/** Whether the user should be allowed to select multiple chips. */
@Input()
get multiple(): boolean {
return this._multiple;
}
set multiple(value: BooleanInput) {
this._multiple = coerceBooleanProperty(value);
this._syncListboxProperties();
}
private _multiple: boolean = false;
/** The array of selected chips inside the chip listbox. */
get selected(): MatChipOption[] | MatChipOption {
const selectedChips = this._chips.toArray().filter(chip => chip.selected);
return this.multiple ? selectedChips : selectedChips[0];
}
/** Orientation of the chip list. */
@Input('aria-orientation') ariaOrientation: 'horizontal' | 'vertical' = 'horizontal';
/**
* Whether or not this chip listbox is selectable.
*
* When a chip listbox is not selectable, the selected states for all
* the chips inside the chip listbox are always ignored.
*/
@Input()
get selectable(): boolean {
return this._selectable;
}
set selectable(value: BooleanInput) {
this._selectable = coerceBooleanProperty(value);
this._syncListboxProperties();
}
protected _selectable: boolean = true;
/**
* A function to compare the option values with the selected values. The first argument
* is a value from an option. The second is a value from the selection. A boolean
* should be returned.
*/
@Input() compareWith: (o1: any, o2: any) => boolean = (o1: any, o2: any) => o1 === o2;
/** Whether this chip listbox is required. */
@Input()
get required(): boolean {
return this._required;
}
set required(value: BooleanInput) {
this._required = coerceBooleanProperty(value);
}
protected _required: boolean = false;
/** Combined stream of all of the child chips' selection change events. */
get chipSelectionChanges(): Observable<MatChipSelectionChange> {
return this._getChipStream<MatChipSelectionChange, MatChipOption>(chip => chip.selectionChange);
}
/** Combined stream of all of the child chips' blur events. */
get chipBlurChanges(): Observable<MatChipEvent> {
return this._getChipStream(chip => chip._onBlur);
}
/** The value of the listbox, which is the combined value of the selected chips. */
@Input()
get value(): any {
return this._value;
}
set value(value: any) {
this.writeValue(value);
this._value = value;
}
protected _value: any;
/** Event emitted when the selected chip listbox value has been changed by the user. */
@Output() readonly change: EventEmitter<MatChipListboxChange> =
new EventEmitter<MatChipListboxChange>();
@ContentChildren(MatChipOption, {
// We need to use `descendants: true`, because Ivy will no longer match
// indirect descendants if it's left as false.
descendants: true,
})
override _chips: QueryList<MatChipOption>;
ngAfterContentInit() {
this._chips.changes.pipe(startWith(null), takeUntil(this._destroyed)).subscribe(() => {
// Update listbox selectable/multiple properties on chips
this._syncListboxProperties();
});
this.chipBlurChanges.pipe(takeUntil(this._destroyed)).subscribe(() => this._blur());
this.chipSelectionChanges.pipe(takeUntil(this._destroyed)).subscribe(event => {
if (!this.multiple) {
this._chips.forEach(chip => {
if (chip !== event.source) {
chip._setSelectedState(false, false, false);
}
});
}
if (event.isUserInput) {
this._propagateChanges();
}
});
}
/**
* Focuses the first selected chip in this chip listbox, or the first non-disabled chip when there
* are no selected chips.
*/
override focus(): void {
if (this.disabled) {
return;
}
const firstSelectedChip = this._getFirstSelectedChip();
if (firstSelectedChip && !firstSelectedChip.disabled) {
firstSelectedChip.focus();
} else if (this._chips.length > 0) {
this._keyManager.setFirstItemActive();
} else {
this._elementRef.nativeElement.focus();
}
}
/**
* Implemented as part of ControlValueAccessor.
* @docs-private
*/
writeValue(value: any): void {
if (this._chips) {
this._setSelectionByValue(value, false);
}
}
/**
* Implemented as part of ControlValueAccessor.
* @docs-private
*/
registerOnChange(fn: (value: any) => void): void {
this._onChange = fn;
}
/**
* Implemented as part of ControlValueAccessor.
* @docs-private
*/
registerOnTouched(fn: () => void): void {
this._onTouched = fn;
}
/**
* Implemented as part of ControlValueAccessor.
* @docs-private
*/
setDisabledState(isDisabled: boolean): void {
this.disabled = isDisabled;
}
/** Selects all chips with value. */
_setSelectionByValue(value: any, isUserInput: boolean = true) {
this._clearSelection();
if (Array.isArray(value)) {
value.forEach(currentValue => this._selectValue(currentValue, isUserInput));
} else {
this._selectValue(value, isUserInput);
}
}
/** When blurred, marks the field as touched when focus moved outside the chip listbox. */
_blur() {
if (!this.disabled) {
// Wait to see if focus moves to an individual chip.
setTimeout(() => {
if (!this.focused) {
this._propagateChanges();
this._markAsTouched();
}
});
}
}
_keydown(event: KeyboardEvent) {
if (event.keyCode === TAB) {
super._allowFocusEscape();
}
}
/** Marks the field as touched */
private _markAsTouched() {
this._onTouched();
this._changeDetectorRef.markForCheck();
}
/** Emits change event to set the model value. */
private _propagateChanges(): void {
let valueToEmit: any = null;
if (Array.isArray(this.selected)) {
valueToEmit = this.selected.map(chip => chip.value);
} else {
valueToEmit = this.selected ? this.selected.value : undefined;
}
this._value = valueToEmit;
this.change.emit(new MatChipListboxChange(this, valueToEmit));
this._onChange(valueToEmit);
this._changeDetectorRef.markForCheck();
}
/**
* Deselects every chip in the listbox.
* @param skip Chip that should not be deselected.
*/
private _clearSelection(skip?: MatChip): void {
this._chips.forEach(chip => {
if (chip !== skip) {
chip.deselect();
}
});
}
/**
* Finds and selects the chip based on its value.
* @returns Chip that has the corresponding value.
*/
private _selectValue(value: any, isUserInput: boolean): MatChip | undefined {
const correspondingChip = this._chips.find(chip => {
return chip.value != null && this.compareWith(chip.value, value);
});
if (correspondingChip) {
isUserInput ? correspondingChip.selectViaInteraction() : correspondingChip.select();
}
return correspondingChip;
}
/** Syncs the chip-listbox selection state with the individual chips. */
private _syncListboxProperties() {
if (this._chips) {
// Defer setting the value in order to avoid the "Expression
// has changed after it was checked" errors from Angular.
Promise.resolve().then(() => {
this._chips.forEach(chip => {
chip._chipListMultiple = this.multiple;
chip.chipListSelectable = this._selectable;
chip._changeDetectorRef.markForCheck();
});
});
}
}
/** Returns the first selected chip in this listbox, or undefined if no chips are selected. */
private _getFirstSelectedChip(): MatChipOption | undefined {
if (Array.isArray(this.selected)) {
return this.selected.length ? this.selected[0] : undefined;
} else {
return this.selected;
}
}
} | the_stack |
import * as React from 'react';
import { Input, Button, Checkbox, message } from 'antd';
import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom';
import { login, register } from '@/store/actions';
import logo from "@/assets/logo_2.png";
import '@/styles/login.less';
import { validUserName, validPass } from '@/utils/valid';
import DocumentTitle from 'react-document-title';
interface IProps {
login: any,
register: any,
history: any
}
interface IState {
formLogin: {
userName: string,
userPwd: string
},
formRegister: {
userName?: string,
userPwd2?: string,
userPwd?: string,
},
typeView: number,
checked: boolean,
isLoading: boolean
}
class Login extends React.Component<IProps, IState> {
constructor(props: any) {
super(props);
this.state = {
formLogin: {
userName: '',
userPwd: '',
},
formRegister: {
userName: '',
userPwd2: '',
userPwd: '',
},
typeView: 0,
checked: false,
isLoading: false
}
}
// ่ฎพ็ฝฎcookie
setCookie = (user_name: string, user_pwd: string, exdays: number) => {
// ่ทๅๆถ้ด
let exdate = new Date();
// ไฟๅญ็ๅคฉๆฐ
exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * exdays);
// ๅญ็ฌฆไธฒๆผๆฅcookie
document.cookie = `userName=${user_name};path=/;expires=${exdate.toUTCString()}`;
document.cookie = `userPwd=${user_pwd};path=/;expires=${exdate.toUTCString()}`;
}
// ่ฏปๅcookie
getCookie = () => {
const { formLogin } = this.state;
if (document.cookie.length > 0) {
// ่ฟ้ๆพ็คบ็ๆ ผๅผ้่ฆๅๅฒไธไธ่ชๅทฑๅฏ่พๅบ็ไธ
let arr = document.cookie.split('; ');
console.log(arr)
for (let i = 0; i < arr.length; i++) {
// ๅๆฌกๅๅฒ
let arr2 = arr[i].split('=');
// ๅคๆญๆฅๆพ็ธๅฏนๅบ็ๅผ
if (arr2[0] === 'userName') {
// ไฟๅญๆฐๆฎๅนถ่ตๅผ
this.setState({
formLogin: {
userName: arr2[1],
userPwd: formLogin.userPwd
}
})
} else if (arr2[0] === 'userPwd') {
this.setState({
formLogin: {
userName: formLogin.userName,
userPwd: arr2[1]
}
})
} else {
}
}
}
}
//ๆธ
้คcookie
clearCookie = () => {
// ไฟฎๆนๅ2ไธชๅผ้ฝไธบ็ฉบ๏ผๅคฉๆฐไธบ่ด1ๅคฉๅฐฑๅฅฝไบ
this.setCookie('', '', -1);
}
// ็ซๅณ็ปๅฝ
handleLogin = () => {
const { login, history } = this.props;
const { formLogin, checked } = this.state;
if (!validUserName(formLogin.userName)) {
message.error('่ฏท่พๅ
ฅๆญฃ็กฎ็้ฎ็ฎฑ/ๆๆบๅท');
return false;
}
if (!validPass(formLogin.userPwd)) {
message.error('ๅฏ็ ๅบไธบ8ๅฐ20ไฝๅญๆฏๆๆฐๅญ๏ผ');
return false;
}
// ๅคๆญๅค้ๆกๆฏๅฆ่ขซๅพ้๏ผๅพ้ๅ่ฐ็จ้
็ฝฎcookieๆนๆณ
if (checked) {
// ไผ ๅ
ฅ่ดฆๅทๅ๏ผๅฏ็ ๏ผๅไฟๅญๅคฉๆฐ3ไธชๅๆฐ
this.setCookie(formLogin.userName, formLogin.userPwd, 7);
} else {
// ๆธ
็ฉบCookie
this.clearCookie();
}
login(
formLogin.userName,
formLogin.userPwd
)
.then((res: any) => {
console.log('login===', res);
if (res.code === 0) {
this.clearInput();
message.success('็ปๅฝๆๅ');
history.push('/');
}
})
.catch((error: any) => {
message.error(error);
})
}
// ็ซๅณๆณจๅ
handleRegister = () => {
console.log(this.props)
const { register, history } = this.props;
const { formRegister } = this.state;
if (!validUserName(formRegister.userName)) {
message.error("่ฏท่พๅ
ฅๆญฃ็กฎ็้ฎ็ฎฑ/ๆๆบๅท");
return false;
} else if (!validPass(formRegister.userPwd)) {
message.error("ๅฏ็ ๅบไธบ8ๅฐ20ไฝๅญๆฏๆๆฐๅญ๏ผ");
return false;
} else if (!validPass(formRegister.userPwd2)){
message.error("็กฎ่ฎคๅฏ็ ๆ่ฏฏ");
return false;
} else if (formRegister.userPwd2 !== formRegister.userPwd){
message.error("ไธคๆฌกๅฏ็ ไธไธ่ด");
return false;
}
register(
formRegister.userName,
formRegister.userPwd2
)
.then((res: any) => {
if (res.code === 0) {
this.clearInput();
message.success('ๆณจๅๆๅ');
history.push('/');
}
})
.catch((error: any) => {
message.error(error);
})
}
// ็ปๅฝ/ๆณจๅtabๅๆข
handleTab = (type: number) => {
// console.log('type===',type);
this.setState({
typeView: type
})
this.clearInput();
}
// ๆฏๅฆๅพ้่ฎฐไฝๅฏ็
checkChange = (e: any) => {
console.log(e.target.checked);
this.setState({
checked: e.target.checked
})
}
// ๆธ
็ฉบ่พๅ
ฅๆก
clearInput = () => {
this.setState({
formLogin: {
userName: '',
userPwd: '',
},
formRegister: {
userName: '',
userPwd2: '',
userPwd: '',
}
})
}
// ๅฟ่ฎฐๅฏ็ ็้ข
forgetPwd = () => {
message.info('ๅฟ่ฎฐๅฏ็ ๏ผ่ฏท่็ณปๅฎขๆ');
}
// ็ๅฌ่พๅ
ฅ็ปๅฝไฟกๆฏ
handleChangeInput = (e: any, type: number) => {
const { formLogin } = this.state;
this.setState({
formLogin: {
userName: type === 1 ? e.target.value : formLogin.userName,
userPwd: type === 2 ? e.target.value : formLogin.userPwd
}
})
}
// ็ๅฌ่พๅ
ฅๆณจๅไฟกๆฏ
handleChangeRegister = (e: any, type: number) => {
const { formRegister } = this.state;
this.setState({
formRegister: {
userName: type === 1 ? e.target.value : formRegister.userName,
userPwd: type === 2 ? e.target.value : formRegister.userPwd,
userPwd2: type === 3 ? e.target.value : formRegister.userPwd2
}
})
}
// ๅคๆญ็นๅป็้ฎ็keyCodeๆฏๅฆไธบ13๏ผๆฏๅฐฑ่ฐ็จ็ปๅฝๅฝๆฐ
handleEnterKey = (e: any, type: number) => {
const { formLogin, formRegister } = this.state;
if (type === 1) {
if (!formLogin.userName || !formLogin.userPwd) {
return;
} else {
if(e.nativeEvent.keyCode === 13){ //e.nativeEvent่ทๅๅ็็ไบไปถๅฏนๅ
this.handleLogin();
}
}
} else {
if (!formRegister.userName || !formRegister.userPwd || !formRegister.userPwd2) {
return;
} else {
if(e.nativeEvent.keyCode === 13){ //e.nativeEvent่ทๅๅ็็ไบไปถๅฏนๅ
this.handleRegister();
}
}
}
}
render () {
const { formLogin, formRegister, typeView, checked } = this.state;
return (
<DocumentTitle title={'็จๆท็ป้'}>
<div className="login-container">
<div className="pageHeader">
<img src={ logo } alt="logo" />
<span>ๅๅฐ็ฎก็ๆจกๆฟ</span>
</div>
<div className="login-box">
<div className="login-text">
<span className={ typeView === 0 ? 'active' : '' } onClick={ () => this.handleTab(0) }>็ปๅฝ</span>
<b>ยท</b>
<span className={ typeView === 1 ? 'active' : '' } onClick={ () => this.handleTab(1) }>ๆณจๅ</span>
</div>
{ typeView === 0 ?
<div className="right-content">
<div className="input-box">
<Input
type="text"
className="input"
value={ formLogin.userName }
onChange={ (e: any) => this.handleChangeInput(e, 1) }
placeholder="่ฏท่พๅ
ฅ็ปๅฝ้ฎ็ฎฑ/ๆๆบๅท"
/>
<Input
type="password"
className="input"
maxLength={ 20 }
value={ formLogin.userPwd }
onChange={ (e: any) => this.handleChangeInput(e, 2) }
onPressEnter={ (e: any) => this.handleEnterKey(e, 1) }
placeholder="่ฏท่พๅ
ฅ็ปๅฝๅฏ็ "
/>
</div>
<Button className="loginBtn" type="primary" onClick={ this.handleLogin } disabled={ !formLogin.userName || !formLogin.userPwd }>็ซๅณ็ปๅฝ</Button>
<div className="option">
<Checkbox className="remember" checked={ checked } onChange={ this.checkChange }>
<span className="checked">่ฎฐไฝๆ</span>
</Checkbox>
<span className="forget-pwd" onClick={ this.forgetPwd }>ๅฟ่ฎฐๅฏ็ ?</span>
</div>
</div>
:
<div className="right_content">
<div className="input-box">
<Input
type="text"
className="input"
value={ formRegister.userName }
onChange={ (e: any) => this.handleChangeRegister(e, 1) }
placeholder="่ฏท่พๅ
ฅๆณจๅ้ฎ็ฎฑ/ๆๆบๅท"
/>
<Input
type="password"
className="input"
maxLength={ 20 }
value={ formRegister.userPwd }
onChange={ (e: any) => this.handleChangeRegister(e, 2) }
placeholder="่ฏท่พๅ
ฅๅฏ็ "
/>
<Input
type="password"
className="input"
maxLength={ 20 }
value={ formRegister.userPwd2 }
onChange={ (e: any) => this.handleChangeRegister(e, 3) }
onPressEnter={ (e: any) => this.handleEnterKey(e, 2) }
placeholder="่ฏทๅๆฌก็กฎ่ฎคๅฏ็ "
/>
</div>
<Button className="loginBtn" type="primary" onClick={ this.handleRegister } disabled={ !formRegister.userName || !formRegister.userPwd || !formRegister.userPwd2 }>็ซๅณๆณจๅ</Button>
</div>
}
</div>
</div>
</DocumentTitle>
)
}
}
export default withRouter(connect((state: any) => state.user, { login, register })(Login)) | the_stack |
import assert from 'assert';
import express from 'express';
import * as ThingTalk from 'thingtalk';
import * as db from '../util/db';
import * as model from '../model/device';
import * as user from '../util/user';
import * as schemaModel from '../model/schema';
import * as exampleModel from '../model/example';
import * as trainingJobModel from '../model/training_job';
import * as I18n from '../util/i18n';
import * as tokenize from '../util/tokenize';
import * as SchemaUtils from '../util/manifest_to_schema';
import * as DatasetUtils from '../util/dataset';
import * as Importer from '../util/import_device';
import * as codeStorage from '../util/code_storage';
import * as iv from '../util/input_validation';
import { NotFoundError } from '../util/errors';
import { parseOldOrNewSyntax } from '../util/compat';
import * as stringModel from '../model/strings';
import * as entityModel from '../model/entity';
const router = express.Router();
function _(x : string) { return x; }
router.get('/', (req, res, next) => {
res.redirect(301, '/thingpedia');
});
function getOrgId(req : express.Request) {
if (!req.user)
return null;
if ((req.user.roles & user.Role.THINGPEDIA_ADMIN) !== 0)
return -1;
else
return req.user.developer_org;
}
const MEASURE_NAMES = {
ms: _("duration"),
C: _("temperature"),
m: _("length"),
mps: _("speed"),
kg: _("weight"),
Pa: _("pressure"),
kcal: _("energy"),
byte: _("size")
};
async function getHumanReadableType(req : express.Request,
language : string,
dbClient : db.Client,
arg : ThingTalk.Ast.ArgumentDef,
type : ThingTalk.Type) : Promise<string> {
if (type instanceof ThingTalk.Type.Array)
return req._("list of %s").format(await getHumanReadableType(req, language, dbClient, arg, type.elem as ThingTalk.Type));
if (arg.annotations.string_values) {
let stringType;
try {
stringType = await stringModel.getByTypeName(dbClient, arg.getImplementationAnnotation<string>('string_values')!, language);
} catch(e) {
if (language === 'en' || !(e instanceof NotFoundError))
throw e;
stringType = await stringModel.getByTypeName(dbClient, arg.getImplementationAnnotation<string>('string_values')!, 'en');
}
return stringType.name.toLowerCase();
} else if (type instanceof ThingTalk.Type.Entity) {
let entityType;
try {
entityType = await entityModel.get(dbClient, type.type, language);
} catch(e) {
if (language === 'en' || !(e instanceof NotFoundError))
throw e;
entityType = await entityModel.get(dbClient, type.type, 'en');
}
return entityType.name.toLowerCase();
} else if (type.isString) {
return req._("free-form text");
} else if (type.isNumber) {
return req._("number");
} else if (type.isBoolean) {
return req._("true or false");
} else if (type.isCurrency) {
return req._("currency amount");
} else if (type instanceof ThingTalk.Type.Measure) {
return req._(MEASURE_NAMES[type.unit as keyof typeof MEASURE_NAMES]);
} else if (type instanceof ThingTalk.Type.Enum) {
return req._("one of %s").format(type.entries!.map(tokenize.clean).join(", "));
} else if (type.isTime) {
return req._("time of day");
} else if (type.isDate) {
return req._("point in time");
} else if (type.isLocation) {
return req._("location");
} else {
// ignore weird/internal types return nothing
return String(type);
}
}
async function loadHumanReadableType(req : express.Request, language : string, dbClient : db.Client, arg : ThingTalk.Ast.ArgumentDef) {
arg.metadata.human_readable_type = await getHumanReadableType(req, language, dbClient, arg, arg.type);
}
function loadHumanReadableTypes(req : express.Request, language : string, dbClient : db.Client, classDef : ThingTalk.Ast.ClassDef) {
const promises = [];
for (const what of ['actions', 'queries'] as const) {
for (const name in classDef[what]) {
for (const argname of classDef[what][name].args) {
const arg = classDef[what][name].getArgument(argname)!;
promises.push(loadHumanReadableType(req, language, dbClient, arg));
}
}
}
return promises;
}
function durationToString(_ : (x : string) => string, ngettext : (x : string, x1 : string, n : number) => string, poll_interval : number) {
if (poll_interval < 1000)
return _("%d milliseconds").format(poll_interval);
poll_interval = Math.round(poll_interval / 1000);
const poll_interval_sec = poll_interval % 60;
poll_interval = Math.floor(poll_interval / 60);
const poll_interval_min = poll_interval % 60;
const poll_interval_h = Math.floor(poll_interval / 60);
if (poll_interval_sec !== 0) {
if (poll_interval_min !== 0) {
if (poll_interval_h !== 0)
return _("%d hours %d minutes %d seconds").format(poll_interval_h, poll_interval_min, poll_interval_sec);
else
return _("%d minutes %d seconds").format(poll_interval_min, poll_interval_sec);
} else {
if (poll_interval_h !== 0)
return _("%d hours %d seconds").format(poll_interval_h, poll_interval_sec);
else
return ngettext("second", "%d seconds", poll_interval_sec).format(poll_interval_sec);
}
} else {
if (poll_interval_min !== 0) {
if (poll_interval_h !== 0)
return _("%d hours %d minutes").format(poll_interval_h, poll_interval_min);
else
return ngettext("minute", "%d minutes", poll_interval_min).format(poll_interval_min);
} else {
return ngettext("hour", "%d hours", poll_interval_h).format(poll_interval_h);
}
}
}
interface DeviceDetails extends model.ByPrimaryKindRow {
version ?: number|null;
translated ?: boolean;
current_jobs ?: Record<string, trainingJobModel.Row[]>;
download_url ?: string;
}
function getDetails<T, ReqQuery extends { version ?: string }>(fn : (dbClient : db.Client, arg : T) => Promise<model.ByPrimaryKindRow>,
param : T,
req : express.Request<any, any, any, ReqQuery>,
res : express.Response) {
const language = I18n.localeToLanguage(req.locale);
return db.withClient(async (client) => {
const device : DeviceDetails = await fn(client, param);
let version : number|null;
if (req.query.version && req.user && (req.user.roles & user.Role.THINGPEDIA_ADMIN) !== 0)
version = parseInt(req.query.version);
else if (req.user &&
(req.user.developer_org === device.owner || (req.user.roles & user.Role.THINGPEDIA_ADMIN) !== 0))
version = device.developer_version;
else
version = device.approved_version;
device.version = version;
const [code, examples, current_jobs] = await Promise.all([
version !== null ? model.getCodeByVersion(client, device.id, version) : Promise.resolve(`class @${device.primary_kind} {}`),
exampleModel.getByKinds(client, [device.primary_kind], getOrgId(req), language, true),
trainingJobModel.getForDevice(client, language, device.primary_kind)
]);
const current_job_queues : Record<string, trainingJobModel.Row[]> = {};
for (const job of current_jobs) {
if (current_job_queues[job.job_type])
current_job_queues[job.job_type].push(job);
else
current_job_queues[job.job_type] = [job];
}
let parsed;
try {
parsed = parseOldOrNewSyntax(code, {
locale: 'en-US',
timezone: 'UTC'
});
} catch(e) {
if (e.name !== 'SyntaxError')
throw e;
// really obsolete device, likely a JSON manifest
parsed = parseOldOrNewSyntax(`abstract class @${device.primary_kind} { }`, {
locale: 'en-US',
timezone: 'UTC'
});
}
assert(parsed instanceof ThingTalk.Ast.Library && parsed.classes.length > 0);
const classDef = parsed.classes[0];
let translated;
if (language === 'en') {
translated = true;
} else {
const schemas = await schemaModel.getMetasByKinds(client, [req.params.kind], getOrgId(req), language);
if (schemas.length !== 0)
translated = SchemaUtils.mergeClassDefAndSchema(classDef, schemas[0]);
else
translated = false;
}
await Promise.all(loadHumanReadableTypes(req, language, client, classDef));
device.translated = translated;
device.current_jobs = current_job_queues;
const online = false;
const sortedexamples = DatasetUtils.sortAndChunkExamples(examples);
let title;
if (online)
title = req._("Thingpedia - Account details");
else
title = req._("Thingpedia - Device details");
if (version !== null && Importer.isDownloadable(classDef)) {
device.download_url = await codeStorage.getDownloadLocation(device.primary_kind, version,
device.approved_version === null || (version !== null && version > device.approved_version));
}
res.render('thingpedia_device_details', { page_title: title,
device: device,
classDef: classDef,
examples: sortedexamples,
clean: tokenize.clean,
durationToString });
}).catch((e) => {
if (e.code !== 'ENOENT')
throw e;
res.status(404).render('error', { page_title: req._("Thingpedia - Error"),
message: e });
});
}
router.get('/by-id/:kind', iv.validateGET({ version: '?integer' }), (req, res, next) => {
getDetails(model.getByPrimaryKind, req.params.kind, req, res).catch(next);
});
router.use(user.requireLogIn);
router.post('/approve', user.requireRole(user.Role.THINGPEDIA_ADMIN), iv.validatePOST({ kind: 'string' }), (req, res, next) => {
db.withTransaction((dbClient) => {
return Promise.all([
model.approve(dbClient, req.body.kind),
schemaModel.approveByKind(dbClient, req.body.kind)
]);
}).then(() => {
res.redirect(303, '/thingpedia/devices/by-id/' + req.body.kind);
}).catch(next);
});
router.post('/unapprove', user.requireRole(user.Role.THINGPEDIA_ADMIN), iv.validatePOST({ kind: 'string' }), (req, res, next) => {
db.withTransaction((dbClient) => {
return Promise.all([
model.unapprove(dbClient, req.body.kind),
schemaModel.unapproveByKind(dbClient, req.body.kind)
]);
}).then(() => {
res.redirect(303, '/thingpedia/devices/by-id/' + req.body.kind);
}).catch(next);
});
router.use(user.requireDeveloper());
router.post('/delete', iv.validatePOST({ kind: 'string' }), (req, res, next) => {
db.withTransaction(async (dbClient) => {
const row = await model.getByPrimaryKind(dbClient, req.body.kind);
if (row.owner !== req.user!.developer_org &&
(req.user!.roles & user.Role.THINGPEDIA_ADMIN) === 0) {
// note that this must be exactly the same error used by util/db.js
// so that a true not found is indistinguishable from not having permission
throw new NotFoundError();
}
await schemaModel.deleteByKind(dbClient, req.body.kind);
await model.delete(dbClient, row.id);
}).then(() => {
res.redirect(303, '/thingpedia/devices');
}).catch(next);
});
export default router; | the_stack |
import { OpSeq } from "rustpad-wasm";
import type {
editor,
IDisposable,
IPosition,
} from "monaco-editor/esm/vs/editor/editor.api";
import debounce from "lodash.debounce";
/** Options passed in to the Rustpad constructor. */
export type RustpadOptions = {
readonly uri: string;
readonly editor: editor.IStandaloneCodeEditor;
readonly onConnected?: () => unknown;
readonly onDisconnected?: () => unknown;
readonly onDesynchronized?: () => unknown;
readonly onChangeLanguage?: (language: string) => unknown;
readonly onChangeUsers?: (users: Record<number, UserInfo>) => unknown;
readonly reconnectInterval?: number;
};
/** A user currently editing the document. */
export type UserInfo = {
readonly name: string;
readonly hue: number;
};
/** Browser client for Rustpad. */
class Rustpad {
private ws?: WebSocket;
private connecting?: boolean;
private recentFailures: number = 0;
private readonly model: editor.ITextModel;
private readonly onChangeHandle: IDisposable;
private readonly onCursorHandle: IDisposable;
private readonly onSelectionHandle: IDisposable;
private readonly beforeUnload: (event: BeforeUnloadEvent) => void;
private readonly tryConnectId: number;
private readonly resetFailuresId: number;
// Client-server state
private me: number = -1;
private revision: number = 0;
private outstanding?: OpSeq;
private buffer?: OpSeq;
private users: Record<number, UserInfo> = {};
private userCursors: Record<number, CursorData> = {};
private myInfo?: UserInfo;
private cursorData: CursorData = { cursors: [], selections: [] };
// Intermittent local editor state
private lastValue: string = "";
private ignoreChanges: boolean = false;
private oldDecorations: string[] = [];
constructor(readonly options: RustpadOptions) {
this.model = options.editor.getModel()!;
this.onChangeHandle = options.editor.onDidChangeModelContent((e) =>
this.onChange(e)
);
const cursorUpdate = debounce(() => this.sendCursorData(), 20);
this.onCursorHandle = options.editor.onDidChangeCursorPosition((e) => {
this.onCursor(e);
cursorUpdate();
});
this.onSelectionHandle = options.editor.onDidChangeCursorSelection((e) => {
this.onSelection(e);
cursorUpdate();
});
this.beforeUnload = (event: BeforeUnloadEvent) => {
if (this.outstanding) {
event.preventDefault();
event.returnValue = "";
} else {
delete event.returnValue;
}
};
window.addEventListener("beforeunload", this.beforeUnload);
const interval = options.reconnectInterval ?? 1000;
this.tryConnect();
this.tryConnectId = window.setInterval(() => this.tryConnect(), interval);
this.resetFailuresId = window.setInterval(
() => (this.recentFailures = 0),
15 * interval
);
}
/** Destroy this Rustpad instance and close any sockets. */
dispose() {
window.clearInterval(this.tryConnectId);
window.clearInterval(this.resetFailuresId);
this.onSelectionHandle.dispose();
this.onCursorHandle.dispose();
this.onChangeHandle.dispose();
window.removeEventListener("beforeunload", this.beforeUnload);
this.ws?.close();
}
/** Try to set the language of the editor, if connected. */
setLanguage(language: string): boolean {
this.ws?.send(`{"SetLanguage":${JSON.stringify(language)}}`);
return this.ws !== undefined;
}
/** Set the user's information. */
setInfo(info: UserInfo) {
this.myInfo = info;
this.sendInfo();
}
/**
* Attempts a WebSocket connection.
*
* Safety Invariant: Until this WebSocket connection is closed, no other
* connections will be attempted because either `this.ws` or
* `this.connecting` will be set to a truthy value.
*
* Liveness Invariant: After this WebSocket connection closes, either through
* error or successful end, both `this.connecting` and `this.ws` will be set
* to falsy values.
*/
private tryConnect() {
if (this.connecting || this.ws) return;
this.connecting = true;
const ws = new WebSocket(this.options.uri);
ws.onopen = () => {
this.connecting = false;
this.ws = ws;
this.options.onConnected?.();
this.users = {};
this.options.onChangeUsers?.(this.users);
this.sendInfo();
this.sendCursorData();
if (this.outstanding) {
this.sendOperation(this.outstanding);
}
};
ws.onclose = () => {
if (this.ws) {
this.ws = undefined;
this.options.onDisconnected?.();
if (++this.recentFailures >= 5) {
// If we disconnect 5 times within 15 reconnection intervals, then the
// client is likely desynchronized and needs to refresh.
this.dispose();
this.options.onDesynchronized?.();
}
} else {
this.connecting = false;
}
};
ws.onmessage = ({ data }) => {
if (typeof data === "string") {
this.handleMessage(JSON.parse(data));
}
};
}
private handleMessage(msg: ServerMsg) {
if (msg.Identity !== undefined) {
this.me = msg.Identity;
} else if (msg.History !== undefined) {
const { start, operations } = msg.History;
if (start > this.revision) {
console.warn("History message has start greater than last operation.");
this.ws?.close();
return;
}
for (let i = this.revision - start; i < operations.length; i++) {
let { id, operation } = operations[i];
this.revision++;
if (id === this.me) {
this.serverAck();
} else {
operation = OpSeq.from_str(JSON.stringify(operation));
this.applyServer(operation);
}
}
} else if (msg.Language !== undefined) {
this.options.onChangeLanguage?.(msg.Language);
} else if (msg.UserInfo !== undefined) {
const { id, info } = msg.UserInfo;
if (id !== this.me) {
this.users = { ...this.users };
if (info) {
this.users[id] = info;
} else {
delete this.users[id];
delete this.userCursors[id];
}
this.updateCursors();
this.options.onChangeUsers?.(this.users);
}
} else if (msg.UserCursor !== undefined) {
const { id, data } = msg.UserCursor;
if (id !== this.me) {
this.userCursors[id] = data;
this.updateCursors();
}
}
}
private serverAck() {
if (!this.outstanding) {
console.warn("Received serverAck with no outstanding operation.");
return;
}
this.outstanding = this.buffer;
this.buffer = undefined;
if (this.outstanding) {
this.sendOperation(this.outstanding);
}
}
private applyServer(operation: OpSeq) {
if (this.outstanding) {
const pair = this.outstanding.transform(operation)!;
this.outstanding = pair.first();
operation = pair.second();
if (this.buffer) {
const pair = this.buffer.transform(operation)!;
this.buffer = pair.first();
operation = pair.second();
}
}
this.applyOperation(operation);
}
private applyClient(operation: OpSeq) {
if (!this.outstanding) {
this.sendOperation(operation);
this.outstanding = operation;
} else if (!this.buffer) {
this.buffer = operation;
} else {
this.buffer = this.buffer.compose(operation);
}
this.transformCursors(operation);
}
private sendOperation(operation: OpSeq) {
const op = operation.to_string();
this.ws?.send(`{"Edit":{"revision":${this.revision},"operation":${op}}}`);
}
private sendInfo() {
if (this.myInfo) {
this.ws?.send(`{"ClientInfo":${JSON.stringify(this.myInfo)}}`);
}
}
private sendCursorData() {
if (!this.buffer) {
this.ws?.send(`{"CursorData":${JSON.stringify(this.cursorData)}}`);
}
}
private applyOperation(operation: OpSeq) {
if (operation.is_noop()) return;
this.ignoreChanges = true;
const ops: (string | number)[] = JSON.parse(operation.to_string());
let index = 0;
for (const op of ops) {
if (typeof op === "string") {
// Insert
const pos = unicodePosition(this.model, index);
index += unicodeLength(op);
this.model.pushEditOperations(
this.options.editor.getSelections(),
[
{
range: {
startLineNumber: pos.lineNumber,
startColumn: pos.column,
endLineNumber: pos.lineNumber,
endColumn: pos.column,
},
text: op,
forceMoveMarkers: true,
},
],
() => null
);
} else if (op >= 0) {
// Retain
index += op;
} else {
// Delete
const chars = -op;
var from = unicodePosition(this.model, index);
var to = unicodePosition(this.model, index + chars);
this.model.pushEditOperations(
this.options.editor.getSelections(),
[
{
range: {
startLineNumber: from.lineNumber,
startColumn: from.column,
endLineNumber: to.lineNumber,
endColumn: to.column,
},
text: "",
forceMoveMarkers: true,
},
],
() => null
);
}
}
this.lastValue = this.model.getValue();
this.ignoreChanges = false;
this.transformCursors(operation);
}
private transformCursors(operation: OpSeq) {
for (const data of Object.values(this.userCursors)) {
data.cursors = data.cursors.map((c) => operation.transform_index(c));
data.selections = data.selections.map(([s, e]) => [
operation.transform_index(s),
operation.transform_index(e),
]);
}
this.updateCursors();
}
private updateCursors() {
const decorations: editor.IModelDeltaDecoration[] = [];
for (const [id, data] of Object.entries(this.userCursors)) {
if (id in this.users) {
const { hue, name } = this.users[id as any];
generateCssStyles(hue);
for (const cursor of data.cursors) {
const position = unicodePosition(this.model, cursor);
decorations.push({
options: {
className: `remote-cursor-${hue}`,
stickiness: 1,
zIndex: 2,
},
range: {
startLineNumber: position.lineNumber,
startColumn: position.column,
endLineNumber: position.lineNumber,
endColumn: position.column,
},
});
}
for (const selection of data.selections) {
const position = unicodePosition(this.model, selection[0]);
const positionEnd = unicodePosition(this.model, selection[1]);
decorations.push({
options: {
className: `remote-selection-${hue}`,
hoverMessage: {
value: name,
},
stickiness: 1,
zIndex: 1,
},
range: {
startLineNumber: position.lineNumber,
startColumn: position.column,
endLineNumber: positionEnd.lineNumber,
endColumn: positionEnd.column,
},
});
}
}
}
this.oldDecorations = this.model.deltaDecorations(
this.oldDecorations,
decorations
);
}
private onChange(event: editor.IModelContentChangedEvent) {
if (!this.ignoreChanges) {
const content = this.lastValue;
const contentLength = unicodeLength(content);
let offset = 0;
let operation = OpSeq.new();
operation.retain(contentLength);
event.changes.sort((a, b) => b.rangeOffset - a.rangeOffset);
for (const change of event.changes) {
// The following dance is necessary to convert from UTF-16 indices (evil
// encoding-dependent JavaScript representation) to portable Unicode
// codepoint indices.
const { text, rangeOffset, rangeLength } = change;
const initialLength = unicodeLength(content.slice(0, rangeOffset));
const deletedLength = unicodeLength(
content.slice(rangeOffset, rangeOffset + rangeLength)
);
const restLength =
contentLength + offset - initialLength - deletedLength;
const changeOp = OpSeq.new();
changeOp.retain(initialLength);
changeOp.delete(deletedLength);
changeOp.insert(text);
changeOp.retain(restLength);
operation = operation.compose(changeOp)!;
offset += changeOp.target_len() - changeOp.base_len();
}
this.applyClient(operation);
this.lastValue = this.model.getValue();
}
}
private onCursor(event: editor.ICursorPositionChangedEvent) {
const cursors = [event.position, ...event.secondaryPositions];
this.cursorData.cursors = cursors.map((p) => unicodeOffset(this.model, p));
}
private onSelection(event: editor.ICursorSelectionChangedEvent) {
const selections = [event.selection, ...event.secondarySelections];
this.cursorData.selections = selections.map((s) => [
unicodeOffset(this.model, s.getStartPosition()),
unicodeOffset(this.model, s.getEndPosition()),
]);
}
}
type UserOperation = {
id: number;
operation: any;
};
type CursorData = {
cursors: number[];
selections: [number, number][];
};
type ServerMsg = {
Identity?: number;
History?: {
start: number;
operations: UserOperation[];
};
Language?: string;
UserInfo?: {
id: number;
info: UserInfo | null;
};
UserCursor?: {
id: number;
data: CursorData;
};
};
/** Returns the number of Unicode codepoints in a string. */
function unicodeLength(str: string): number {
let length = 0;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
for (const c of str) ++length;
return length;
}
/** Returns the number of Unicode codepoints before a position in the model. */
function unicodeOffset(model: editor.ITextModel, pos: IPosition): number {
const value = model.getValue();
const offsetUTF16 = model.getOffsetAt(pos);
return unicodeLength(value.slice(0, offsetUTF16));
}
/** Returns the position after a certain number of Unicode codepoints. */
function unicodePosition(model: editor.ITextModel, offset: number): IPosition {
const value = model.getValue();
let offsetUTF16 = 0;
for (const c of value) {
// Iterate over Unicode codepoints
if (offset <= 0) break;
offsetUTF16 += c.length;
offset -= 1;
}
return model.getPositionAt(offsetUTF16);
}
/** Cache for private use by `generateCssStyles()`. */
const generatedStyles = new Set<number>();
/** Add CSS styles for a remote user's cursor and selection. */
function generateCssStyles(hue: number) {
if (!generatedStyles.has(hue)) {
generatedStyles.add(hue);
const css = `
.monaco-editor .remote-selection-${hue} {
background-color: hsla(${hue}, 90%, 80%, 0.5);
}
.monaco-editor .remote-cursor-${hue} {
border-left: 2px solid hsl(${hue}, 90%, 25%);
}
`;
const element = document.createElement("style");
const text = document.createTextNode(css);
element.appendChild(text);
document.head.appendChild(element);
}
}
export default Rustpad; | the_stack |
import * as fluent from "./fluent";
import {
isCommentToken,
isDefineToken,
isMacroToken,
isWhitespaceToken,
MacroToken,
Token,
} from "./tokens";
export abstract class ParsedWat {
abstract get type(): "list" | "atom" | "builtin";
abstract get line(): number;
abstract toString(): string;
abstract expand(scope: ExpansionScope): ParsedWat | ParsedWat[];
}
type BuiltinFn = (
scope: ExpansionScope,
args: Map<string, ParsedWat>
) => ParsedWat[];
export class Builtin extends ParsedWat {
private readonly fn_: BuiltinFn;
constructor(fn: BuiltinFn) {
super();
this.fn_ = fn;
}
get type(): "list" | "atom" | "builtin" {
return "builtin";
}
get line() {
return 0;
}
toString(): string {
throw new Error("Method not implemented.");
}
expand(scope: ExpansionScope): ParsedWat | ParsedWat[] {
throw new Error("Method not implemented.");
}
expandBuiltin(
scope: ExpansionScope,
args: Map<string, ParsedWat>
): ParsedWat[] {
return this.fn_(scope, args);
}
}
function isBuiltin(value: any): value is Builtin {
return value && value.type === "builtin";
}
interface MacroDefinition {
name: string;
args: string[];
body: ParsedWat[];
}
export class ExpansionScope {
private parent_: ExpansionScope | undefined;
private readonly definitions_: Map<string, MacroDefinition> = new Map();
constructor(parent?: ExpansionScope) {
this.parent_ = parent;
}
add(macroDefinition: MacroDefinition) {
this.definitions_.set(macroDefinition.name, macroDefinition);
}
lookup(name: string): MacroDefinition | undefined {
if (this.definitions_.has(name)) {
return this.definitions_.get(name);
}
return this.parent_?.lookup(name);
}
}
export function convertStr(bits: number, str: string): string {
if (bits != 32 && bits != 64 && bits != 128 && bits != 192 && bits != 256) {
throw new Error(
`Unknown bit length while converting string: ${bits} ${JSON.stringify(
str
)}`
);
}
const buffer = Buffer.from(str, "utf-8");
if (buffer.length * 8 > bits) {
throw new Error(
`String is too long for number of bits: ${bits} ${JSON.stringify(str)}`
);
}
const fullBuffer = new Uint8Array(bits / 8);
fullBuffer.set(buffer);
if (bits == 32) {
const words = new Uint32Array(fullBuffer);
return `0x${words[0].toString(16)} ${buffer.length}`;
}
const dwords = new BigUint64Array(fullBuffer.buffer);
const array = Array.from(dwords).map((el) => "0x" + el.toString(16));
array.push(buffer.length.toString());
return array.join(" ");
}
interface ListOptions {
isComment?: boolean;
isMacroScope?: boolean;
}
export class List extends ParsedWat {
private readonly elements_: ParsedWat[];
private readonly isComment_: boolean;
private readonly isMacroScope_: boolean;
constructor(elements: ParsedWat[], { isComment, isMacroScope }: ListOptions) {
super();
this.elements_ = elements;
this.isComment_ = !!isComment;
this.isMacroScope_ = !!isMacroScope;
}
get type(): "list" | "atom" {
return "list";
}
get line() {
const atom = this.firstSignificantAtom();
return atom ? atom.line : 0;
}
get elements(): ParsedWat[] {
return this.elements_;
}
get isComment(): boolean {
return this.isComment_;
}
get isMacroScope(): boolean {
return this.isMacroScope_;
}
get isDefinition(): boolean {
const atom = this.firstSignificantAtom();
return atom !== undefined && isDefineToken(atom.token);
}
get isMacro(): boolean {
const atom = this.firstSignificantAtom();
return atom !== undefined && isMacroToken(atom.token);
}
get macroName(): string {
const atom = this.firstSignificantAtom();
if (atom !== undefined && isMacroToken(atom.token)) {
return atom.token.content;
}
throw new Error("This is not a macro");
}
// a macro definition is a list, with the following format
// ( %define %name (%arg1 %arg2 ...) ...)
// for example:
// (%define %inc (%var)
// (local.set %var (i32.add (local.get %var) (i32.const 1)))
// )
// usage:
// (%inc $index)
// expands to
// (local.set $index (i32.add (local.get $index) (i32.const 1)))
buildDefinition(): MacroDefinition {
const macroDefinition = Array.from(
fluent.take(this.getSignificantElements(), 3)
);
// The length must be 3, to include a define token, a macro token and a
// list of argument names (each of which must be a macro token).
if (
macroDefinition.length != 3 ||
!isAtom(macroDefinition[0]) ||
!isDefineToken(macroDefinition[0].token) ||
!isAtom(macroDefinition[1]) ||
!isMacroToken(macroDefinition[1].token) ||
!isList(macroDefinition[2]) ||
!macroDefinition[2].isArgList()
) {
throw new Error("Poorly defined macro");
}
const name = macroDefinition[1].token.content;
const argList = macroDefinition[2].argList.map((el) => el.content);
const bodyIndex = 1 + this.elements.indexOf(macroDefinition[2]);
const body = this.elements.slice(bodyIndex);
return { name: name, args: argList, body: this.trim(body) };
}
trim(arr: ParsedWat[]): ParsedWat[] {
const first = arr.findIndex(
(v) => !isAtom(v) || !isWhitespaceToken(v.token)
);
let last = arr.length - 1;
while (
last > first &&
isAtom(arr[last]) &&
isWhitespaceToken((arr[last] as Atom).token)
) {
last--;
}
return arr.slice(first, last + 1);
}
expandMacro(
scope: ExpansionScope,
macroDefinition: MacroDefinition
): ParsedWat[] {
const args = Array.from(fluent.skip(this.getSignificantElements(), 1));
if (args.length != macroDefinition.args.length) {
throw new Error(
`Macro ${this.macroName} called with ${args.length} args ${args
.map((el) => el.toString())
.join(" ")}, expecting ${macroDefinition.args.length}`
);
}
const argMap: Map<string, ParsedWat> = new Map();
for (let i = 0; i != args.length; i++) {
argMap.set(macroDefinition.args[i], args[i]);
}
if (macroDefinition.body.length == 1) {
const first = macroDefinition.body[0];
if (isBuiltin(first)) {
return first.expandBuiltin(scope, argMap);
}
}
return macroDefinition.body.map((el) => List.expandMacroItem(el, argMap));
}
private static expandMacroItem(
item: ParsedWat,
argMap: Map<string, ParsedWat>
): ParsedWat {
if (isAtom(item)) {
const token = item.token;
if (isMacroToken(token)) {
if (argMap.has(token.content)) {
return argMap.get(token.content) as ParsedWat;
}
}
return item;
}
const list = item as List;
if (list.isComment) {
return list;
}
const expanded = list.elements.map((el) =>
List.expandMacroItem(el, argMap)
);
return new List(expanded, {});
}
private isArgList(): boolean {
return (
fluent.some(
this.getSignificantElements(),
(el) => isAtom(el) && isMacroToken(el.token)
) || fluent.empty(this.getSignificantElements())
);
}
private get argList(): MacroToken[] {
return Array.from(
fluent.map(this.getSignificantElements(), (el) => {
if (isAtom(el)) {
const token = el.token;
if (isMacroToken(token)) {
return token;
}
}
throw new Error(
`Unexpected element in argument list '${el.toString()}'`
);
})
);
}
firstSignificantAtom(): Atom | undefined {
const iter = this.getSignificantElements();
const first = iter.next();
if (!first.done && isAtom(first.value)) {
return first.value;
}
}
*getSignificantElements(): Generator<ParsedWat> {
for (const element of this.elements) {
if (!isAtom(element)) {
yield element;
continue;
}
const token = element.token;
if (!isWhitespaceToken(token) && !isCommentToken(token)) {
yield element;
}
}
}
toString(): string {
if (this.isComment) {
return `(;${this.elements.map((el) => el.toString()).join("")};)`;
} else if (this.isMacroScope_) {
const atom = this.firstSignificantAtom();
if (!atom || !atom.token.content.match(/^\w+$/)) {
throw new Error("Macro Scope must start with a name");
}
const content = this.elements.slice(this.elements.indexOf(atom) + 1);
const name = atom.token.content.toUpperCase();
return `(; %( begin macro scope ${name} ;)${content
.map((el) => el.toString())
.join("")}(; end macro scope ${name} )% ;)`;
} else {
return `(${this.elements.map((el) => el.toString()).join("")})`;
}
}
expand(scope: ExpansionScope): ParsedWat | ParsedWat[] {
if (this.isComment) {
return this;
}
if (this.isDefinition) {
const defn = this.buildDefinition();
scope.add(defn);
return new List([this], { isComment: true });
} else if (this.isMacro) {
const name = this.macroName;
const defn = scope.lookup(name);
if (defn) {
return this.expandMacro(scope, defn)
.map((el) => {
if (isList(el)) {
const twoex = el.expand(scope);
if (Array.isArray(twoex)) {
return twoex;
} else {
return [twoex];
}
} else {
return [el];
}
})
.flat();
} else {
throw new Error(
`Unknown macro ${name} at ${this.firstSignificantAtom()?.line}`
);
}
}
const currScope = new ExpansionScope(scope);
const expandedElements: ParsedWat[] = [];
for (const el of this.elements) {
const expanded = el.expand(currScope);
if (Array.isArray(expanded)) {
expandedElements.push(...expanded);
} else {
expandedElements.push(expanded);
}
}
return new List(expandedElements, { isMacroScope: this.isMacroScope_ });
}
}
export function isList(value: any): value is List {
return value && value.type === "list";
}
export class Atom extends ParsedWat {
private readonly token_: Token;
constructor(token: Token) {
super();
this.token_ = token;
}
get type(): "list" | "atom" {
return "atom";
}
get line() {
return this.token_.line;
}
get token(): Token {
return this.token_;
}
toString(): string {
return this.token.content;
}
expand(scope: ExpansionScope): ParsedWat | ParsedWat[] {
return this;
}
}
export function isAtom(value: any): value is Atom {
return value && value.type === "atom";
} | the_stack |
import {DatasetView, IDatasetSerialization} from "./datasetView";
import {SchemaReceiver, TableTargetAPI} from "./modules";
import {
FileSetDescription,
FileSizeSketchInfo,
JdbcConnectionInformation,
RemoteObjectId, FederatedDatabase, TableMetadata, DeltaTableDescription,
} from "./javaBridge";
import {OnCompleteReceiver, RemoteObject} from "./rpc";
import {BaseReceiver} from "./tableTarget";
import {FullPage, PageTitle} from "./ui/fullPage";
import {ICancellable, significantDigits, getUUID, assertNever} from "./util";
export interface FilesLoaded {
kind: "Files";
description: FileSetDescription;
}
export interface TablesLoaded {
kind: "DB";
description: JdbcConnectionInformation;
}
export interface DeltaTableLoaded {
kind: "Delta table";
description: DeltaTableDescription;
}
export interface HillviewLogs {
kind: "Hillview logs";
}
export interface Merged {
kind: "Merged";
first: DataLoaded;
second: DataLoaded;
}
export type DataLoaded = FilesLoaded | TablesLoaded | DeltaTableLoaded | HillviewLogs | IDatasetSerialization | Merged;
export function getDescription(data: DataLoaded): PageTitle {
switch (data.kind) {
case "Saved dataset":
return new PageTitle("saved", "");
case "Files":
if (data.description.name != null)
return new PageTitle(data.description.name, "loaded from files");
else
return new PageTitle(data.description.fileNamePattern, "loaded from files");
case "DB":
return new PageTitle(data.description.database + "/" + data.description.table,
"loaded from database");
case "Hillview logs":
return new PageTitle("logs", "Hillview installation logs");
case "Merged":
const name = getDescription(data.first).format + "+" + getDescription(data.second).format;
return new PageTitle("Merged " + name,
getDescription(data.first).provenance + "+" + getDescription(data.second).provenance);
case "Delta table":
if (data.description.snapshotVersion == null)
return new PageTitle(data.description.path, "Loaded from delta table")
else
return new PageTitle(`${data.description.path}:v${data.description.snapshotVersion}`,"Loaded from delta table");
}
}
/**
* A renderer which receives a remote object id that denotes a set of files.
* Initiates an RPC to get the file size.
*/
class FilesReceiver extends OnCompleteReceiver<RemoteObjectId> {
constructor(sourcePage: FullPage, operation: ICancellable<RemoteObjectId>,
protected data: DataLoaded,
protected newDataset: boolean) {
super(sourcePage, operation, "Discovering files on disk");
}
public run(remoteObjId: RemoteObjectId): void {
const fn = new RemoteObject(remoteObjId);
const rr = fn.createStreamingRpcRequest<FileSizeSketchInfo>("getFileSize", null);
rr.chain(this.operation);
const observer = new FileSizeReceiver(this.page, rr, this.data, fn, this.newDataset);
rr.invoke(observer);
}
}
/**
* Receives the file size.
* It initiates a loadTable RPC request to load data from these files as a table.
*/
class FileSizeReceiver extends OnCompleteReceiver<FileSizeSketchInfo> {
constructor(sourcePage: FullPage, operation: ICancellable<FileSizeSketchInfo>,
protected data: DataLoaded,
protected remoteObj: RemoteObject,
protected newDataset: boolean) {
super(sourcePage, operation, "Enumerating files");
}
public run(size: FileSizeSketchInfo): void {
if (size.fileCount === 0) {
this.page.reportError("No files matching " + getDescription(this.data).format);
return;
}
/*
if (false) {
// Prune the dataset; may increase efficiency
// TODO: prune seems to be broken.
const rr = this.remoteObj.createStreamingRpcRequest<RemoteObjectId>("prune", null);
rr.chain(this.operation);
const observer = new FilePruneReceiver(this.page, rr, this.data, size, this.newDataset);
rr.invoke(observer);
} else */
{
const fileSize = "Loading " + size.fileCount + " file(s), total size " +
significantDigits(size.totalSize) + " bytes";
const fn = new RemoteObject(this.remoteObj.getRemoteObjectId());
const rr = fn.createStreamingRpcRequest<RemoteObjectId>("loadTable", null);
rr.chain(this.operation);
const observer = new RemoteTableReceiver(this.page, rr, this.data, fileSize, this.newDataset);
rr.invoke(observer);
}
}
}
class FilePruneReceiver extends OnCompleteReceiver<RemoteObjectId> {
constructor(sourcePage: FullPage, operation: ICancellable<RemoteObjectId>,
protected data: DataLoaded, protected readonly size: FileSizeSketchInfo,
protected newDataset: boolean) {
super(sourcePage, operation, "Disconnecting workers without data");
}
public run(remoteObjId: RemoteObjectId): void {
const fileSize = "Loading " + this.size.fileCount + " file(s), total size " +
significantDigits(this.size.totalSize) + " bytes";
const fn = new RemoteObject(remoteObjId);
const rr = fn.createStreamingRpcRequest<RemoteObjectId>("loadTable", null);
rr.chain(this.operation);
const observer = new RemoteTableReceiver(this.page, rr, this.data, fileSize, this.newDataset);
rr.invoke(observer);
}
}
/**
* Receives the ID for a remote table and initiates a request to get the
* table schema.
*/
export class RemoteTableReceiver extends BaseReceiver {
/**
* Create a renderer for a new table.
* @param sourcePage Parent page initiating this request.
* @param data Data that has been loaded.
* @param operation Operation that will bring the results.
* @param description Description of the files that are being loaded.
* @param newDataset If true this is a new dataset.
*/
constructor(sourcePage: FullPage, operation: ICancellable<RemoteObjectId>, protected data: DataLoaded,
description: string, protected newDataset: boolean) {
super(sourcePage, operation, description, null);
}
public run(value: RemoteObjectId): void {
super.run(value);
const rr = this.remoteObject.createGetMetadataRequest();
rr.chain(this.operation);
const title = getDescription(this.data);
if (this.newDataset) {
const dataset = new DatasetView(this.remoteObject.getRemoteObjectId()!, title.format, this.data, this.page);
const newPage = dataset.newPage(title, null);
rr.invoke(new SchemaReceiver(newPage, rr, this.remoteObject, dataset, null, null));
} else {
rr.invoke(new SchemaReceiver(this.page, rr, this.remoteObject, this.page.dataset!, null, null));
}
}
}
/**
* Receives the ID for a remote GreenplumTarget and initiates a request to get the
* table schema.
*/
class GreenplumTableReceiver extends BaseReceiver {
/**
* Create a renderer for a new table.
* @param loadMenuPage Parent page initiating this request, always the page of the LoadMenu.
* @param data Data that has been loaded.
* @param initialObject Handle to the initial object; used later to load the files
* obtained from dumping the table.
* @param operation Operation that will bring the results.
*/
constructor(loadMenuPage: FullPage, operation: ICancellable<RemoteObjectId>,
protected initialObject: InitialObject,
protected data: TablesLoaded) {
super(loadMenuPage, operation, "Connecting to Greenplum database", null);
}
public run(value: RemoteObjectId): void {
super.run(value);
const rr = this.remoteObject.createGetMetadataRequest();
rr.chain(this.operation);
const title = getDescription(this.data);
const dataset = new DatasetView(this.remoteObject.getRemoteObjectId()!, title.format, this.data, this.page);
const newPage = dataset.newPage(title, null);
rr.invoke(new GreenplumSchemaReceiver(
newPage, rr, this.initialObject, this.remoteObject, this.data.description));
}
}
class GreenplumSchemaReceiver extends OnCompleteReceiver<TableMetadata> {
constructor(page: FullPage, operation: ICancellable<TableMetadata>,
protected initialObject: InitialObject,
protected remoteObject: TableTargetAPI,
protected jdbc: JdbcConnectionInformation) {
super(page, operation, "Reading table metadata");
}
public run(ts: TableMetadata): void {
if (ts.schema == null) {
this.page.reportError("No schema received; empty dataset?");
return;
}
if (ts.rowCount == 0) {
this.page.reportError("Table has 0 rows");
return;
}
// Ask Greenplum to dump the data; receive back the name of the temporary files
// where the tables are stored on the remote machines.
// This is the name of the temporary table used.
const tableName = "T" + getUUID().replace(/-/g, '');
const rr = this.remoteObject.createStreamingRpcRequest<string>("dumpGreenplumTable", tableName);
rr.chain(this.operation);
rr.invoke(new GreenplumLoader(this.page, ts, this.initialObject, this.jdbc, rr));
}
}
class GreenplumLoader extends OnCompleteReceiver<string> {
constructor(page: FullPage, protected summary: TableMetadata,
protected remoteObject: InitialObject,
protected jdbc: JdbcConnectionInformation,
operation: ICancellable<string>) {
super(page, operation, "Dumping data from database");
}
public run(value: string): void {
/*
This was an attempt to only load one column from greenplum, but it
does not seem to work.
const files: FileSetDescription = {
fileKind: "lazycsv",
fileNamePattern: value,
schemaFile: null,
headerRow: false,
schema: this.summary.schema,
name: (this.page.dataset?.loaded as TablesLoaded).description.table,
deleteAfterLoading: true,
};
const rr = this.remoteObject.createStreamingRpcRequest<RemoteObjectId>(
"findGreenplumFiles", {
files: files,
schema: this.summary.schema,
jdbc: this.jdbc
});
*/
const loaded = this.page.dataset?.loaded as TablesLoaded;
const files: FileSetDescription = {
fileKind: "lazycsv",
fileNamePattern: value,
schemaFile: null,
headerRow: false,
schema: this.summary.schema,
name: loaded.description.database + "/" + loaded.description.table,
deleteAfterLoading: true,
};
const rr = this.remoteObject.createStreamingRpcRequest<RemoteObjectId>(
"findFiles", files);
rr.chain(this.operation);
const observer = new FilesReceiver(this.page, rr,
{ kind: "Files", description: files }, false);
rr.invoke(observer);
}
}
/**
* This is the first object created that refers to a remote object.
*/
export class InitialObject extends RemoteObject {
public static instance: InitialObject = new InitialObject();
// noinspection JSUnusedLocalSymbols
private constructor() {
// The "-1" argument is the object id for the initial object.
// It must match the id of the object declared in RpcServer.java.
// This is a "well-known" name used for bootstrapping the system.
// noinspection JSUnusedLocalSymbols
super("-1");
}
public loadFiles(files: FileSetDescription, loadMenuPage: FullPage): void {
const rr = this.createStreamingRpcRequest<RemoteObjectId>("findFiles", files);
const observer = new FilesReceiver(loadMenuPage, rr,
{ kind: "Files", description: files }, true);
rr.invoke(observer);
}
public loadLogs(loadMenuPage: FullPage): void {
// Use a guid to force the request to reload every time
const rr = this.createStreamingRpcRequest<RemoteObjectId>("findLogs", getUUID());
const observer = new FilesReceiver(loadMenuPage, rr, { kind: "Hillview logs"}, true);
rr.invoke(observer);
}
protected loadTable(conn: JdbcConnectionInformation, loadMenuPage: FullPage, method: string): void {
const rr = this.createStreamingRpcRequest<RemoteObjectId>(method, conn);
const observer = new RemoteTableReceiver(loadMenuPage, rr,
{ kind: "DB", description: conn }, "loading database table", true);
rr.invoke(observer);
}
public loadSimpleDBTable(conn: JdbcConnectionInformation, loadMenuPage: FullPage): void {
this.loadTable(conn, loadMenuPage, "loadSimpleDBTable");
}
protected loadGreenplumTable(conn: JdbcConnectionInformation, loadMenuPage: FullPage, method: string): void {
const rr = this.createStreamingRpcRequest<RemoteObjectId>(method, conn);
const observer = new GreenplumTableReceiver(loadMenuPage, rr, this,
{ kind: "DB", description: conn });
rr.invoke(observer);
}
public loadFederatedDBTable(conn: JdbcConnectionInformation | null,
db: FederatedDatabase | null, loadMenuPage: FullPage): void {
if (db == null || conn == null) {
loadMenuPage.reportError("Unknown database kind");
return;
}
if (conn.table == "" || conn.database == "") {
loadMenuPage.reportError("You need to specify a database and a table");
return;
}
switch (db) {
case "mysql":
case "impala":
this.loadTable(conn as JdbcConnectionInformation, loadMenuPage, "loadDBTable");
break;
case "greenplum":
this.loadGreenplumTable(conn as JdbcConnectionInformation, loadMenuPage, "loadGreenplumTable");
break;
default:
assertNever(db);
}
}
public loadDeltaTable(description: DeltaTableDescription, loadMenuPage: FullPage): void{
const rr = this.createStreamingRpcRequest<RemoteObjectId>("loadDeltaTable", description);
const observer = new FilesReceiver(loadMenuPage, rr, { kind: "Delta table", description: description}, true);
rr.invoke(observer);
}
} | the_stack |
import { ConfigService } from '@nestjs/config';
import { common } from '~blockml/barrels/common';
import { constants } from '~blockml/barrels/constants';
import { enums } from '~blockml/barrels/enums';
import { helper } from '~blockml/barrels/helper';
import { interfaces } from '~blockml/barrels/interfaces';
import { BmError } from '~blockml/models/bm-error';
let func = enums.FuncEnum.CheckTopUnknownParameters;
export function checkTopUnknownParameters(
item: {
filesAny: any[];
errors: BmError[];
structId: string;
caller: enums.CallerEnum;
},
cs: ConfigService<interfaces.Config>
): any[] {
let { caller, structId } = item;
helper.log(cs, caller, func, structId, enums.LogTypeEnum.Input, item);
let newFilesAny: any[] = [];
item.filesAny.forEach(file => {
let errorsOnStart = item.errors.length;
Object.keys(file)
.filter(x => !x.toString().match(common.MyRegex.ENDS_WITH_LINE_NUM()))
.forEach(parameter => {
if (
[
enums.ParameterEnum.Path.toString(),
enums.ParameterEnum.Ext.toString(),
enums.ParameterEnum.Name.toString()
].indexOf(parameter) > -1
) {
return;
}
switch (file.ext) {
case common.FileExtensionEnum.Udf: {
if (
[
enums.ParameterEnum.Udf.toString(),
enums.ParameterEnum.Sql.toString()
].indexOf(parameter) < 0
) {
item.errors.push(
new BmError({
title: enums.ErTitleEnum.UNKNOWN_UDF_PARAMETER,
message:
`parameter "${parameter}" can not be used on top level of ` +
`${common.FileExtensionEnum.Udf} file`,
lines: [
{
line: file[parameter + constants.LINE_NUM],
name: file.name,
path: file.path
}
]
})
);
return;
}
break;
}
case common.FileExtensionEnum.View: {
if (
[
enums.ParameterEnum.View.toString(),
enums.ParameterEnum.Connection.toString(),
enums.ParameterEnum.Label.toString(),
enums.ParameterEnum.Description.toString(),
enums.ParameterEnum.Udfs.toString(),
enums.ParameterEnum.Table.toString(),
enums.ParameterEnum.DerivedTable.toString(),
enums.ParameterEnum.Fields.toString()
].indexOf(parameter) < 0
) {
item.errors.push(
new BmError({
title: enums.ErTitleEnum.UNKNOWN_VIEW_PARAMETER,
message:
`parameter "${parameter}" can not be used on top level of ` +
`${common.FileExtensionEnum.View} file`,
lines: [
{
line: file[parameter + constants.LINE_NUM],
name: file.name,
path: file.path
}
]
})
);
return;
}
break;
}
case common.FileExtensionEnum.Model: {
if (
[
enums.ParameterEnum.Model.toString(),
enums.ParameterEnum.Connection.toString(),
enums.ParameterEnum.Label.toString(),
// enums.ParameterEnum.Group.toString(),
// enums.ParameterEnum.Hidden.toString(),
enums.ParameterEnum.Description.toString(),
enums.ParameterEnum.AccessUsers.toString(),
enums.ParameterEnum.AccessRoles.toString(),
enums.ParameterEnum.AlwaysJoin.toString(),
enums.ParameterEnum.SqlAlwaysWhere.toString(),
enums.ParameterEnum.SqlAlwaysWhereCalc.toString(),
enums.ParameterEnum.Udfs.toString(),
enums.ParameterEnum.Joins.toString(),
enums.ParameterEnum.Fields.toString()
].indexOf(parameter) < 0
) {
item.errors.push(
new BmError({
title: enums.ErTitleEnum.UNKNOWN_MODEL_PARAMETER,
message:
`parameter "${parameter}" can not be used on top level of ` +
`${common.FileExtensionEnum.Model} file`,
lines: [
{
line: file[parameter + constants.LINE_NUM],
name: file.name,
path: file.path
}
]
})
);
return;
}
break;
}
case common.FileExtensionEnum.Dashboard: {
if (
[
enums.ParameterEnum.Dashboard.toString(),
enums.ParameterEnum.Title.toString(),
// enums.ParameterEnum.Group.toString(),
// enums.ParameterEnum.Hidden.toString(),
enums.ParameterEnum.Description.toString(),
enums.ParameterEnum.AccessUsers.toString(),
enums.ParameterEnum.AccessRoles.toString(),
enums.ParameterEnum.Fields.toString(),
enums.ParameterEnum.Reports.toString()
].indexOf(parameter) < 0
) {
item.errors.push(
new BmError({
title: enums.ErTitleEnum.UNKNOWN_DASHBOARD_PARAMETER,
message:
`parameter "${parameter}" can not be used on top level of ` +
`${common.FileExtensionEnum.Dashboard} file`,
lines: [
{
line: file[parameter + constants.LINE_NUM],
name: file.name,
path: file.path
}
]
})
);
return;
}
break;
}
case common.FileExtensionEnum.Viz: {
if (
[
enums.ParameterEnum.Viz.toString(),
// enums.ParameterEnum.Group.toString(),
// enums.ParameterEnum.Hidden.toString(),
enums.ParameterEnum.AccessUsers.toString(),
enums.ParameterEnum.AccessRoles.toString(),
enums.ParameterEnum.Reports.toString()
].indexOf(parameter) < 0
) {
item.errors.push(
new BmError({
title: enums.ErTitleEnum.UNKNOWN_VIZ_PARAMETER,
message:
`parameter "${parameter}" can not be used on top level of ` +
`${common.FileExtensionEnum.Viz} file`,
lines: [
{
line: file[parameter + constants.LINE_NUM],
name: file.name,
path: file.path
}
]
})
);
return;
}
break;
}
case common.FileExtensionEnum.Conf: {
if (
[
enums.ParameterEnum.WeekStart.toString(),
enums.ParameterEnum.DefaultTimezone.toString(),
enums.ParameterEnum.AllowTimezones.toString(),
enums.ParameterEnum.FormatNumber.toString(),
enums.ParameterEnum.CurrencyPrefix.toString(),
enums.ParameterEnum.CurrencySuffix.toString()
].indexOf(parameter) < 0
) {
item.errors.push(
new BmError({
title: enums.ErTitleEnum.UNKNOWN_PROJECT_CONFIG_PARAMETER,
message:
`parameter "${parameter}" can not be used on top level of ` +
`${common.FileExtensionEnum.Conf} file`,
lines: [
{
line: file[parameter + constants.LINE_NUM],
name: file.name,
path: file.path
}
]
})
);
return;
}
break;
}
}
if (
Array.isArray(file[parameter]) &&
[
enums.ParameterEnum.Udfs.toString(),
enums.ParameterEnum.Fields.toString(),
enums.ParameterEnum.Reports.toString(),
enums.ParameterEnum.Joins.toString(),
enums.ParameterEnum.AccessUsers.toString(),
enums.ParameterEnum.AccessRoles.toString()
].indexOf(parameter) < 0
) {
item.errors.push(
new BmError({
title: enums.ErTitleEnum.UNEXPECTED_LIST,
message: `parameter "${parameter}" must have a single value`,
lines: [
{
line: file[parameter + constants.LINE_NUM],
name: file.name,
path: file.path
}
]
})
);
return;
}
if (file[parameter]?.constructor === Object) {
item.errors.push(
new BmError({
title: enums.ErTitleEnum.UNEXPECTED_DICTIONARY,
message: `parameter "${parameter}" must have a single value`,
lines: [
{
line: file[parameter + constants.LINE_NUM],
name: file.name,
path: file.path
}
]
})
);
return;
}
if (
!Array.isArray(file[parameter]) &&
[
enums.ParameterEnum.Udfs.toString(),
enums.ParameterEnum.Fields.toString(),
enums.ParameterEnum.Reports.toString(),
enums.ParameterEnum.Joins.toString(),
enums.ParameterEnum.AccessUsers.toString(),
enums.ParameterEnum.AccessRoles.toString()
].indexOf(parameter) > -1
) {
item.errors.push(
new BmError({
title: enums.ErTitleEnum.PARAMETER_IS_NOT_A_LIST,
message: `parameter "${parameter}" must be a List`,
lines: [
{
line: file[parameter + constants.LINE_NUM],
name: file.name,
path: file.path
}
]
})
);
return;
}
});
if (errorsOnStart === item.errors.length) {
newFilesAny.push(file);
}
});
helper.log(
cs,
caller,
func,
structId,
enums.LogTypeEnum.FilesAny,
newFilesAny
);
helper.log(cs, caller, func, structId, enums.LogTypeEnum.Errors, item.errors);
return newFilesAny;
} | the_stack |
import {
GeoDistanceUnit,
GEO_DISTANCE_UNITS,
GeoPointInput,
GeoShape,
GeoPoint,
GeoDistanceObj,
GeoShapeType,
ESGeoShapeType,
GeoShapePoint,
GeoShapePolygon,
GeoShapeMultiPolygon,
ESGeoShape,
CoordinateTuple,
GeoShapeRelation,
GeoInput
} from '@terascope/types';
import bbox from '@turf/bbox';
import bboxPolygon from '@turf/bbox-polygon';
import equal from '@turf/boolean-equal';
import createCircle from '@turf/circle';
import pointInPolygon from '@turf/boolean-point-in-polygon';
import within from '@turf/boolean-within';
import contains from '@turf/boolean-contains';
import disjoint from '@turf/boolean-disjoint';
import intersect from '@turf/boolean-intersects';
import {
lineString,
multiPolygon,
polygon as tPolygon,
point as tPoint,
MultiPolygon,
Feature,
Properties,
Polygon,
Position,
} from '@turf/helpers';
import lineToPolygon from '@turf/line-to-polygon';
import { getCoords } from '@turf/invariant';
// @ts-expect-error
import geoToTimezone from 'geo-tz';
import { isArrayLike } from './arrays';
import { isPlainObject, geoHash, getTypeOf } from './deps';
import { trim, toString } from './strings';
import { parseNumberList, toNumber, isNumber } from './numbers';
export const geoJSONTypes = Object.keys(GeoShapeType).map((key) => key.toLowerCase());
export function isGeoJSON(input: unknown): input is GeoShape|ESGeoShape {
if (!isPlainObject(input)) return false;
if (!isArrayLike((input as any).coordinates)) return false;
const type = (input as any).type as unknown;
if (typeof type !== 'string') return false;
return geoJSONTypes.includes(type.toLowerCase());
}
export function isGeoShapePoint(input: unknown): input is GeoShapePoint {
return isGeoJSON(input)
&& (input.type === GeoShapeType.Point || input.type === ESGeoShapeType.Point);
}
export function isGeoShapePolygon(input: unknown): input is GeoShapePolygon {
return isGeoJSON(input)
&& (input.type === GeoShapeType.Polygon || input.type === ESGeoShapeType.Polygon);
}
export function isGeoShapeMultiPolygon(input: unknown): input is GeoShapeMultiPolygon {
return isGeoJSON(input)
&& (input.type === GeoShapeType.MultiPolygon || input.type === ESGeoShapeType.MultiPolygon);
}
export function parseGeoDistance(str: string): GeoDistanceObj {
const matches = trim(str).match(/(\d+)(.*)$/);
if (!matches || !matches.length) {
throw new TypeError(`Incorrect geo distance parameter provided: ${str}`);
}
const distance = Number(matches[1]);
const unit = parseGeoDistanceUnit(matches[2]);
return { distance, unit };
}
export function parseGeoDistanceUnit(input: string): GeoDistanceUnit {
const unit = GEO_DISTANCE_UNITS[trim(input)];
if (!unit) {
throw new TypeError(`Incorrect distance unit provided: ${input}`);
}
return unit;
}
function getLonAndLat(input: unknown, throwInvalid = true): GeoPoint | null {
if (!isPlainObject(input)) {
if (!throwInvalid) return null;
throw new TypeError(`Invalid geo point, expected object, got ${input} (${getTypeOf(input)})`);
}
const obj = input as Record<string, unknown>;
let lat: unknown;
let lon: unknown;
if ('lat' in obj && 'lon' in obj) {
if (isNumber(obj.lat) && isNumber(obj.lon)) {
return obj as unknown as GeoPoint;
}
lat = obj.lat;
lon = obj.lon;
} else if ('latitude' in obj && 'longitude' in obj) {
lat = obj.latitude;
lon = obj.longitude;
} else if (isGeoShapePoint(obj)) {
[lon, lat] = obj.coordinates;
}
if (throwInvalid && (lat == null || lon == null)) {
if (isGeoShapePolygon(obj) || isGeoShapeMultiPolygon(obj)) {
throw new TypeError([
`Expected a Point geo shape, received a geo ${obj.type} shape,`,
'you may need to switch to a polygon compatible operation'
].join(' '));
}
throw new TypeError('Invalid geo point object, it must contain keys lat,lon or latitude/longitude');
}
lat = toNumber(lat);
lon = toNumber(lon);
if (!isNumber(lat) || !isNumber(lon)) {
if (throwInvalid) {
throw new TypeError('Invalid geo point, lat and lon must be numbers');
}
return null;
}
return { lat, lon };
}
/**
* Convert an input into a Geo Point object with lat and lon
*/
export function parseGeoPoint(point: GeoPointInput|unknown): GeoPoint;
export function parseGeoPoint(point: GeoPointInput|unknown, throwInvalid: true): GeoPoint;
export function parseGeoPoint(point: GeoPointInput|unknown, throwInvalid: false): GeoPoint | null;
export function parseGeoPoint(point: GeoPointInput|unknown, throwInvalid = true): GeoPoint | null {
let lat: number | undefined;
let lon: number | undefined;
if (typeof point === 'string') {
if (point.includes(',')) {
[lat, lon] = parseNumberList(point);
} else {
try {
return geoHash.decode(point);
} catch (err) {
// do nothing
}
}
} else if (isPlainObject(point)) {
const results = getLonAndLat(point, throwInvalid);
if (results) return results;
} else if (isArrayLike(point)) {
// array of points are meant to be lon/lat format
[lon, lat] = parseNumberList(point);
}
if (throwInvalid && (lat == null || lon == null)) {
throw new TypeError(`Invalid geo point given to parse, got ${point} (${getTypeOf(point)})`);
}
// data incoming is lat,lon and we must return lon,lat
if (lat != null && lon != null) {
return {
lat,
lon
};
}
return null;
}
export function isGeoPoint(input: unknown): boolean {
return parseGeoPoint(input as GeoPointInput, false) != null;
}
export function makeGeoBBox(point1: GeoPoint, point2: GeoPoint): Feature<Polygon, Properties> {
const line = lineString([
makeCoordinatesFromGeoPoint(point1),
makeCoordinatesFromGeoPoint(point2)
]);
const box = bbox(line);
return bboxPolygon(box);
}
export function inGeoBoundingBox(
top_left: GeoPointInput, bottom_right: GeoPointInput, point: GeoPointInput
): boolean {
const topLeft = parseGeoPoint(top_left);
const bottomRight = parseGeoPoint(bottom_right);
const polygon = makeGeoBBox(topLeft, bottomRight);
if (polygon == null) {
throw new Error(`Invalid bounding box created from topLeft: ${topLeft}, bottomRight: ${bottomRight}`);
}
return geoPolyHasPoint(polygon)(point);
}
export function inGeoBoundingBoxFP(
top_left: GeoPointInput, bottom_right: GeoPointInput
): (input: unknown) => boolean {
const topLeft = parseGeoPoint(top_left);
const bottomRight = parseGeoPoint(bottom_right);
const polygon = makeGeoBBox(topLeft, bottomRight);
if (polygon == null) {
throw new Error(`Invalid bounding box created from topLeft: ${topLeft}, bottomRight: ${bottomRight}`);
}
return geoPolyHasPoint(polygon);
}
export function makeCoordinatesFromGeoPoint(point: GeoPoint): CoordinateTuple {
return [point.lon, point.lat];
}
export function geoPolyHasPoint<G extends Polygon | MultiPolygon>(polygon: Feature<G>|G) {
return (fieldData: unknown): boolean => {
const point = parseGeoPoint(fieldData as any, false);
if (!point) return false;
return pointInPolygon(makeCoordinatesFromGeoPoint(point), polygon);
};
}
export function makeGeoCircle(
point: GeoPoint, distance: number, unitVal?: GeoDistanceUnit
): Feature<Polygon>|undefined {
// There is a mismatch between elasticsearch and turf on "inch" naming
const units = unitVal === 'inch' ? 'inches' : unitVal;
return createCircle(makeCoordinatesFromGeoPoint(point), distance, { units });
}
export function geoPointWithinRange(
startingPoint: GeoPointInput, distanceValue: string, point: GeoPointInput
): boolean {
const sPoint = parseGeoPoint(startingPoint);
const { distance, unit } = parseGeoDistance(distanceValue);
const polygon = makeGeoCircle(sPoint, distance, unit);
if (polygon == null) {
throw new Error(`Invalid startingPoint: ${startingPoint}`);
}
return geoPolyHasPoint(polygon)(point);
}
export function geoPointWithinRangeFP(
startingPoint: GeoPointInput, distanceValue: string
): (input: unknown) => boolean {
const sPoint = parseGeoPoint(startingPoint);
const { distance, unit } = parseGeoDistance(distanceValue);
const polygon = makeGeoCircle(sPoint, distance, unit);
if (polygon == null) {
throw new Error(`Invalid startingPoint: ${startingPoint}`);
}
return geoPolyHasPoint(polygon);
}
export function geoRelationFP(
geoShape: GeoInput, relation: GeoShapeRelation
): (input: unknown) => boolean {
if (relation === GeoShapeRelation.Within) {
return geoWithinFP(geoShape);
}
if (relation === GeoShapeRelation.Contains) {
return geoContainsFP(geoShape);
}
if (relation === GeoShapeRelation.Intersects) {
return geoIntersectsFP(geoShape);
}
if (relation === GeoShapeRelation.Disjoint) {
return geoDisjointFP(geoShape);
}
throw new Error(`Unsupported relation ${relation}`);
}
/** Converts a geoJSON object to its turf geo feature counterpart */
export function makeGeoFeature(geoShape: unknown): Feature<any>|undefined {
if (isGeoShapePoint(geoShape)) {
return tPoint(geoShape.coordinates);
}
if (isGeoShapeMultiPolygon(geoShape)) {
return multiPolygon(geoShape.coordinates);
}
if (isGeoShapePolygon(geoShape)) {
return tPolygon(geoShape.coordinates);
}
return;
}
/** Converts a geoJSON object to its turf geo feature counterpart, will throw if not valid */
export function makeGeoFeatureOrThrow(geoShape: unknown): Feature<any> {
const results = makeGeoFeature(geoShape);
if (!results) {
throw new Error(`Invalid input: ${JSON.stringify(geoShape)}, is not a valid geo-shape`);
}
return results;
}
/**
* Returns true if the second geometry is completely contained by the first geometry.
* The interiors of both geometries must intersect and, the interior and boundary of
* the secondary geometry must not intersect the exterior of the first geometry.
*/
export function geoContains(firstGeoEntity: GeoInput, secondGeoEntity: GeoInput): boolean {
return geoContainsFP(secondGeoEntity)(firstGeoEntity);
}
/**
* When provided with geoInput that acts as the argument geo-feature, it will return a function
* that accepts any geoInput and checks to see if the new input contains the argument geo-feature
*/
export function geoContainsFP(queryGeoEntity: GeoInput): (input: unknown) => boolean {
const queryGeo = toGeoJSONOrThrow(queryGeoEntity);
const queryFeature = makeGeoFeatureOrThrow(queryGeo);
if (isGeoShapePoint(queryGeo)) return _pointContains(queryFeature);
const {
polygons: queryPolygons,
holes: queryHoles
} = _featureToPolygonAndHoles(queryFeature);
return function _geoContains(input: unknown): boolean {
const inputGeoEntity = toGeoJSON(input);
if (!inputGeoEntity) return false;
if (isGeoPoint(inputGeoEntity)) {
// point cannot contain a poly like feature
return false;
}
const inputFeature = makeGeoFeature(inputGeoEntity);
if (!inputFeature) return false;
const {
polygons: inputPolygons,
holes: inputHoles
} = _featureToPolygonAndHoles(inputFeature);
if (inputHoles.length) {
const withinInputHole = inputHoles.some(
(iHolePoly) => queryPolygons.some((qPoly) => intersect(qPoly, iHolePoly))
);
if (withinInputHole) {
// check to see if holes are the same, if so they don't overlap
if (queryHoles.length) {
return queryHoles.some(
(qHole) => inputHoles.some((iHole) => equal(qHole, iHole))
);
}
return false;
}
}
return queryPolygons.every(
(qPoly) => inputPolygons.some((iPoly) => contains(iPoly, qPoly))
);
};
}
function _pointContains(queryFeature: Feature<any>) {
return (input: unknown) => {
const inputGeoEntity = toGeoJSON(input);
if (!inputGeoEntity) return false;
const inputFeature = makeGeoFeature(inputGeoEntity);
if (!inputFeature) return false;
if (isGeoPoint(inputGeoEntity)) {
return equal(inputFeature, queryFeature);
}
const {
polygons,
holes
} = _featureToPolygonAndHoles(inputFeature);
let pointInHole = false;
if (holes.length) {
pointInHole = holes.some((iPolyHole) => contains(iPolyHole, queryFeature));
}
return !pointInHole && polygons.some((poly) => contains(poly, queryFeature));
};
}
function _featureToPolygonAndHoles(inputFeature: Feature<any>) {
const inputHoles: Feature<any>[] = [];
const inputCoords = getCoords(inputFeature);
let inputPolygons: Feature<any>[];
if (inputFeature.geometry.type === 'MultiPolygon') {
inputPolygons = inputCoords
.map((coords) => {
if (coords.length > 1) {
const [polygon, ...holes] = coords.map(
(innerCords: Position[]) => tPolygon([innerCords])
);
inputHoles.push(...holes);
return polygon;
}
return tPolygon(coords);
}) as Feature<any>[];
} else if (inputFeature.geometry.type === 'Polygon') {
const [polyCoords, ...holeCords] = inputCoords;
inputPolygons = [tPolygon([polyCoords])];
const holePolygons = holeCords.map((coords) => tPolygon([coords])) as Feature<any>[];
inputHoles.push(...holePolygons);
} else {
throw new Error(`Cannot convert ${toString(inputFeature)} to a polygon`);
}
return { holes: inputHoles, polygons: inputPolygons };
}
function _pointToPointMatch(queryInput: Feature<any>) {
return (input: unknown) => {
const inputGeoEntity = toGeoJSON(input);
if (!inputGeoEntity) return false;
if (!isGeoShapePoint(inputGeoEntity)) return false;
const inputFeature = makeGeoFeature(inputGeoEntity);
if (!inputFeature) return false;
return equal(queryInput, inputFeature);
};
}
/**
* Returns true if the first geometry is completely within the second geometry.
* The interiors of both geometries must intersect and, the interior and boundary
* of the first geometry must not intersect the exterior of the second geometry
*/
export function geoWithin(firstGeoEntity: GeoInput, secondGeoEntity: GeoInput): boolean {
return geoWithinFP(secondGeoEntity)(firstGeoEntity);
}
/**
* When provided with geoInput that acts as the parent geo-feature, it will return a function
* that accepts any geoInput and checks to see if the new input is within the parent geo-feature
*/
export function geoWithinFP(queryGeoEntity: GeoInput): (input: unknown) => boolean {
const queryGeo = toGeoJSONOrThrow(queryGeoEntity);
const queryFeature = makeGeoFeatureOrThrow(queryGeo);
// point can only be compared to other points
if (isGeoShapePoint(queryGeo)) return _pointToPointMatch(queryFeature);
const { polygons: queryPolygons, holes: queryHoles } = _featureToPolygonAndHoles(queryFeature);
const hasQueryHoles = queryHoles.length > 0;
return function _geoWithinFP(input) {
const inputGeoEntity = toGeoJSON(input);
if (!inputGeoEntity) return false;
const inputFeature = makeGeoFeature(inputGeoEntity);
if (!inputFeature) return false;
if (isGeoShapePoint(inputGeoEntity)) {
if (hasQueryHoles) {
const withinQueryHole = queryHoles.some(
intersect.bind(intersect, inputFeature)
);
if (withinQueryHole) return false;
}
return queryPolygons.some(within.bind(within, inputFeature));
}
const {
polygons: inputPolygons,
holes: inputHoles
} = _featureToPolygonAndHoles(inputFeature);
if (hasQueryHoles) {
// holes intersect main body
const withinQueryHole = queryHoles.some(
(qHole) => {
const bool = intersect(inputFeature, qHole);
if (bool && inputHoles.length) {
// if they are equal, then don't immediately falsify
const inner = !inputHoles.some(equal.bind(equal, qHole));
return inner;
}
return bool;
}
);
if (withinQueryHole) return false;
}
return inputPolygons.every(
(iPoly) => queryPolygons.some(within.bind(within, iPoly))
);
};
}
/** Returns true if both geo entities intersect each other, if one of the input geo entity
* is a point, it will check if the other geo-entity contains the point
*/
export function geoIntersects(firstGeoEntity: GeoInput, secondGeoEntity: GeoInput):boolean {
return geoIntersectsFP(firstGeoEntity)(secondGeoEntity);
}
export function geoIntersectsFP(queryGeoEntity: GeoInput): (input: unknown) => boolean {
const queryGeo = toGeoJSONOrThrow(queryGeoEntity);
const queryFeature = makeGeoFeatureOrThrow(queryGeo);
return function _geoIntersectsFP(input: unknown) {
const inputGeoEntity = toGeoJSON(input);
if (!inputGeoEntity) return false;
const inputFeature = makeGeoFeature(inputGeoEntity);
if (!inputFeature) return false;
return intersect(inputFeature, queryFeature);
};
}
export function geoDisjointFP(queryGeoEntity: GeoInput): (input: unknown) => boolean {
const queryGeo = toGeoJSONOrThrow(queryGeoEntity);
const queryFeature = makeGeoFeatureOrThrow(queryGeo);
return function _geoDisjointFP(input: unknown) {
const inputGeoEntity = toGeoJSON(input);
if (!inputGeoEntity) return false;
const inputFeature = makeGeoFeature(inputGeoEntity);
if (!inputFeature) return false;
return disjoint(inputFeature, queryFeature);
};
}
/** Returns true if both geo entities have no overlap */
export function geoDisjoint(firstGeoEntity: GeoInput, secondGeoEntity: GeoInput):boolean {
return geoDisjointFP(firstGeoEntity)(secondGeoEntity);
}
const esTypeMap = {
[ESGeoShapeType.Point]: GeoShapeType.Point,
[ESGeoShapeType.MultiPolygon]: GeoShapeType.MultiPolygon,
[ESGeoShapeType.Polygon]: GeoShapeType.Polygon,
} as const;
/** Only able to convert geo-points to either a geo-json point or a simple polygon.
* There is no current support for creating polygon with holes or multi-polygon
* as of right now. geoJSON input is made sure to be properly formatted for its type value
*/
export function toGeoJSON(input: unknown): GeoShape|undefined {
if (isGeoJSON(input)) {
const { type: inputType } = input;
const type = esTypeMap[inputType] ? esTypeMap[inputType] : inputType;
return { ...input, type };
}
if (isGeoPoint(input)) {
const coordinates = makeCoordinatesFromGeoPoint(parseGeoPoint(input as GeoPointInput));
return {
type: GeoShapeType.Point,
coordinates
};
}
if (Array.isArray(input)) {
try {
const points = input.map((point) => makeCoordinatesFromGeoPoint(
parseGeoPoint(point as GeoPointInput)
));
const coordinates = validateListCoords(points);
return {
type: GeoShapeType.Polygon,
coordinates
};
} catch (_err) {
// ignore here
}
}
}
export function toGeoJSONOrThrow(input: unknown): GeoShape {
const geoJSON = toGeoJSON(input);
if (!geoJSON) {
throw new Error(`Cannot convert ${JSON.stringify(input)} to valid geoJSON`);
}
return geoJSON;
}
export function validateListCoords(coords: CoordinateTuple[]): any[] {
if (coords.length < 3) {
throw new Error('Points parameter for a geoPolygon query must have at least three geo-points');
}
const line = lineString(coords);
const polygon = lineToPolygon(line);
// @ts-expect-error
return getCoords(polygon);
}
export function polyHasHoles(input: GeoShape): boolean {
if (isGeoShapePolygon(input)) {
return input.coordinates.length > 1;
}
if (isGeoShapeMultiPolygon(input)) {
return input.coordinates[0].length > 1;
}
return false;
}
/** Takes in a geo point like entity and returns the timezone of its location */
export function lookupTimezone(input: unknown): string {
const { lat, lon } = parseGeoPoint(input as GeoPointInput);
// it returns an array, return the first one
return geoToTimezone(lat, lon)[0];
} | the_stack |
import rule from "./no-unsafe-readonly-mutable-assignment";
import { RuleTester } from "@typescript-eslint/experimental-utils/dist/ts-eslint";
import { AST_NODE_TYPES } from "@typescript-eslint/experimental-utils/dist/ts-estree";
const ruleTester = new RuleTester({
parserOptions: {
sourceType: "module",
project: "./tsconfig.tests.json",
},
parser: require.resolve("@typescript-eslint/parser"),
});
// eslint-disable-next-line functional/no-expression-statement
ruleTester.run("no-unsafe-readonly-mutable-assignment", rule, {
valid: [
/**
* Call expressions
*/
// zero parameters
{
filename: "file.ts",
code: `
const foo = () => {
return undefined;
};
foo();
`,
},
// zero parameters with extra argument (TypeScript will catch this so we don't flag it)
{
filename: "file.ts",
code: `
const foo = () => {
return undefined;
};
foo("");
`,
},
// non-object parameter
{
filename: "file.ts",
code: `
const foo = (a: string) => {
return undefined;
};
foo("a");
`,
},
// missing arguments (TypeScript will catch this so we don't flag it)
{
filename: "file.ts",
code: `
const foo = (a: string) => {
return undefined;
};
foo();
`,
},
// readonly -> readonly (type doesn't change)
{
filename: "file.ts",
code: `
type ReadonlyA = { readonly a: string };
const func = (param: ReadonlyA): void => {
return undefined;
};
const readonlyA: ReadonlyA = { a: "" };
func(readonlyA);
`,
},
// readonly -> readonly (nested object; type doesn't change)
{
filename: "file.ts",
code: `
type ReadonlyA = { readonly a: { readonly b: string } };
const func = (param: ReadonlyA): void => {
return undefined;
};
const readonlyA: ReadonlyA = { a: { b: "" } };
func(readonlyA);
`,
},
// mutable -> mutable (type doesn't change)
{
filename: "file.ts",
code: `
type MutableA = {a: string};
const foo = (mut: MutableA) => {
mut.a = "whoops";
};
const mut: MutableA = { a: "" };
foo(mut);
`,
},
// object literal -> mutable (no reference to object retained)
{
filename: "file.ts",
code: `
type MutableA = {a: string};
const foo = (mut: MutableA) => {
mut.a = "whoops";
};
foo({ a: "" });
`,
},
// object literal -> mutable (mutable reference to property retained)
{
filename: "file.ts",
code: `
type MutableB = { b: string };
type MutableA = { readonly a: MutableB };
const func = (param: MutableA): void => {
return undefined;
};
const b: MutableB = { b: "" };
func({ a: b });
`,
},
// object literal -> readonly (mutable reference to property retained)
{
filename: "file.ts",
code: `
type MutableB = { b: string };
type ReadonlyA = { readonly a: { readonly b: string } };
const func = (param: ReadonlyA): void => {
return undefined;
};
const b: MutableB = { b: "" };
func({ a: b });
`,
},
// object literal -> readonly (readonly reference to property retained)
{
filename: "file.ts",
code: `
type ReadonlyB = { readonly b: string };
type ReadonlyA = { readonly a: ReadonlyB };
const func = (param: ReadonlyA): void => {
return undefined;
};
const b: ReadonlyB = { b: "" };
func({ a: b });
`,
},
// object literal -> readonly (no reference to object or its property retained)
{
filename: "file.ts",
code: `
type ReadonlyB = { readonly b: string };
type ReadonlyA = { readonly a: ReadonlyB };
const func = (param: ReadonlyA): void => {
return undefined;
};
func({ a: { b: "" } });
`,
},
// mutable (union) -> mutable
{
filename: "file.ts",
code: `
type MutableA = {a: string};
const foo = (mut: MutableA) => {
mut.a = "whoops";
};
const mut: MutableA | number = { a: "" };
foo(mut);
`,
},
// mutable -> mutable (union)
{
filename: "file.ts",
code: `
type MutableA = {a: string};
const foo = (mut: MutableA | number): void => {
return;
};
const mut: MutableA = { a: "" };
foo(mut);
`,
},
// multiple type signatures (readonly -> readonly)
{
filename: "file.ts",
code: `
type ReadonlyA = { readonly a: string };
export function func(a: number): number;
export function func(a: ReadonlyA): ReadonlyA;
export function func(a: any): any {
return a;
}
const readonlyA: ReadonlyA = { a: "" };
func(readonlyA);
`,
},
// multiple type signatures (no matching signature)
// we don't bother flagging this because TypeScript itself will catch it
{
filename: "file.ts",
code: `
type ReadonlyA = { readonly a: string };
export function func(a: number): number;
export function func(a: string): string;
export function func(a: any): any {
return a;
}
const readonlyA: ReadonlyA = { a: "" };
func(readonlyA);
`,
},
// readonly array concat.
{
filename: "file.ts",
code: `
const arr: ReadonlyArray<never> = [];
const foo = arr.concat(arr, arr);
`,
},
// mutable array concat.
{
filename: "file.ts",
code: `
const arr: Array<never> = [];
const foo = arr.concat(arr, arr);
`,
},
// Mixed mutable and readonly array concat.
// TODO this should be invalid.
{
filename: "file.ts",
code: `
const ro: ReadonlyArray<never> = [];
const mut: Array<never> = [];
const foo = ro.concat(ro, mut);
`,
},
// mixed (union) -> mixed (union)
// The readonlys align and mutables align, so no surprising mutation can arise.
{
filename: "file.ts",
code: `
type MutableA = { a: string };
type ReadonlyB = { readonly b: string };
const func = (foo: MutableA | ReadonlyB): void => {
return;
};
const foo: MutableA | ReadonlyB = Date.now() > 0 ? { a: "" } : { b: "" };
func(foo);
`,
},
// Recursive type (linting must terminate)
{
filename: "file.ts",
code: `
type Foo = ReadonlyArray<Foo>;
const func = (foo: Foo): void => {
return;
};
const foo: Foo = [[]];
func(foo);
`,
},
// why does this hang?
// TODO fix
{
filename: "file.ts",
code: `
const foo = document.createElement("div");
`,
},
// readonly array of readonly object -> readonly array of readonly object
{
filename: "file.ts",
code: `
type Obj = { readonly foo: string };
const foo = (a: ReadonlyArray<Obj>): number => a.length;
const arr: ReadonlyArray<Obj> = [];
foo(arr);
`,
},
// readonly function parameter -> mutable function parameter
// (contravariant position so not flagged by this rule)
{
filename: "file.ts",
code: `
type MutableA = { a: string };
type ReadonlyA = { readonly a: string };
const takesMutable = (f: (roa: MutableA) => void): void => undefined;
takesMutable((roa: ReadonlyA): void => undefined);
`,
},
// readonly function parameter -> mutable function parameter (rest param)
// (contravariant position so not flagged by this rule)
{
filename: "file.ts",
code: `
type MutableA = { a: string };
type ReadonlyA = { readonly a: string };
const takesMutable = (f: (...roa: readonly MutableA[]) => void): void => undefined;
takesMutable((...roa: readonly MutableA[]): void => undefined);
`,
},
// readonly function parameter -> readonly function parameter (rest param array is mutable -> readonly)
// TODO should we flag this?
{
filename: "file.ts",
code: `
type MutableA = { a: string };
type ReadonlyA = { readonly a: string };
const takesReadonly = (f: (...roa: readonly ReadonlyA[]) => void): void => undefined;
takesReadonly((...roa: MutableA[]): void => undefined);
`,
},
/**
* Assignment expressions
*/
// TODO
/**
* Arrow functions
*/
// Arrow function (compact form) (readonly -> readonly)
{
filename: "file.ts",
code: `
type ReadonlyA = { readonly a: string };
const ro: ReadonlyA = { a: "" };
const func = (): ReadonlyA => ro;
`,
},
// Arrow function (compact form) (object literal -> readonly)
{
filename: "file.ts",
code: `
type ReadonlyA = { readonly a: string };
const func = (): ReadonlyA => { a: "" };
`,
},
// Arrow function (compact form) (object literal -> mutable)
{
filename: "file.ts",
code: `
type MutableA = { a: string };
const func = (): MutableA => { a: "" };
`,
},
// Arrow function (compact form) (mutable -> mutable)
{
filename: "file.ts",
code: `
type MutableA = { a: string };
const ro: MutableA = { a: "" };
const func = (): MutableA => ro;
`,
},
/**
* type assertions
*/
// readonly -> readonly
{
filename: "file.ts",
code: `
type ReadonlyA = { readonly a: string };
const ro: ReadonlyA = { a: "" };
const mut = ro as ReadonlyA;
`,
},
// mutable -> mutable
{
filename: "file.ts",
code: `
type MutableA = { a: string };
const ro: MutableA = { a: "" };
const mut = ro as MutableA;
`,
},
// mutable -> readonly
{
filename: "file.ts",
code: `
type MutableA = { a: string };
type ReadonlyA = { readonly a: string };
const ro: MutableA = { a: "" };
const mut = ro as ReadonlyA;
`,
},
// readonly -> readonly
{
filename: "file.ts",
code: `
type ReadonlyA = { readonly a: string };
const ro: ReadonlyA = { a: "" };
const mut = <ReadonlyA>ro;
`,
},
// mutable -> mutable
{
filename: "file.ts",
code: `
type MutableA = { a: string };
const ro: MutableA = { a: "" };
const mut = <MutableA>ro;
`,
},
// mutable -> readonly
{
filename: "file.ts",
code: `
type MutableA = { a: string };
type ReadonlyA = { readonly a: string };
const ro: MutableA = { a: "" };
const mut = <ReadonlyA>ro;
`,
},
// Symbol.declarations claims to be of type Declaration[] but it's really Declaration[] | undefined
// This test exercises the case where it is undefined to ensure we handle it appropriately.
// TODO: what else in the typescript lib lies about its type?
// TODO: use patch-package to fix this type, forcing us to handle it.
{
filename: "file.ts",
code: `
Object.keys({}) as ReadonlyArray<string>;
`,
},
// as const
{
filename: "file.ts",
code: `
const foo: readonly string[] = [];
const bar = [
{ key: -1, value: "" },
...foo.map((c, i) => ({
key: i,
value: c,
})),
] as const;
`,
},
// <const>
{
filename: "file.ts",
code: `
const foo: readonly string[] = [];
const bar = <const>[
{ key: -1, value: "" },
...foo.map((c, i) => ({
key: i,
value: c,
})),
];
`,
},
// as unknown
{
filename: "file.ts",
code: `
const foo = [{ key: -1, label: "", value: "" }] as unknown;
`,
},
/**
* Return statement
*/
// mutable -> mutable (function return)
{
filename: "file.ts",
code: `
type MutableA = { a: string };
type ReadonlyA = { readonly a: string };
function foo(): MutableA {
const ma: MutableA = { a: "" };
return ma;
}
`,
},
// readonly -> readonly (function return)
{
filename: "file.ts",
code: `
type MutableA = { a: string };
type ReadonlyA = { readonly a: string };
function foo(): ReadonlyA {
const ma: ReadonlyA = { a: "" };
return ma;
}
`,
},
// void (function return)
{
filename: "file.ts",
code: `
function foo(): void {
return;
}
`,
},
{
filename: "file.ts",
code: `
interface Foo {
foo: 'bar'
}
interface Bar {
foo: 'bar'
}
const foo: Recursive<Foo> = 42 as any
export default foo as Recursive<Bar>
type Recursive<P> = P | Nested<P>;
type Nested<P> = ReadonlyArray<Recursive<P>>;
`,
},
{
filename: "file.ts",
code: `
interface Foo {
foo: 'bar'
}
interface Bar {
foo: 'bar'
}
const foo: Recursive<Foo> = 42 as any
export default foo as Recursive<Bar>
type Recursive<P> = P | Nested<P>;
type Nested<P> = () => Recursive<P>
`,
},
{
filename: "file.ts",
code: `
interface Foo {
foo: 'bar'
}
interface Bar {
foo: 'bar'
}
const foo: Recursive<Foo> = 42 as any
export default foo as Recursive<Bar>
type Recursive<P> = P | Nested<P>;
type Nested<P> = { baz: Recursive<P> }
`,
},
],
invalid: [
/**
* Call expressions
*/
// readonly -> mutable
{
filename: "file.ts",
code: `
type MutableA = { a: string };
type ReadonlyA = { readonly a: string };
const mutate = (mut: MutableA): void => {
mut.a = "whoops";
};
const readonlyA: ReadonlyA = { a: "readonly?" };
mutate(readonlyA);
`,
errors: [
{
messageId: "errorStringCallExpression",
type: AST_NODE_TYPES.Identifier,
},
],
},
// readonly -> mutable (union)
// this is invalid because it _could be_ readonly -> mutable
{
filename: "file.ts",
code: `
type MutableA = { a: string };
type ReadonlyA = { readonly a: string };
const mutate = (mixed: MutableA | undefined | null | number | string | boolean): void => {
return;
};
const mixedA: ReadonlyA = { a: "readonly?" };
mutate(mixedA);
`,
errors: [
{
messageId: "errorStringCallExpression",
type: AST_NODE_TYPES.Identifier,
},
],
},
// readonly (union) -> mutable (union)
// this is invalid because it _could be_ readonly -> mutable
{
filename: "file.ts",
code: `
type MutableA = { a: string };
type ReadonlyA = { readonly a: string };
const mutate = (mixed: MutableA | undefined | null): void => {
return;
};
const mixedA: ReadonlyA | undefined | null = { a: "readonly?" };
mutate(mixedA);
`,
errors: [
{
messageId: "errorStringCallExpression",
type: AST_NODE_TYPES.Identifier,
},
],
},
// callee has multiple type signatures (readonly -> mutable)
{
filename: "file.ts",
code: `
type MutableA = { a: string };
type ReadonlyA = { readonly a: string };
export function func(a: MutableA): MutableA;
export function func(a: number): number;
export function func(a: any): any {
return a;
}
const readonlyA: ReadonlyA = { a: "" };
func(readonlyA);
`,
errors: [
{
messageId: "errorStringCallExpression",
type: AST_NODE_TYPES.Identifier,
},
],
},
// readonly -> mutable (nested object)
{
filename: "file.ts",
code: `
type MutableA = { readonly a: { b: string } };
type ReadonlyA = { readonly a: { readonly b: string } };
const mutate = (mut: MutableA): void => {
mut.a.b = "whoops";
};
const readonlyA: ReadonlyA = { a: { b: "readonly?" } };
mutate(readonlyA);
`,
errors: [
{
messageId: "errorStringCallExpression",
type: AST_NODE_TYPES.Identifier,
},
],
},
// object literal -> mutable (readonly reference to property retained)
// this can lead to surprising mutation in the readonly reference that is retained
{
filename: "file.ts",
code: `
type MutableB = { b: string };
type ReadonlyB = { readonly b: string };
type MutableA = { readonly a: MutableB };
const func = (param: MutableA): void => {
return undefined;
};
const b: ReadonlyB = { b: "" };
func({ a: b });
`,
errors: [
{
messageId: "errorStringCallExpression",
type: AST_NODE_TYPES.ObjectExpression,
},
],
},
// readonly -> mutable (rest parameter)
{
filename: "file.ts",
code: `
type MutableA = { a: string };
type ReadonlyA = { readonly a: string };
const foo = (...as: readonly MutableA[]): void => {
return;
};
const ma: MutableA = { a: "" };
const ra: ReadonlyA = { a: "" };
foo(ma, ra);
`,
errors: [
{
messageId: "errorStringCallExpression",
type: AST_NODE_TYPES.Identifier,
},
],
},
// readonly (union) -> mutable (union)
{
filename: "file.ts",
code: `
type MutableA = { a: string };
type ReadonlyA = { readonly a: string };
type MutableB = { b: string };
type ReadonlyB = { readonly b: string };
const mutate = (mut: MutableA | MutableB): void => {
return;
};
const ro: ReadonlyA | ReadonlyB = { a: "" };
mutate(ro);
`,
errors: [
{
messageId: "errorStringCallExpression",
type: AST_NODE_TYPES.Identifier,
},
],
},
// readonly (union) -> mixed (union)
{
filename: "file.ts",
code: `
type ReadonlyA = { readonly a: string };
type MutableB = { b: string };
type ReadonlyB = { readonly b: string };
const mutate = (mut: ReadonlyA | MutableB): void => {
return;
};
const ro: ReadonlyA | ReadonlyB = Date.now() > 0 ? { a: "" } : { b: "" };
mutate(ro);
`,
errors: [
{
messageId: "errorStringCallExpression",
type: AST_NODE_TYPES.Identifier,
},
],
},
// readonly function return type -> mutable function return type.
{
filename: "file.ts",
code: `
type MutableA = { a: string };
type ReadonlyA = { readonly a: string };
const mutate = (mut: () => MutableA): void => {
const mutable = mut();
mutable.a = "whoops";
};
const ro: ReadonlyA = { a: "" } as const;
mutate((): ReadonlyA => ro);
`,
errors: [
{
messageId: "errorStringCallExpression",
type: AST_NODE_TYPES.ArrowFunctionExpression,
},
],
},
// mutable function parameter -> readonly function parameter
// (contravariant position)
{
filename: "file.ts",
code: `
type MutableA = { a: string };
type ReadonlyA = { readonly a: string };
const takesReadonly = (f: (roa: ReadonlyA) => void): void => undefined;
takesReadonly((ma: MutableA): void => undefined);
`,
errors: [
{
messageId: "errorStringCallExpression",
type: AST_NODE_TYPES.ArrowFunctionExpression,
},
],
},
// mutable function parameter -> readonly function parameter (rest param)
// (contravariant position)
{
filename: "file.ts",
code: `
type MutableA = { a: string };
type ReadonlyA = { readonly a: string };
const takesReadonly = (f: (...roa: readonly ReadonlyA[]) => void): void => undefined;
takesReadonly((...ma: readonly MutableA[]): void => undefined);
`,
errors: [
{
messageId: "errorStringCallExpression",
type: AST_NODE_TYPES.ArrowFunctionExpression,
},
],
},
/**
* Assignment expressions
*/
// readonly -> mutable
{
filename: "file.ts",
code: `
type MutableA = { a: string };
type ReadonlyA = { readonly a: string };
const readonlyA: ReadonlyA = { a: "readonly?" };
let mutableA: MutableA;
mutableA = readonlyA;
`,
errors: [
{
messageId: "errorStringAssignmentExpression",
type: AST_NODE_TYPES.AssignmentExpression,
},
],
},
// readonly -> mutable (short-circuiting assignment)
{
filename: "file.ts",
code: `
type MutableA = { a: string };
type ReadonlyA = { readonly a: string };
const readonlyA: ReadonlyA = { a: "readonly?" };
let mutableA: MutableA | undefined;
mutableA ??= readonlyA;
`,
errors: [
{
messageId: "errorStringAssignmentExpression",
type: AST_NODE_TYPES.AssignmentExpression,
},
],
},
/**
* Variable declaration
*/
// readonly (type) -> mutable
{
filename: "file.ts",
code: `
type MutableA = { a: string };
type ReadonlyA = { readonly a: string };
const readonlyA: ReadonlyA = { a: "readonly?" };
const mutableA: MutableA = readonlyA;
`,
errors: [
{
messageId: "errorStringVariableDeclaration",
type: AST_NODE_TYPES.VariableDeclaration,
},
],
},
// readonly (class) -> mutable
// this is arguably worse than the above because instead of surprise mutation it results in a TypeError
{
filename: "file.ts",
code: `
class Box {
get area(): number {
return 42;
}
}
type Area = {
area: number;
};
const a: Area = new Box();
`,
errors: [
{
messageId: "errorStringVariableDeclaration",
type: AST_NODE_TYPES.VariableDeclaration,
},
],
},
// readonly (string index type) -> mutable (string index type)
{
filename: "file.ts",
code: `
type MutableA = Record<string, { a: string }>;
type ReadonlyA = Record<string, { readonly a: string }>;
const readonlyA: ReadonlyA = {};
const mutableA: MutableA = readonlyA;
`,
errors: [
{
messageId: "errorStringVariableDeclaration",
type: AST_NODE_TYPES.VariableDeclaration,
},
],
},
// readonly (string index signature) -> mutable (string index signature) (recursive types)
{
filename: "file.ts",
code: `
type MutableA = {
[P in string]: MutableA;
};
type ReadonlyA = {
readonly [P in string]: ReadonlyA;
};
const readonlyA: ReadonlyA = {};
const mutableA: MutableA = readonlyA;
`,
errors: [
{
messageId: "errorStringVariableDeclaration",
type: AST_NODE_TYPES.VariableDeclaration,
},
],
},
// readonly (number index signature) -> mutable (number index signature) (recursive types)
{
filename: "file.ts",
code: `
type MutableA = {
[P in number]: MutableA;
};
type ReadonlyA = {
readonly [P in number]: ReadonlyA;
};
const readonlyA: ReadonlyA = {};
const mutableA: MutableA = readonlyA;
`,
errors: [
{
messageId: "errorStringVariableDeclaration",
type: AST_NODE_TYPES.VariableDeclaration,
},
],
},
// readonly array prop with readonly generic type -> readonly array prop with mutable generic type
{
filename: "file.ts",
code: `
type MutableA = { readonly a: ReadonlyArray<{ b: string }> };
type ReadonlyA = { readonly a: ReadonlyArray<{ readonly b: string }> };
const readonlyA: ReadonlyA = { a: [] };
const mutableA: MutableA = readonlyA;
`,
errors: [
{
messageId: "errorStringVariableDeclaration",
type: AST_NODE_TYPES.VariableDeclaration,
},
],
},
/**
* Arrow functions
*/
// Arrow function (compact form) (readonly -> mutable)
{
filename: "file.ts",
code: `
type MutableA = { a: string };
type ReadonlyA = { readonly a: string };
const ro: ReadonlyA = { a: "" };
const func = (): MutableA => ro;
`,
errors: [
{
messageId: "errorStringArrowFunctionExpression",
type: AST_NODE_TYPES.Identifier,
},
],
},
/**
* type assertions
*/
// readonly -> mutable
{
filename: "file.ts",
code: `
type MutableA = { a: string };
type ReadonlyA = { readonly a: string };
const ro: ReadonlyA = { a: "" };
const mut = ro as MutableA;
`,
errors: [
{
messageId: "errorStringTSAsExpression",
type: AST_NODE_TYPES.TSAsExpression,
},
],
},
// readonly -> mutable
{
filename: "file.ts",
code: `
type MutableA = { a: string };
type ReadonlyA = { readonly a: string };
const ro: ReadonlyA = { a: "" };
const mut = <MutableA>ro;
`,
errors: [
{
messageId: "errorStringTSTypeAssertion",
type: AST_NODE_TYPES.TSTypeAssertion,
},
],
},
/**
* Return statement
*/
// readonly -> mutable (function return)
{
filename: "file.ts",
code: `
type MutableA = { a: string };
type ReadonlyA = { readonly a: string };
function foo(): MutableA {
const ma: ReadonlyA = { a: "" };
return ma;
}
`,
errors: [
{
messageId: "errorStringArrowFunctionExpression",
type: AST_NODE_TYPES.ReturnStatement,
},
],
},
// Arrow function (block form) (readonly -> mutable)
{
filename: "file.ts",
code: `
type MutableA = { a: string };
type ReadonlyA = { readonly a: string };
const ro: ReadonlyA = { a: "" };
const func = (): MutableA => {
return ro;
};
`,
errors: [
{
messageId: "errorStringArrowFunctionExpression",
type: AST_NODE_TYPES.ReturnStatement,
},
],
},
],
} as const); | the_stack |
import * as utils from "ckeditor__ckeditor5-utils";
declare const document: Document;
declare const locale: utils.Locale;
declare let bool: boolean;
declare let changes: utils.Change[];
declare let emitter: utils.Emitter;
declare let htmlElement: HTMLElement;
declare let map: Map<string, number>;
declare let num: number;
declare let rect: utils.Rect;
declare let rectOrNull: utils.Rect | null;
declare let str: string;
// utils/dom
utils.createElement(document, "p");
utils.createElement(document, "p", {class: "foo"});
utils.createElement(document, "p", null, "foo");
utils.createElement(document, "p", null, ["foo", utils.createElement(document, "img")]);
// TODO? utils/dom/emittermixin
utils.getAncestors(htmlElement);
utils.getBorderWidths(htmlElement);
utils.getCommonAncestor(htmlElement, htmlElement);
str = utils.getDataFromElement(htmlElement);
let strNull: HTMLElement | null = utils.getPositionedAncestor();
strNull = utils.getPositionedAncestor(htmlElement);
num = utils.indexOf(htmlElement);
utils.insertAt(htmlElement, 2, htmlElement);
bool = utils.isNode(htmlElement);
bool = utils.isNode(new Date());
bool = utils.isRange(new Range());
bool = utils.isRange(new Date());
bool = utils.isText(new Text("foo"));
bool = utils.isText(new Date());
bool = utils.isWindow(window);
bool = utils.isWindow(new Date());
let position: utils.Position;
position = utils.getOptimalPosition({
element: htmlElement,
target: () => htmlElement,
positions: [(targetRect, elementRect) => ({
top: targetRect.top,
left: targetRect.left + elementRect.width,
name: "right"
})]
});
position = utils.getOptimalPosition({
element: htmlElement,
target: htmlElement,
positions: [
(targetRect) => ({
top: targetRect.bottom,
left: targetRect.left,
name: "mySouthEastPosition"
}),
(targetRect, elementRect) => ({
top: targetRect.top - elementRect.height,
left: targetRect.left,
name: "myNorthEastPosition"
})
],
limiter: document.body,
fitInViewport: true,
});
rect = new utils.Rect(document.body);
rect = new utils.Rect(document.getSelection()!.getRangeAt(0));
rect = new utils.Rect(window);
rect = new utils.Rect({top: 0, right: 10, bottom: 10, left: 0, width: 10, height: 10});
rect = new utils.Rect(rect);
rect = new utils.Rect(document.body.getClientRects().item(0)!);
rect = rect.clone();
bool = rect.contains(rect);
rect = rect.excludeScrollbarsAndBorders();
num = rect.getArea();
rect = rect.getIntersection(rect);
num = rect.getIntersectionArea(rect);
rectOrNull = rect.getVisible();
bool = rect.isEqual(rect);
rect = rect.moveBy(1, 1);
rect = rect.moveTo(1, 1);
utils.remove(htmlElement);
utils.scrollAncestorsToShowTarget(new Range());
utils.scrollAncestorsToShowTarget(htmlElement);
utils.scrollViewportToShowTarget({target: new Range()});
utils.scrollViewportToShowTarget({target: htmlElement});
utils.scrollViewportToShowTarget({target: new Range(), viewportOffset: 30});
utils.scrollViewportToShowTarget({target: htmlElement, viewportOffset: 30});
utils.setDataInElement(htmlElement, "<b>foo</b>");
str = utils.toUnit("rem")(10);
// utils/ckeditorerror ========================================================
const regularError = new Error("foo");
let ckeditorError: utils.CKEditorError;
const data = {bar: 1};
ckeditorError = new utils.CKEditorError("foo");
ckeditorError = new utils.CKEditorError("foo", data);
utils.CKEditorError.isCKEditorError(ckeditorError);
utils.CKEditorError.isCKEditorError(regularError);
// utils/collection ===========================================================
interface Foo {
foo: number;
}
interface Props {
id: string;
}
interface PropsStr {
id: string;
name: string;
}
declare let foo: Foo;
let items: PropsStr[];
let itemOrNull: Props | null;
let itemOrUndef: Props | undefined;
const item1 = {id: "id1"};
const item2 = {id: "id2"};
const itemStr1 = {id: "foo", name: "yy"};
const itemStr2 = {id: "foo", name: "xx"};
const coll = new utils.Collection<Props>();
const collStr = new utils.Collection<PropsStr>({idProperty: "name"});
coll.add(item1);
coll.add(item2);
collStr.add(itemStr1);
collStr.add(itemStr2);
coll.add(item1, 0);
coll.add(item1).add(item2);
coll.clear();
items = collStr.filter((item) => item.name === "yy");
items = collStr.filter((_, idx) => idx > 0);
items = collStr.filter(function(this: Foo, _, idx) {return this.foo > 0 && idx === 0; }, foo);
itemOrUndef = collStr.find((item) => item.name === "yy");
itemOrUndef = collStr.find((_, idx) => idx === 3);
itemOrUndef = collStr.find(function(this: Foo, _, idx) {return this.foo > 0 && idx === 0; }, foo);
itemOrNull = coll.get(0);
itemOrNull = coll.get("id1");
num = coll.getIndex("id1");
num = coll.getIndex(item1);
coll.remove(0);
coll.remove("id1");
coll.remove(item1);
const strings: string[] = collStr.map((item) => item.name);
const nums: number[] = collStr.map((_, idx) => idx);
const bools: boolean[] = collStr.map(function(this: Foo, _, idx) {return this.foo === idx; }, foo);
// collection#bindTo
interface LabelObj {
label: string;
}
interface LabelValueObj {
label: {value: string};
}
interface HiddenObj {
hidden: boolean;
}
class FactoryClass {
factoryLabel: string;
constructor(data: LabelObj) {
this.factoryLabel = data.label;
}
}
const source1 = new utils.Collection<LabelObj>({idProperty: "label"});
const target1 = new utils.Collection<FactoryClass>();
target1.bindTo(source1).as(FactoryClass);
source1.add({label: "foo"});
source1.add({label: "bar"});
source1.remove(0);
console.log(target1.length);
console.log(target1.get(0)!.factoryLabel);
class FooClass {
fooLabel: string;
constructor(data: LabelObj) {
this.fooLabel = data.label;
}
}
class BarClass {
barLabel: string;
constructor(data: LabelObj) {
this.barLabel = data.label;
}
}
const source2 = new utils.Collection<LabelObj>({idProperty: "label"});
const target2 = new utils.Collection<FooClass | BarClass>();
target2.bindTo(source2).using((item) => {
if (item.label === "foo") {
return new FooClass(item);
} else {
return new BarClass(item);
}
});
source2.add({label: "foo"});
source2.add({label: "bar"});
console.log(target2.length);
console.log(target2.get(0)! instanceof FooClass);
console.log(target2.get(1)! instanceof BarClass);
const source3 = new utils.Collection<LabelValueObj>({idProperty: "label"});
const target3 = new utils.Collection<LabelValueObj["label"]>();
target3.bindTo(source2).using("label");
source3.add({label: {value: "foo"}});
source3.add({label: {value: "bar"}});
console.log(target3.length);
console.log(target3.get(0)!.value);
console.log(target3.get(1)!.value);
const source4 = new utils.Collection<HiddenObj>();
const target4 = new utils.Collection<HiddenObj | null>();
target4.bindTo(source4).using(item => {
if (item.hidden) {
return null;
}
return item;
});
source4.add({hidden: true});
source4.add({hidden: false});
// utils/comparearrays ========================================================
utils.compareArrays([0, 2], [0, 2, 1]);
utils.compareArrays(["abc", 0 ], ["abc", 0, 3]);
// utils/config ===============================================================
let strOrUndef: string | undefined;
let config: utils.Config;
const defaultConfig = {
foo: 1, bar: 2,
};
config = new utils.Config();
config = new utils.Config({foo: 10});
config = new utils.Config({}, defaultConfig);
config = new utils.Config({foo: 10}, defaultConfig);
config.define({
resize: {
minHeight: 400,
hidden: true
}
});
config.define("resize", {minHeight: 400, hidden: true});
config.define("language", "en");
config.define("resize.minHeight", 400);
str = config.get("language");
num = config.get("resize.minHeight");
config.define("language", undefined);
strOrUndef = config.get("language");
// utils/count ================================================================
num = utils.count([1, 2, 3, 4, 5]);
// utils/diff =================================================================
changes = utils.diff("aba", "acca");
changes = utils.diff(Array.from("aba"), Array.from("acca"));
// utils/difftochanges ========================================================
const input = Array.from("abc");
const output = Array.from("xaby");
const allChanges = utils.diffToChanges(utils.diff(input, output), output);
allChanges.forEach(change => {
if (change.type === "insert") {
input.splice(change.index, 0, ...change.values);
} else if (change.type === "delete") {
input.splice(change.index, change.howMany);
}
});
// utils/elementreplacer ======================================================
const replacer = new utils.ElementReplacer();
replacer.replace(htmlElement, htmlElement);
replacer.replace(htmlElement);
replacer.restore();
// utils/emittermixin
emitter = utils.EmitterMixin;
emitter = Object.create(utils.EmitterMixin);
emitter.delegate("foo") ;
emitter.delegate("foo", "bar");
emitter.delegate("foo").to(emitter);
emitter.delegate("foo").to(emitter, "bar");
emitter.delegate("foo").to(emitter, name => name + "-delegated");
emitter.fire("foo");
emitter.fire("foo", 1, "b", true);
emitter.fire("getSelectedContent", (evt: utils.EventInfo<any>) => {
evt.return = new DocumentFragment();
evt.stop();
});
emitter.listenTo(emitter, "foo", () => {});
emitter.listenTo(emitter, "foo", () => {}, {priority: 10});
emitter.listenTo(emitter, "foo", () => {}, {priority: "highest"});
emitter.off("foo");
emitter.off("foo", () => {});
emitter.on("foo", () => {});
emitter.on("foo", () => {}, {priority: 10});
emitter.on("foo", () => {}, {priority: "normal"});
emitter.once("foo", () => {});
emitter.once("foo", () => {}, {priority: 10});
emitter.once("foo", () => {}, {priority: "lowest"});
emitter.stopDelegating();
emitter.stopDelegating("foo");
emitter.stopDelegating("foo", emitter);
emitter.stopListening();
emitter.stopListening(emitter);
emitter.stopListening(emitter, "foo");
emitter.stopListening(emitter, "foo", () => {});
// utils/env ==================================================================
bool = utils.env.isEdge;
bool = utils.env.isMac;
// utils/eventinfo ============================================================
const event = new utils.EventInfo({a: 1}, "test");
num = event.source.a;
str = event.name;
event.path[0];
event.stop();
event.off();
bool = event.stop.called;
bool = event.off.called;
// utils/fastdiff =============================================================
utils.fastDiff(str, "2ab").forEach(change => {
if (change.type === "insert") {
str = str.substring(0, change.index) + change.values.join("") + str.substring(change.index);
} else if (change.type === "delete") {
str = str.substring(0, change.index) + str.substring(change.index + change.howMany);
}
});
// utils/first ================================================================
const collection = [ 11, 22 ];
const iterator = collection[Symbol.iterator]();
utils.first(iterator);
// utils/focustracker =========================================================
const focusTracker = new utils.FocusTracker();
htmlElement = focusTracker.focusedElement;
bool = focusTracker.isFocused;
focusTracker.add(htmlElement);
focusTracker.remove(htmlElement);
// utils/isiterable ===========================================================
bool = utils.isIterable(str);
bool = utils.isIterable([1, 2, 3]);
// utils/keyboard =============================================================
num = utils.keyCodes.a;
num = utils.keyCodes["a"];
num = utils.getCode("0");
num = utils.getCode({keyCode: 48}) ;
num = utils.getCode({keyCode: 48, altKey: true, ctrlKey: true, shiftKey: true});
str = utils.getEnvKeystrokeText("alt+A");
num = utils.parseKeystroke("Ctrl+A");
num = utils.parseKeystroke(["ctrl", "a"]);
num = utils.parseKeystroke(["shift", 33]);
// utils/keystrokehandler =====================================================
declare const keystroke: utils.KeystrokeInfo;
const keystrokes = new utils.KeystrokeHandler();
const spy = utils.spy();
keystrokes.set("Ctrl+A", spy);
keystrokes.set(["Ctrl", "A"], spy);
keystrokes.set(["Ctrl", "A"], spy, {priority: "high"});
keystrokes.set(["Ctrl", 33], spy, {priority: 10});
const emitterMixxin = Object.create(utils.EmitterMixin) as utils.Emitter;
keystrokes.listenTo(emitterMixxin);
bool = keystrokes.press(keystroke);
keystrokes.destroy();
// utils/locale ===============================================================
locale.t("Label");
locale.t('Created file "%0" in %1ms.', ["fileName", "100"]);
// utils/log ==================================================================
utils.log.warn("message");
utils.log.warn('plugin-load: It was not possible to load the "{$pluginName}" plugin in module "{$moduleName}', {
pluginName: "foo",
moduleName: "bar"
});
utils.log.error("message");
utils.log.error('plugin-load: It was not possible to load the "{$pluginName}" plugin in module "{$moduleName}', {
pluginName: "foo",
moduleName: "bar"
});
// utils/mapsequal ============================================================
utils.mapsEqual(map, map);
// utils/mix ==================================================================
interface SomeMixin {
a: () => string;
}
class Editor implements SomeMixin {
a: () => string;
b() { return 3; }
}
const SomeMixin = {
a() { return "a"; }
};
const SomeMixinNum = {
a() { return 3; }
};
utils.mix(Editor, SomeMixin);
// $ExpectError
utils.mix(Editor, SomeMixinNum);
const editor = new Editor();
str = editor.a();
num = editor.b();
// utils/nth ==================================================================
function* getGenerator() {
yield 11;
yield 22;
yield 33;
}
utils.nth(2, getGenerator());
// utils/objecttomap ==========================================================
const objMap: Map<string, number> = utils.objectToMap({foo: 1, bar: 2});
num = objMap.get("foo")!;
// utils/observablemixin ======================================================
const observable: utils.Observable = utils.ObservableMixin;
const vehicle = Object.create(utils.ObservableMixin) as utils.Observable;
const car = Object.create(utils.ObservableMixin) as utils.Observable;
vehicle.bind("color");
vehicle.bind("color", "year");
vehicle.bind("color", "year").to(car);
vehicle.bind("color", "year").to(car, "color");
vehicle.bind("color", "year").to(car, "color", car, "year");
vehicle.bind("year").to(car, "color", car, "year", (a: string, b: number) => a + b);
vehicle.bind("custom").to(car, "color", car, "year", car, "hue", (...args: Array<string | number>) => args.join("/")); // TS 3.0: [string, number, string]
vehicle.bind("color").toMany([car, car], "color", () => {});
vehicle.decorate("method");
car.set("color", "red");
car.set("seats", undefined);
car.set({
color: "blue",
wheels: 4,
seats: 5,
});
vehicle.unbind();
vehicle.unbind("color");
vehicle.unbind("color", "year");
// utils/priorities ===========================================================
num = utils.priorities.get(2);
num = utils.priorities.get("normal");
// utils/spy
const fn1 = utils.spy();
fn1();
bool = fn1.called;
// utils/tomap
map = utils.toMap({foo: 1, bar: 2});
map = utils.toMap([["foo", 1], ["bar", 2]]);
map = utils.toMap(map);
// utils/translation-service ==================================================
utils.add("pl", {
OK: "OK",
"Cancel [context: reject]": "Anuluj"
});
utils.translate("pl", "Cancel [context: reject]");
// utils/uid ==================================================================
str = utils.uid();
// utils/unicode ==============================================================
bool = utils.isCombiningMark("a");
bool = utils.isHighSurrogateHalf("a");
bool = utils.isInsideCombinedSymbol(str, 2);
bool = utils.isInsideSurrogatePair(str, 2);
bool = utils.isLowSurrogateHalf(String.fromCharCode(57166));
// utils/version ============================================================== | the_stack |
module AutoMapperJs {
'use strict';
/**
* AutoMapper helper functions
*/
export class AutoMapperHelper {
public static getClassName(classType: new () => any): string {
if (classType && (<any>classType).name) {
return (<any>classType).name;
}
// source: http://stackoverflow.com/a/13914278/702357
if (classType && classType.constructor) {
let className = classType.toString();
if (className) {
// classType.toString() is "function classType (...) { ... }"
let matchParts = className.match(/function\s*(\w+)/);
if (matchParts && matchParts.length === 2) {
return matchParts[1];
}
}
// for browsers which have name property in the constructor
// of the object, such as chrome
if ((<any>classType.constructor).name) {
return (<any>classType.constructor).name;
}
if (classType.constructor.toString()) {
let str = classType.constructor.toString();
let regExpMatchArray: RegExpMatchArray;
if (str.charAt(0) === '[') {
// executed if the return of object.constructor.toString() is "[object objectClass]"
regExpMatchArray = str.match(/\[\w+\s*(\w+)\]/);
} else {
// executed if the return of object.constructor.toString() is "function objectClass () {}"
// (IE and Firefox)
regExpMatchArray = str.match(/function\s*(\w+)/);
}
if (regExpMatchArray && regExpMatchArray.length === 2) {
return regExpMatchArray[1];
}
}
}
throw new Error(`Unable to extract class name from type '${classType}'`);
}
public static getFunctionParameters(functionStr: string): Array<string> {
const stripComments = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
const argumentNames = /([^\s,]+)/g;
var functionString = functionStr.replace(stripComments, '');
var functionParameterNames = functionString.slice(functionString.indexOf('(') + 1, functionString.indexOf(')')).match(argumentNames);
if (functionParameterNames === null) {
functionParameterNames = new Array<string>();
}
return functionParameterNames;
}
public static handleCurrying(func: Function, args: IArguments, closure: any): any {
const argumentsStillToCome = func.length - args.length;
// saved accumulator array
// NOTE BL this does not deep copy array objects, only the array itself; should side effects occur, please report (or refactor).
var argumentsCopy = Array.prototype.slice.apply(args);
function accumulator(moreArgs: IArguments, alreadyProvidedArgs: Array<any>, stillToCome: number): Function {
var previousAlreadyProvidedArgs = alreadyProvidedArgs.slice(0); // to reset
var previousStillToCome = stillToCome; // to reset
for (let i = 0; i < moreArgs.length; i++ , stillToCome--) {
alreadyProvidedArgs[alreadyProvidedArgs.length] = moreArgs[i];
}
if (stillToCome - moreArgs.length <= 0) {
var functionCallResult = func.apply(closure, alreadyProvidedArgs);
// reset vars, so curried function can be applied to new params.
alreadyProvidedArgs = previousAlreadyProvidedArgs;
stillToCome = previousStillToCome;
return functionCallResult;
} else {
return function (): Function {
// arguments are params, so closure bussiness is avoided.
return accumulator(arguments, alreadyProvidedArgs.slice(0), stillToCome);
};
}
}
return accumulator(<IArguments>(<any>[]), argumentsCopy, argumentsStillToCome);
}
public static getMappingMetadataFromTransformationFunction(destination: string, func: any, sourceMapping: boolean): IMemberMappingMetaData {
if (typeof func !== 'function') {
return {
destination: destination,
source: destination,
transformation: AutoMapperHelper.getDestinationTransformation(func, false, sourceMapping, false),
sourceMapping: sourceMapping,
condition: null,
ignore: false,
async: false
};
}
var functionStr = func.toString();
var parameterNames = AutoMapperHelper.getFunctionParameters(functionStr);
var optsParamName = parameterNames.length >= 1 ? parameterNames[0] : '';
var source = sourceMapping
? destination
: AutoMapperHelper.getMapFromString(functionStr, destination, optsParamName);
var metadata: IMemberMappingMetaData = {
destination: destination,
source: source,
transformation: AutoMapperHelper.getDestinationTransformation(func, true, sourceMapping, parameterNames.length === 2),
sourceMapping: sourceMapping,
condition: null,
ignore: AutoMapperHelper.getIgnoreFromString(functionStr, destination),
async: parameterNames.length === 2
};
// calling the member options function when used asynchronous would be too 'dangerous'.
if (!metadata.async && AutoMapperHelper.getFunctionCallIndex(functionStr, 'condition', optsParamName) >= 0) {
metadata.condition = AutoMapperHelper.getConditionFromFunction(func, source);
}
return metadata;
}
private static getDestinationTransformation(func: any, isFunction: boolean, sourceMapping: boolean, async: boolean): IDestinationTransformation {
if (!isFunction) {
return {
transformationType: DestinationTransformationType.Constant,
constant: func
};
}
var transformation: IDestinationTransformation;
if (sourceMapping) {
if (async) {
transformation = {
transformationType: DestinationTransformationType.AsyncSourceMemberOptions,
asyncSourceMemberConfigurationOptionsFunc: func
};
} else {
transformation = {
transformationType: DestinationTransformationType.SourceMemberOptions,
sourceMemberConfigurationOptionsFunc: func
};
}
} else {
if (async) {
transformation = {
transformationType: DestinationTransformationType.AsyncMemberOptions,
asyncMemberConfigurationOptionsFunc: func
};
} else {
transformation = {
transformationType: DestinationTransformationType.MemberOptions,
memberConfigurationOptionsFunc: func
};
}
}
return transformation;
}
private static getIgnoreFromString(functionString: string, optionsParameterName: string): boolean {
var indexOfIgnore = AutoMapperHelper.getFunctionCallIndex(functionString, 'ignore', optionsParameterName);
if (indexOfIgnore < 0) {
return false;
}
var indexOfMapFromStart = functionString.indexOf('(', indexOfIgnore) + 1;
var indexOfMapFromEnd = functionString.indexOf(')', indexOfMapFromStart);
if (indexOfMapFromStart < 0 || indexOfMapFromEnd < 0) {
return false;
}
var ignoreString = functionString.substring(indexOfMapFromStart, indexOfMapFromEnd).replace(/\r/g, '').replace(/\n/g, '').trim();
return ignoreString === null || ignoreString === ''
? true // <optionsParameterName>.ignore()
: false; // <optionsParameterName>.ignore(<ignoreString> -> unexpected content)
}
private static getMapFromString(functionString: string, defaultValue: string, optionsParameterName: string): string {
var indexOfMapFrom = AutoMapperHelper.getFunctionCallIndex(functionString, 'mapFrom', optionsParameterName);
if (indexOfMapFrom < 0) {
return defaultValue;
}
var indexOfMapFromStart = functionString.indexOf('(', indexOfMapFrom) + 1;
var indexOfMapFromEnd = functionString.indexOf(')', indexOfMapFromStart);
if (indexOfMapFromStart < 0 || indexOfMapFromEnd < 0) {
return defaultValue;
}
var mapFromString = functionString.substring(indexOfMapFromStart, indexOfMapFromEnd).replace(/'/g, '').replace(/"/g, '').trim();
return mapFromString === null || mapFromString === ''
? defaultValue
: mapFromString;
}
private static getFunctionCallIndex(functionString: string, functionToLookFor: string, optionsParameterName: string): number {
var indexOfFunctionCall = functionString.indexOf(optionsParameterName + '.' + functionToLookFor);
if (indexOfFunctionCall < 0) {
indexOfFunctionCall = functionString.indexOf('.' + functionToLookFor);
}
return indexOfFunctionCall;
}
private static getConditionFromFunction(func: Function, sourceProperty: string): ((sourceObject: any) => boolean) {
// Since we are calling the valueOrFunction function to determine whether to ignore or map from another property, we
// want to prevent the call to be error prone when the end user uses the '(opts)=> opts.sourceObject.sourcePropertyName'
// syntax. We don't actually have a source object when creating a mapping; therefore, we 'stub' a source object for the
// function call.
var sourceObject: any = {};
sourceObject[sourceProperty] = {};
var condition: (sourceObject: any) => boolean;
// calling the function will result in calling our stubbed ignore() and mapFrom() functions if used inside the function.
const configFuncOptions: IMemberConfigurationOptions = {
ignore: (): void => {
// do nothing
},
condition: (predicate: ((sourceObject: any) => boolean)): void => {
condition = predicate;
},
mapFrom: (sourcePropertyName: string): void => {
// do nothing
},
sourceObject: sourceObject,
sourcePropertyName: sourceProperty,
intermediatePropertyValue: {}
};
try {
func(configFuncOptions);
} catch (exc) {
// do not handle by default.
}
return condition;
}
}
} | the_stack |
import { GradientSky, Light, Sky } from "@here/harp-datasource-protocol";
import { ProjectionType, Vector3Like } from "@here/harp-geoutils";
import { getOptionValue, LoggerManager } from "@here/harp-utils";
import THREE = require("three");
import { BackgroundDataSource } from "./BackgroundDataSource";
import { MapView, MapViewOptions } from "./MapView";
import { MapViewFog } from "./MapViewFog";
import { SkyBackground } from "./SkyBackground";
import { createLight } from "./ThemeHelpers";
const logger = LoggerManager.instance.create("MapViewEnvironment");
// the default breaks the ibct tests, seems it had not been used in all cases before
export const DEFAULT_CLEAR_COLOR = 0xffffff; //0xefe9e1;
const cache = {
vector3: [new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3()],
frustumPoints: [
new THREE.Vector3(),
new THREE.Vector3(),
new THREE.Vector3(),
new THREE.Vector3(),
new THREE.Vector3(),
new THREE.Vector3(),
new THREE.Vector3(),
new THREE.Vector3()
]
};
export type MapViewEnvironmentOptions = Pick<
MapViewOptions,
"addBackgroundDatasource" | "backgroundTilingScheme"
>;
/**
* Class handling the Scene Environment, like fog, sky, background datasource, clearColor etc
* for MapView
*/
export class MapViewEnvironment {
private readonly m_fog: MapViewFog;
private m_skyBackground?: SkyBackground;
private m_createdLights?: THREE.Light[];
private m_overlayCreatedLights?: THREE.Light[];
private readonly m_backgroundDataSource?: BackgroundDataSource;
constructor(private readonly m_mapView: MapView, options: MapViewEnvironmentOptions) {
this.m_fog = new MapViewFog(this.m_mapView.scene);
if (options.addBackgroundDatasource !== false) {
this.m_backgroundDataSource = new BackgroundDataSource();
this.m_mapView.addDataSource(this.m_backgroundDataSource);
}
if (
options.backgroundTilingScheme !== undefined &&
this.m_backgroundDataSource !== undefined
) {
this.m_backgroundDataSource.setTilingScheme(options.backgroundTilingScheme);
}
this.updateClearColor();
}
get lights(): THREE.Light[] {
return this.m_createdLights ?? [];
}
get fog(): MapViewFog {
return this.m_fog;
}
updateBackgroundDataSource() {
if (this.m_backgroundDataSource) {
this.m_backgroundDataSource.updateStorageLevelOffset();
}
}
clearBackgroundDataSource() {
if (this.m_backgroundDataSource !== undefined) {
this.m_mapView.clearTileCache(this.m_backgroundDataSource.name);
}
}
update() {
this.m_fog.update(this.m_mapView, this.m_mapView.viewRanges.maximum);
if (
this.m_skyBackground !== undefined &&
this.m_mapView.projection.type === ProjectionType.Planar
) {
this.m_skyBackground.updateCamera(this.m_mapView.camera);
}
this.updateLights();
}
updateClearColor(clearColor?: string, clearAlpha?: number) {
if (clearColor !== undefined) {
this.m_mapView.renderer.setClearColor(new THREE.Color(clearColor), clearAlpha);
} else {
this.m_mapView.renderer.setClearColor(DEFAULT_CLEAR_COLOR, clearAlpha);
}
}
updateSkyBackground(sky?: Sky, clearColor?: string) {
if (this.m_skyBackground instanceof SkyBackground && sky !== undefined) {
// there is a sky in the view and there is a sky option in the theme. Update the colors
this.updateSkyBackgroundColors(sky, clearColor);
} else if (this.m_skyBackground === undefined && sky !== undefined) {
// there is no sky in the view but there is a sky option in the theme
this.addNewSkyBackground(sky, clearColor);
return;
} else if (this.m_skyBackground instanceof SkyBackground && sky === undefined) {
// there is a sky in the view, but not in the theme
this.removeSkyBackGround();
}
}
updateLighting(lights?: Light[]) {
if (this.m_createdLights) {
this.m_createdLights.forEach((light: THREE.Light) => {
this.m_mapView.scene.remove(light);
});
}
this.m_overlayCreatedLights?.forEach(light => {
this.m_mapView.overlayScene.remove(light);
if (light instanceof THREE.DirectionalLight) {
this.m_mapView.overlayScene.remove(light.target);
}
});
if (lights !== undefined) {
this.m_createdLights = [];
this.m_overlayCreatedLights = [];
lights.forEach((lightDescription: Light) => {
const light = createLight(lightDescription);
if (!light) {
logger.warn(
`MapView: failed to create light ${lightDescription.name} of type ${lightDescription.type}`
);
return;
}
this.m_mapView.scene.add(light);
if ((light as any).isDirectionalLight) {
const directionalLight = light as THREE.DirectionalLight;
// This is needed so that the target is updated automatically, see:
// https://threejs.org/docs/#api/en/lights/DirectionalLight.target
this.m_mapView.scene.add(directionalLight.target);
}
this.m_createdLights!.push(light);
const clonedLight: THREE.Light = light.clone() as THREE.Light;
this.m_mapView.overlayScene.add(clonedLight);
if (clonedLight instanceof THREE.DirectionalLight) {
this.m_mapView.overlayScene.add(clonedLight.target.clone());
}
});
}
}
/**
* Update the directional light camera. Note, this requires the cameras to first be updated.
*/
updateLights() {
// TODO: HARP-9479 Globe doesn't support shadows.
if (
!this.m_mapView.shadowsEnabled ||
this.m_mapView.projection.type === ProjectionType.Spherical ||
this.m_createdLights === undefined ||
this.m_createdLights.length === 0
) {
return;
}
const points: Vector3Like[] = [
// near plane points
{ x: -1, y: -1, z: -1 },
{ x: 1, y: -1, z: -1 },
{ x: -1, y: 1, z: -1 },
{ x: 1, y: 1, z: -1 },
// far planes points
{ x: -1, y: -1, z: 1 },
{ x: 1, y: -1, z: 1 },
{ x: -1, y: 1, z: 1 },
{ x: 1, y: 1, z: 1 }
];
const transformedPoints = points.map((p, i) =>
this.m_mapView.ndcToView(p, cache.frustumPoints[i])
);
this.m_createdLights.forEach(element => {
const directionalLight = element as THREE.DirectionalLight;
if (directionalLight.isDirectionalLight === true) {
const lightDirection = cache.vector3[0];
lightDirection.copy(directionalLight.target.position);
lightDirection.sub(directionalLight.position);
lightDirection.normalize();
const normal = cache.vector3[1];
if (this.m_mapView.projection.type === ProjectionType.Planar) {
// -Z points to the camera, we can't use Projection.surfaceNormal, because
// webmercator and mercator give different results.
normal.set(0, 0, -1);
} else {
// Enable shadows for globe...
//this.projection.surfaceNormal(target, normal);
}
// The camera of the shadow has the same height as the map camera, and the target is
// also the same. The position is then calculated based on the light direction and
// the height
// using basic trigonometry.
const tilt = this.m_mapView.tilt;
const cameraHeight =
this.m_mapView.targetDistance * Math.cos(THREE.MathUtils.degToRad(tilt));
const lightPosHyp = cameraHeight / normal.dot(lightDirection);
directionalLight.target.position
.copy(this.m_mapView.worldTarget)
.sub(this.m_mapView.camera.position);
directionalLight.position.copy(this.m_mapView.worldTarget);
directionalLight.position.addScaledVector(lightDirection, -lightPosHyp);
directionalLight.position.sub(this.m_mapView.camera.position);
directionalLight.updateMatrixWorld();
directionalLight.shadow.updateMatrices(directionalLight);
const camera = directionalLight.shadow.camera;
const pointsInLightSpace = transformedPoints.map(p =>
this.viewToLightSpace(p.clone(), camera)
);
const box = new THREE.Box3();
pointsInLightSpace.forEach(point => {
box.expandByPoint(point);
});
camera.left = box.min.x;
camera.right = box.max.x;
camera.top = box.max.y;
camera.bottom = box.min.y;
// Moving back to the light the near plane in order to catch high buildings, that
// are not visible by the camera, but existing on the scene.
camera.near = -box.max.z * 0.95;
camera.far = -box.min.z;
camera.updateProjectionMatrix();
}
});
}
private addNewSkyBackground(sky: Sky, clearColor: string | undefined) {
if (sky.type === "gradient" && (sky as GradientSky).groundColor === undefined) {
sky.groundColor = getOptionValue(clearColor, "#000000");
}
this.m_skyBackground = new SkyBackground(
sky,
this.m_mapView.projection.type,
this.m_mapView.camera
);
this.m_mapView.scene.background = this.m_skyBackground.texture;
}
private removeSkyBackGround() {
this.m_mapView.scene.background = null;
if (this.m_skyBackground !== undefined) {
this.m_skyBackground.dispose();
this.m_skyBackground = undefined;
}
}
private updateSkyBackgroundColors(sky: Sky, clearColor: string | undefined) {
if (sky.type === "gradient" && (sky as GradientSky).groundColor === undefined) {
sky.groundColor = getOptionValue(clearColor, "#000000");
}
if (this.m_skyBackground !== undefined) {
this.m_skyBackground.updateTexture(sky, this.m_mapView.projection.type);
this.m_mapView.scene.background = this.m_skyBackground?.texture;
}
}
/**
* Transfer from view space to camera space.
* @param viewPos - position in view space, result is stored here.
*/
private viewToLightSpace(viewPos: THREE.Vector3, camera: THREE.Camera): THREE.Vector3 {
return viewPos.applyMatrix4(camera.matrixWorldInverse);
}
} | the_stack |
import * as deepClone from 'deep.clone';
import jq, { data } from 'jquery';
import mime from 'mime-types';
import { AppUIState } from './appUIState';
import { AppUtils } from './appUtils';
import { composeQuery, Field as SOQLField } from 'soql-parser-js';
import { Config } from '../models/config';
import {
CONSTANTS,
DATA_MEDIA_TYPE,
MIGRATION_DIRECTION,
OPERATION,
SOURCE_TYPE,
CONSOLE_COMMAND_EVENT_TYPE
} from './statics';
import { DbUtils } from './dbUtils';
import { FieldItem } from '../models/fieldItem';
import { Form } from '../models/form';
import { IAngularScope } from './helper_interfaces';
import { ObjectEditData } from './helper_classes';
import { Org } from '../models/org';
import { RESOURCES } from './resources';
import { ScriptMappingItem } from '../models/scriptMappingItem';
import { ScriptObject } from '../models/scriptObject';
import { ScriptObjectField } from '../models/ScriptObjectField';
import { UserDataWrapper } from '../models/userDataWrapper';
import fs = require('fs');
import path = require('path');
import { ConsoleUtils } from './consoleUtils';
import { ScriptMockField } from '../models/scriptMockField';
const $ = <any>jq;
export class Controller {
////////////////////////////////////////////////////////////
// Declarations ////////////////////////////////////////////
////////////////////////////////////////////////////////////
// --------- //
$copyToClipboard: any;
$scope: IAngularScope;
$rootScope: any;
$http: any;
$timeout: any;
$window: any;
$q: any;
$sce: any;
// --------- //
$state: {
go: (page: string) => any
};
bootbox: {
confirm: Function,
prompt: Function
}
get ui(): AppUIState {
return this.$scope.ui;
}
// --------- //
constructor(controllerData: any) {
AppUtils.objectApply(this, controllerData);
}
////////////////////////////////////////////////////////////
// Common //////////////////////////////////////////////////
////////////////////////////////////////////////////////////
init() {
// Setup controller //////
this.controllerSetup(true);
}
controllerSetup(isInitialSetup?: boolean) {
let self = this;
// Each-time setup ////////
this.$scope.ui = new AppUIState(this);
this.$scope.res = RESOURCES;
// Initial setup only ///////
if (isInitialSetup) {
// Setup window object
document.title = AppUIState.appSettings.app_title;
this.bootbox = this.$window["bootbox"];
// Setup watchers
this._addWhatcher("ui.state.sobject().query", this.objectQueryChangedHandler);
this._addWhatcher("ui.homePage.currentSourceOrgIds", this.orgChangedHandler);
this._addWhatcher("ui.homePage.currentTargetOrgIds", this.orgChangedHandler);
this._addWhatcher("ui.configPage.allConfigIds", this.configChangedHandler);
this.$rootScope.$on('$stateChangeStart', function (event: any,
toState: any, toParams: any,
fromState: any) {
// Switch between tabs in the main menu
$('.side-nav a').removeClass('active');
$(`.side-nav a[data-state="${toState.name}"]`).addClass('active');
// What to do on state change ?
switch (toState.name) {
case "login":
self.loginPageSetup();
break;
case "register":
self.registerPageSetup();
break;
case "home":
if (fromState.name == "login") {
self.homePageSetup();
}
break;
// case "config":
// break;
// case "preview":
// // TODO:
// break;
// case "execute":
// // TODO:
// break;
case "profile":
self.profilePageSetup();
break;
}
});
// Go to the login page
AppUtils.execAsyncSync(async () => {
$('#wrapper').removeClass('hidden');
this.$state.go('login');
this._refreshUI();
}, 50);
}
}
switchStateHandler(state: string) {
this.$state.go(state);
}
openBasePathInExplorerHandler() {
AppUtils.openExplorer(this.ui.state.userData.basePath);
}
openConfigInExplorerHandler() {
if (fs.existsSync(this.ui.state.config().exportJsonFilepath))
AppUtils.openExplorer(this.ui.state.config().exportJsonFilepath);
else
this.openBasePathInExplorerHandler();
}
////////////////////////////////////////////////////////////////
// Login page //////////////////////////////////////////////////
////////////////////////////////////////////////////////////////
loginPageSetup() {
this.controllerSetup();
this._displayNewVersionMessage();
this._refreshUI();
}
loginHandler() {
if (this.ui.loginPage.form.isValid()) {
this._execAsyncSync(async () => {
let u = await DbUtils.findAndLoadUserDataAsync(this.ui.loginPage.form.email, this.ui.loginPage.form.password);
if (u) {
this.ui.state.userData = new UserDataWrapper().fromSecuredObject(u, this.ui.loginPage.form.password);
await DbUtils.compactDbAsync();
this.$state.go('home');
this._refreshUI();
} else {
this.$scope.$apply(() => this.ui.loginPage.form.invalid = true);
}
});
}
}
logOffHandler() {
this.ui.state.userData = undefined;
this.ui.loginPage.form = new Form();
this.ui.registerPage.form = new Form();
this.$state.go('login');
this._refreshUI();
}
//////////////////////////////////////////////////////////////
// Register page /////////////////////////////////////////////
//////////////////////////////////////////////////////////////
registerPageSetup() {
this.controllerSetup();
this._refreshUI();
}
registerHandler() {
if (this.ui.registerPage.form.isValid()) {
this._execAsyncSync(async () => {
let u = await DbUtils.findAndLoadUserDataAsync(this.ui.registerPage.form.email, this.ui.registerPage.form.password);
if (u) {
this.$scope.$apply(() => this.ui.registerPage.form.invalid = true);
return;
}
this.ui.state.userData = new UserDataWrapper({
plainEmail: this.ui.registerPage.form.email,
plainPassword: this.ui.registerPage.form.password
});
await DbUtils.insertUserAsync(this.ui.state.userData);
await DbUtils.compactDbAsync();
// Go next page
this.$state.go('home');
});
}
}
/////////////////////////////////////////////////////////////////////
// Profile page ///////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////
profilePageSetup() {
this.ui.profilePage.form = new Form({
email: this.ui.state.userData.plainEmail,
password: this.ui.state.userData.plainPassword
});
AppUtils.objectAssignSafe(this.ui.profilePage.settingsForm, AppUIState.appSettings);
this._refreshUI();
}
saveEmailAndPasswordHandler() {
if (this.ui.profilePage.form.isValid()) {
this._execAsyncSync(async () => {
let u = this.ui.profilePage.form.email != this.ui.state.userData.plainEmail
&& await DbUtils.findAndLoadUserDataAsync(this.ui.profilePage.form.email, this.ui.profilePage.form.password);
if (u) {
this.$scope.$apply(() => this.ui.profilePage.form.invalid = true);
return;
}
this.ui.state.userData.plainEmail = this.ui.profilePage.form.email;
this.ui.state.userData.plainPassword = this.ui.profilePage.form.password;
await DbUtils.saveUserAsync(this.ui.state.userData);
this.ui.profilePage.form.invalid = false;
this.$scope.$apply(undefined);
this._showUIToast("success", {
content: RESOURCES.Profile_UserProfileSaved
});
});
}
}
openChangeBasePathDialogHandler() {
let newPaths = AppUtils.selectFolder(AppUIState.appSettings.db_basePath);
this.ui.profilePage.settingsForm.db_basePath = newPaths && newPaths[0] || this.ui.profilePage.settingsForm.db_basePath;
}
saveApplicationSettingsHandler() {
this._execAsyncSync(async () => {
AppUtils.writeUserJson(this.ui.profilePage.settingsForm);
AppUtils.objectAssignSafe(AppUIState.appSettings, this.ui.profilePage.settingsForm);
if (DbUtils.getDbFilePath() != this.ui.profilePage.settingsForm.db_basePath // Path is changed
|| DbUtils.getDbFilenameWithoutPath() != this.ui.profilePage.settingsForm.db_name /*Name is changed*/) {
await DbUtils.moveDbAsync(this.ui.profilePage.settingsForm.db_moveFiles);
}
this._refreshUI();
this._showUIToast("success", {
content: RESOURCES.Profile_UserProfileSaved
});
});
}
/////////////////////////////////////////////////////////////////////
// Home (connection) page ///////////////////////////////////////////
/////////////////////////////////////////////////////////////////////
homePageSetup() {
this._refreshUI();
}
orgChangedHandler($new: Array<string>, $old: Array<string>, $scope: IAngularScope) {
$scope.ui.state.setSourceTargetOrgs();
}
refreshOrgsListHandler() {
this._execAsyncSync(async () => {
this._showUILoader(RESOURCES.Home_Message_ReadingOrgList);
let orgList = await AppUtils.execForceOrgList();
if (orgList.orgs.length == 0) {
this._showUIToast("warning", {
title: RESOURCES.DefaultToastWarningTitle,
content: RESOURCES.Home_Message_NoSFDXOrgsDetected
});
}
this.ui.state.userData.orgs = [].concat(orgList.orgs.map(org => {
return new Org({
instanceUrl: org.instanceUrl,
orgId: org.orgId,
orgName: org.username,
name: org.username,
alias: org.alias,
media: DATA_MEDIA_TYPE.Org
})
}), this.ui.state.userData.orgs.filter(org => org.orgName == CONSTANTS.CSV_FILES_SOURCENAME));
await DbUtils.saveUserAsync(this.ui.state.userData);
this.$scope.$apply(undefined);
});
}
executeForceOrgListHandler() {
this._execAsyncSync(async () => {
this._showUILoader(RESOURCES.Home_Message_ExecutingForceOrgList);
let result = await AppUtils.execForceOrgList();
this.ui.homePage.cliOutputPlain = result.commandOutput;
this.ui.homePage.cliOutput = this._textToHtml(result.commandOutput);
this.$scope.$apply(undefined);
});
}
executeForceOrgDisplayHandler() {
this._execAsyncSync(async () => {
let commandOutputArr = [];
if (this.ui.state.sourceOrg().isOrg()) {
this._showUILoader(RESOURCES.Home_Message_ExecutingForceOrgDisplay.format(this.ui.state.sourceOrg().name));
commandOutputArr.push((await AppUtils.execForceOrgDisplay(this.ui.state.sourceOrg().name, true)).commandOutput.trim());
}
if (this.ui.state.targetOrg().isOrg()) {
this._showUILoader(RESOURCES.Home_Message_ExecutingForceOrgDisplay.format(this.ui.state.targetOrg().name));
commandOutputArr.push((await AppUtils.execForceOrgDisplay(this.ui.state.targetOrg().name, true)).commandOutput.trim());
}
let commandOutput = "";
if (commandOutputArr.length > 0) {
commandOutput = `[${commandOutputArr.join(',')}]`;
commandOutput = AppUtils.pretifyJson(commandOutput);
} else {
commandOutput = RESOURCES.Home_Message_SelectSourceOrTarget;
}
this.ui.homePage.cliOutputPlain = commandOutput;
this.ui.homePage.cliOutput = this._textToHtml(commandOutput);
this.$scope.$apply(undefined);
});
}
downloadCLICommadOutputHandler() {
this._showUILoader();
let fileName = this.ui.state.userData.cliCommadOutputFilename;
fs.writeFileSync(fileName, this.ui.homePage.cliOutputPlain);
this._hideUILoader();
this._downloadFile(fileName);
}
homeGoNext() {
this._execAsyncSync(async () => {
// Set Source/Target orgs
this.ui.state.setSourceTargetOrgs();
await this._connectOrgsAsync();
// Go next page
this.configPageSetup();
this.$state.go('config');
});
}
/////////////////////////////////////////////////////////////////////
// Configuration page ///////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////
configPageSetup() {
this.ui.configPage.allConfigIds = new Array<string>();
this.ui.configPage.currentSObjectId = undefined;
this.ui.previewPage.allowShowing = false;
this.ui.executePage.allowShowing = false;
this._refreshUI();
}
initConfig($scope: IAngularScope) {
$scope.ui.controller.$timeout(() => {
$scope.ui.configPage.currentSObjectId = undefined;
$scope.ui.state.config().initialize();
$scope.ui.controller._refreshUI();
}, 50);
}
configChangedHandler($new: Array<string>, $old: Array<string>, $scope: IAngularScope) {
$scope.ui.controller.initConfig($scope);
}
switchOrgsHandler() {
this._showUILoader();
let sourceOrg = this.ui.state.sourceOrg();
let targetOrg = this.ui.state.targetOrg();
sourceOrg.sourceType = sourceOrg.sourceType == SOURCE_TYPE.Source ? SOURCE_TYPE.Target : SOURCE_TYPE.Source;
targetOrg.sourceType = targetOrg.sourceType == SOURCE_TYPE.Source ? SOURCE_TYPE.Target : SOURCE_TYPE.Source;
this.initConfig(this.$scope);
this._hideUILoader();
}
addConfigClickHandler() {
this._execAsyncSync(async () => {
let configName = await this._showPromptAsync(RESOURCES.Config_CreateConfigPrompt, RESOURCES.Config_CreateConfigTitle, "");
if (configName) {
this._showUILoader();
let config = new Config({
id: AppUtils.makeId(),
name: configName,
userData: this.ui.state.userData
});
this.ui.state.userData.configs.push(config);
await DbUtils.saveUserAsync(this.ui.state.userData);
this.ui.configPage.allConfigIds = [config.id];
this.$scope.$apply(undefined);
}
}, null, null, false);
}
editConfigClickHandler() {
this._execAsyncSync(async () => {
let configName = await this._showPromptAsync(RESOURCES.Config_EditConfigPrompt, RESOURCES.Config_EditConfigTitle, this.ui.state.config().name);
if (configName) {
this._showUILoader();
this.ui.state.config().initialize({
name: configName
});
await DbUtils.saveUserAsync(this.ui.state.userData);
this.$scope.$apply(undefined);
}
}, null, null, false);
}
cloneConfigClickHandler() {
this._execAsyncSync(async () => {
let configName = await this._showPromptAsync(RESOURCES.Config_CloneConfigPrompt, RESOURCES.Config_CloneConfigTitle, this.ui.state.config().name);
if (configName) {
this._showUILoader();
let config = deepClone.deepCloneSync(this.ui.state.config(), {
absolute: true,
});
config.initialize({
id: AppUtils.makeId(),
name: configName,
userData: this.ui.state.userData
})
this.ui.state.userData.configs.push(config);
await DbUtils.saveUserAsync(this.ui.state.userData);
this.ui.configPage.allConfigIds = [config.id];
this.$scope.$apply(undefined);
}
}, null, null, false);
}
uploadConfigChangeHandler(event: any) {
let self = this;
this._readSingleFile(event).then(function (json) {
self._execAsyncSync(async () => {
let config = new Config({
id: AppUtils.makeId(),
name: path.basename(event.target.value).split('.').slice(0, -1).join('.'),
userData: self.ui.state.userData
});
config.fromExportObjectJson(json);
self.ui.state.userData.configs.push(config);
await DbUtils.saveUserAsync(self.ui.state.userData);
self.ui.configPage.allConfigIds = [config.id];
self.$scope.$apply(undefined);
self._refreshUI();
});
});
}
downloadConfigClickHandler() {
this._showUILoader();
let fileName = this.ui.state.config().exportObjectFilename;
fs.writeFileSync(fileName, this.ui.state.config().toExportObjectJson());
this._hideUILoader();
this._downloadFile(fileName);
}
removeConfigClickHandler() {
this._execAsyncSync(async () => {
let confirmed = await this._showConfirmAsync(null, RESOURCES.Config_DeleteConfigTitle);
if (confirmed) {
this._showUILoader();
this.ui.state.configs(AppUtils.remove(this.ui.state.configs(), this.ui.state.config()));
await DbUtils.saveUserAsync(this.ui.state.userData);
this.ui.configPage.allConfigIds = [];
this.$scope.$apply(undefined);
}
}, null, null, false);
}
addObjectsClickHandler() {
this._execAsyncSync(async () => {
if (this.ui.configPage.allSObjectIds.length == 0) {
return;
}
for (let index = 0; index < this.ui.configPage.allSObjectIds.length; index++) {
const objectName = this.ui.configPage.allSObjectIds[index];
await this._describeSObjectAsync(objectName);
let scriptObject = new ScriptObject({
config: this.ui.state.config(),
fields: [new ScriptObjectField({ name: "Id" })],
name: objectName
});
if (scriptObject.defaultExternalId != "Id") {
scriptObject.fields.push(new ScriptObjectField({ name: scriptObject.defaultExternalId }));
}
scriptObject.externalId = scriptObject.defaultExternalId;
if (scriptObject.externalId == "Id") {
scriptObject.operation = OPERATION[OPERATION.Insert].toString();
}
this.ui.state.config().objects.push(scriptObject);
}
await DbUtils.saveUserAsync(this.ui.state.userData);
this.ui.configPage.allSObjectIds = [];
this.$scope.$apply(undefined);
});
}
selectObjectClickHandler($event: any) {
let self = this;
let isButtonClicked = $event.target.className.indexOf('btn') >= 0
|| $event.target.className.indexOf('custom-control-label') >= 0
|| $event.target.className.indexOf('custom-control-input') >= 0;
if (this.ui.configPage.currentSObjectId == $event.currentTarget.dataset.id || isButtonClicked) {
return;
}
this._execAsyncSync(async () => {
this.ui.configPage.currentSObjectId = $event.currentTarget.dataset.id;
let scriptObject = this.ui.state.config().objects.filter(object => object.name == this.ui.configPage.currentSObjectId)[0];
if (scriptObject) {
await this._describeSObjectAsync(scriptObject.name);
this.ui.configPage.objectEditData = new ObjectEditData({
noRecords: true,
isOpen: false,
oldExternalId: undefined
});
this.ui.configPage.isComplexExternalIdEditMode = scriptObject.isComplexExternalId;
// Workarround to refresh the externalId selector ----
this._preventExtraEvents();
let temp = this.ui.externalId;
this.ui.externalId = ['Dummy'];
this.$timeout(function () {
self._preventExtraEvents();
self.ui.externalId = temp;
}, 200);
// -------------------------------------------------------
this._displayDataTable('#testQueryRecordTable', [{}]);
this._updateFieldItems(scriptObject);
$(`[data-target="#fields"]`).click();
this._preventExtraEvents();
}
this.$scope.$apply(undefined);
});
}
addRemoveObjectFieldsHandler($scope: IAngularScope, selectedFields: Array<ScriptObjectField>, $element: JQuery) {
if ($scope.ui.controller._blockAddRemoveObjectFieldsEvent) {
return;
}
this._blockAddRemoveObjectFieldsEvent = true;
$scope.ui.controller._execAsyncSync(async () => {
// Add/Remove fields -------------------
$scope.ui.state.sobject().fields = AppUtils.distinctArray([].concat(
selectedFields,
CONSTANTS.MANDATORY_FIELDS.map(name => new ScriptObjectField({ name }))
), "name");
// Filter other parameters --------------
let fullQueryFields = $scope.ui.state.sobject().getFullQueryFields();
// Remove incorect field mappings
$scope.ui.state.sobject().fieldMapping = $scope.ui.state
.sobject().fieldMapping.filter(field => fullQueryFields.some(name => name == field.sourceField)
|| !field.sourceField && field.targetObject);
// Remove incorrect field mocking
$scope.ui.state.sobject().mockFields = $scope.ui.state
.sobject().mockFields.filter(field => fullQueryFields.some(name => name == field.name));
// Save user +++++++++++++++++++++++++++
$scope.ui.controller._updateFieldItems($scope.ui.state.sobject());
await DbUtils.saveUserAsync($scope.ui.state.userData);
this._preventExtraEvents();
$scope.$apply(undefined);
this._showUIToast("success", { content: RESOURCES.Config_Message_ConfigSucessfullyUpdated, delay: CONSTANTS.UI_SHORT_TOAST_TIMEOUT_MS });
}, null, null, false);
}
addRemoveObjectExcludedFieldsHandler($scope: IAngularScope, selectedFields: Array<FieldItem>, $element: JQuery) {
if ($scope.ui.controller._blockRemoveObjectExcludedFieldsEvent) {
return;
}
this._blockRemoveObjectExcludedFieldsEvent = true;
$scope.ui.controller._execAsyncSync(async () => {
$scope.ui.state.sobject().excludedFields = selectedFields.map(field => field.name);
$scope.ui.controller._updateFieldItems($scope.ui.state.sobject());
await DbUtils.saveUserAsync($scope.ui.state.userData);
this.objectQueryChangedHandler([], [], $scope);
this._preventExtraEvents();
$scope.$apply(undefined);
this._showUIToast("success", { content: RESOURCES.Config_Message_ConfigSucessfullyUpdated, delay: CONSTANTS.UI_SHORT_TOAST_TIMEOUT_MS });
}, null, null, false);
}
removeUnusedConfigFoldersHandler() {
this._execAsyncSync(async () => {
let confirmed = await this._showConfirmAsync(RESOURCES.Config_AreYouSureToRemoveUnusedFolders, RESOURCES.Config_CleanupDataDirectory);
if (confirmed) {
let folders = AppUtils.getListOfDirs(this.ui.state.userData.basePath);
let toDelete = folders.filter(folder => {
if (!this.ui.state.configs().map(c => c.name).some(x => folder.name == x)) {
return !folder.name.startsWith(CONSTANTS.WORKING_SUBFOLDER_NAME_PREFIX);
}
}).map(folder => folder.fullPath);
AppUtils.deleteDirs(toDelete);
this._showUIToast("success", {
content: RESOURCES.Config_Message_UnusedFolderSuccessfullyRemoved
});
this.$scope.$apply(undefined);
}
}, null, null, false);
}
objectQueryChangedHandler($new: Array<string>, $old: Array<string>, $scope: IAngularScope) {
$scope.ui.controller._initObjectEditorDataQuery();
}
executeTestQueryHandler() {
this._execAsyncSync(async () => {
this.ui.configPage.objectEditData.error = undefined;
try {
if (!this.ui.configPage.objectEditData.query) {
this.ui.configPage.objectEditData.query = this.ui.configPage.objectEditData.originalQuery;
}
let parsedQuery = this.ui.state.sobject().parseQueryString(this.ui.configPage.objectEditData.query);
this.ui.configPage.objectEditData.query = composeQuery(parsedQuery);
parsedQuery.limit = 1;
let query = composeQuery(parsedQuery);
let org = this.ui.configPage.objectEditData.isSource && this.ui.state.sourceOrg().isOrg() ? this.ui.state.sourceOrg() : this.ui.state.targetOrg();
let records = (await AppUtils.queryAsync(org, query, false)).records;
let data = [];
if (records.length > 0) {
data = AppUtils.transposeArrayMany(records, RESOURCES.Column_Field, RESOURCES.Column_Value);
data.forEach(item => item[RESOURCES.Column_Value] = item[RESOURCES.Column_Value][0]);
setTimeout(() => {
this._displayDataTable('#testQueryRecordTable', data);
}, 300);
} else {
data = [];
}
this.ui.configPage.objectEditData.noRecords = data.length == 0;
this.ui.configPage.objectEditData.isOpen = true;
} catch (ex) {
this.ui.configPage.objectEditData.error = ex.message;
}
}).finally(() => this.$scope.$apply(undefined));
}
updateSObjectQueryHandler() {
this._execAsyncSync(async () => {
this.ui.configPage.objectEditData.error = undefined;
try {
if (!this.ui.configPage.objectEditData.query) {
this.ui.configPage.objectEditData.query = this.ui.configPage.objectEditData.originalQuery;
}
let scriptObject = this.ui.state.sobject();
// Parse + fix the query fields (find closest names)
let parsedQuery = this.ui.state.sobject().parseQueryString(this.ui.configPage.objectEditData.query);
let composedQuery = composeQuery(parsedQuery);
// Fix (upper-case) all soql statemets
let soqlKeywords = AppUtils.createSoqlKeywords(composedQuery);
// Update query in UI
this.ui.configPage.objectEditData.query = soqlKeywords.query;
// Add excluded fields
let fields = [].concat(parsedQuery.fields.map(field => (<SOQLField>field).field), scriptObject.excludedFields);
fields = AppUtils.uniqueArray(fields);
// Update script object fields
scriptObject.fields = fields.map(name => {
//let name = (<SOQLField>field).rawValue || (<SOQLField>field).field;
let descr = scriptObject.sObjectDescribe.fieldsMap.get(name);
let label = descr && descr.label || name;
return new ScriptObjectField({
name,
label
});
});
// Set optional query properties (where / limit / order by)
scriptObject.limit = parsedQuery.limit;
let parseResult = AppUtils.parseSoql(soqlKeywords);
let where = parseResult.filter(item => item.word == 'WHERE')[0];
let orderBy = parseResult.filter(item => item.word == 'ORDER BY')[0];
scriptObject.where = where && where.text;
scriptObject.orderBy = orderBy && orderBy.text;
// Save script object and user data
this._updateFieldItems(scriptObject);
await DbUtils.saveUserAsync(this.ui.state.userData);
this._preventExtraEvents();
this.$scope.$apply(undefined);
this._showUIToast("success", { content: RESOURCES.Config_Message_ConfigSucessfullyUpdated, delay: CONSTANTS.UI_SHORT_TOAST_TIMEOUT_MS });
} catch (ex) {
this.ui.configPage.objectEditData.error = ex.message;
this._showUIToast("error", { content: ex.message });
}
}, null, null, false);
}
saveConfigParameterHandler() {
this._execAsyncSync(async () => {
//this._filterScriptObjectData(this.ui.state.sobject());
await DbUtils.saveUserAsync(this.ui.state.userData);
}, RESOURCES.Config_Message_ConfigSucessfullyUpdated, null, false, CONSTANTS.UI_SHORT_TOAST_TIMEOUT_MS);
}
saveConfigParameterDelayedHandler() {
if (this._saveConfigParameterDelayedTimeout) {
clearTimeout(this._saveConfigParameterDelayedTimeout);
}
this._saveConfigParameterDelayedTimeout = setTimeout(() => {
this._execAsyncSync(async () => {
//this._filterScriptObjectData(this.ui.state.sobject());
await DbUtils.saveUserAsync(this.ui.state.userData);
}, RESOURCES.Config_Message_ConfigSucessfullyUpdated, null, false, CONSTANTS.UI_SHORT_TOAST_TIMEOUT_MS);
}, 3000);
}
upDownObjectHandler(objectIndex: number, moveDirection: number, first: boolean, last: boolean) {
if (first && moveDirection < 0 || last && moveDirection > 0) {
return;
}
this._execAsyncSync(async () => {
let scriptObject = this.ui.state.config().objects.splice(objectIndex, 1)[0];
this.ui.state.config().objects.splice(objectIndex + moveDirection, 0, scriptObject);
await DbUtils.saveUserAsync(this.ui.state.userData);
this.$scope.$apply(undefined);
}, RESOURCES.Config_Message_ConfigSucessfullyUpdated, null, false, CONSTANTS.UI_SHORT_TOAST_TIMEOUT_MS);
}
removeObjectHandler(objectIndex: number) {
this._execAsyncSync(async () => {
this.ui.state.config().objects.splice(objectIndex, 1);
await DbUtils.saveUserAsync(this.ui.state.userData);
this.ui.configPage.currentSObjectId = undefined;
this.$scope.$apply(undefined);
}, RESOURCES.Config_Message_ConfigSucessfullyUpdated, null, true, CONSTANTS.UI_SHORT_TOAST_TIMEOUT_MS);
}
saveConfigHandler() {
this._execAsyncSync(async () => {
await DbUtils.saveUserAsync(this.ui.state.userData);
this.$scope.$apply(undefined);
}, RESOURCES.Config_Message_ConfigSucessfullyUpdated, null, true, CONSTANTS.UI_SHORT_TOAST_TIMEOUT_MS);
}
saveConfigDelayedHandler() {
if (this._saveConfigDelayedTimeout) {
clearTimeout(this._saveConfigDelayedTimeout);
}
this._saveConfigDelayedTimeout = setTimeout(() => {
this._execAsyncSync(async () => {
await DbUtils.saveUserAsync(this.ui.state.userData);
this.$scope.$apply(undefined);
}, RESOURCES.Config_Message_ConfigSucessfullyUpdated, null, true, CONSTANTS.UI_SHORT_TOAST_TIMEOUT_MS);
}, 3000);
}
externalIdChangedHandler($new: Array<string>, $old: Array<string>, $scope: IAngularScope) {
if ($new.length == 0
|| $scope.ui.controller._blockExternalIdChangedEvent
|| $scope.ui.configPage.objectEditData.oldExternalId == $new[0]
|| !$scope.ui.state.sobject().isOrgDescribed) {
return;
}
$scope.ui.controller._execAsyncSync(async () => {
$scope.ui.configPage.objectEditData.oldExternalId = $new[0];
$scope.ui.state.sobject().externalId = $new[0];
$scope.ui.controller._updateFieldItems($scope.ui.state.sobject());
$scope.ui.controller._initObjectEditorDataQuery();
await DbUtils.saveUserAsync($scope.ui.state.userData);
$scope.ui.controller._preventExtraEvents();
}, RESOURCES.Config_Message_ConfigSucessfullyUpdated, null, false, CONSTANTS.UI_SHORT_TOAST_TIMEOUT_MS);
}
polymorphicFieldChangedHandler($new: Array<any>, $old: Array<any>, $scope: IAngularScope, $element: JQuery) {
if (this._blockOnPolymorphicFieldChangedEvent) {
return;
}
this._blockOnPolymorphicFieldChangedEvent = true;
this._blockAddRemoveObjectFieldsEvent = true;
this._execAsyncSync(async () => {
let scriptObject = $scope.ui.state.sobject();
let fieldName = $element.attr('data-field-name');
let field = scriptObject.fields.filter(field => field.name == fieldName)[0];
if (field) {
if ($new.length > 0) {
field.name = field.cleanName + CONSTANTS.REFERENCE_FIELD_OBJECT_SEPARATOR + $new[0];
} else {
field.name = field.cleanName;
}
}
this._updateFieldItems(scriptObject);
await DbUtils.saveUserAsync($scope.ui.state.userData);
this._preventExtraEvents();
this._showUIToast("success", { content: RESOURCES.Config_Message_ConfigSucessfullyUpdated, delay: CONSTANTS.UI_SHORT_TOAST_TIMEOUT_MS });
$scope.$apply(undefined)
}, null, null, false);
}
externalIdEnterModeChangeHandler() {
this._blockExternalIdChangedEvent = this.ui.configPage.isComplexExternalIdEditMode;
}
addFieldMappingHandler() {
this._execAsyncSync(async () => {
this.ui.state.sobject().fieldMapping.push(new ScriptMappingItem());
this._updateFieldItems(this.ui.state.sobject());
await DbUtils.saveUserAsync(this.ui.state.userData);
this.$scope.$apply(undefined);
}, RESOURCES.Config_Message_ConfigSucessfullyUpdated, null, true, CONSTANTS.UI_SHORT_TOAST_TIMEOUT_MS);
}
removeFieldMappingHandler(index: number) {
this._execAsyncSync(async () => {
this.ui.state.sobject().fieldMapping.splice(index, 1);
this._updateFieldItems(this.ui.state.sobject());
await DbUtils.saveUserAsync(this.ui.state.userData);
this.$scope.$apply(undefined);
}, RESOURCES.Config_Message_ConfigSucessfullyUpdated, null, true, CONSTANTS.UI_SHORT_TOAST_TIMEOUT_MS);
}
fieldMappingChangedHandler(options: any, field: string) {
this._execAsyncSync(async () => {
if (typeof options.id != 'undefined') {
options.id = parseInt(options.id);
this.ui.state.sobject().fieldMapping[options.id][field] = options.value;
if (field == 'targetObject' && options.value) {
await this._describeSObjectAsync(options.value);
this._hideUILoader();
}
this._updateFieldItems(this.ui.state.sobject());
await DbUtils.saveUserAsync(this.ui.state.userData);
this.$scope.$apply(undefined);
}
}, RESOURCES.Config_Message_ConfigSucessfullyUpdated, null, true, CONSTANTS.UI_SHORT_TOAST_TIMEOUT_MS);
}
fieldMappingInitializeHandler(options: any) {
this._execAsyncSync(async () => {
if (typeof options.id != 'undefined') {
options.id = parseInt(options.id);
if (options.id == 0) {
if (options.value) {
await this._describeSObjectAsync(options.value);
this._hideUILoader();
}
this._updateFieldItems(this.ui.state.sobject());
this.$scope.$apply(undefined);
}
}
}, null, null, false);
}
validateConfigurationHandler() {
this._execAsyncSync(async () => {
this._showUILoader(RESOURCES.Config_ValidateConfigurationStarted);
await AppUtils.sleepAsync(1500);
await this._validateConfigurationAsync();
this._preventExtraEvents();
if (this.ui.configPage.isValid()) {
this._showUIToast("success", { content: RESOURCES.Config_ValidateConfigurationSucceeded });
} else {
this._showUIToast("warning", { title: RESOURCES.DefaultToastWarningTitle, content: RESOURCES.Config_ValidateConfigurationFailed });
}
this.$scope.$apply(undefined);
}, null, null, false);
}
reconnectOrgsHandler() {
this._execAsyncSync(async () => {
await this._connectOrgsAsync();
this.ui.configPage.currentSObjectId = undefined;
this.$scope.$apply(undefined);
});
}
configGoNext() {
this._execAsyncSync(async () => {
this._showUILoader(RESOURCES.Config_ValidateConfigurationStarted);
await AppUtils.sleepAsync(1500);
await this._validateConfigurationAsync();
this._preventExtraEvents();
if (this.ui.configPage.isValid()) {
this._showUIToast("success", { content: RESOURCES.Config_ValidateConfigurationSucceeded });
this.$state.go('preview');
this.ui.previewPage.allowShowing = true;
this.previewPageSetup();
} else {
this._showUIToast("warning", { title: RESOURCES.DefaultToastWarningTitle, content: RESOURCES.Config_ValidateConfigurationFailed });
}
this.$scope.$apply(undefined);
}, null, null, false);
}
addMockingItemHandler() {
this.ui.state.sobject().mockFields.push(new ScriptMockField({
name: this.ui.configPage.selectedFieldNameForMock,
pattern: CONSTANTS.DEFAULT_MOCK_PATTERN
}));
this._updateFieldItems(this.ui.state.sobject());
this.saveConfigParameterHandler();
}
removeMockingItemHandler(index: number) {
this.ui.state.sobject().mockFields.splice(index, 1);
this._updateFieldItems(this.ui.state.sobject());
this.saveConfigParameterHandler();
}
/////////////////////////////////////////////////////////////////////
// Preview Page /////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////
previewPageSetup() {
this.ui.previewPage.selectedMigrationDirection =
this.ui.state.sourceOrg().media == DATA_MEDIA_TYPE.File ? MIGRATION_DIRECTION[MIGRATION_DIRECTION.File2Org]
: this.ui.state.targetOrg().media == DATA_MEDIA_TYPE.File ? MIGRATION_DIRECTION[MIGRATION_DIRECTION.Org2File]
: MIGRATION_DIRECTION[MIGRATION_DIRECTION.Orgs];
this._generateExportJson();
}
generateExportJsonHandler() {
this._generateExportJson();
}
copyCLICommandStringToClipboardHandler() {
let self = this;
this.$copyToClipboard.copy(this.ui.previewPage.getCLICommandString()).then(function () {
self._showUIToast('success', {
content: RESOURCES.Preview_CLICommandCopiedMessage,
delay: CONSTANTS.UI_SHORT_TOAST_TIMEOUT_MS
})
});
}
previewGoNext() {
this._execAsyncSync(async () => {
let self = this;
let command = this.ui.previewPage.getCLICommandString();
this.ui.executePage.allowShowing = true;
this.ui.state.scriptIsExecuting = true;
this.ui.executePage.executeLogHtml = "";
let executeLogPlain = "";
self.$scope.$apply(undefined);
this.$state.go('execute');
setTimeout(async () => {
await ConsoleUtils.callConsoleCommand(command, (data) => {
switch (data.type) {
case CONSOLE_COMMAND_EVENT_TYPE.Close:
___printLog(`<br/><br/>${RESOURCES.Execute_Message_ExecuteFinishedWithCode} ${data.exitCode}`, true);
break;
case CONSOLE_COMMAND_EVENT_TYPE.Error:
___printLog("", true);
break;
case CONSOLE_COMMAND_EVENT_TYPE.Exit:
___printLog(`<br/><br/>${RESOURCES.Execute_Message_ExecuteFinishedWithCode} ${data.exitCode}`, true);
break;
case CONSOLE_COMMAND_EVENT_TYPE.Start:
___printLog(`<br/><b class='text-secondary'>${command}</b><br/>`);
break;
case CONSOLE_COMMAND_EVENT_TYPE.StdErrData:
___printLog("<span style='color:red'>" + data.message.toString().replace(/\n/g, '<br/>') + '</span>');
break;
case CONSOLE_COMMAND_EVENT_TYPE.StdOutData:
___printLog(data.message.toString().replace(/\n/g, '<br/>'));
break;
}
return false;
});
}, 500);
// ------------- Local function ------------------- //
function ___printLog(message: string, stopExecuting: boolean = false) {
executeLogPlain += message;
self.ui.executePage.executeLogHtml = self._trustHtml(executeLogPlain);
self.ui.state.scriptIsExecuting = !stopExecuting;
self.$scope.$apply(undefined);
$(".execute-page-section").animate({ scrollTop: $(".execute-page-section").prop("scrollHeight") }, 100);
}
}, null, null, false);
}
/////////////////////////////////////////////////////////////////////
// Execute Page /////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////
abortExecutionHandler() {
this._execAsyncSync(async () => {
if (this.ui.state.scriptIsExecuting) {
let confirmed = await this._showConfirmAsync(null, RESOURCES.Execute_AreYouSureToAbortExecution);
if (confirmed) {
ConsoleUtils.killRunningConsoleProcess();
this.ui.state.scriptIsExecuting = false;
this.$scope.$apply(undefined);
}
}
}, null, null, false);
}
/////////////////////////////////////////////////////////////////////
// Private members //////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////
// Fields **************************************************
private _blockAddRemoveObjectFieldsEvent = false;
private _blockRemoveObjectExcludedFieldsEvent = false;
private _blockExternalIdChangedEvent = false;
private _blockOnPolymorphicFieldChangedEvent = false;
private _saveConfigParameterDelayedTimeout: NodeJS.Timeout;
private _saveConfigDelayedTimeout: NodeJS.Timeout;
// Loader **************************************************
private _uILoader(show?: boolean, message?: string) {
if (show) {
$('.ajax-loader, .ajax-load-message').removeClass('hidden');
$('.ajax-load-message > span').text(message);
} else {
$('.ajax-loader, .ajax-load-message').addClass('hidden');
}
}
private _showUILoader(message?: string) {
this._uILoader(true, message || RESOURCES.Loader_DefaultLoaderMessage);
}
private _hideUILoader() {
setTimeout(() => {
this._uILoader();
}, 200);
}
// Toast **************************************************
private _showUIToast(type: "info" | "success" | "warning" | 'error' = CONSTANTS.DEFAULT_TOAST_TYPE,
options?: {
title?: string,
content?: string,
delay?: number
}) {
$.toastDefaults = {
position: 'top-center',
dismissible: false,
stackable: true,
pauseDelayOnHover: true,
style: {
toast: 'toast-element'
}
};
$.toast({
type,
title: options.title || RESOURCES.DefaultToastTitle,
content: options.content || RESOURCES.DefaultToastMessage,
delay: options.delay || CONSTANTS.UI_TOAST_TIMEOUT_MS
});
}
// Modal dialogs **************************************************
private _showPromptAsync(message: string, title: string, defaultValue: string): Promise<string> {
return new Promise(resolve => {
title = title || RESOURCES.DefaultModalTitlePrompt;
message = message || RESOURCES.DefaultModalMessagePrompt;
this.bootbox.prompt({
title,
message,
value: defaultValue,
backdrop: true,
callback: function (value: any) {
if (value == null)
resolve(undefined);
else
resolve(value);
}
});
});
}
private _showConfirmAsync(message: string, title: string): Promise<boolean> {
return new Promise(resolve => {
message = message || RESOURCES.DefaultModalMessageConfirm;
title = title || RESOURCES.DefaultModalTitleConfirm;
this.bootbox.confirm({
title,
message,
backdrop: true,
callback: function (value: any) {
if (value != "")
resolve(true);
else
resolve(undefined);
}
});
});
}
// Others **************************************************
// Methods ------------ //
private _preventExtraEvents() {
this._blockAddRemoveObjectFieldsEvent = true;
this._blockRemoveObjectExcludedFieldsEvent = true;
this._blockOnPolymorphicFieldChangedEvent = true;
this._blockExternalIdChangedEvent = true;
setTimeout(() => {
this._blockAddRemoveObjectFieldsEvent = false;
this._blockRemoveObjectExcludedFieldsEvent = false;
this._blockOnPolymorphicFieldChangedEvent = false;
this._blockExternalIdChangedEvent = false;
}, 500);
}
private _execAsyncSync(fn: () => Promise<any>, successMessage?: string, errorMessage?: string,
showLoader: boolean = true,
toastDelayMs: number = undefined): Promise<any> {
let self = this;
if (showLoader) {
this._showUILoader();
}
return new Promise<any>((resolve, reject) => {
AppUtils.execAsyncSync(async () => fn()).then((result) => {
if (successMessage) {
self._showUIToast('success', {
title: RESOURCES.DefaultToastMessage,
content: successMessage,
delay: toastDelayMs
});
}
resolve(result);
}).catch((err) => {
if (typeof err == 'string') {
err = {
message: err
};
}
self._showUIToast('error', {
title: RESOURCES.DefaultToastErrorTitle,
content: errorMessage || err.message || RESOURCES.DefaultToastErrorMessage,
delay: toastDelayMs
});
reject(err);
}).finally(() => {
this._hideUILoader();
this._refreshUI();
});
});
}
private _refreshUI() {
let self = this;
this.$timeout(function () {
$('[data-toggle="tooltip"]').tooltip('dispose');
$('[data-toggle="tooltip"]').tooltip();
$('[data-config-selector],[data-org-selector1],[data-org-selector2],[data-config-sobjects-selector],[data-config-externalid-selector]').selectpicker('refresh');
$('.btn-switch:contains("Off")').addClass('.switch-off').attr('style', 'background-color: #FFF !important; color: #495057 !important; border: none !important;');
self._addBsSelectWatcher("[data-config-externalid-selector]", self.externalIdChangedHandler);
}, 500);
}
private _addWhatcher(propertyName: string, handler: ($new: any, $old: any, $scope: any) => void) {
this.$scope.$watch(propertyName, ($new: any, $old: any, $scope: any) => {
if (!AppUtils.isEquals($old, $new) && handler) {
handler($new, $old, $scope);
}
});
}
private _addBsSelectWatcher(selector: string, handler: ($new: any, $old: any, $scope: any) => void) {
let self = this;
$(selector).off('changed.bs.select').on('changed.bs.select', function (e: any) {
let $new = [];
for (let opt of e.target.selectedOptions) {
$new.push(opt.value);
}
handler($new, [], self.$scope);
});
}
private _downloadFile(filePath: string) {
if (fs.existsSync(filePath)) {
const content = fs.readFileSync(filePath, 'utf-8').trim();
const element = document.createElement("a");
const type = mime.lookup(filePath);
const file = new Blob([content], { type: String(type) });
element.href = URL.createObjectURL(file);
element.download = path.basename(filePath);
element.click();
}
}
private _readSingleFile(e: any) {
var deffered = jQuery.Deferred();
var file = e.target.files[0];
if (!file) {
deffered.resolve();
return;
}
var reader = new FileReader();
reader.onload = function (e) {
var contents = e.target.result;
deffered.resolve(contents);
};
reader.readAsText(file);
return deffered.promise();
}
private async _describeSObjectAsync(objectName: string): Promise<void> {
if (this.ui.state.sourceOrg().isOrg()) {
let object = this.ui.state.sourceOrg().objectsMap.get(objectName);
if (object) {
if (!object.isValid()) {
// Describe Source...
this._showUILoader(RESOURCES.Config_DescribingSObject.format(objectName, RESOURCES.Source));
await AppUtils.describeSObjectAsync(this.ui.state.sourceOrg(), objectName, object);
}
}
}
if (this.ui.state.targetOrg().isOrg()) {
let object = this.ui.state.targetOrg().objectsMap.get(objectName);
if (object) {
if (!object.isValid()) {
// Describe Target...
this._showUILoader(RESOURCES.Config_DescribingSObject.format(objectName, RESOURCES.Target));
await AppUtils.describeSObjectAsync(this.ui.state.targetOrg(), objectName, object);
}
}
}
}
private _initObjectEditorDataQuery() {
this.ui.configPage.objectEditData.originalQuery = this.ui.state.sobject().getTestQuery(null);
this.ui.configPage.objectEditData.query = this.ui.state.sobject().getTestQuery(null);
}
private _displayDataTable(selector: string, data: Array<any>, columnsMap?: Map<string, string>) {
if (!data || data.length == 0) {
return;
}
let columns = Object.keys(data[0]).map(key => {
return {
field: key,
title: columnsMap && columnsMap.get(key) || key
};
});
$(selector).bootstrapTable('destroy');
$(selector).bootstrapTable({
columns,
data,
classes: 'table table-hover table-striped data-table'
});
}
private _textToHtml(text: string) {
return this._trustHtml(AppUtils.textToHtmlString(text));
}
private _trustHtml(html: string) {
return this.$sce.trustAsHtml(html);
}
private _updateFieldItems(scriptObject: ScriptObject) {
scriptObject.updateFieldItems();
this.ui.configPage.updateFieldItems();
this.ui.configPage.selectedFieldNameForMock = scriptObject.availableFieldItemsForMocking[0]
&& scriptObject.availableFieldItemsForMocking[0].name;
}
private async _validateConfigurationAsync(): Promise<void> {
for (let index = 0; index < this.ui.state.config().objects.length; index++) {
const scriptObject = this.ui.state.config().objects[index];
await this._describeSObjectAsync(scriptObject.name);
this._updateFieldItems(scriptObject);
}
}
private async _connectOrgsAsync(): Promise<void> {
// Connect to Source
if (this.ui.state.sourceOrg().isOrg()) {
try {
this._showUILoader(RESOURCES.Home_Message_ConnectingOrg.format(RESOURCES.Source));
await AppUtils.connectOrg(this.ui.state.sourceOrg());
} catch (ex) {
throw new Error(RESOURCES.Home_Error_UnableToConnectToOrg.format(RESOURCES.Source));
}
}
// Connect to Target
if (this.ui.state.targetOrg().isOrg()) {
try {
this._showUILoader(RESOURCES.Home_Message_ConnectingOrg.format(RESOURCES.Target));
await AppUtils.connectOrg(this.ui.state.targetOrg());
} catch (ex) {
throw new Error(RESOURCES.Home_Error_UnableToConnectToOrg.format(RESOURCES.Target));
}
}
// Reading the Source objects list
if (this.ui.state.sourceOrg().isOrg()) {
try {
this._showUILoader(RESOURCES.Home_Message_RetrievingOrgMetadata.format(RESOURCES.Source));
let objects = await AppUtils.getOrgObjectsList(this.ui.state.sourceOrg());
this.ui.state.sourceOrg().objectsMap.clear();
objects.forEach(obj => {
this.ui.state.sourceOrg().objectsMap.set(obj.name, obj);
})
} catch (ex) {
throw new Error(RESOURCES.Home_Error_UnableToRetrieveMetadata.format(RESOURCES.Source));
}
}
// Reading the Target objects list
if (this.ui.state.targetOrg().isOrg()) {
try {
this._showUILoader(RESOURCES.Home_Message_RetrievingOrgMetadata.format(RESOURCES.Target));
let objects = await AppUtils.getOrgObjectsList(this.ui.state.targetOrg());
this.ui.state.targetOrg().objectsMap.clear();
objects.forEach(obj => {
this.ui.state.targetOrg().objectsMap.set(obj.name, obj);
})
} catch (ex) {
throw new Error(RESOURCES.Home_Error_UnableToRetrieveMetadata.format(RESOURCES.Target));
}
}
this._showUIToast('success', { content: RESOURCES.Home_Message_MetadataRetrieveSuccess });
}
private _generateExportJson() {
this.ui.previewPage.exportJson =
this.ui.previewPage.isFullExportJson
? this.ui.state.config().toExportJson(this.ui,
AppUIState.appSettings.isDebug,
CONSTANTS.EXPORT_JSON_FULL_TAG) :
this.ui.state.config().toExportJson(this.ui,
AppUIState.appSettings.isDebug,
CONSTANTS.EXPORT_JSON_TAG);
try {
fs.writeFileSync(this.ui.state.config().exportJsonFilename, this.ui.previewPage.exportJson);
} catch (ex) { }
}
private _displayNewVersionMessage() {
setTimeout(async () => {
await this.ui.state.setNewVersionMessage();
this.$scope.$apply(undefined);
});
}
} | the_stack |
// IMPORTANT
// This file was generated by https://github.com/Bolisov/google-api-typings-generator. Please do not edit it manually.
// In case of any problems please post issue to https://github.com/Bolisov/google-api-typings-generator
// Generated from: https://www.googleapis.com/discovery/v1/apis/adsense/v1.4/rest
/// <reference types="gapi.client" />
declare namespace gapi.client {
/** Load AdSense Management API v1.4 */
function load(name: "adsense", version: "v1.4"): PromiseLike<void>;
function load(name: "adsense", version: "v1.4", callback: () => any): void;
const accounts: adsense.AccountsResource;
const adclients: adsense.AdclientsResource;
const adunits: adsense.AdunitsResource;
const alerts: adsense.AlertsResource;
const customchannels: adsense.CustomchannelsResource;
const metadata: adsense.MetadataResource;
const payments: adsense.PaymentsResource;
const reports: adsense.ReportsResource;
const savedadstyles: adsense.SavedadstylesResource;
const urlchannels: adsense.UrlchannelsResource;
namespace adsense {
interface Account {
creation_time?: string;
/** Unique identifier of this account. */
id?: string;
/** Kind of resource this is, in this case adsense#account. */
kind?: string;
/** Name of this account. */
name?: string;
/** Whether this account is premium. */
premium?: boolean;
/** Sub accounts of the this account. */
subAccounts?: Account[];
/** AdSense timezone of this account. */
timezone?: string;
}
interface Accounts {
/** ETag of this response for caching purposes. */
etag?: string;
/** The accounts returned in this list response. */
items?: Account[];
/** Kind of list this is, in this case adsense#accounts. */
kind?: string;
/** Continuation token used to page through accounts. To retrieve the next page of results, set the next request's "pageToken" value to this. */
nextPageToken?: string;
}
interface AdClient {
/** Whether this ad client is opted in to ARC. */
arcOptIn?: boolean;
/** Unique identifier of this ad client. */
id?: string;
/** Kind of resource this is, in this case adsense#adClient. */
kind?: string;
/** This ad client's product code, which corresponds to the PRODUCT_CODE report dimension. */
productCode?: string;
/** Whether this ad client supports being reported on. */
supportsReporting?: boolean;
}
interface AdClients {
/** ETag of this response for caching purposes. */
etag?: string;
/** The ad clients returned in this list response. */
items?: AdClient[];
/** Kind of list this is, in this case adsense#adClients. */
kind?: string;
/** Continuation token used to page through ad clients. To retrieve the next page of results, set the next request's "pageToken" value to this. */
nextPageToken?: string;
}
interface AdCode {
/** The ad code snippet. */
adCode?: string;
/** Kind this is, in this case adsense#adCode. */
kind?: string;
}
interface AdStyle {
/**
* The colors which are included in the style. These are represented as six hexadecimal characters, similar to HTML color codes, but without the leading
* hash.
*/
colors?: {
/** The color of the ad background. */
background?: string;
/** The color of the ad border. */
border?: string;
/** The color of the ad text. */
text?: string;
/** The color of the ad title. */
title?: string;
/** The color of the ad url. */
url?: string;
};
/** The style of the corners in the ad (deprecated: never populated, ignored). */
corners?: string;
/** The font which is included in the style. */
font?: {
/** The family of the font. */
family?: string;
/** The size of the font. */
size?: string;
};
/** Kind this is, in this case adsense#adStyle. */
kind?: string;
}
interface AdUnit {
/** Identity code of this ad unit, not necessarily unique across ad clients. */
code?: string;
/** Settings specific to content ads (AFC) and highend mobile content ads (AFMC - deprecated). */
contentAdsSettings?: {
/** The backup option to be used in instances where no ad is available. */
backupOption?: {
/** Color to use when type is set to COLOR. */
color?: string;
/** Type of the backup option. Possible values are BLANK, COLOR and URL. */
type?: string;
/** URL to use when type is set to URL. */
url?: string;
};
/** Size of this ad unit. */
size?: string;
/** Type of this ad unit. */
type?: string;
};
/** Custom style information specific to this ad unit. */
customStyle?: AdStyle;
/** Settings specific to feed ads (AFF) - deprecated. */
feedAdsSettings?: {
/** The position of the ads relative to the feed entries. */
adPosition?: string;
/** The frequency at which ads should appear in the feed (i.e. every N entries). */
frequency?: number;
/** The minimum length an entry should be in order to have attached ads. */
minimumWordCount?: number;
/** The type of ads which should appear. */
type?: string;
};
/** Unique identifier of this ad unit. This should be considered an opaque identifier; it is not safe to rely on it being in any particular format. */
id?: string;
/** Kind of resource this is, in this case adsense#adUnit. */
kind?: string;
/** Settings specific to WAP mobile content ads (AFMC) - deprecated. */
mobileContentAdsSettings?: {
/** The markup language to use for this ad unit. */
markupLanguage?: string;
/** The scripting language to use for this ad unit. */
scriptingLanguage?: string;
/** Size of this ad unit. */
size?: string;
/** Type of this ad unit. */
type?: string;
};
/** Name of this ad unit. */
name?: string;
/** ID of the saved ad style which holds this ad unit's style information. */
savedStyleId?: string;
/**
* Status of this ad unit. Possible values are:
* NEW: Indicates that the ad unit was created within the last seven days and does not yet have any activity associated with it.
*
* ACTIVE: Indicates that there has been activity on this ad unit in the last seven days.
*
* INACTIVE: Indicates that there has been no activity on this ad unit in the last seven days.
*/
status?: string;
}
interface AdUnits {
/** ETag of this response for caching purposes. */
etag?: string;
/** The ad units returned in this list response. */
items?: AdUnit[];
/** Kind of list this is, in this case adsense#adUnits. */
kind?: string;
/** Continuation token used to page through ad units. To retrieve the next page of results, set the next request's "pageToken" value to this. */
nextPageToken?: string;
}
interface AdsenseReportsGenerateResponse {
/** The averages of the report. This is the same length as any other row in the report; cells corresponding to dimension columns are empty. */
averages?: string[];
/** The requested end date in yyyy-mm-dd format. */
endDate?: string;
/**
* The header information of the columns requested in the report. This is a list of headers; one for each dimension in the request, followed by one for
* each metric in the request.
*/
headers?: Array<{
/** The currency of this column. Only present if the header type is METRIC_CURRENCY. */
currency?: string;
/** The name of the header. */
name?: string;
/** The type of the header; one of DIMENSION, METRIC_TALLY, METRIC_RATIO, or METRIC_CURRENCY. */
type?: string;
}>;
/** Kind this is, in this case adsense#report. */
kind?: string;
/**
* The output rows of the report. Each row is a list of cells; one for each dimension in the request, followed by one for each metric in the request. The
* dimension cells contain strings, and the metric cells contain numbers.
*/
rows?: string[][];
/** The requested start date in yyyy-mm-dd format. */
startDate?: string;
/**
* The total number of rows matched by the report request. Fewer rows may be returned in the response due to being limited by the row count requested or
* the report row limit.
*/
totalMatchedRows?: string;
/** The totals of the report. This is the same length as any other row in the report; cells corresponding to dimension columns are empty. */
totals?: string[];
/** Any warnings associated with generation of the report. */
warnings?: string[];
}
interface Alert {
/** Unique identifier of this alert. This should be considered an opaque identifier; it is not safe to rely on it being in any particular format. */
id?: string;
/** Whether this alert can be dismissed. */
isDismissible?: boolean;
/** Kind of resource this is, in this case adsense#alert. */
kind?: string;
/** The localized alert message. */
message?: string;
/** Severity of this alert. Possible values: INFO, WARNING, SEVERE. */
severity?: string;
/**
* Type of this alert. Possible values: SELF_HOLD, MIGRATED_TO_BILLING3, ADDRESS_PIN_VERIFICATION, PHONE_PIN_VERIFICATION, CORPORATE_ENTITY,
* GRAYLISTED_PUBLISHER, API_HOLD.
*/
type?: string;
}
interface Alerts {
/** The alerts returned in this list response. */
items?: Alert[];
/** Kind of list this is, in this case adsense#alerts. */
kind?: string;
}
interface CustomChannel {
/** Code of this custom channel, not necessarily unique across ad clients. */
code?: string;
/** Unique identifier of this custom channel. This should be considered an opaque identifier; it is not safe to rely on it being in any particular format. */
id?: string;
/** Kind of resource this is, in this case adsense#customChannel. */
kind?: string;
/** Name of this custom channel. */
name?: string;
/** The targeting information of this custom channel, if activated. */
targetingInfo?: {
/** The name used to describe this channel externally. */
adsAppearOn?: string;
/** The external description of the channel. */
description?: string;
/**
* The locations in which ads appear. (Only valid for content and mobile content ads (deprecated)). Acceptable values for content ads are: TOP_LEFT,
* TOP_CENTER, TOP_RIGHT, MIDDLE_LEFT, MIDDLE_CENTER, MIDDLE_RIGHT, BOTTOM_LEFT, BOTTOM_CENTER, BOTTOM_RIGHT, MULTIPLE_LOCATIONS. Acceptable values for
* mobile content ads (deprecated) are: TOP, MIDDLE, BOTTOM, MULTIPLE_LOCATIONS.
*/
location?: string;
/** The language of the sites ads will be displayed on. */
siteLanguage?: string;
};
}
interface CustomChannels {
/** ETag of this response for caching purposes. */
etag?: string;
/** The custom channels returned in this list response. */
items?: CustomChannel[];
/** Kind of list this is, in this case adsense#customChannels. */
kind?: string;
/** Continuation token used to page through custom channels. To retrieve the next page of results, set the next request's "pageToken" value to this. */
nextPageToken?: string;
}
interface Metadata {
items?: ReportingMetadataEntry[];
/** Kind of list this is, in this case adsense#metadata. */
kind?: string;
}
interface Payment {
/** Unique identifier of this Payment. */
id?: string;
/** Kind of resource this is, in this case adsense#payment. */
kind?: string;
/** The amount to be paid. */
paymentAmount?: string;
/** The currency code for the amount to be paid. */
paymentAmountCurrencyCode?: string;
/** The date this payment was/will be credited to the user, or none if the payment threshold has not been met. */
paymentDate?: string;
}
interface Payments {
/** The list of Payments for the account. One or both of a) the account's most recent payment; and b) the account's upcoming payment. */
items?: Payment[];
/** Kind of list this is, in this case adsense#payments. */
kind?: string;
}
interface ReportingMetadataEntry {
/**
* For metrics this is a list of dimension IDs which the metric is compatible with, for dimensions it is a list of compatibility groups the dimension
* belongs to.
*/
compatibleDimensions?: string[];
/** The names of the metrics the dimension or metric this reporting metadata entry describes is compatible with. */
compatibleMetrics?: string[];
/** Unique identifier of this reporting metadata entry, corresponding to the name of the appropriate dimension or metric. */
id?: string;
/** Kind of resource this is, in this case adsense#reportingMetadataEntry. */
kind?: string;
/**
* The names of the dimensions which the dimension or metric this reporting metadata entry describes requires to also be present in order for the report
* to be valid. Omitting these will not cause an error or warning, but may result in data which cannot be correctly interpreted.
*/
requiredDimensions?: string[];
/**
* The names of the metrics which the dimension or metric this reporting metadata entry describes requires to also be present in order for the report to
* be valid. Omitting these will not cause an error or warning, but may result in data which cannot be correctly interpreted.
*/
requiredMetrics?: string[];
/** The codes of the projects supported by the dimension or metric this reporting metadata entry describes. */
supportedProducts?: string[];
}
interface SavedAdStyle {
/** The AdStyle itself. */
adStyle?: AdStyle;
/** Unique identifier of this saved ad style. This should be considered an opaque identifier; it is not safe to rely on it being in any particular format. */
id?: string;
/** Kind of resource this is, in this case adsense#savedAdStyle. */
kind?: string;
/** The user selected name of this SavedAdStyle. */
name?: string;
}
interface SavedAdStyles {
/** ETag of this response for caching purposes. */
etag?: string;
/** The saved ad styles returned in this list response. */
items?: SavedAdStyle[];
/** Kind of list this is, in this case adsense#savedAdStyles. */
kind?: string;
/** Continuation token used to page through ad units. To retrieve the next page of results, set the next request's "pageToken" value to this. */
nextPageToken?: string;
}
interface SavedReport {
/** Unique identifier of this saved report. */
id?: string;
/** Kind of resource this is, in this case adsense#savedReport. */
kind?: string;
/** This saved report's name. */
name?: string;
}
interface SavedReports {
/** ETag of this response for caching purposes. */
etag?: string;
/** The saved reports returned in this list response. */
items?: SavedReport[];
/** Kind of list this is, in this case adsense#savedReports. */
kind?: string;
/** Continuation token used to page through saved reports. To retrieve the next page of results, set the next request's "pageToken" value to this. */
nextPageToken?: string;
}
interface UrlChannel {
/** Unique identifier of this URL channel. This should be considered an opaque identifier; it is not safe to rely on it being in any particular format. */
id?: string;
/** Kind of resource this is, in this case adsense#urlChannel. */
kind?: string;
/** URL Pattern of this URL channel. Does not include "http://" or "https://". Example: www.example.com/home */
urlPattern?: string;
}
interface UrlChannels {
/** ETag of this response for caching purposes. */
etag?: string;
/** The URL channels returned in this list response. */
items?: UrlChannel[];
/** Kind of list this is, in this case adsense#urlChannels. */
kind?: string;
/** Continuation token used to page through URL channels. To retrieve the next page of results, set the next request's "pageToken" value to this. */
nextPageToken?: string;
}
interface AdclientsResource {
/** List all ad clients in the specified account. */
list(request: {
/** Account for which to list ad clients. */
accountId: string;
/** Data format for the response. */
alt?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The maximum number of ad clients to include in the response, used for paging. */
maxResults?: number;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/**
* A continuation token, used to page through ad clients. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous
* response.
*/
pageToken?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<AdClients>;
}
interface CustomchannelsResource {
/** List all custom channels which the specified ad unit belongs to. */
list(request: {
/** Account to which the ad client belongs. */
accountId: string;
/** Ad client which contains the ad unit. */
adClientId: string;
/** Ad unit for which to list custom channels. */
adUnitId: string;
/** Data format for the response. */
alt?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The maximum number of custom channels to include in the response, used for paging. */
maxResults?: number;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/**
* A continuation token, used to page through custom channels. To retrieve the next page, set this parameter to the value of "nextPageToken" from the
* previous response.
*/
pageToken?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<CustomChannels>;
}
interface AdunitsResource {
/** Gets the specified ad unit in the specified ad client for the specified account. */
get(request: {
/** Account to which the ad client belongs. */
accountId: string;
/** Ad client for which to get the ad unit. */
adClientId: string;
/** Ad unit to retrieve. */
adUnitId: string;
/** Data format for the response. */
alt?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<AdUnit>;
/** Get ad code for the specified ad unit. */
getAdCode(request: {
/** Account which contains the ad client. */
accountId: string;
/** Ad client with contains the ad unit. */
adClientId: string;
/** Ad unit to get the code for. */
adUnitId: string;
/** Data format for the response. */
alt?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<AdCode>;
/** List all ad units in the specified ad client for the specified account. */
list(request: {
/** Account to which the ad client belongs. */
accountId: string;
/** Ad client for which to list ad units. */
adClientId: string;
/** Data format for the response. */
alt?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** Whether to include inactive ad units. Default: true. */
includeInactive?: boolean;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The maximum number of ad units to include in the response, used for paging. */
maxResults?: number;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/**
* A continuation token, used to page through ad units. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous
* response.
*/
pageToken?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<AdUnits>;
customchannels: CustomchannelsResource;
}
interface AlertsResource {
/** Dismiss (delete) the specified alert from the specified publisher AdSense account. */
delete(request: {
/** Account which contains the ad unit. */
accountId: string;
/** Alert to delete. */
alertId: string;
/** Data format for the response. */
alt?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<void>;
/** List the alerts for the specified AdSense account. */
list(request: {
/** Account for which to retrieve the alerts. */
accountId: string;
/** Data format for the response. */
alt?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/**
* The locale to use for translating alert messages. The account locale will be used if this is not supplied. The AdSense default (English) will be used
* if the supplied locale is invalid or unsupported.
*/
locale?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<Alerts>;
}
interface AdunitsResource {
/** List all ad units in the specified custom channel. */
list(request: {
/** Account to which the ad client belongs. */
accountId: string;
/** Ad client which contains the custom channel. */
adClientId: string;
/** Data format for the response. */
alt?: string;
/** Custom channel for which to list ad units. */
customChannelId: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** Whether to include inactive ad units. Default: true. */
includeInactive?: boolean;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The maximum number of ad units to include in the response, used for paging. */
maxResults?: number;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/**
* A continuation token, used to page through ad units. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous
* response.
*/
pageToken?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<AdUnits>;
}
interface CustomchannelsResource {
/** Get the specified custom channel from the specified ad client for the specified account. */
get(request: {
/** Account to which the ad client belongs. */
accountId: string;
/** Ad client which contains the custom channel. */
adClientId: string;
/** Data format for the response. */
alt?: string;
/** Custom channel to retrieve. */
customChannelId: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<CustomChannel>;
/** List all custom channels in the specified ad client for the specified account. */
list(request: {
/** Account to which the ad client belongs. */
accountId: string;
/** Ad client for which to list custom channels. */
adClientId: string;
/** Data format for the response. */
alt?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The maximum number of custom channels to include in the response, used for paging. */
maxResults?: number;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/**
* A continuation token, used to page through custom channels. To retrieve the next page, set this parameter to the value of "nextPageToken" from the
* previous response.
*/
pageToken?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<CustomChannels>;
adunits: AdunitsResource;
}
interface PaymentsResource {
/** List the payments for the specified AdSense account. */
list(request: {
/** Account for which to retrieve the payments. */
accountId: string;
/** Data format for the response. */
alt?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<Payments>;
}
interface SavedResource {
/** Generate an AdSense report based on the saved report ID sent in the query parameters. */
generate(request: {
/** Account to which the saved reports belong. */
accountId: string;
/** Data format for the response. */
alt?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** Optional locale to use for translating report output to a local language. Defaults to "en_US" if not specified. */
locale?: string;
/** The maximum number of rows of report data to return. */
maxResults?: number;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** The saved report to retrieve. */
savedReportId: string;
/** Index of the first row of report data to return. */
startIndex?: number;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<AdsenseReportsGenerateResponse>;
/** List all saved reports in the specified AdSense account. */
list(request: {
/** Account to which the saved reports belong. */
accountId: string;
/** Data format for the response. */
alt?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The maximum number of saved reports to include in the response, used for paging. */
maxResults?: number;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/**
* A continuation token, used to page through saved reports. To retrieve the next page, set this parameter to the value of "nextPageToken" from the
* previous response.
*/
pageToken?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<SavedReports>;
}
interface ReportsResource {
/**
* Generate an AdSense report based on the report request sent in the query parameters. Returns the result as JSON; to retrieve output in CSV format
* specify "alt=csv" as a query parameter.
*/
generate(request: {
/** Account upon which to report. */
accountId: string;
/** Data format for the response. */
alt?: string;
/** Optional currency to use when reporting on monetary metrics. Defaults to the account's currency if not set. */
currency?: string;
/** Dimensions to base the report on. */
dimension?: string;
/** End of the date range to report on in "YYYY-MM-DD" format, inclusive. */
endDate: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** Filters to be run on the report. */
filter?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** Optional locale to use for translating report output to a local language. Defaults to "en_US" if not specified. */
locale?: string;
/** The maximum number of rows of report data to return. */
maxResults?: number;
/** Numeric columns to include in the report. */
metric?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/**
* The name of a dimension or metric to sort the resulting report on, optionally prefixed with "+" to sort ascending or "-" to sort descending. If no
* prefix is specified, the column is sorted ascending.
*/
sort?: string;
/** Start of the date range to report on in "YYYY-MM-DD" format, inclusive. */
startDate: string;
/** Index of the first row of report data to return. */
startIndex?: number;
/** Whether the report should be generated in the AdSense account's local timezone. If false default PST/PDT timezone will be used. */
useTimezoneReporting?: boolean;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<AdsenseReportsGenerateResponse>;
saved: SavedResource;
}
interface SavedadstylesResource {
/** List a specific saved ad style for the specified account. */
get(request: {
/** Account for which to get the saved ad style. */
accountId: string;
/** Data format for the response. */
alt?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** Saved ad style to retrieve. */
savedAdStyleId: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<SavedAdStyle>;
/** List all saved ad styles in the specified account. */
list(request: {
/** Account for which to list saved ad styles. */
accountId: string;
/** Data format for the response. */
alt?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The maximum number of saved ad styles to include in the response, used for paging. */
maxResults?: number;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/**
* A continuation token, used to page through saved ad styles. To retrieve the next page, set this parameter to the value of "nextPageToken" from the
* previous response.
*/
pageToken?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<SavedAdStyles>;
}
interface UrlchannelsResource {
/** List all URL channels in the specified ad client for the specified account. */
list(request: {
/** Account to which the ad client belongs. */
accountId: string;
/** Ad client for which to list URL channels. */
adClientId: string;
/** Data format for the response. */
alt?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The maximum number of URL channels to include in the response, used for paging. */
maxResults?: number;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/**
* A continuation token, used to page through URL channels. To retrieve the next page, set this parameter to the value of "nextPageToken" from the
* previous response.
*/
pageToken?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<UrlChannels>;
}
interface AccountsResource {
/** Get information about the selected AdSense account. */
get(request: {
/** Account to get information about. */
accountId: string;
/** Data format for the response. */
alt?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** Whether the tree of sub accounts should be returned. */
tree?: boolean;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<Account>;
/** List all accounts available to this AdSense account. */
list(request: {
/** Data format for the response. */
alt?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The maximum number of accounts to include in the response, used for paging. */
maxResults?: number;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/**
* A continuation token, used to page through accounts. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous
* response.
*/
pageToken?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<Accounts>;
adclients: AdclientsResource;
adunits: AdunitsResource;
alerts: AlertsResource;
customchannels: CustomchannelsResource;
payments: PaymentsResource;
reports: ReportsResource;
savedadstyles: SavedadstylesResource;
urlchannels: UrlchannelsResource;
}
interface AdclientsResource {
/** List all ad clients in this AdSense account. */
list(request: {
/** Data format for the response. */
alt?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The maximum number of ad clients to include in the response, used for paging. */
maxResults?: number;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/**
* A continuation token, used to page through ad clients. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous
* response.
*/
pageToken?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<AdClients>;
}
interface CustomchannelsResource {
/** List all custom channels which the specified ad unit belongs to. */
list(request: {
/** Ad client which contains the ad unit. */
adClientId: string;
/** Ad unit for which to list custom channels. */
adUnitId: string;
/** Data format for the response. */
alt?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The maximum number of custom channels to include in the response, used for paging. */
maxResults?: number;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/**
* A continuation token, used to page through custom channels. To retrieve the next page, set this parameter to the value of "nextPageToken" from the
* previous response.
*/
pageToken?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<CustomChannels>;
}
interface AdunitsResource {
/** Gets the specified ad unit in the specified ad client. */
get(request: {
/** Ad client for which to get the ad unit. */
adClientId: string;
/** Ad unit to retrieve. */
adUnitId: string;
/** Data format for the response. */
alt?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<AdUnit>;
/** Get ad code for the specified ad unit. */
getAdCode(request: {
/** Ad client with contains the ad unit. */
adClientId: string;
/** Ad unit to get the code for. */
adUnitId: string;
/** Data format for the response. */
alt?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<AdCode>;
/** List all ad units in the specified ad client for this AdSense account. */
list(request: {
/** Ad client for which to list ad units. */
adClientId: string;
/** Data format for the response. */
alt?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** Whether to include inactive ad units. Default: true. */
includeInactive?: boolean;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The maximum number of ad units to include in the response, used for paging. */
maxResults?: number;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/**
* A continuation token, used to page through ad units. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous
* response.
*/
pageToken?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<AdUnits>;
customchannels: CustomchannelsResource;
}
interface AlertsResource {
/** Dismiss (delete) the specified alert from the publisher's AdSense account. */
delete(request: {
/** Alert to delete. */
alertId: string;
/** Data format for the response. */
alt?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<void>;
/** List the alerts for this AdSense account. */
list(request: {
/** Data format for the response. */
alt?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/**
* The locale to use for translating alert messages. The account locale will be used if this is not supplied. The AdSense default (English) will be used
* if the supplied locale is invalid or unsupported.
*/
locale?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<Alerts>;
}
interface AdunitsResource {
/** List all ad units in the specified custom channel. */
list(request: {
/** Ad client which contains the custom channel. */
adClientId: string;
/** Data format for the response. */
alt?: string;
/** Custom channel for which to list ad units. */
customChannelId: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** Whether to include inactive ad units. Default: true. */
includeInactive?: boolean;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The maximum number of ad units to include in the response, used for paging. */
maxResults?: number;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/**
* A continuation token, used to page through ad units. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous
* response.
*/
pageToken?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<AdUnits>;
}
interface CustomchannelsResource {
/** Get the specified custom channel from the specified ad client. */
get(request: {
/** Ad client which contains the custom channel. */
adClientId: string;
/** Data format for the response. */
alt?: string;
/** Custom channel to retrieve. */
customChannelId: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<CustomChannel>;
/** List all custom channels in the specified ad client for this AdSense account. */
list(request: {
/** Ad client for which to list custom channels. */
adClientId: string;
/** Data format for the response. */
alt?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The maximum number of custom channels to include in the response, used for paging. */
maxResults?: number;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/**
* A continuation token, used to page through custom channels. To retrieve the next page, set this parameter to the value of "nextPageToken" from the
* previous response.
*/
pageToken?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<CustomChannels>;
adunits: AdunitsResource;
}
interface DimensionsResource {
/** List the metadata for the dimensions available to this AdSense account. */
list(request: {
/** Data format for the response. */
alt?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<Metadata>;
}
interface MetricsResource {
/** List the metadata for the metrics available to this AdSense account. */
list(request: {
/** Data format for the response. */
alt?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<Metadata>;
}
interface MetadataResource {
dimensions: DimensionsResource;
metrics: MetricsResource;
}
interface PaymentsResource {
/** List the payments for this AdSense account. */
list(request: {
/** Data format for the response. */
alt?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<Payments>;
}
interface SavedResource {
/** Generate an AdSense report based on the saved report ID sent in the query parameters. */
generate(request: {
/** Data format for the response. */
alt?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** Optional locale to use for translating report output to a local language. Defaults to "en_US" if not specified. */
locale?: string;
/** The maximum number of rows of report data to return. */
maxResults?: number;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** The saved report to retrieve. */
savedReportId: string;
/** Index of the first row of report data to return. */
startIndex?: number;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<AdsenseReportsGenerateResponse>;
/** List all saved reports in this AdSense account. */
list(request: {
/** Data format for the response. */
alt?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The maximum number of saved reports to include in the response, used for paging. */
maxResults?: number;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/**
* A continuation token, used to page through saved reports. To retrieve the next page, set this parameter to the value of "nextPageToken" from the
* previous response.
*/
pageToken?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<SavedReports>;
}
interface ReportsResource {
/**
* Generate an AdSense report based on the report request sent in the query parameters. Returns the result as JSON; to retrieve output in CSV format
* specify "alt=csv" as a query parameter.
*/
generate(request: {
/** Accounts upon which to report. */
accountId?: string;
/** Data format for the response. */
alt?: string;
/** Optional currency to use when reporting on monetary metrics. Defaults to the account's currency if not set. */
currency?: string;
/** Dimensions to base the report on. */
dimension?: string;
/** End of the date range to report on in "YYYY-MM-DD" format, inclusive. */
endDate: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** Filters to be run on the report. */
filter?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** Optional locale to use for translating report output to a local language. Defaults to "en_US" if not specified. */
locale?: string;
/** The maximum number of rows of report data to return. */
maxResults?: number;
/** Numeric columns to include in the report. */
metric?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/**
* The name of a dimension or metric to sort the resulting report on, optionally prefixed with "+" to sort ascending or "-" to sort descending. If no
* prefix is specified, the column is sorted ascending.
*/
sort?: string;
/** Start of the date range to report on in "YYYY-MM-DD" format, inclusive. */
startDate: string;
/** Index of the first row of report data to return. */
startIndex?: number;
/** Whether the report should be generated in the AdSense account's local timezone. If false default PST/PDT timezone will be used. */
useTimezoneReporting?: boolean;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<AdsenseReportsGenerateResponse>;
saved: SavedResource;
}
interface SavedadstylesResource {
/** Get a specific saved ad style from the user's account. */
get(request: {
/** Data format for the response. */
alt?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** Saved ad style to retrieve. */
savedAdStyleId: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<SavedAdStyle>;
/** List all saved ad styles in the user's account. */
list(request: {
/** Data format for the response. */
alt?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The maximum number of saved ad styles to include in the response, used for paging. */
maxResults?: number;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/**
* A continuation token, used to page through saved ad styles. To retrieve the next page, set this parameter to the value of "nextPageToken" from the
* previous response.
*/
pageToken?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<SavedAdStyles>;
}
interface UrlchannelsResource {
/** List all URL channels in the specified ad client for this AdSense account. */
list(request: {
/** Ad client for which to list URL channels. */
adClientId: string;
/** Data format for the response. */
alt?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The maximum number of URL channels to include in the response, used for paging. */
maxResults?: number;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/**
* A continuation token, used to page through URL channels. To retrieve the next page, set this parameter to the value of "nextPageToken" from the
* previous response.
*/
pageToken?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<UrlChannels>;
}
}
} | the_stack |
import * as Utils from "./Utils/Utils-Index";
// Note: These methods are designed to work in both Node.js and a browser.
// The native Buffer methods for string encoding/decoding are at least 2-to-3x faster.
// The native methods might also work in the browser by using a third-party Buffer library, like https://github.com/feross/buffer.
// Note: Internally, JavaScript strings are UTF-16, but Ambrosia messages only use UTF-8, so only toUTF8Bytes() and fromUTF8Bytes() are actually used.
// Note: console.log() [in VSCode at least] does not appear to render Unicode characters greater
// than 0xFFFF correctly: the Unicode replacement character (U+FFFD ๏ฟฝ) precedes the character.
// This seems to describe the [Windows-specific] problem: https://exceptionshub.com/how-to-output-emoji-to-console-in-node-js-on-windows-2.html.
// See also: https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings.
let _textEncoder: TextEncoder = new TextEncoder();
let _textDecoder: TextDecoder = new TextDecoder();
/** Converts a string to UTF-8, returned as a byte array. */
export function toUTF8Bytes(s: string): Uint8Array
{
return (Utils.isNode() ? new Uint8Array(Buffer.from(s, "utf8")) : _textEncoder.encode(s));
}
/** Returns a string from an array of UTF-8 bytes. Note: Be careful when specifying startIndex and/or length since these are in bytes, not characters. */
export function fromUTF8Bytes(bytes: Uint8Array | Buffer, startIndex: number = 0, length: number = bytes.length): string
{
let buffer: Buffer;
if ((startIndex !== 0) || (length !== bytes.length))
{
if ((bytes instanceof Buffer) && Utils.isNode())
{
// Optimization to [theoretically] minimize memory copies, but [from observation] with no improvement in execution time
return ((bytes as Buffer).toString("utf8", startIndex, startIndex + length));
}
buffer = (bytes instanceof Buffer) ? bytes.slice(startIndex, startIndex + length) : Buffer.from(bytes.slice(startIndex, startIndex + length));
}
else
{
buffer = (bytes instanceof Buffer) ? bytes : Buffer.from(bytes);
}
if (Utils.isNode())
{
return (buffer.toString("utf8"));
}
else
{
return (_textDecoder.decode(buffer));
}
}
/** Converts a string to UTF-16, returned as a byte array. */
export function toUTF16Bytes(s: string): Uint8Array
{
let bytes: Uint8Array;
if (Utils.isNode())
{
if (!Utils.isLittleEndian())
{
throw new Error("Node.js only supports UTF-16 strings on little-endian operating systems")
}
bytes = new Uint8Array(Buffer.from(s, "utf16le"));
}
else
{
let buffer: Uint16Array = new Uint16Array(s.length);
// Note: UTF-16 is the default encoding in JavaScript, requiring either 2 or 4 bytes per character.
// If 4 bytes are required for a character, the length of the string will be +1 (because of the surrogate-pair).
for (let i = 0, length = s.length; i < length; i++)
{
let charCode: number = s.charCodeAt(i);
buffer[i] = charCode;
}
bytes = new Uint8Array(buffer.buffer); // Use the ArrayBuffer so that the values in it can be reinterpreted as 8-bit values
}
return (bytes);
}
/** Returns a string from an array of UTF-16 bytes. Note: Be careful when specifying startIndex and/or length since these are in bytes, not characters. */
export function fromUTF16Bytes(bytes: Uint8Array | Buffer, startIndex: number = 0, length: number = bytes.length): string
{
let buffer: Buffer;
if ((startIndex !== 0) || (length !== bytes.length))
{
buffer = (bytes instanceof Buffer) ? bytes.slice(startIndex, startIndex + length) : Buffer.from(bytes.slice(startIndex, startIndex + length));
}
else
{
buffer = (bytes instanceof Buffer) ? bytes : Buffer.from(bytes);
}
if (Utils.isNode())
{
if (!Utils.isLittleEndian())
{
throw new Error("Node.js only supports UTF-16 strings on little-endian operating systems")
}
return (buffer.toString("utf16le"));
}
else
{
// Since 'buffer' may have been passed in (as 'bytes'), we must handle the case where it's a view (ie. we must respect the byteOffset/byteLength properties)
const buffer16: Uint16Array = new Uint16Array(buffer.buffer, buffer.byteOffset, buffer.byteLength / 2); // Use the ArrayBuffer so that the values in it can be reinterpreted as 16-bit values
return (String.fromCharCode(...buffer16));
}
}
/** Converts a string to UTF-8, returned as a byte array. */
export function toUTF8Bytes_Alt(s: string): Uint8Array
{
let encoded: string = encodeURI(s); // Converts to a string representation of UTF-8
let percentCharCount: number = 0;
// Note: In UTF-8, chars outside of the 0..127 range get encoded [by encodeURI] as "%HH" where "HH" is a 2-digit hex value, eg. "%D1"
// [See https://www.fileformat.info/info/unicode/utf8.htm]
for (let i = 0; i < encoded.length; i++)
{
if (encoded[i] === "%")
{
percentCharCount++;
}
}
let byteCount: number = encoded.length - (percentCharCount * 2);
let bytes: Uint8Array = new Uint8Array(byteCount);
for (let i = 0, pos = 0; i < encoded.length; i++, pos++)
{
const charCode: number = encoded.charCodeAt(i);
if (encoded[i] === "%") // eg. "%D1"
{
const encodedCharCode: number = parseInt(encoded.substr(i + 1, 2), 16);
bytes[pos] = encodedCharCode;
i += 2;
}
else
{
bytes[pos] = charCode;
}
}
return (bytes);
}
/** Returns a string from an array of UTF-8 bytes. */
export function fromUTF8Bytes_Alt(bytes: Uint8Array): string
{
let s: string = "";
for (let i = 0; i < bytes.length; i++)
{
if (bytes[i] < 128)
{
s += String.fromCharCode(bytes[i]);
}
else
{
s += "%" + bytes[i].toString(16).toUpperCase();
}
}
return (decodeURI(s));
}
/*
** Notes on Buffer/TypedArray "view" behavior:
** ===========================================
// A Buffer can be a view (by creating it from an ArrayBuffer):
let arr: Uint8Array = new Uint8Array([65, 66, 67, 68]); // "ABCD"
let bufSlice: Buffer = Buffer.from(arr.buffer, 1, 2); // Creates a VIEW ("BC") [shared memory: byteOffset = 1, byteLength = 2]
bufSlice[1] = 99; // Updates BOTH bufSlice and arr
console.log(bufSlice.toString("utf8")); // "Bc"
console.log(arr[2]); // 99
let buf2: Buffer = Buffer.from(bufSlice); // Creates a COPY
buf2[0] = 99; // "c"
console.log(bufSlice.toString("utf8")); // Still "Bc"
console.log(buf2.toString("utf8")); // "cc"
let buf3: Buffer = Buffer.from(bufSlice.buffer); // Creates a VIEW [shared memory] of the ENTIRE ArrayBuffer (so "ABcD"), not just the sliced region
console.log(buf3.toString("utf8")); // "ABcD"
// A TypedArray (like Uint8Array) can also be a view (by creating it using subarray()):
let baseArr: Uint8Array = new Uint8Array([65, 66, 67, 68]); // "ABCD"
let subArr: Uint8Array = baseArr.subarray(1, 4); // Creates a VIEW ("BCD") [shared memory: byteOffset = 1, byteLength = 3]
console.log(Buffer.from(subArr.buffer.slice(0, 1)).toString()); // "A" (not "B")
console.log(Buffer.from(subArr.buffer.slice(subArr.byteOffset + 0, subArr.byteOffset + 1)).toString()); // "B"
*/
/** Runs unit/perf tests. */
export function runUnitTests()
{
// UTF-16 encoding of ๐ (\u{1F600}): (see https://en.wikipedia.org/wiki/UTF-16)
// Note: The curly braces are the ES6 code-point escape syntax for unicode characters over 4 hex digits
// 0x1F600 - 0x10000 = 0xF600 = 00001111011000000000 = 2 groups of 10-bits: 0000111101 (0x3D) and 1000000000 (0x200)
// 0xD800 + 0x3D = 0xD83D = 55357 (High surrogate) = charCodeAt(0)
// 0xDC00 + 0x200 = 0xDE00 = 56832 (Low surrogate) = charCodeAt(1)
// = [3D, D8, 00, DE] - Note: Node.js only supports little-endian UTF-16
// UTF-8 encoding of ๐: (see https://en.wikipedia.org/wiki/UTF-8)
// 0x1F600 is greater than 0x10000 so requires 21 code-point bits = 0 0001 1111 0110 0000 0000
// 11110 [This indicates that 4 bytes are needed] + 0 00 = 11110000 = 0xF0
// 10 [This indicates a continuation byte] + 01 1111 = 10011111 = 0x9F
// 10 [This indicates a continuation byte] + 0110 00 = 10011000 = 0x98
// 10 [This indicates a continuation byte] + 00 0000 = 10000000 - 0x80
// = [F0, 9F, 98, 80]
// 1) Buffer (vs. Uint8Array) tests
let sBufTest: string = "ABC๐ัะตะปะปั!"
let sBuf: string = fromUTF8Bytes(Buffer.from(sBufTest, "utf8"));
if (sBuf !== sBufTest)
{
throw new Error(`UTF-8 Buffer test failed for '${sBufTest}'`);
}
sBuf = fromUTF8Bytes(Buffer.from(sBufTest, "utf8"), 3, 4);
if (sBuf !== "๐")
{
throw new Error(`UTF-8 Buffer offset test failed for '${sBufTest}'`);
}
// 2) Buffer [that's a view] test
let utf16ByteArr: Uint8Array = new Uint8Array([65, 0, 66, 0, 67, 0, 68, 0]);
let viewBuffer: Buffer = Buffer.from(utf16ByteArr.buffer, 2, 6);
if (fromUTF16Bytes(viewBuffer) !== "BCD")
{
throw new Error(`UTF-16 Buffer view test failed for 'BCD'`);
}
// 3) Offset tests
let utf8Bytes: Uint8Array = toUTF8Bytes("AB๐C");
let s8: string = fromUTF8Bytes(utf8Bytes, 2, 4); // ๐ takes 4 bytes
if (s8 !== "๐")
{
throw new Error("UTF-8 startIndex/length test failed for 'AB๐C'");
}
let utf16Bytes: Uint8Array = toUTF16Bytes("ABCัะตะปะปั");
let s16: string = fromUTF16Bytes(utf16Bytes, 3 * 2, 3 * 2);
if (s16 !== "ัะตะป")
{
throw new Error("UTF-16 startIndex/length test failed for 'ABCัะตะปะปั'");
}
let s: string = "ABC๐ัะตะปะปั!";
if (fromUTF8Bytes_Alt(toUTF8Bytes_Alt(s)) !== s)
{
throw new Error(`UTF-8_Alt test failed for '${s}'`);
}
// 4) Performance tests
let testStrings: string[] = ["AB๐C", "ABCัะตะปะปั", "\u0041\u0042\u0043"];
for (let s of testStrings)
{
let startTimeInMs: number = 0;
let iterations: number = 100000;
let elapsedMs: number = 0;
startTimeInMs = Date.now();
for (let i = 0; i < iterations; i++)
{
let utf8Bytes: Uint8Array = toUTF8Bytes(s);
let s8: string = fromUTF8Bytes(utf8Bytes);
if (s !== s8)
{
throw new Error("UTF-8 test failed for '" + s + "'");
}
}
elapsedMs = Date.now() - startTimeInMs;
Utils.log(`UTF-8 test elapsed time: ${elapsedMs}ms for ${iterations} iterations of '${s}' (Node: ${Utils.isNode()})`);
startTimeInMs = Date.now();
for (let i = 0; i < iterations; i++)
{
let utf16Bytes: Uint8Array = toUTF16Bytes(s);
let s16: string = fromUTF16Bytes(utf16Bytes);
if (s !== s16)
{
throw new Error("UTF-16 test failed for '" + s + "'");
}
}
elapsedMs = Date.now() - startTimeInMs;
Utils.log(`UTF-16 test elapsed time: ${elapsedMs}ms for ${iterations} iterations of '${s}' (Node: ${Utils.isNode()})`);
}
Utils.log("Success: All tests passed!");
} | the_stack |
import {
IExecuteFunctions,
} from 'n8n-core';
import {
IDataObject,
INodeExecutionData,
INodeType,
INodeTypeDescription,
NodeOperationError,
} from 'n8n-workflow';
import {
actionNetworkApiRequest,
adjustEventPayload,
adjustPersonPayload,
adjustPetitionPayload,
handleListing,
makeOsdiLink,
resourceLoaders,
simplifyResponse,
} from './GenericFunctions';
import {
attendanceFields,
attendanceOperations,
eventFields,
eventOperations,
personFields,
personOperations,
personTagFields,
personTagOperations,
petitionFields,
petitionOperations,
signatureFields,
signatureOperations,
tagFields,
tagOperations,
} from './descriptions';
import {
AllFieldsUi,
EmailAddressUi,
Operation,
PersonResponse,
Resource,
Response,
} from './types';
export class ActionNetwork implements INodeType {
description: INodeTypeDescription = {
displayName: 'Action Network',
name: 'actionNetwork',
icon: 'file:actionNetwork.svg',
group: ['transform'],
version: 1,
subtitle: '={{$parameter["resource"] + ": " + $parameter["operation"]}}',
description: 'Consume the Action Network API',
defaults: {
name: 'Action Network',
},
inputs: ['main'],
outputs: ['main'],
credentials: [
{
name: 'actionNetworkApi',
required: true,
},
],
properties: [
{
displayName: 'Resource',
name: 'resource',
type: 'options',
options: [
{
name: 'Attendance',
value: 'attendance',
},
{
name: 'Event',
value: 'event',
},
{
name: 'Person',
value: 'person',
},
{
name: 'Person Tag',
value: 'personTag',
},
{
name: 'Petition',
value: 'petition',
},
{
name: 'Signature',
value: 'signature',
},
{
name: 'Tag',
value: 'tag',
},
],
default: 'attendance',
description: 'Resource to consume',
},
...attendanceOperations,
...attendanceFields,
...eventOperations,
...eventFields,
...personOperations,
...personFields,
...petitionOperations,
...petitionFields,
...signatureOperations,
...signatureFields,
...tagOperations,
...tagFields,
...personTagOperations,
...personTagFields,
],
};
methods = {
loadOptions: resourceLoaders,
};
async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> {
const items = this.getInputData();
const returnData: IDataObject[] = [];
const resource = this.getNodeParameter('resource', 0) as Resource;
const operation = this.getNodeParameter('operation', 0) as Operation;
let response;
for (let i = 0; i < items.length; i++) {
try {
if (resource === 'attendance') {
// **********************************************************************
// attendance
// **********************************************************************
// https://actionnetwork.org/docs/v2/attendances
if (operation === 'create') {
// ----------------------------------------
// attendance: create
// ----------------------------------------
const personId = this.getNodeParameter('personId', i) as string;
const eventId = this.getNodeParameter('eventId', i);
const body = makeOsdiLink(personId) as IDataObject;
const endpoint = `/events/${eventId}/attendances`;
response = await actionNetworkApiRequest.call(this, 'POST', endpoint, body);
} else if (operation === 'get') {
// ----------------------------------------
// attendance: get
// ----------------------------------------
const eventId = this.getNodeParameter('eventId', i);
const attendanceId = this.getNodeParameter('attendanceId', i);
const endpoint = `/events/${eventId}/attendances/${attendanceId}`;
response = await actionNetworkApiRequest.call(this, 'GET', endpoint);
} else if (operation === 'getAll') {
// ----------------------------------------
// attendance: getAll
// ----------------------------------------
const eventId = this.getNodeParameter('eventId', i);
const endpoint = `/events/${eventId}/attendances`;
response = await handleListing.call(this, 'GET', endpoint);
}
} else if (resource === 'event') {
// **********************************************************************
// event
// **********************************************************************
// https://actionnetwork.org/docs/v2/events
if (operation === 'create') {
// ----------------------------------------
// event: create
// ----------------------------------------
const body = {
origin_system: this.getNodeParameter('originSystem', i),
title: this.getNodeParameter('title', i),
} as IDataObject;
const additionalFields = this.getNodeParameter('additionalFields', i) as AllFieldsUi;
if (Object.keys(additionalFields).length) {
Object.assign(body, adjustEventPayload(additionalFields));
}
response = await actionNetworkApiRequest.call(this, 'POST', '/events', body);
} else if (operation === 'get') {
// ----------------------------------------
// event: get
// ----------------------------------------
const eventId = this.getNodeParameter('eventId', i);
response = await actionNetworkApiRequest.call(this, 'GET', `/events/${eventId}`);
} else if (operation === 'getAll') {
// ----------------------------------------
// event: getAll
// ----------------------------------------
response = await handleListing.call(this, 'GET', '/events');
}
} else if (resource === 'person') {
// **********************************************************************
// person
// **********************************************************************
// https://actionnetwork.org/docs/v2/people
if (operation === 'create') {
// ----------------------------------------
// person: create
// ----------------------------------------
const emailAddresses = this.getNodeParameter('email_addresses', i) as EmailAddressUi;
const body = {
person: {
email_addresses: [emailAddresses.email_addresses_fields], // only one accepted by API
},
} as IDataObject;
const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject;
if (Object.keys(additionalFields).length) {
Object.assign(body.person, adjustPersonPayload(additionalFields));
}
response = await actionNetworkApiRequest.call(this, 'POST', '/people', body);
} else if (operation === 'get') {
// ----------------------------------------
// person: get
// ----------------------------------------
const personId = this.getNodeParameter('personId', i);
response = await actionNetworkApiRequest.call(this, 'GET', `/people/${personId}`) as PersonResponse;
} else if (operation === 'getAll') {
// ----------------------------------------
// person: getAll
// ----------------------------------------
response = await handleListing.call(this, 'GET', '/people') as PersonResponse[];
} else if (operation === 'update') {
// ----------------------------------------
// person: update
// ----------------------------------------
const personId = this.getNodeParameter('personId', i);
const body = {} as IDataObject;
const updateFields = this.getNodeParameter('updateFields', i) as IDataObject;
if (Object.keys(updateFields).length) {
Object.assign(body, adjustPersonPayload(updateFields));
} else {
throw new NodeOperationError(
this.getNode(),
`Please enter at least one field to update for the ${resource}.`,
);
}
response = await actionNetworkApiRequest.call(this, 'PUT', `/people/${personId}`, body);
}
} else if (resource === 'petition') {
// **********************************************************************
// petition
// **********************************************************************
// https://actionnetwork.org/docs/v2/petitions
if (operation === 'create') {
// ----------------------------------------
// petition: create
// ----------------------------------------
const body = {
origin_system: this.getNodeParameter('originSystem', i),
title: this.getNodeParameter('title', i),
} as IDataObject;
const additionalFields = this.getNodeParameter('additionalFields', i) as AllFieldsUi;
if (Object.keys(additionalFields).length) {
Object.assign(body, adjustPetitionPayload(additionalFields));
}
response = await actionNetworkApiRequest.call(this, 'POST', '/petitions', body);
} else if (operation === 'get') {
// ----------------------------------------
// petition: get
// ----------------------------------------
const petitionId = this.getNodeParameter('petitionId', i);
const endpoint = `/petitions/${petitionId}`;
response = await actionNetworkApiRequest.call(this, 'GET', endpoint);
} else if (operation === 'getAll') {
// ----------------------------------------
// petition: getAll
// ----------------------------------------
response = await handleListing.call(this, 'GET', '/petitions');
} else if (operation === 'update') {
// ----------------------------------------
// petition: update
// ----------------------------------------
const petitionId = this.getNodeParameter('petitionId', i);
const body = {} as IDataObject;
const updateFields = this.getNodeParameter('updateFields', i) as AllFieldsUi;
if (Object.keys(updateFields).length) {
Object.assign(body, adjustPetitionPayload(updateFields));
} else {
throw new NodeOperationError(
this.getNode(),
`Please enter at least one field to update for the ${resource}.`,
);
}
response = await actionNetworkApiRequest.call(this, 'PUT', `/petitions/${petitionId}`, body);
}
} else if (resource === 'signature') {
// **********************************************************************
// signature
// **********************************************************************
// https://actionnetwork.org/docs/v2/signatures
if (operation === 'create') {
// ----------------------------------------
// signature: create
// ----------------------------------------
const personId = this.getNodeParameter('personId', i) as string;
const petitionId = this.getNodeParameter('petitionId', i);
const body = makeOsdiLink(personId) as IDataObject;
const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject;
if (Object.keys(additionalFields).length) {
Object.assign(body, additionalFields);
}
const endpoint = `/petitions/${petitionId}/signatures`;
response = await actionNetworkApiRequest.call(this, 'POST', endpoint, body);
} else if (operation === 'get') {
// ----------------------------------------
// signature: get
// ----------------------------------------
const petitionId = this.getNodeParameter('petitionId', i);
const signatureId = this.getNodeParameter('signatureId', i);
const endpoint = `/petitions/${petitionId}/signatures/${signatureId}`;
response = await actionNetworkApiRequest.call(this, 'GET', endpoint);
} else if (operation === 'getAll') {
// ----------------------------------------
// signature: getAll
// ----------------------------------------
const petitionId = this.getNodeParameter('petitionId', i);
const endpoint = `/petitions/${petitionId}/signatures`;
response = await handleListing.call(this, 'GET', endpoint);
} else if (operation === 'update') {
// ----------------------------------------
// signature: update
// ----------------------------------------
const petitionId = this.getNodeParameter('petitionId', i);
const signatureId = this.getNodeParameter('signatureId', i);
const body = {};
const updateFields = this.getNodeParameter('updateFields', i) as AllFieldsUi;
if (Object.keys(updateFields).length) {
Object.assign(body, updateFields);
} else {
throw new NodeOperationError(
this.getNode(),
`Please enter at least one field to update for the ${resource}.`,
);
}
const endpoint = `/petitions/${petitionId}/signatures/${signatureId}`;
response = await actionNetworkApiRequest.call(this, 'PUT', endpoint, body);
}
} else if (resource === 'tag') {
// **********************************************************************
// tag
// **********************************************************************
// https://actionnetwork.org/docs/v2/tags
if (operation === 'create') {
// ----------------------------------------
// tag: create
// ----------------------------------------
const body = {
name: this.getNodeParameter('name', i),
} as IDataObject;
response = await actionNetworkApiRequest.call(this, 'POST', '/tags', body);
} else if (operation === 'get') {
// ----------------------------------------
// tag: get
// ----------------------------------------
const tagId = this.getNodeParameter('tagId', i);
response = await actionNetworkApiRequest.call(this, 'GET', `/tags/${tagId}`);
} else if (operation === 'getAll') {
// ----------------------------------------
// tag: getAll
// ----------------------------------------
response = await handleListing.call(this, 'GET', '/tags');
}
} else if (resource === 'personTag') {
// **********************************************************************
// personTag
// **********************************************************************
// https://actionnetwork.org/docs/v2/taggings
if (operation === 'add') {
// ----------------------------------------
// personTag: add
// ----------------------------------------
const personId = this.getNodeParameter('personId', i) as string;
const tagId = this.getNodeParameter('tagId', i);
const body = makeOsdiLink(personId) as IDataObject;
const endpoint = `/tags/${tagId}/taggings`;
response = await actionNetworkApiRequest.call(this, 'POST', endpoint, body);
} else if (operation === 'remove') {
// ----------------------------------------
// personTag: remove
// ----------------------------------------
const tagId = this.getNodeParameter('tagId', i);
const taggingId = this.getNodeParameter('taggingId', i);
const endpoint = `/tags/${tagId}/taggings/${taggingId}`;
response = await actionNetworkApiRequest.call(this, 'DELETE', endpoint);
}
}
const simplify = this.getNodeParameter('simple', i, false) as boolean;
if (simplify) {
response = operation === 'getAll'
? response.map((i: Response) => simplifyResponse(i, resource))
: simplifyResponse(response, resource);
}
Array.isArray(response)
? returnData.push(...response)
: returnData.push(response);
} catch (error) {
if (this.continueOnFail()) {
returnData.push({ error: error.message });
continue;
}
throw error;
}
}
return [this.helpers.returnJsonArray(returnData)];
}
} | the_stack |
import * as assert from "power-assert";
import {
createJob,
JobTaskType,
} from "../../../../lib/api-helper/misc/job/createJob";
import { CommandHandlerRegistration } from "../../../../lib/api/registration/CommandHandlerRegistration";
describe("createJob", () => {
it("should create job with one task and command name", async () => {
const result = await createJob({
command: "TestCommand",
registration: "@atomist/sdm-test",
description: "This is a test command",
parameters: {
foo: "bar",
},
}, {
context: {
name: "@atomist/sdm-test",
},
graphClient: {
mutate: async options => {
if (options.name === "CreateJob") {
const vars = options.variables;
assert.strictEqual(vars.name, "TestCommand");
assert.strictEqual(vars.description, "This is a test command");
assert.strictEqual(vars.owner, "@atomist/sdm-test");
assert.strictEqual(vars.tasks.length, 1);
assert.strictEqual(vars.tasks[0].name, "TestCommand");
assert.strictEqual(vars.tasks[0].data, JSON.stringify({
type: JobTaskType.Command,
parameters: { foo: "bar" },
}));
}
return {
createAtmJob: { id: "123456" },
} as any;
},
} as any,
} as any);
assert.deepStrictEqual(result, { id: "123456" });
});
it("should create job with one task and command registration", async () => {
const result = await createJob({
// tslint:disable-next-line:no-object-literal-type-assertion
command: { name: "TestCommand" } as CommandHandlerRegistration,
registration: "@atomist/sdm-test",
description: "This is a test command",
parameters: {
foo: "bar",
},
}, {
context: {
name: "@atomist/sdm-test",
},
graphClient: {
mutate: async options => {
if (options.name === "CreateJob") {
const vars = options.variables;
assert.strictEqual(vars.name, "TestCommand");
assert.strictEqual(vars.description, "This is a test command");
assert.strictEqual(vars.owner, "@atomist/sdm-test");
assert.strictEqual(vars.tasks.length, 1);
assert.strictEqual(vars.tasks[0].name, "TestCommand");
assert.strictEqual(vars.tasks[0].data, JSON.stringify({
type: JobTaskType.Command,
parameters: { foo: "bar" },
}));
}
return {
createAtmJob: { id: "123456" },
} as any;
},
} as any,
} as any);
assert.deepStrictEqual(result, { id: "123456" });
});
it("should create job with several tasks", async () => {
const result = await createJob({
command: "TestCommand",
registration: "@atomist/sdm-test",
description: "This is a test command",
parameters: [{
color: "blue",
}, {
color: "red",
}, {
color: "green",
}],
}, {
context: {
name: "@atomist/sdm-test",
},
graphClient: {
mutate: async options => {
if (options.name === "CreateJob") {
const vars = options.variables;
assert.strictEqual(vars.name, "TestCommand");
assert.strictEqual(vars.description, "This is a test command");
assert.strictEqual(vars.owner, "@atomist/sdm-test");
assert.strictEqual(vars.tasks.length, 3);
assert.strictEqual(vars.tasks[0].name, "TestCommand");
assert.strictEqual(vars.tasks[0].data, JSON.stringify({
type: JobTaskType.Command,
parameters: { color: "blue" },
}));
assert.strictEqual(vars.tasks[1].name, "TestCommand");
assert.strictEqual(vars.tasks[1].data, JSON.stringify({
type: JobTaskType.Command,
parameters: { color: "red" },
}));
assert.strictEqual(vars.tasks[2].name, "TestCommand");
assert.strictEqual(vars.tasks[2].data, JSON.stringify({
type: JobTaskType.Command,
parameters: { color: "green" },
}));
}
return {
createAtmJob: { id: "123456" },
} as any;
},
} as any,
} as any);
assert.deepStrictEqual(result, { id: "123456" });
});
it("should allow an empty parameter array to create no tasks", async () => {
const result = await createJob({
command: "TestCommand",
registration: "@atomist/sdm-test",
description: "This is a test command",
parameters: [],
}, {
context: {
name: "@atomist/sdm-test",
},
graphClient: {
mutate: async options => {
if (options.name === "CreateJob") {
const vars = options.variables;
assert.strictEqual(vars.name, "TestCommand");
assert.strictEqual(vars.description, "This is a test command");
assert.strictEqual(vars.owner, "@atomist/sdm-test");
assert.strictEqual(vars.tasks.length, 0);
// assert.strictEqual(vars.tasks[0].name, "TestCommand");
// assert.strictEqual(vars.tasks[0].data, JSON.stringify({
// type: JobTaskType.Command,
// parameters: { },
// }));
}
return {
createAtmJob: { id: "123456" },
} as any;
},
} as any,
} as any);
assert.deepStrictEqual(result, { id: "123456" });
});
it("should allow an parameter array with empty object to create at least one task", async () => {
const result = await createJob({
command: "TestCommand",
registration: "@atomist/sdm-test",
description: "This is a test command",
parameters: [{}],
}, {
context: {
name: "@atomist/sdm-test",
},
graphClient: {
mutate: async options => {
if (options.name === "CreateJob") {
const vars = options.variables;
assert.strictEqual(vars.name, "TestCommand");
assert.strictEqual(vars.description, "This is a test command");
assert.strictEqual(vars.owner, "@atomist/sdm-test");
assert.strictEqual(vars.tasks.length, 1);
assert.strictEqual(vars.tasks[0].name, "TestCommand");
assert.strictEqual(vars.tasks[0].data, JSON.stringify({
type: JobTaskType.Command,
parameters: {},
}));
}
return {
createAtmJob: { id: "123456" },
} as any;
},
} as any,
} as any);
assert.deepStrictEqual(result, { id: "123456" });
});
it("should allow split parameter into multiple addJobTask calls", async () => {
const parameters = Array.from({ length: 500 }, (v, k) => ({ counter: k }));
const result = await createJob({
command: "TestCommand",
registration: "@atomist/sdm-test",
description: "This is a test command",
parameters,
}, {
context: {
name: "@atomist/sdm-test",
},
graphClient: {
mutate: async options => {
if (options.name === "CreateJob") {
const vars = options.variables;
assert.strictEqual(vars.name, "TestCommand");
assert.strictEqual(vars.description, "This is a test command");
assert.strictEqual(vars.owner, "@atomist/sdm-test");
assert.strictEqual(vars.tasks.length, 250);
assert.strictEqual(vars.tasks[0].name, "TestCommand");
assert.strictEqual(vars.tasks[0].data, JSON.stringify({
type: JobTaskType.Command,
parameters: { counter: 0 },
}));
return {
createAtmJob: { id: "123456" },
} as any;
} else if (options.name === "AddTasks") {
const vars = options.variables;
assert.strictEqual(vars.id, "123456");
assert.strictEqual(vars.tasks.length, 250);
assert.strictEqual(vars.tasks[0].name, "TestCommand");
assert.strictEqual(vars.tasks[0].data, JSON.stringify({
type: JobTaskType.Command,
parameters: { counter: 250 },
}));
return {
createAtmJob: { id: "123456" },
} as any;
}
},
} as any,
} as any);
assert.deepStrictEqual(result, { id: "123456" });
});
}); | the_stack |
namespace phasereditor2d.scene.ui.editor.properties {
import controls = colibri.ui.controls;
export abstract class UserPropertiesSection extends controls.properties.PropertySection<any> {
private _propArea: HTMLDivElement;
protected abstract getSectionHelpPath(): string;
protected abstract getUserProperties(): sceneobjects.UserProperties;
protected abstract runOperation(action: (props?: sceneobjects.UserProperties) => void, updateSelection?: boolean);
hasMenu() {
return true;
}
createMenu(menu: controls.Menu) {
ide.IDEPlugin.getInstance().createHelpMenuItem(menu, this.getSectionHelpPath());
}
createForm(parent: HTMLDivElement) {
const comp = this.createGridElement(parent);
comp.style.gridTemplateColumns = "1fr";
this._propArea = this.createGridElement(comp, 2);
comp.appendChild(this._propArea);
const propTypes = ScenePlugin.getInstance().createUserPropertyTypes();
const btn = this.createMenuButton(comp, "Add Property", () => propTypes.map(t => ({
name: t.getName() + " Property",
value: t.getId()
})), (typeId: string) => {
const newType = ScenePlugin.getInstance().createUserPropertyType(typeId);
this.runOperation(userProps => {
const prop = userProps.createProperty(newType);
userProps.add(prop);
this.setExpandedStateInStorage(prop, true);
}, true);
});
btn.style.gridColumn = "1 / span 2";
btn.style.justifySelf = "center";
this.addUpdater(() => {
this._propArea.innerHTML = "";
const properties = this.getUserProperties().getProperties();
for (const prop of properties) {
const propPane = this.createGridElement(this._propArea, 2);
propPane.style.gridColumn = "1 / span 2";
const titleLabel = this.createTitlePanel(propPane, prop);
this._propArea.appendChild(propPane);
const info = prop.getInfo();
this.simpleField(propPane, info, "name", "Name", "The property name. Like in 'speedMin'.");
this.simpleField(
propPane, info, "label", "Label", "The property display label. Like in 'Speed Min'.", () => {
titleLabel.innerHTML = prop.getInfo().label;
});
this.simpleField(propPane, info, "tooltip", "Tooltip", "The property tooltip.");
{
this.createLabel(propPane, "Type", "The property type.");
const text = this.createText(propPane, true);
text.value = prop.getType().getName();
}
if (prop.getType() instanceof sceneobjects.OptionPropertyType) {
this.createOptionsField(propPane, prop);
} else if (prop.getType() instanceof sceneobjects.ExpressionPropertyType) {
this.createExpressionTypeField(propPane, prop);
}
{
this.createLabel(propPane, "Default", "The property default value.");
const propEditor = info.type.createEditorElement(
() => {
return prop.getInfo().defValue;
},
value => {
this.runOperation(() => {
prop.getInfo().defValue = value;
this.setExpandedStateInStorage(prop, true);
}, true);
});
propPane.appendChild(propEditor.element);
propEditor.update();
}
{
const check = this.createCheckbox(propPane,
this.createLabel(propPane, "Custom Definition", "The compiler delegates the property's definition to the user."));
check.checked = prop.isCustomDefinition();
check.addEventListener("change", e => {
this.runOperation(() => {
prop.getInfo().customDefinition = check.checked;
}, false);
});
}
}
});
}
private setExpandedStateInStorage(prop: sceneobjects.UserProperty, value: boolean) {
window.localStorage[`PrefabPropertiesSection[${prop.getName()}].expanded`] = value;
}
private getExpandedStateInStorage(prop: sceneobjects.UserProperty) {
return window.localStorage[`PrefabPropertiesSection[${prop.getName()}].expanded`];
}
createTitlePanel(propPane: HTMLDivElement, prop: sceneobjects.UserProperty) {
const titlePanel = document.createElement("div");
titlePanel.classList.add("PropertySubTitlePanel");
this._propArea.insertBefore(titlePanel, propPane);
const collapsedIcon = colibri.ColibriPlugin.getInstance().getIcon(colibri.ICON_CONTROL_TREE_COLLAPSE);
const expandedIcon = colibri.ColibriPlugin.getInstance().getIcon(colibri.ICON_CONTROL_TREE_EXPAND);
const expanderControl = new controls.IconControl();
titlePanel.appendChild(expanderControl.getCanvas());
const titleLabel = this.createLabel(titlePanel, prop.getLabel());
titleLabel.classList.add("PropertySubTitleLabel");
const expanded = this.getExpandedStateInStorage(prop) === "true";
propPane.style.display = expanded ? "grid" : "none";
expanderControl.setIcon(expanded ? collapsedIcon : expandedIcon);
const expandListener = () => {
const expandIt = propPane.style.display === "none";
propPane.style.display = expandIt ? "grid" : "none";
this.setExpandedStateInStorage(prop, expandIt);
expanderControl.setIcon(expandIt ? collapsedIcon : expandedIcon);
};
expanderControl.getCanvas().addEventListener("click", expandListener);
titleLabel.addEventListener("click", expandListener);
this.createPropertiesMenu(titlePanel, prop);
return titleLabel;
}
private createPropertiesMenu(titlePanel: HTMLElement, prop: sceneobjects.UserProperty) {
const icon = new controls.IconControl(colibri.ColibriPlugin.getInstance().getIcon(colibri.ICON_SMALL_MENU));
icon.getCanvas().classList.add("IconButton");
titlePanel.appendChild(icon.getCanvas());
icon.getCanvas().addEventListener("click", e => {
const menu = new controls.Menu();
menu.addAction({
text: "Move Up",
callback: () => {
this.runOperation(userProps => {
const list = userProps.getProperties();
const i = list.indexOf(prop);
if (i > 0) {
const temp = list[i - 1];
list[i - 1] = prop;
list[i] = temp;
}
}, true);
}
});
menu.addAction({
text: "Move Down",
callback: () => {
this.runOperation(userProps => {
const list = userProps.getProperties();
const i = list.indexOf(prop);
if (i < list.length - 1) {
const temp = list[i + 1];
list[i + 1] = prop;
list[i] = temp;
}
}, true);
}
});
menu.addSeparator();
menu.addMenu(this.createMorphMenu(prop));
menu.addSeparator();
menu.addAction({
text: "Delete",
callback: () => {
this.runOperation(userProps => {
const list = userProps.getProperties();
const i = list.indexOf(prop);
list.splice(i, 1);
}, true);
}
});
menu.createWithEvent(e);
});
}
private createMorphMenu(prop: sceneobjects.UserProperty) {
const menu = new controls.Menu("Change Type");
const propTypes = ScenePlugin.getInstance().createUserPropertyTypes();
for (const propType of propTypes) {
menu.addAction({
text: propType.getName(),
callback: () => {
this.runOperation(userProps => {
prop.getInfo().type = propType;
}, true);
}
});
}
// const btn = this.createMenuButton(comp, "Add Property", propTypes.map(t => ({
// name: t.getName() + " Property",
// value: t.getId()
// })), (typeId: string) => {
// const newType = ScenePlugin.getInstance().createUserPropertyType(typeId);
// this.runOperation(userProps => {
// const prop = userProps.createProperty(newType);
// userProps.add(prop);
// this.setExpandedStateInStorage(prop, true);
// }, true);
// });
return menu;
}
private createExpressionTypeField(parent: HTMLDivElement, prop: sceneobjects.UserProperty) {
const type = prop.getType() as sceneobjects.ExpressionPropertyType;
this.createLabel(
parent, "Expression Type", "The type of the expression. Like <code>'ICustomType'</code> or <code>'() => void'</code>.");
const text = this.createText(parent);
text.value = type.getExpressionType();
text.addEventListener("change", e => {
this.runOperation(() => {
type.setExpressionType(text.value);
this.setExpandedStateInStorage(prop, true);
}, true);
});
}
private createOptionsField(parent: HTMLDivElement, prop: sceneobjects.UserProperty) {
const type = prop.getType() as sceneobjects.OptionPropertyType;
this.createLabel(
parent, "Options", "An array of possible string values, like in <code>['good', 'bad', 'ugly']</code>.");
const text = this.createTextArea(parent);
text.value = JSON.stringify(type.getOptions());
text.addEventListener("change", e => {
this.runOperation(() => {
const array = JSON.parse(text.value);
if (Array.isArray(array)) {
const array2 = array.filter(v => typeof v === "string" || typeof v === "number")
.map(v => v.toString());
type.setOptions(array2);
}
this.setExpandedStateInStorage(prop, true);
}, true);
});
}
private simpleField(
parent: HTMLDivElement, propInfo: any, infoProp: string, fieldLabel: string, fieldTooltip: string, updateCallback?: () => void) {
this.createLabel(parent, fieldLabel, fieldTooltip);
const text = this.createText(parent);
text.value = propInfo[infoProp];
text.addEventListener("change", e => {
this.runOperation(() => {
propInfo[infoProp] = text.value;
if (updateCallback) {
updateCallback();
}
}, false);
});
}
}
} | the_stack |
import Button from "antd/lib/button";
import { FormComponentProps } from "antd/lib/form";
import Form from "antd/lib/form/Form";
import Input from "antd/lib/input";
import Select from "antd/lib/select";
// @ts-ignore
import window from "global/window";
import { Link } from "react-router-dom";
// @ts-ignore
// @ts-ignore
import { t } from "onefx/lib/iso-i18n";
// @ts-ignore
import Helmet from "onefx/lib/react-helmet";
import React, { Component } from "react";
import { isValidBytes } from "../validator";
import Dropdown from "antd/lib/dropdown";
import Icon from "antd/lib/icon";
import Menu from "antd/lib/menu";
import { toRau } from "iotex-antenna/lib/account/utils";
import { Query, QueryResult } from "react-apollo";
import ConfirmContractModal from "../../common/confirm-contract-modal";
import { formItemLayout } from "../../common/form-item-layout";
import { numberFromCommaString } from "../../common/vertical-table";
import { COMPILE_SOLIDITY, GET_SOLC_VERSIONS } from "../../queries";
import { BroadcastFailure, BroadcastSuccess } from "../broadcast-status";
import { getAntenna } from "../get-antenna";
import { inputStyle } from "../wallet";
import {
AbiFormInputItem,
AmountFormInputItem,
FormItemLabel,
GasLimitFormInputItem,
GasPriceFormInputItem
} from "./cards";
import { ContractLayout } from "./contract-layout";
const { TextArea } = Input;
const { Option } = Select;
export class Deploy extends Component<{ address: string }> {
public render(): JSX.Element {
return (
<ContractLayout title={t("wallet.deploy.title")} icon={"upload"}>
<DeployForm address={this.props.address} />
</ContractLayout>
);
}
}
interface DeployProps extends FormComponentProps {
address?: string;
updateWalletInfo?: any;
}
interface SolcVersion {
name: string;
version: string;
type: string;
}
interface State {
solidityReleaseVersion: string | undefined;
message: string;
sending: boolean;
generatingByte: boolean;
deploying: boolean;
hasErrors: boolean;
rawTransaction: any;
showConfirmation: boolean;
broadcast: {
success: boolean;
} | null;
txHash: string;
constructorArgs: Array<{ name: string; type: string }>;
}
class DeployFormInner extends Component<DeployProps, State> {
public state: State = {
solidityReleaseVersion: undefined,
message: "",
sending: false,
generatingByte: false,
deploying: false,
hasErrors: false,
rawTransaction: null,
showConfirmation: false,
broadcast: null,
txHash: "",
constructorArgs: []
};
public handleGenerateAbiAndByteCode(contract: any): void {
const {
form: { setFieldsValue }
} = this.props;
setFieldsValue({
byteCode: contract.bytecode,
abi: contract.abi
});
}
public renderConfirmation = () => {
const { form, address } = this.props;
const { showConfirmation } = this.state;
const {
byteCode,
gasLimit,
gasPrice,
amount: commaAmount
} = form.getFieldsValue();
const amount = numberFromCommaString(commaAmount);
const dataSource = {
address: address,
data: byteCode,
amount: `${Number(amount).toLocaleString()} IOTX`,
price: toRau(gasPrice, "Qev"),
limit: gasLimit
};
return (
<ConfirmContractModal
dataSource={dataSource}
confirmContractOk={this.sendContract}
showModal={showConfirmation}
/>
);
};
public sendContract = async (shouldContinue: boolean) => {
const { form, address } = this.props;
const antenna = getAntenna();
if (!shouldContinue) {
return this.setState({
showConfirmation: false
});
}
form.validateFields(async (err, value) => {
if (err) {
return;
}
const { constructorArgs } = this.state;
const { byteCode, gasLimit, gasPrice, abi } = value;
const amount = numberFromCommaString(value.amount);
const trimmed0xHex = String(byteCode).replace(/^0x/, "");
const args = constructorArgs.map(arg => value[`ctor${arg.name}`]);
const price = gasPrice ? toRau(gasPrice, "Qev") : undefined;
window.console.log(
`antenna.iotx.deployContract(${JSON.stringify({
from: String(address),
amount: toRau(amount, "Iotx"),
data: Buffer.from(trimmed0xHex, "hex"),
gasPrice: price,
gasLimit: gasLimit || undefined
})}${args.length ? ["", ...args].join(",") : ""})`
);
const txHash = await antenna.iotx.deployContract(
{
abi: abi,
from: String(address),
amount: toRau(amount, "Iotx"),
data: Buffer.from(trimmed0xHex, "hex"),
gasPrice: price,
gasLimit: gasLimit || undefined
},
...args
);
this.setState({
sending: false,
broadcast: {
success: Boolean(txHash)
},
txHash
});
});
};
private readonly onClickSubmit = () => {
this.props.form.validateFields(err => {
if (err) {
return;
}
this.setState({ showConfirmation: true });
});
};
private readonly deployNewContract: JSX.Element = (
<Button>
<Link to="/wallet/smart-contract">{t("wallet.transfer.startOver")}</Link>
</Button>
);
private renderBroadcast(): JSX.Element | null {
const { txHash, broadcast } = this.state;
if (!broadcast) {
return null;
}
if (broadcast.success) {
return (
<BroadcastSuccess txHash={txHash} action={this.deployNewContract} />
);
}
return (
<BroadcastFailure
suggestedMessage={t("wallet.transfer.broadcast.fail", {
token: t("account.testnet.token")
})}
errorMessage={""}
action={this.deployNewContract}
/>
);
}
public renderContractMenu(
contracts: Array<{ name: string; abi: string; bytecode: string }>
): JSX.Element {
const contractMenu = (
<Menu>
{contracts.map(contract => (
<Menu.Item
key={`contract-${contract.name}`}
onClick={() => this.handleGenerateAbiAndByteCode(contract)}
>
{`Contract ${contract.name.substr(1)}`}
</Menu.Item>
))}
</Menu>
);
return (
<Dropdown overlay={contractMenu}>
{/*
// @ts-ignore */}
<Button
type="primary"
style={{
fontSize: "0.8em",
padding: "0 5px",
marginBottom: "32px"
}}
>
{t("wallet.deploy.generateAbiAndByteCode")} <Icon type="down" />
</Button>
</Dropdown>
);
}
public renderGenerateAbiButton(): JSX.Element {
const { setFields, getFieldsValue, getFieldError } = this.props.form;
const source = getFieldsValue().solidity;
const version = this.state.solidityReleaseVersion;
if (!source || !version) {
return (
<Button
disabled={true}
style={{ fontSize: "0.8em", padding: "0 5px", marginBottom: "32px" }}
>
{t("wallet.deploy.generateAbiAndByteCode")}
</Button>
);
}
return (
<Query query={COMPILE_SOLIDITY} variables={{ source, version }}>
{({ data, loading, error }: QueryResult) => {
if (loading) {
return (
<Button
loading={true}
disabled={true}
style={{
fontSize: "0.8em",
padding: "0 15px",
marginBottom: "32px"
}}
>
{t("wallet.contract.loadindSolc")}
</Button>
);
}
const returnGetFieldError = getFieldError("solidity");
if (error && (!returnGetFieldError || !returnGetFieldError.length)) {
setFields({
solidity: {
value: source,
errors: [error]
}
});
}
if (!error && returnGetFieldError && returnGetFieldError.length) {
setFields({
solidity: {
value: source,
errors: error ? [error] : []
}
});
}
if (
error ||
!data ||
!data.compileSolidity ||
data.compileSolidity.length === 0
) {
return (
<Button
disabled={true}
style={{
fontSize: "0.8em",
padding: "0 5px",
marginBottom: "32px"
}}
>
{t("wallet.deploy.generateAbiAndByteCode")}
</Button>
);
}
if (data.compileSolidity.length === 1) {
return (
// @ts-ignore
<Button
type="primary"
style={{
fontSize: "0.8em",
padding: "0 5px",
marginBottom: "32px"
}}
onClick={() =>
this.handleGenerateAbiAndByteCode(data.compileSolidity[0])
}
>
{t("wallet.deploy.generateAbiAndByteCode")}
</Button>
);
}
return this.renderContractMenu(data.compileSolidity);
}}
</Query>
);
}
private validateTimeoutID: NodeJS.Timeout;
public onABIChange = () => {
const { form } = this.props;
clearTimeout(this.validateTimeoutID);
this.validateTimeoutID = setTimeout(() => {
form.validateFields(["abi"], (error, { abi }) => {
this.setState({ constructorArgs: [] });
if (error) {
return;
}
const jsonABI = JSON.parse(abi);
const ctor = jsonABI.find(
(a: { type: string }) => a.type === "constructor"
);
if (!ctor) {
return;
}
const { inputs } = ctor;
this.setState({ constructorArgs: [...inputs] });
});
}, 250);
};
public renderConstructorArgsForm(): JSX.Element | null {
const { constructorArgs } = this.state;
if (!constructorArgs.length) {
return null;
}
const { form } = this.props;
const { getFieldDecorator } = form;
return (
<>
<h3 style={{ marginBottom: 30 }}>
{t("wallet.contract.executeParameter")}
</h3>
{constructorArgs.map((arg, key) => {
const { name, type } = arg;
return (
<Form.Item
{...formItemLayout}
label={<FormItemLabel>{name}</FormItemLabel>}
key={key}
>
{getFieldDecorator(`ctor${name}`, {
rules: [{ required: true, message: t("wallet.error.required") }]
})(<Input className="form-input" addonAfter={type} />)}
</Form.Item>
);
})}
</>
);
}
public updateInputVersion = (version: string) => {
this.setState({ solidityReleaseVersion: version });
};
public renderVersionInput(): JSX.Element | null {
const { form } = this.props;
const { getFieldDecorator } = form;
return (
<Form.Item
{...formItemLayout}
label={<FormItemLabel>{t("wallet.input.solVersion")}</FormItemLabel>}
>
<Query query={GET_SOLC_VERSIONS}>
{({ data, loading }: QueryResult) => {
if (loading) {
return (
<div style={{ textAlign: "center" }}>
<Icon type="loading" spin={true} />
</div>
);
}
if (
data &&
data.getSolcVersions &&
data.getSolcVersions.length > 0
) {
return getFieldDecorator("solVersion")(
<Select
showSearch={true}
placeholder={t("wallet.placeholder.compile")}
onChange={(value: string) => {
this.updateInputVersion(value);
}}
>
{data.getSolcVersions.map((solcVersion: SolcVersion) => {
return (
<Option
value={solcVersion.version}
key={solcVersion.name}
>
{`${solcVersion.name}`}
</Option>
);
})}
</Select>
);
}
return null;
}}
</Query>
</Form.Item>
);
}
public render(): JSX.Element | null {
const { broadcast } = this.state;
if (broadcast) {
return this.renderBroadcast();
}
const { form } = this.props;
const { getFieldDecorator } = form;
return (
<Form layout={"vertical"}>
{this.renderVersionInput()}
<Form.Item
{...formItemLayout}
label={<FormItemLabel>{t("wallet.input.solidity")}</FormItemLabel>}
>
{getFieldDecorator("solidity", {
initialValue: ""
})(
<TextArea
rows={4}
style={inputStyle}
placeholder={t("wallet.placeholder.solidity")}
/>
)}
</Form.Item>
{this.renderGenerateAbiButton()}
<AbiFormInputItem
form={form}
initialValue=""
onChange={this.onABIChange}
/>
<Form.Item
{...formItemLayout}
label={<FormItemLabel>{t("wallet.input.byteCode")}</FormItemLabel>}
>
{getFieldDecorator("byteCode", {
initialValue: "",
rules: [
{ required: true, message: t("wallet.error.required") },
{
validator: (_, value, callback) => {
const isValidErrorMessageKey = isValidBytes(value);
if (isValidErrorMessageKey) {
callback(t(isValidErrorMessageKey));
}
callback();
}
}
]
})(
<TextArea
rows={4}
style={inputStyle}
placeholder={t("wallet.placeholder.byteCode")}
/>
)}
</Form.Item>
<AmountFormInputItem form={form} initialValue={0} />
<GasPriceFormInputItem form={form} />
<GasLimitFormInputItem form={form} initialValue={1000000} />
{this.renderConstructorArgsForm()}
{/*
// @ts-ignore */}
<Button
type="primary"
onClick={() => this.onClickSubmit()}
style={{ marginBottom: "32px" }}
>
{t("wallet.deploy.signTransaction")}
</Button>
{this.renderConfirmation()}
</Form>
);
}
}
export const DeployForm = Form.create<DeployProps>({ name: "deploy-contract" })(
DeployFormInner
); | the_stack |
import { shapes, endpoints } from '@useoptic/graph-lib';
import { CQRSCommand, JsonType } from '@useoptic/optic-domain';
import { IOpticEngine, IOpticEngineIdGenerationStrategy } from './types';
export function buildEndpointsGraph(spec: any, opticEngine: any) {
const serializedGraph = JSON.parse(
opticEngine.get_endpoints_projection(spec)
);
const { nodes, edges, nodeIndexToId } = serializedGraph;
const indexer = new endpoints.GraphIndexer();
function remapId(arrayIndex: number) {
const fallbackId = arrayIndex.toString();
const id = nodeIndexToId[fallbackId];
if (id !== undefined) {
return id;
}
return fallbackId;
}
nodes.forEach((node: endpoints.Node, index: number) => {
const id = remapId(index);
indexer.addNode({
...node,
id,
});
});
edges.forEach((e: [number, number, any]) => {
const [sourceIndex, targetIndex, edge] = e;
indexer.addEdge(edge, remapId(sourceIndex), remapId(targetIndex));
});
const queries = new endpoints.GraphQueries(indexer);
return queries;
}
export function buildShapesGraph(spec: any, opticEngine: any) {
const serializedGraph = JSON.parse(opticEngine.get_shapes_projection(spec));
const { nodes, edges, nodeIndexToId } = serializedGraph;
// console.log('nodes', nodes);
const indexer = new shapes.GraphIndexer();
function remapId(arrayIndex: number) {
const fallbackId = arrayIndex.toString();
const id = nodeIndexToId[fallbackId];
if (id !== undefined) {
return id;
}
return fallbackId;
}
nodes.forEach((node: shapes.Node, index: number) => {
const id = remapId(index);
indexer.addNode({
...node,
id,
});
});
edges.forEach((e: [number, number, any]) => {
const [sourceIndex, targetIndex, edge] = e;
indexer.addEdge(edge, remapId(sourceIndex), remapId(targetIndex));
});
const queries = new shapes.GraphQueries(indexer);
return queries;
}
export type EndpointChange = {
change: {
category: string;
};
pathId: string;
path: string;
method: string;
};
export type EndpointChanges = {
data: {
endpoints: EndpointChange[];
};
};
export function buildEndpointChanges(
endpointQueries: endpoints.GraphQueries,
shapeQueries: shapes.GraphQueries,
sinceBatchCommitId?: string
): EndpointChanges {
const deltaBatchCommits = getDeltaBatchCommitsForEndpoints(
endpointQueries,
// In this case specifically, we want _all_ endpoint changes
sinceBatchCommitId || ALL_BATCH_COMMITS
);
const changes = new Changes();
for (const [_, batchCommit] of deltaBatchCommits) {
for (const { edgeType, nodes } of [
{ edgeType: 'created', nodes: batchCommit.createdInEdgeNodes().results },
{ edgeType: 'updated', nodes: batchCommit.updatedInEdgeNodes().results },
{ edgeType: 'removed', nodes: batchCommit.removedInEdgeNodes().results },
]) {
for (const node of nodes) {
if (
node instanceof endpoints.RequestNodeWrapper ||
node instanceof endpoints.ResponseNodeWrapper ||
node instanceof endpoints.QueryParametersNodeWrapper
) {
const endpoint = node.endpoint();
if (endpoint) {
let changeType: ChangeCategory = 'updated';
if (
node instanceof endpoints.RequestNodeWrapper &&
edgeType === 'created'
) {
changeType = 'added';
} else if (
node instanceof endpoints.RequestNodeWrapper &&
edgeType === 'removed'
) {
changeType = 'removed';
}
changes.captureChange(changeType, endpoint);
}
}
}
}
}
// Gather batch commit neighbors
const batchCommitNeighborIds = new Map();
[...deltaBatchCommits.values()].forEach((batchCommit: any) => {
const batchCommitId = batchCommit.result.id;
// TODO: create query for neighbors of all types
shapeQueries
.listIncomingNeighborsByType(batchCommitId, shapes.NodeType.Shape)
.results.forEach((shape: any) => {
batchCommitNeighborIds.set(shape.result.id, batchCommitId);
});
shapeQueries
.listIncomingNeighborsByType(batchCommitId, shapes.NodeType.Field)
.results.forEach((field: any) => {
batchCommitNeighborIds.set(field.result.id, batchCommitId);
});
});
// Both body nodes and query parameter nodes have rootShapeIds
const rootShapesWithEndpoint: {
rootShapeId: string;
endpoint: endpoints.EndpointNodeWrapper;
}[] = [];
for (const bodyNode of endpointQueries.listNodesByType(
endpoints.NodeType.Body
).results) {
const rootShapeId = bodyNode.value.rootShapeId;
const endpoint =
bodyNode.response()?.endpoint() || bodyNode.request()?.endpoint();
if (endpoint) {
rootShapesWithEndpoint.push({
rootShapeId,
endpoint,
});
}
}
for (const queryParamaterNode of endpointQueries.listNodesByType(
endpoints.NodeType.QueryParameters
).results) {
const rootShapeId = queryParamaterNode.value.rootShapeId;
const endpoint = queryParamaterNode.endpoint();
if (endpoint && rootShapeId) {
rootShapesWithEndpoint.push({
rootShapeId,
endpoint,
});
}
}
const filteredRootShapesWithEndpoint = rootShapesWithEndpoint.filter(
({ rootShapeId }) => {
if (batchCommitNeighborIds.has(rootShapeId)) {
return true;
}
// TODO this does not handle array children and polymorphic type changes
for (const descendant of shapeQueries.descendantsIterator(rootShapeId)) {
if (batchCommitNeighborIds.has(descendant.id)) {
return true;
}
}
return false;
}
);
filteredRootShapesWithEndpoint.forEach(({ endpoint }) => {
changes.captureChange('updated', endpoint);
});
return changes.toEndpointChanges();
}
type ChangeCategory = 'added' | 'updated' | 'removed';
class Changes {
public changes: Map<string, EndpointChange>;
constructor() {
this.changes = new Map();
}
captureChange(
category: ChangeCategory,
endpoint: endpoints.EndpointNodeWrapper
): boolean {
if (this.changes.has(endpoint.value.id)) return false;
this.changes.set(endpoint.value.id, {
change: { category },
pathId: endpoint.path().value.pathId,
path: endpoint.path().absolutePathPatternWithParameterNames,
method: endpoint.value.httpMethod,
});
return true;
}
toEndpointChanges(): EndpointChanges {
return {
data: {
endpoints: Array.from(this.changes.values()),
},
};
}
}
export function getEndpointGraphNodeChange(
endpointQueries: endpoints.GraphQueries,
nodeId: string,
sinceBatchCommitId?: string
): ChangeResult {
const results = {
added: false,
changed: false,
removed: false,
};
const deltaBatchCommits = getDeltaBatchCommitsForEndpoints(
endpointQueries,
sinceBatchCommitId
);
for (const batchCommitId of deltaBatchCommits.keys()) {
for (const node of endpointQueries.listOutgoingNeighborsByEdgeType(
nodeId,
endpoints.EdgeType.CreatedIn
).results) {
if (node.result.id === batchCommitId) return { ...results, added: true };
}
for (const node of endpointQueries.listOutgoingNeighborsByEdgeType(
nodeId,
endpoints.EdgeType.UpdatedIn
).results) {
if (node.result.id === batchCommitId)
return { ...results, changed: true };
}
for (const node of endpointQueries.listOutgoingNeighborsByEdgeType(
nodeId,
endpoints.EdgeType.RemovedIn
).results) {
if (node.result.id === batchCommitId)
return { ...results, removed: true };
}
}
return results;
}
export function getFieldChanges(
shapeQueries: shapes.GraphQueries,
fieldId: string,
shapeId: string,
sinceBatchCommitId?: string
): ChangeResult {
const results = {
added: false,
changed: false,
removed: false,
};
const deltaBatchCommits = getDeltaBatchCommitsForShapes(
shapeQueries,
sinceBatchCommitId
);
for (const batchCommitId of deltaBatchCommits.keys()) {
for (const node of shapeQueries.listOutgoingNeighborsByEdgeType(
fieldId,
shapes.EdgeType.CreatedIn
).results) {
if (node.result.id === batchCommitId) return { ...results, added: true };
}
}
// This will not deal with array item changes
for (const batchCommitId of deltaBatchCommits.keys()) {
for (const node of shapeQueries.listOutgoingNeighborsByEdgeType(
fieldId,
shapes.EdgeType.UpdatedIn
).results) {
if (node.result.id === batchCommitId)
return { ...results, changed: true };
}
}
// If a field is an array, there may be changes related to the shape but not
// the field itself.
return checkForArrayChanges(
shapeQueries,
deltaBatchCommits,
results,
shapeId
);
}
export function getArrayChanges(
shapeQueries: shapes.GraphQueries,
shapeId: string,
sinceBatchCommitId?: string
): ChangeResult {
const results = {
added: false,
changed: false,
removed: false,
};
const deltaBatchCommits = getDeltaBatchCommitsForShapes(
shapeQueries,
sinceBatchCommitId
);
return checkForArrayChanges(
shapeQueries,
deltaBatchCommits,
results,
shapeId
);
}
function checkForArrayChanges(
shapeQueries: shapes.GraphQueries,
deltaBatchCommits: any,
results: ChangeResult,
shapeId: string
): ChangeResult {
for (const batchCommitId of deltaBatchCommits.keys()) {
for (const node of shapeQueries.listOutgoingNeighborsByEdgeType(
shapeId,
shapes.EdgeType.CreatedIn
).results) {
if (node.result.id === batchCommitId) return { ...results, added: true };
}
}
// This will not deal with array item changes
for (const batchCommitId of deltaBatchCommits.keys()) {
for (const node of shapeQueries.listOutgoingNeighborsByEdgeType(
shapeId,
shapes.EdgeType.UpdatedIn
).results) {
if (node.result.id === batchCommitId)
return { ...results, changed: true };
}
}
return results;
}
type ChangeResult = {
added: boolean;
changed: boolean;
removed: boolean;
};
const ALL_BATCH_COMMITS = 'ALL_BATCH_COMMITS';
function getDeltaBatchCommitsForEndpoints(
endpointQueries: endpoints.GraphQueries,
sinceBatchCommitId?: string
): Map<string, endpoints.BatchCommitNodeWrapper> {
const deltaBatchCommits: Map<
string,
endpoints.BatchCommitNodeWrapper
> = new Map();
if (!sinceBatchCommitId) {
return deltaBatchCommits;
}
let sortedBatchCommits = endpointQueries
.listNodesByType(endpoints.NodeType.BatchCommit)
.results.sort((a: any, b: any) => {
return a.result.data.createdAt < b.result.data.createdAt ? 1 : -1;
});
const sinceBatchCommit: any = endpointQueries.findNodeById(
sinceBatchCommitId
)!;
sortedBatchCommits
.filter(
(batchCommit: any) =>
sinceBatchCommitId === ALL_BATCH_COMMITS ||
batchCommit.result.data.createdAt >
sinceBatchCommit!.result.data.createdAt
)
.forEach((batchCommit: any) => {
deltaBatchCommits.set(batchCommit.result.id, batchCommit);
});
return deltaBatchCommits;
}
function getDeltaBatchCommitsForShapes(
shapeQueries: shapes.GraphQueries,
sinceBatchCommitId?: string
): Map<string, shapes.BatchCommitNodeWrapper> {
const deltaBatchCommits: Map<
string,
shapes.BatchCommitNodeWrapper
> = new Map();
if (!sinceBatchCommitId) {
return deltaBatchCommits;
}
let sortedBatchCommits = shapeQueries
.listNodesByType(shapes.NodeType.BatchCommit)
.results.sort((a: any, b: any) => {
return a.result.data.createdAt < b.result.data.createdAt ? 1 : -1;
});
const sinceBatchCommit: any = shapeQueries.findNodeById(sinceBatchCommitId)!;
sortedBatchCommits
.filter(
(batchCommit: any) =>
sinceBatchCommitId === ALL_BATCH_COMMITS ||
batchCommit.result.data.createdAt >
sinceBatchCommit!.result.data.createdAt
)
.forEach((batchCommit: any) => {
deltaBatchCommits.set(batchCommit.result.id, batchCommit);
});
return deltaBatchCommits;
}
export type ContributionsProjection = Record<string, Record<string, string>>;
export function getContributionsProjection(
spec: any,
opticEngine: any
): ContributionsProjection {
return JSON.parse(opticEngine.get_contributions_projection(spec));
}
export class CommandGenerator {
constructor(private spec: any, private opticEngine: IOpticEngine) {}
public endpoint = {
remove: (pathId: string, method: string): CQRSCommand[] => {
const specEndpointDeleteCommands = this.opticEngine.spec_endpoint_delete_commands(
this.spec,
pathId,
method
);
return JSON.parse(specEndpointDeleteCommands).commands;
},
};
public field = {
remove: (fieldId: string): CQRSCommand[] => {
const fieldRemovalCommands = this.opticEngine.spec_field_remove_commands(
this.spec,
fieldId
);
return JSON.parse(fieldRemovalCommands);
},
edit: (fieldId: string, requestedTypes: JsonType[]): CQRSCommand[] => {
const fieldEditCommands = this.opticEngine.spec_field_edit_commands(
this.spec,
fieldId,
requestedTypes,
IOpticEngineIdGenerationStrategy.UNIQUE
);
return JSON.parse(fieldEditCommands);
},
};
} | the_stack |
import { Injectable } from '@angular/core';
import { toFormatDateTime } from '@angular-ru/cdk/date';
import { PlainTableComposerService } from '@angular-ru/cdk/table-utils';
import { Any, EmptyValue, Nullable, PlainObject } from '@angular-ru/cdk/typings';
import { downloadFile, isNotNil } from '@angular-ru/cdk/utils';
import { WebWorkerThreadService } from '@angular-ru/cdk/webworker';
import { ColumnParameters } from './domain/column-parameters';
import { ColumnWidth } from './domain/column-width';
import { ExcelWorkbook } from './domain/excel-workbook';
import { ExcelWorksheet } from './domain/excel-worksheet';
import { PreparedExcelWorkbook, WidthOfSymbols } from './domain/prepared-excel-workbook';
import { PreparedExcelWorksheet } from './domain/prepared-excel-worksheet';
import widthOfSymbolsMap from './domain/width-of-symbols-map.json';
interface StyleSizes {
fontWidth: number;
fontSize: number;
minColumnWidth: number;
rowHeight: number;
}
const enum StyleType {
HEAD = 'HeadCellStyle',
BODY = 'BodyCellStyle',
BIG_DATA = 'CellBigDataStyle'
}
@Injectable()
export class ExcelBuilderService {
constructor(public plainTableComposer: PlainTableComposerService, public webWorker: WebWorkerThreadService) {}
private static downloadWorkbook(blob: Blob, workbookName: string): void {
downloadFile({ blob, name: `${workbookName}.${toFormatDateTime()}`, extension: 'xls' });
}
// eslint-disable-next-line max-lines-per-function
public async exportExcelByWorkbook<T>(workbook: ExcelWorkbook<T>): Promise<void> {
const preparedWorkbook: PreparedExcelWorkbook<T> = await this.prepareWorkbook(workbook);
this.webWorker
// eslint-disable-next-line max-lines-per-function,sonarjs/cognitive-complexity
.run((input: PreparedExcelWorkbook<T>): Blob => {
function isEmptyValue(value: Any): value is EmptyValue {
const val: Any = typeof value === 'string' ? value.trim() : value;
return [undefined, null, NaN, '', Infinity].includes(val);
}
class ExcelBuilder {
private static commonBorderStyles: string = `
<Borders>
<Border ss:Position="Top" ss:Color="#000000" ss:LineStyle="Continuous" ss:Weight="1"/>
<Border ss:Position="Bottom" ss:Color="#000000" ss:LineStyle="Continuous" ss:Weight="1"/>
<Border ss:Position="Right" ss:Color="#000000" ss:LineStyle="Continuous" ss:Weight="1"/>
<Border ss:Position="Left" ss:Color="#000000" ss:LineStyle="Continuous" ss:Weight="1"/>
</Borders>`;
private static commonStyles: string = `
<Styles>
<Style ss:ID="${StyleType.HEAD}">
<Alignment ss:Horizontal="Center" ss:Vertical="Center" ss:WrapText="0" />
<Font ss:Bold="1" ss:FontName="Arial" />
${ExcelBuilder.commonBorderStyles}
</Style>
<Style ss:ID="${StyleType.BIG_DATA}">
<Alignment ss:Horizontal="Center" ss:Vertical="Center" ss:WrapText="1" />
<Font ss:Bold="0" ss:FontName="Arial" />
${ExcelBuilder.commonBorderStyles}
</Style>
<Style ss:ID="${StyleType.BODY}">
<Alignment ss:Horizontal="Center" ss:Vertical="Center" ss:WrapText="0" />
<Font ss:Bold="0" ss:FontName="Arial" />
${ExcelBuilder.commonBorderStyles}
</Style>
</Styles>`;
constructor(
private readonly sizes: StyleSizes,
private readonly flattenTranslatedKeys: PlainObject
) {}
private static generateWorkbook(xmlWorksheets: string): string {
return `
<?xml version="1.0"?>
<?mso-application progid="Excel.Sheet"?>
<Workbook
xmlns="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:excel"
xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:html="https://www.w3.org/TR/html40/"
>
${ExcelBuilder.commonStyles}
${xmlWorksheets}
</Workbook>`;
}
private static renderCell(value: Any, styleId: StyleType): string {
const type: Any = typeof value === 'number' ? 'Number' : 'String';
let cellValue: Any = isEmptyValue(value) ? '-' : value;
if (typeof cellValue === 'string') {
cellValue = cellValue.trim();
cellValue = cellValue.replace(/[<>]/g, '');
}
return `<Cell ss:StyleID="${styleId}"><Data ss:Type="${type}">${cellValue}</Data></Cell>`;
}
private static isFilled(value: Nullable<string>): value is string {
return typeof value === 'string' && value.length > 0;
}
public buildWorkbook(worksheets: PreparedExcelWorksheet<T>[]): string {
const xmlWorksheets: string = this.generateWorksheets(worksheets);
return ExcelBuilder.generateWorkbook(xmlWorksheets);
}
private generateWorksheets(worksheets: PreparedExcelWorksheet<T>[]): string {
const xmlSheets: string[] = worksheets.map((worksheet: PreparedExcelWorksheet<T>): string =>
this.generateWorksheet(worksheet)
);
return xmlSheets.join('');
}
private generateWorksheet(worksheet: PreparedExcelWorksheet<T>): string {
const { minColumnWidth, rowHeight }: StyleSizes = this.sizes;
const xmlColumns: string = this.generateColumnsDescriptor(worksheet);
const xmlBodyRows: string = this.generateBodyRows(worksheet.flatEntries);
return `
<Worksheet ss:Name="${worksheet.worksheetName}">
<Table ss:DefaultColumnWidth="${minColumnWidth}" ss:DefaultRowHeight="${rowHeight}">
${xmlColumns}
${xmlBodyRows}
</Table>
</Worksheet>`;
}
private generateColumnsDescriptor(worksheet: PreparedExcelWorksheet<T>): string {
const keys: string[] = Object.keys(worksheet.flatEntries?.[0] ?? []);
let columnsDescriptor: string = '';
let columnCells: string = '';
keys.forEach((key: string): void => {
const title: string = this.getTranslatedTitle(key, worksheet.prefixKeyForTranslate);
const parameters: Nullable<ColumnParameters> = worksheet.columnParameters?.[key];
const entriesColumn: string[] = worksheet.flatEntries.map(
(entry: PlainObject): string => entry[key]?.toString() ?? ''
);
const widthSetting: Nullable<number | ColumnWidth> =
parameters?.width ?? worksheet.generalColumnParameters?.width;
const width: number = this.getWidthOfColumn(title, entriesColumn, widthSetting);
columnsDescriptor += `<Column ss:Width="${width}" />`;
columnCells += ExcelBuilder.renderCell(title, StyleType.HEAD);
});
return `
${columnsDescriptor}
<Row>${columnCells}</Row>`;
}
private getWidthOfColumn(
title: string,
entries: string[],
width: Nullable<number | ColumnWidth>
): number {
const { minColumnWidth }: StyleSizes = this.sizes;
if (width === ColumnWidth.MAX_WIDTH) {
return this.calcMaxWidthByEntries(entries, title);
} else if (typeof width === 'number') {
return width;
} else {
return minColumnWidth;
}
}
private calcMaxWidthByEntries(entries: string[], title: string): number {
const titleLength: number = this.getWidthOfString(title, 'bold');
const indentMeasuredInSymbols: number = 2;
const indent: number = this.sizes.fontWidth * indentMeasuredInSymbols;
const maxLength: number = entries.reduce((length: number, entry: string): number => {
const currentLength: number = this.getWidthOfString(entry, 'regular');
return Math.max(currentLength, length);
}, titleLength);
return Math.round(maxLength) + indent;
}
private getWidthOfString(string: string, fontWeight: keyof WidthOfSymbols): number {
let width: number = 0;
for (const symbol of string) {
width += input.widthOfSymbols[fontWeight][symbol] ?? this.sizes.fontWidth;
}
return width;
}
private getTranslatedTitle(key: string, translatePrefix?: Nullable<string>): string {
const translatePath: string = ExcelBuilder.isFilled(translatePrefix)
? `${translatePrefix}.${key}`
: key;
return this.flattenTranslatedKeys[translatePath] ?? key;
}
private generateBodyRows(entries: PlainObject[]): string {
const { rowHeight }: StyleSizes = this.sizes;
const xmlRows: string[] = entries.map((cell: PlainObject): string => {
const xmlCells: string = this.generateCells(cell);
return `<Row ss:Height="${rowHeight}">${xmlCells}</Row>`;
});
return xmlRows.join('');
}
private generateCells(flatCell: PlainObject): string {
const { fontWidth, minColumnWidth }: StyleSizes = this.sizes;
const keys: string[] = Object.keys(flatCell);
const xmlCells: string[] = keys.map((key: string): string => {
const value: string = flatCell[key];
const symbolCount: number = String(value).length;
const overflow: boolean = symbolCount * fontWidth >= minColumnWidth;
const localStyleId: StyleType = overflow ? StyleType.BIG_DATA : StyleType.BODY;
return ExcelBuilder.renderCell(value, localStyleId);
});
return xmlCells.join('');
}
}
const xmlBookTemplate: string = new ExcelBuilder(
{ fontWidth: 6, fontSize: 7, minColumnWidth: 150, rowHeight: 40 },
input.preparedTranslatedKeys
).buildWorkbook(input.worksheets);
const UTF8: string = '\ufeff';
return new Blob([UTF8, xmlBookTemplate], { type: 'application/vnd.ms-excel;charset=UTF-8' });
}, preparedWorkbook)
.then((blob: Blob): void => ExcelBuilderService.downloadWorkbook(blob, workbook.filename));
}
private async prepareWorkbook<T>(workbook: ExcelWorkbook<T>): Promise<PreparedExcelWorkbook<T>> {
const preparedWorksheets: PreparedExcelWorksheet<T>[] = await Promise.all(
workbook.worksheets.map(
async (worksheet: ExcelWorksheet<T>): Promise<PreparedExcelWorksheet<T>> =>
await this.prepareWorksheet(worksheet)
)
);
const preparedTranslatedKeys: PlainObject = workbook.translatedKeys
? await this.plainTableComposer.composeSingle<PlainObject>(workbook.translatedKeys)
: {};
return {
...workbook,
worksheets: preparedWorksheets,
preparedTranslatedKeys,
widthOfSymbols: widthOfSymbolsMap
};
}
private async prepareWorksheet<T>(worksheet: ExcelWorksheet<T>): Promise<PreparedExcelWorksheet<T>> {
let flatEntries: PlainObject[] = [];
if (isNotNil(worksheet.entries)) {
flatEntries = await this.plainTableComposer.compose(worksheet.entries, {
includeKeys: worksheet.keys,
excludeKeys: worksheet.excludeKeys
});
}
return { ...worksheet, flatEntries };
}
} | the_stack |
import {Bot, Context as BaseContext} from 'grammy'
import test from 'ava'
import {MenuLike, Submenu} from '../../source/menu-like'
import {MenuMiddleware} from '../../source/menu-middleware'
import {ButtonAction} from '../../source/action-hive'
// TODO: Ugly workaround. This library should know better...
type MyContext = BaseContext & {match: RegExpExecArray | null | undefined}
test('action is run without updating menu afterwards', async t => {
t.plan(3)
const action: ButtonAction<MyContext> = {
trigger: /^\/what$/,
doFunction: (context, path) => {
t.is(context.match![0], '/what')
t.is(context.match![1], undefined)
t.is(path, '/what')
return false
},
}
const menu: MenuLike<MyContext> = {
listSubmenus: () => new Set([]),
renderActionHandlers: () => new Set([action]),
renderBody: () => 'whatever',
renderKeyboard: () => [],
}
const mm = new MenuMiddleware('/', menu, {
sendMenu: async () => {
throw new Error('dont open the menu')
},
})
const bot = new Bot<MyContext>('123:ABC');
(bot as any).botInfo = {}
bot.use(async (ctx, next) => {
ctx.reply = () => {
throw new Error('Use sendMenu instead')
}
ctx.answerCallbackQuery = async () => {
t.fail()
return Promise.resolve(true)
}
return next()
})
bot.use(mm.middleware())
bot.use(() => {
t.fail()
})
await bot.handleUpdate({
update_id: 666,
callback_query: {
id: '666',
from: {} as any,
chat_instance: '666',
data: '/what',
},
})
})
test('action is run and updating menu afterwards with path', async t => {
t.plan(5)
const action: ButtonAction<MyContext> = {
trigger: /^\/what$/,
doFunction: (context, path) => {
t.is(context.match![0], '/what')
t.is(context.match![1], undefined)
t.is(path, '/what')
return '.'
},
}
const menu: MenuLike<MyContext> = {
listSubmenus: () => new Set([]),
renderActionHandlers: () => new Set([action]),
renderBody: () => 'whatever',
renderKeyboard: () => [],
}
const mm = new MenuMiddleware('/', menu, {
sendMenu: async (_menu, _context, path) => {
t.is(path, '/')
return Promise.resolve()
},
})
const bot = new Bot<MyContext>('123:ABC');
(bot as any).botInfo = {}
bot.use(async (ctx, next) => {
ctx.reply = () => {
throw new Error('Use sendMenu instead')
}
ctx.answerCallbackQuery = async () => {
t.pass()
return Promise.resolve(true)
}
return next()
})
bot.use(mm.middleware())
bot.use(() => {
t.fail()
})
await bot.handleUpdate({
update_id: 666,
callback_query: {
id: '666',
from: {} as any,
chat_instance: '666',
data: '/what',
},
})
})
test('action is run and updating menu afterwards with true', async t => {
t.plan(5)
const action: ButtonAction<MyContext> = {
trigger: /^\/what$/,
doFunction: (context, path) => {
t.is(context.match![0], '/what')
t.is(context.match![1], undefined)
t.is(path, '/what')
return true
},
}
const menu: MenuLike<MyContext> = {
listSubmenus: () => new Set([]),
renderActionHandlers: () => new Set([action]),
renderBody: () => 'whatever',
renderKeyboard: () => [],
}
const mm = new MenuMiddleware('/', menu, {
sendMenu: async (_menu, _context, path) => {
t.is(path, '/')
return Promise.resolve()
},
})
const bot = new Bot<MyContext>('123:ABC');
(bot as any).botInfo = {}
bot.use(async (ctx, next) => {
ctx.reply = () => {
throw new Error('Use sendMenu instead')
}
ctx.answerCallbackQuery = async () => {
t.pass()
return Promise.resolve(true)
}
return next()
})
bot.use(mm.middleware())
bot.use(() => {
t.fail()
})
await bot.handleUpdate({
update_id: 666,
callback_query: {
id: '666',
from: {} as any,
chat_instance: '666',
data: '/what',
},
})
})
test.skip('action returns non existing path afterwards throws Error', async t => {
t.plan(1)
const action: ButtonAction<MyContext> = {
trigger: /^custom\/what$/,
doFunction: () => '/foo/',
}
const menu: MenuLike<MyContext> = {
listSubmenus: () => new Set([]),
renderActionHandlers: () => new Set([action]),
renderBody: () => 'whatever',
renderKeyboard: () => [],
}
const mm = new MenuMiddleware('custom/', menu, {
sendMenu: async () => {
throw new Error('dont send main menu')
},
})
const bot = new Bot<MyContext>('123:ABC');
(bot as any).botInfo = {}
bot.use(async (ctx, next) => {
ctx.reply = () => {
throw new Error('Use sendMenu instead')
}
ctx.answerCallbackQuery = async () => {
t.fail()
return Promise.resolve(true)
}
return next()
})
bot.use(mm.middleware())
bot.use(() => {
t.fail()
})
// False positive
// eslint-disable-next-line promise/prefer-await-to-then
bot.catch(error => {
if (error instanceof Error) {
t.is(error.message, 'There is no menu "/foo/" which can be reached in this menu')
} else {
t.fail()
}
})
await bot.handleUpdate({
update_id: 666,
callback_query: {
id: '666',
from: {} as any,
chat_instance: '666',
data: 'custom/what',
},
})
})
test('not existing action updates menu', async t => {
t.plan(2)
const action: ButtonAction<MyContext> = {
trigger: /^\/what$/,
doFunction: () => {
throw new Error('not the correct action')
},
}
const menu: MenuLike<MyContext> = {
listSubmenus: () => new Set([]),
renderActionHandlers: () => new Set([action]),
renderBody: () => 'whatever',
renderKeyboard: () => [],
}
const mm = new MenuMiddleware('/', menu, {
sendMenu: async (_menu, _context, path) => {
t.is(path, '/')
return Promise.resolve()
},
})
const bot = new Bot<MyContext>('123:ABC');
(bot as any).botInfo = {}
bot.use(async (ctx, next) => {
ctx.reply = () => {
throw new Error('Use sendMenu instead')
}
ctx.answerCallbackQuery = async () => {
t.pass()
return Promise.resolve(true)
}
return next()
})
bot.use(mm.middleware())
bot.use(() => {
t.fail()
})
await bot.handleUpdate({
update_id: 666,
callback_query: {
id: '666',
from: {} as any,
chat_instance: '666',
data: '/where',
},
})
})
test('action in submenu is run', async t => {
t.plan(3)
const action: ButtonAction<MyContext> = {
trigger: /^\/submenu\/what$/,
doFunction: (context, path) => {
t.is(context.match![0], '/submenu/what')
t.is(context.match![1], undefined)
t.is(path, '/submenu/what')
return false
},
}
const submenuMenu: MenuLike<MyContext> = {
listSubmenus: () => new Set(),
renderActionHandlers: () => new Set([action]),
renderBody: () => 'submenu',
renderKeyboard: () => [],
}
const submenu: Submenu<MyContext> = {
action: /submenu\//,
hide: () => false,
menu: submenuMenu,
}
const menu: MenuLike<MyContext> = {
listSubmenus: () => new Set([submenu]),
renderActionHandlers: () => new Set(),
renderBody: () => 'whatever',
renderKeyboard: () => [],
}
const mm = new MenuMiddleware('/', menu, {
sendMenu: async () => {
throw new Error('dont open the menu')
},
})
const bot = new Bot<MyContext>('123:ABC');
(bot as any).botInfo = {}
bot.use(async (ctx, next) => {
ctx.reply = () => {
throw new Error('Use sendMenu instead')
}
ctx.answerCallbackQuery = async () => {
t.fail()
return Promise.resolve(true)
}
return next()
})
bot.use(mm.middleware())
bot.use(() => {
t.fail()
})
await bot.handleUpdate({
update_id: 666,
callback_query: {
id: '666',
from: {} as any,
chat_instance: '666',
data: '/submenu/what',
},
})
})
test('not existing action in submenu updates submenu', async t => {
t.plan(2)
const action: ButtonAction<MyContext> = {
trigger: /^\/submenu\/what$/,
doFunction: () => {
throw new Error('not the correct action')
},
}
const submenuMenu: MenuLike<MyContext> = {
listSubmenus: () => new Set(),
renderActionHandlers: () => new Set([action]),
renderBody: () => 'submenu',
renderKeyboard: () => [],
}
const submenu: Submenu<MyContext> = {
action: /submenu\//,
hide: () => false,
menu: submenuMenu,
}
const menu: MenuLike<MyContext> = {
listSubmenus: () => new Set([submenu]),
renderActionHandlers: () => new Set(),
renderBody: () => 'whatever',
renderKeyboard: () => [],
}
const mm = new MenuMiddleware('/', menu, {
sendMenu: async (_menu, _context, path) => {
t.is(path, '/submenu/')
return Promise.resolve()
},
})
const bot = new Bot<MyContext>('123:ABC');
(bot as any).botInfo = {}
bot.use(async (ctx, next) => {
ctx.reply = () => {
throw new Error('Use sendMenu instead')
}
ctx.answerCallbackQuery = async () => {
t.pass()
return Promise.resolve(true)
}
return next()
})
bot.use(mm.middleware())
bot.use(() => {
t.fail()
})
await bot.handleUpdate({
update_id: 666,
callback_query: {
id: '666',
from: {} as any,
chat_instance: '666',
data: '/submenu/where',
},
})
})
test('action in hidden submenu updates main menu', async t => {
t.plan(2)
const action: ButtonAction<MyContext> = {
trigger: /^\/submenu\/what$/,
doFunction: () => {
throw new Error('submenu is hidden')
},
}
const submenuMenu: MenuLike<MyContext> = {
listSubmenus: () => new Set(),
renderActionHandlers: () => new Set([action]),
renderBody: () => 'submenu',
renderKeyboard: () => [],
}
const submenu: Submenu<MyContext> = {
action: /submenu\//,
hide: () => true,
menu: submenuMenu,
}
const menu: MenuLike<MyContext> = {
listSubmenus: () => new Set([submenu]),
renderActionHandlers: () => new Set(),
renderBody: () => 'whatever',
renderKeyboard: () => [],
}
const mm = new MenuMiddleware('/', menu, {
sendMenu: async (_menu, _context, path) => {
t.is(path, '/')
return Promise.resolve()
},
})
const bot = new Bot<MyContext>('123:ABC');
(bot as any).botInfo = {}
bot.use(async (ctx, next) => {
ctx.reply = () => {
throw new Error('Use sendMenu instead')
}
ctx.answerCallbackQuery = async () => {
t.pass()
return Promise.resolve(true)
}
return next()
})
bot.use(mm.middleware())
bot.use(() => {
t.fail()
})
await bot.handleUpdate({
update_id: 666,
callback_query: {
id: '666',
from: {} as any,
chat_instance: '666',
data: '/submenu/what',
},
})
})
test('action in non existing submenu updates main menu', async t => {
t.plan(2)
const action: ButtonAction<MyContext> = {
trigger: /^\/submenu\/what$/,
doFunction: () => {
throw new Error('submenu is hidden')
},
}
const submenuMenu: MenuLike<MyContext> = {
listSubmenus: () => new Set(),
renderActionHandlers: () => new Set([action]),
renderBody: () => 'submenu',
renderKeyboard: () => [],
}
const submenu: Submenu<MyContext> = {
action: /submenu\//,
hide: () => true,
menu: submenuMenu,
}
const menu: MenuLike<MyContext> = {
listSubmenus: () => new Set([submenu]),
renderActionHandlers: () => new Set(),
renderBody: () => 'whatever',
renderKeyboard: () => [],
}
const mm = new MenuMiddleware('/', menu, {
sendMenu: async (_menu, _context, path) => {
t.is(path, '/')
return Promise.resolve()
},
})
const bot = new Bot<MyContext>('123:ABC');
(bot as any).botInfo = {}
bot.use(async (ctx, next) => {
ctx.reply = () => {
throw new Error('Use sendMenu instead')
}
ctx.answerCallbackQuery = async () => {
t.pass()
return Promise.resolve(true)
}
return next()
})
bot.use(mm.middleware())
bot.use(() => {
t.fail()
})
await bot.handleUpdate({
update_id: 666,
callback_query: {
id: '666',
from: {} as any,
chat_instance: '666',
data: '/foo/bar',
},
})
})
test('action run took too long and updating menu afterwards tries to answerCallbackQuery and fails as being old but does not throw', async t => {
t.plan(2)
const action: ButtonAction<MyContext> = {
trigger: /^\/what$/,
doFunction: () => '.',
}
const menu: MenuLike<MyContext> = {
listSubmenus: () => new Set([]),
renderActionHandlers: () => new Set([action]),
renderBody: () => 'whatever',
renderKeyboard: () => [],
}
const mm = new MenuMiddleware('/', menu, {
sendMenu: async () => Promise.resolve(),
})
const bot = new Bot<MyContext>('123:ABC');
(bot as any).botInfo = {}
bot.use(async (ctx, next) => {
ctx.reply = () => {
throw new Error('Use sendMenu instead')
}
ctx.answerCallbackQuery = async () => {
t.pass()
throw new Error('Bad Request: query is too old and response timeout expired or query ID is invalid')
}
return next()
})
bot.use(mm.middleware())
bot.use(() => {
t.fail()
})
await t.notThrowsAsync(async () =>
bot.handleUpdate({
update_id: 666,
callback_query: {
id: '666',
from: {} as any,
chat_instance: '666',
data: '/what',
},
}),
)
})
test.skip('updating menu still throws unknown error from answerCallbackQuery', async t => {
t.plan(2)
const action: ButtonAction<MyContext> = {
trigger: /^\/what$/,
doFunction: () => '.',
}
const menu: MenuLike<MyContext> = {
listSubmenus: () => new Set([]),
renderActionHandlers: () => new Set([action]),
renderBody: () => 'whatever',
renderKeyboard: () => [],
}
const mm = new MenuMiddleware('/', menu, {
sendMenu: async () => Promise.resolve(),
})
const bot = new Bot<MyContext>('123:ABC');
(bot as any).botInfo = {}
bot.use(async (ctx, next) => {
ctx.reply = () => {
throw new Error('Use sendMenu instead')
}
ctx.answerCallbackQuery = async () => {
t.pass()
throw new Error('Whatever went wrong here for the test')
}
return next()
})
bot.use(mm.middleware())
bot.use(() => {
t.fail()
})
// False positive
// eslint-disable-next-line promise/prefer-await-to-then
bot.catch(error => {
if (error instanceof Error) {
t.is(error.message, 'Whatever went wrong here for the test')
} else {
t.fail('not an error?')
}
})
await bot.handleUpdate({
update_id: 666,
callback_query: {
id: '666',
from: {} as any,
chat_instance: '666',
data: '/what',
},
})
}) | the_stack |
import { mdiPlus, mdiResizeBottomRight } from '@mdi/js';
import {
computeCardSize,
computeRTL,
fireEvent,
HomeAssistant,
LovelaceCard,
LovelaceViewConfig,
} from 'custom-card-helpers';
import {
css,
CSSResult,
customElement,
html,
internalProperty,
LitElement,
property,
PropertyValues,
TemplateResult,
} from 'lit-element';
import 'lit-grid-layout';
import { classMap } from 'lit-html/directives/class-map';
import { v4 as uuidv4 } from 'uuid';
import { nextRender, replaceView } from './functions';
import './hui-grid-card-options';
import { HuiGridCardOptions } from './hui-grid-card-options';
const mediaQueryColumns = [2, 6, 9, 12];
interface LovelaceGridCard extends LovelaceCard, HuiGridCardOptions {
key: string;
grid?: {
key: string;
width: number;
height: number;
posX: number;
posY: number;
};
}
const RESIZE_HANDLE = document.createElement('div') as HTMLElement;
RESIZE_HANDLE.style.cssText = 'width: 100%; height: 100%; cursor: se-resize; fill: var(--primary-text-color)';
RESIZE_HANDLE.innerHTML = `
<svg
viewBox="0 0 24 24"
preserveAspectRatio="xMidYMid meet"
focusable="false"
>
<g><path d=${mdiResizeBottomRight}></path></g>
</svg>
`;
@customElement('grid-dnd')
export class GridView extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public lovelace?: any;
@property({ type: Number }) public index?: number;
@property({ attribute: false }) public cards: Array<LovelaceGridCard> = [];
@property({ attribute: false }) public badges: any[] = [];
@internalProperty() private _columns?: number;
@internalProperty() private _layout?: Array<{
width: number;
height: number;
posX: number;
posY: number;
key: string;
}>;
@internalProperty() public _cards: {
[key: string]: LovelaceCard | any;
} = {};
private _config?: LovelaceViewConfig;
private _layoutEdit?: Array<{
width: number;
height: number;
posX: number;
posY: number;
key: string;
}>;
private _createColumnsIteration = 0;
private _mqls?: MediaQueryList[];
public constructor() {
super();
this.addEventListener('iron-resize', (ev: Event) => ev.stopPropagation());
}
public setConfig(config: LovelaceViewConfig): void {
this._config = config;
}
protected render(): TemplateResult {
return html`
${this.lovelace.editMode
? html`
<div class="toolbar">
<mwc-button @click=${this._saveView} raised>Save Layout</mwc-button>
</div>
`
: ''}
<div id="badges" style=${this.badges.length > 0 ? 'display: block' : 'display: none'}>
${this.badges.map(
badge =>
html`
${badge}
`,
)}
</div>
<lit-grid-layout
rowHeight="40"
.containerPadding=${[8, 8]}
.margin=${[8, 8]}
.resizeHandle=${RESIZE_HANDLE}
.itemRenderer=${this._itemRenderer}
.layout=${this._layout}
.columns=${this._columns}
.dragHandle=${'.overlay'}
.dragDisabled=${!this.lovelace?.editMode}
.resizeDisabled=${!this.lovelace?.editMode}
@item-changed=${this._saveLayout}
></lit-grid-layout>
${this.lovelace?.editMode
? html`
<mwc-fab
class=${classMap({
rtl: computeRTL(this.hass!),
})}
.title=${this.hass!.localize('ui.panel.lovelace.editor.edit_card.add')}
@click=${this._addCard}
>
<ha-svg-icon slot="icon" .path=${mdiPlus}></ha-svg-icon>
</mwc-fab>
`
: ''}
`;
}
protected firstUpdated(): void {
this._updateColumns = this._updateColumns.bind(this);
this._mqls = [300, 600, 900, 1200].map(width => {
const mql = matchMedia(`(min-width: ${width}px)`);
mql.addEventListener('change', this._updateColumns);
return mql;
});
this._updateCardsWithID();
this._updateColumns();
}
protected updated(changedProperties: PropertyValues): void {
super.updated(changedProperties);
if (changedProperties.has('hass')) {
const oldHass = changedProperties.get('hass') as HomeAssistant;
if ((oldHass && this.hass!.dockedSidebar !== oldHass.dockedSidebar) || (!oldHass && this.hass)) {
this._updateColumns();
}
if (changedProperties.size === 1) {
return;
}
}
const oldLovelace = changedProperties.get('lovelace') as any | undefined;
if (
(changedProperties.has('lovelace') &&
(oldLovelace?.config !== this.lovelace?.config || oldLovelace?.editMode !== this.lovelace?.editMode)) ||
changedProperties.has('_columns')
) {
if (!this._layout?.length) {
this._createLayout();
return;
}
this._createCards();
}
if (changedProperties.has('lovelace') && this.lovelace.editMode && !oldLovelace.editMode) {
this._layoutEdit = this._layout;
}
if (changedProperties.has('lovelace') && !this.lovelace.editMode && oldLovelace.editMode) {
this._layout = (this._config as any).layout;
}
}
private _updateCardsWithID(): void {
if (!this._config) {
return;
}
if (this._config.cards!.filter(card => !card.layout?.key).length === 0) {
return;
}
const cards = this._config.cards!.map(card => {
if (card.layout?.key) {
return card;
}
card = { ...card, layout: { key: card.layout?.key || uuidv4() } };
return card;
});
const newConfig = { ...this._config, cards };
this.lovelace.saveConfig(replaceView(this.lovelace!.config, this.index!, newConfig));
}
private async _createLayout(): Promise<void> {
this._createColumnsIteration++;
const iteration = this._createColumnsIteration;
if (this._layout?.length) {
return;
}
const newLayout: Array<{
width: number;
height: number;
posX: number;
posY: number;
key: string;
minHeight: number;
}> = [];
let tillNextRender: Promise<unknown> | undefined;
let start: Date | undefined;
// Calculate the size of every card and determine in what column it should go
for (const [index, card] of this.cards.entries()) {
const cardConfig = this._config!.cards![index];
const currentLayout = (this._config as any).layout?.find(item => item.key === cardConfig.layout?.key);
if (currentLayout) {
newLayout.push(currentLayout);
continue;
}
console.log('not in current layout: ', cardConfig);
if (tillNextRender === undefined) {
// eslint-disable-next-line no-loop-func
tillNextRender = nextRender().then(() => {
tillNextRender = undefined;
start = undefined;
});
}
let waitProm: Promise<unknown> | undefined;
// We should work for max 16ms (60fps) before allowing a frame to render
if (start === undefined) {
// Save the time we start for this frame, no need to wait yet
start = new Date();
} else if (new Date().getTime() - start.getTime() > 16) {
// We are working too long, we will prevent a render, wait to allow for a render
waitProm = tillNextRender;
}
const cardSizeProm = computeCardSize(card);
// @ts-ignore
// eslint-disable-next-line no-await-in-loop
const [cardSize] = await Promise.all([cardSizeProm, waitProm]);
if (iteration !== this._createColumnsIteration) {
// An other create columns is started, abort this one
return;
}
const computedLayout = {
width: 3,
height: cardSize,
key: cardConfig.layout?.key,
};
newLayout.push({
...computedLayout,
...currentLayout,
});
}
this._layout = newLayout;
this._createCards();
}
private _createCards(): void {
const elements = {};
this.cards.forEach((card: LovelaceGridCard, index) => {
const cardLayout = this._layout![index];
if (!cardLayout) {
return;
}
card.editMode = this.lovelace?.editMode;
let element = card;
if (this.lovelace?.editMode) {
const wrapper = document.createElement('hui-grid-card-options') as LovelaceGridCard;
wrapper.hass = this.hass;
wrapper.lovelace = this.lovelace;
wrapper.path = [this.index!, index];
wrapper.appendChild(card);
element = wrapper;
}
elements[cardLayout.key] = element;
});
this._cards = elements;
}
private _saveLayout(ev: CustomEvent): void {
this._layoutEdit = ev.detail.layout;
}
private async _saveView(): Promise<void> {
const viewConf: any = {
...this._config,
layout: this._layoutEdit,
};
await this.lovelace?.saveConfig(replaceView(this.lovelace!.config, this.index!, viewConf));
}
private _itemRenderer = (key: string): TemplateResult => {
if (!this._cards) {
return html``;
}
return html`
${this._cards[key]}
`;
};
private _addCard(): void {
fireEvent(this, 'll-create-card' as any);
}
private _updateColumns(): void {
if (!this._mqls) {
return;
}
const matchColumns = this._mqls!.reduce((cols, mql) => cols + Number(mql.matches), 0);
// Do -1 column if the menu is docked and open
this._columns = Math.max(1, mediaQueryColumns[matchColumns - 1]);
}
static get styles(): CSSResult {
return css`
:host {
display: block;
box-sizing: border-box;
padding: 4px 4px env(safe-area-inset-bottom);
transform: translateZ(0);
position: relative;
color: var(--primary-text-color);
background: var(--lovelace-background, var(--primary-background-color));
}
lit-grid-layout {
--placeholder-background-color: var(--accent-color);
--resize-handle-size: 32px;
}
#badges {
margin: 8px 16px;
font-size: 85%;
text-align: center;
}
mwc-fab {
position: sticky;
float: right;
right: calc(16px + env(safe-area-inset-right));
bottom: calc(16px + env(safe-area-inset-bottom));
z-index: 5;
}
mwc-fab.rtl {
float: left;
right: auto;
left: calc(16px + env(safe-area-inset-left));
}
.toolbar {
background-color: var(--divider-color);
border-bottom-left-radius: var(--ha-card-border-radius, 4px);
border-bottom-right-radius: var(--ha-card-border-radius, 4px);
padding: 8px;
}
`;
}
}
declare global {
interface HTMLElementTagNameMap {
'grid-dnd': GridView;
}
} | the_stack |
import 'hammerjs';
import 'mousetrap';
import { DebugElement } from '@angular/core';
import { By } from '@angular/platform-browser';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { InternalButtonConfig, UpperButtonsComponent } from './upper-buttons.component';
import { Image } from '../../model/image.class';
import { ButtonConfig, ButtonEvent, ButtonsConfig, ButtonsStrategy, ButtonType } from '../../model/buttons-config.interface';
import { Size } from '../../model/size.interface';
import { KS_DEFAULT_BTN_CLOSE, KS_DEFAULT_BTN_DELETE, KS_DEFAULT_BTN_DOWNLOAD,
KS_DEFAULT_BTN_EXTURL, KS_DEFAULT_BTN_FULL_SCREEN, KS_DEFAULT_SIZE } from './upper-buttons-default';
import { Action } from '../../model/action.enum';
import { ConfigService } from '../../services/config.service';
import { SizeDirective } from '../../directives/size.directive';
let comp: UpperButtonsComponent;
let fixture: ComponentFixture<UpperButtonsComponent>;
const GALLERY_ID = 1;
// const BAD_IMAGE: Image = new Image(0, null);
const IMAGE_EXTURL: Image = new Image(0, {
img: '../../../../../apps/src/assets/images/gallery/img1.jpg',
description: 'Description 1',
extUrl: 'http://www.google.com'
});
const IMAGE_NO_EXTURL: Image = new Image(0, {
img: '../../../../../apps/src/assets/images/gallery/img1.jpg'
});
const NO_EXTURL_CASES: Image[] = [IMAGE_NO_EXTURL/*, BAD_IMAGE*/];
const CUSTOM_SIZE: Size = {height: '40px', width: '40px'};
const CUSTOM_SIZE_AUTO_HEIGHT: Size = {height: 'auto', width: '40px'};
const CUSTOM_SIZE_AUTO_WIDTH: Size = {height: '40px', width: 'auto'};
const UNKNOWN_STRATEGY = 6;
const UNKNOWN_BUTTON_TYPE = 99;
const CUSTOM_BTN: ButtonConfig = {
className: 'custom-image',
size: KS_DEFAULT_SIZE,
type: ButtonType.CUSTOM,
title: 'Custom title',
ariaLabel: 'Custom aria label'
};
const WRONG_TYPE_BTN: ButtonConfig = {
className: 'wrong-type-image',
size: KS_DEFAULT_SIZE,
type: UNKNOWN_BUTTON_TYPE,
title: 'Custom wrong-type title',
ariaLabel: 'Custom wrong-type aria label'
};
const CUSTOM_FA_BUTTONS: ButtonConfig[] = [
{
className: 'fa fa-plus white',
type: ButtonType.CUSTOM,
ariaLabel: 'custom plus aria label',
title: 'custom plus title',
fontSize: '20px'
},
{
className: 'fa fa-trash white',
type: ButtonType.DELETE,
ariaLabel: 'custom delete aria label',
title: 'custom delete title',
fontSize: '20px'
},
{
className: 'fa fa-close white',
type: ButtonType.CLOSE,
ariaLabel: 'custom close aria label',
title: 'custom close title',
fontSize: '20px'
},
{
className: 'fa fa-download white',
type: ButtonType.DOWNLOAD,
ariaLabel: 'custom download aria label',
title: 'custom download title',
fontSize: '20px'
},
{
className: 'fa fa-external-link white',
type: ButtonType.EXTURL,
ariaLabel: 'custom exturl aria label',
title: 'custom exturl title',
fontSize: '20px'
}];
const VISIBILITY_CASES: ButtonsConfig[] = [
{visible: false, strategy: ButtonsStrategy.DEFAULT},
{visible: false, strategy: ButtonsStrategy.SIMPLE},
{visible: false, strategy: ButtonsStrategy.ADVANCED},
{visible: false, strategy: ButtonsStrategy.FULL},
{visible: false, strategy: ButtonsStrategy.CUSTOM}
];
const DEFAULT_CASES: ButtonsConfig[] = [
{visible: true, strategy: ButtonsStrategy.DEFAULT},
{visible: true, strategy: ButtonsStrategy.SIMPLE},
{visible: true, strategy: ButtonsStrategy.ADVANCED},
{visible: true, strategy: ButtonsStrategy.FULL}
];
const CUSTOM_NO_BUTTONS_CASES: ButtonsConfig[] = [{visible: true, strategy: ButtonsStrategy.CUSTOM}];
// should be ignored by the component and consider ButtonStrategy
const IGNORE_CUSTOM_CASES: ButtonsConfig[] = [
{visible: true, strategy: ButtonsStrategy.DEFAULT, buttons: [CUSTOM_BTN]},
{visible: true, strategy: ButtonsStrategy.SIMPLE, buttons: [CUSTOM_BTN]},
{visible: true, strategy: ButtonsStrategy.ADVANCED, buttons: [CUSTOM_BTN]},
{visible: true, strategy: ButtonsStrategy.FULL, buttons: [CUSTOM_BTN]}
];
const UNKNOWN_CASES: ButtonsConfig[] = [
{visible: true, strategy: UNKNOWN_STRATEGY, buttons: [CUSTOM_BTN]},
{visible: true, strategy: UNKNOWN_STRATEGY}
];
const CUSTOM_CASES: ButtonsConfig[] = [
{visible: true, strategy: ButtonsStrategy.CUSTOM, buttons: [CUSTOM_BTN]},
{visible: true, strategy: ButtonsStrategy.CUSTOM, buttons: [CUSTOM_BTN, CUSTOM_BTN]},
{
visible: true,
strategy: ButtonsStrategy.CUSTOM,
buttons: [KS_DEFAULT_BTN_CLOSE, CUSTOM_BTN, CUSTOM_BTN, KS_DEFAULT_BTN_DOWNLOAD, KS_DEFAULT_BTN_DOWNLOAD]
},
{
visible: true,
strategy: ButtonsStrategy.CUSTOM,
buttons: [KS_DEFAULT_BTN_DOWNLOAD, KS_DEFAULT_BTN_CLOSE,
KS_DEFAULT_BTN_DELETE, KS_DEFAULT_BTN_EXTURL, KS_DEFAULT_BTN_CLOSE]
}
];
const CUSTOM_SIZES: ButtonsConfig[] = [
{
visible: true, strategy: ButtonsStrategy.CUSTOM, buttons: [
buildBtnWithCustomSize(ButtonType.DOWNLOAD, CUSTOM_SIZE), buildBtnWithCustomSize(ButtonType.CLOSE, CUSTOM_SIZE),
buildBtnWithCustomSize(ButtonType.CUSTOM, CUSTOM_SIZE), buildBtnWithCustomSize(ButtonType.DELETE, CUSTOM_SIZE)]
},
{
visible: true, strategy: ButtonsStrategy.CUSTOM, buttons: [
buildBtnWithCustomSize(ButtonType.DOWNLOAD, CUSTOM_SIZE_AUTO_HEIGHT), buildBtnWithCustomSize(ButtonType.CLOSE, CUSTOM_SIZE_AUTO_HEIGHT),
buildBtnWithCustomSize(ButtonType.CUSTOM, CUSTOM_SIZE_AUTO_HEIGHT), buildBtnWithCustomSize(ButtonType.DELETE, CUSTOM_SIZE_AUTO_HEIGHT)]
},
{
visible: true, strategy: ButtonsStrategy.CUSTOM, buttons: [
buildBtnWithCustomSize(ButtonType.DOWNLOAD, CUSTOM_SIZE_AUTO_WIDTH), buildBtnWithCustomSize(ButtonType.CLOSE, CUSTOM_SIZE_AUTO_WIDTH),
buildBtnWithCustomSize(ButtonType.CUSTOM, CUSTOM_SIZE_AUTO_WIDTH), buildBtnWithCustomSize(ButtonType.DELETE, CUSTOM_SIZE_AUTO_WIDTH)]
}
];
const CUSTOM_FA_CASE: ButtonsConfig = {visible: true, strategy: ButtonsStrategy.CUSTOM, buttons: CUSTOM_FA_BUTTONS};
const NOT_VALID_BTN_TYPE_CASES: ButtonsConfig[] = [
{visible: true, strategy: ButtonsStrategy.CUSTOM, buttons: [WRONG_TYPE_BTN]}
];
const EXTURL_BTN_NEW_TAB: ButtonConfig = Object.assign({}, KS_DEFAULT_BTN_EXTURL, {extUrlInNewTab: true});
const EXT_URL_IN_A_NEW_TAB_CASES: ButtonsConfig[] = [
{visible: true, strategy: ButtonsStrategy.CUSTOM, buttons: [EXTURL_BTN_NEW_TAB]},
{visible: true, strategy: ButtonsStrategy.CUSTOM, buttons: [CUSTOM_BTN, EXTURL_BTN_NEW_TAB]},
{
visible: true,
strategy: ButtonsStrategy.CUSTOM,
buttons: [KS_DEFAULT_BTN_CLOSE, EXTURL_BTN_NEW_TAB, CUSTOM_BTN, KS_DEFAULT_BTN_DOWNLOAD, KS_DEFAULT_BTN_DOWNLOAD]
},
{
visible: true,
strategy: ButtonsStrategy.CUSTOM,
buttons: [KS_DEFAULT_BTN_DOWNLOAD, KS_DEFAULT_BTN_CLOSE, KS_DEFAULT_BTN_DELETE, EXTURL_BTN_NEW_TAB]
}
];
function getButtonEvent(button: ButtonConfig): ButtonEvent {
return {
galleryId: GALLERY_ID,
button,
// upper-buttons.component always returns a null image to the main component, so I should test for a null
image: null,
action: Action.CLICK
};
}
function updateInputs(image: Image, configButtons: ButtonsConfig): void {
const configService = fixture.debugElement.injector.get(ConfigService);
configService.setConfig(GALLERY_ID, {buttonsConfig: configButtons});
comp.id = GALLERY_ID;
comp.currentImage = image;
comp.ngOnInit();
fixture.detectChanges();
}
function buildBtnWithCustomSize(btnType: ButtonType, size: Size): ButtonConfig {
switch (btnType) {
case ButtonType.CLOSE:
return Object.assign({}, KS_DEFAULT_BTN_CLOSE, {size});
case ButtonType.DOWNLOAD:
return Object.assign({}, KS_DEFAULT_BTN_DOWNLOAD, {size});
case ButtonType.EXTURL:
return Object.assign({}, KS_DEFAULT_BTN_EXTURL, {size});
case ButtonType.DELETE:
return Object.assign({}, KS_DEFAULT_BTN_DELETE, {size});
case ButtonType.FULLSCREEN:
return Object.assign({}, KS_DEFAULT_BTN_FULL_SCREEN, {size});
case ButtonType.CUSTOM:
return Object.assign({}, CUSTOM_BTN, {size});
default:
throw new Error('this test should run only with known button types');
}
}
function testCurrentHtmlBtn(btnDebugElement: DebugElement, btnIndex: number, size: Size, withFontAwesome: boolean = false): void {
if (!comp.buttons || !comp.buttons[btnIndex]) {
throw new Error('There is something wrong in this test, because currentButton must be defined!');
}
const currentButton: InternalButtonConfig = comp.buttons[btnIndex] as InternalButtonConfig;
expect(btnDebugElement.name).toBe('a');
expect(btnDebugElement.attributes.class).toBe('upper-button');
expect(btnDebugElement.attributes.kssize).not.toBeNull();
expect(btnDebugElement.attributes.sizeConfig).toBeUndefined();
if (size) {
// I don't know why I cannot retrieve styles from btnDebugElement, so I decided to
// get elements via Directive.
const sizes: DebugElement[] = fixture.debugElement.queryAll(By.directive(SizeDirective));
let width = '';
let height = '';
const split: string[] | undefined = sizes[0].attributes.style?.split(';');
if (!split) {
throw new Error('This test expects to check styles applies by ksSize directive');
}
split.pop(); // remove last element because it contains ''
if (!withFontAwesome) {
split.forEach((item: string) => {
if (item.trim().startsWith('width:')) {
width = item.replace('width:', '').trim();
} else if (item.trim().startsWith('height:')) {
height = item.replace('height:', '').trim();
}
});
expect(width).toBe(size.width);
expect(height).toBe(size.height);
} else {
expect(split.length).toBe(1);
const fontSize: string = split[0].replace('font-size:', '').trim();
// TODO improve this check because here I'm using always FA buttons with the same size
expect(fontSize).toBe(CUSTOM_FA_BUTTONS[0]?.fontSize as string);
}
}
expect(btnDebugElement.attributes['aria-label']).toBe(currentButton.ariaLabel ? currentButton.ariaLabel : null);
expect(btnDebugElement.attributes.role).toBe('button');
expect(btnDebugElement.properties.tabIndex).toBe(0);
// expect(btnDebugElement.properties['hidden']).toBe(false);
// console.log('btnDebugElement.attributes ' + btnIndex, btnDebugElement.attributes);
// console.log('btnDebugElement.properties ' + btnIndex, btnDebugElement.properties);
if (currentButton.fontSize) {
expect(btnDebugElement.nativeElement.style.fontSize).toBe(currentButton.fontSize);
}
if (currentButton.size) {
expect(btnDebugElement.nativeElement.style.width).toBe(currentButton.size.width);
expect(btnDebugElement.nativeElement.style.height).toBe(currentButton.size.height);
}
const childrenElements: DebugElement[] = btnDebugElement.children;
expect(childrenElements.length).toBe(1);
expect(childrenElements[0].attributes['aria-hidden']).toBe('true');
expect(containsClasses(childrenElements[0].properties.className, currentButton.className + ' inside')).toBeTrue();
expect(childrenElements[0].properties.title).toBe(currentButton.title);
// console.log('childrenElements.attributes ' + btnIndex, childrenElements[0].attributes);
// console.log('childrenElements.properties ' + btnIndex, childrenElements[0].properties);
}
function containsClasses(actualClasses: string, expectedClasses: string): boolean {
const actual: string[] = actualClasses.split(' ');
const expected: string[] = expectedClasses.split(' ');
let count = 0;
if (actual.length !== expected.length) {
return false;
}
expected.forEach((item: string) => {
if (actual.includes(item)) {
count++;
}
});
return count === expected.length;
}
function testBtnNumberByStrategy(strategy: ButtonsStrategy, btnDebugElementsCount: number): void {
switch (strategy) {
case ButtonsStrategy.DEFAULT:
expect(btnDebugElementsCount).toBe(1);
break;
case ButtonsStrategy.SIMPLE:
expect(btnDebugElementsCount).toBe(2);
break;
case ButtonsStrategy.ADVANCED:
expect(btnDebugElementsCount).toBe(3);
break;
case ButtonsStrategy.FULL:
expect(btnDebugElementsCount).toBe(5);
break;
case ButtonsStrategy.CUSTOM:
// no constraints with custom strategy
break;
default:
fail('input strategy is not allowed');
}
}
function initTestBed(): void {
TestBed.configureTestingModule({
declarations: [UpperButtonsComponent, SizeDirective]
}).overrideComponent(UpperButtonsComponent, {
set: {
providers: [
{
provide: ConfigService,
useClass: ConfigService
}
]
}
});
}
describe('UpperButtonsComponent', () => {
beforeEach(() => {
initTestBed();
fixture = TestBed.createComponent(UpperButtonsComponent);
comp = fixture.componentInstance;
});
it('should instantiate it', () => expect(comp).not.toBeNull());
describe('---YES---', () => {
DEFAULT_CASES.forEach((currentButtonConfig: ButtonsConfig, index: number) => {
it(`should display buttons for every default buttonConfigs and subscribe to click events. Test i=${index}`, () => {
updateInputs(IMAGE_EXTURL, currentButtonConfig);
// expect a valid ButtonStrategy because passed to this test as input (via currentButtonConfig)
expect(ButtonsStrategy[currentButtonConfig.strategy]).not.toBeUndefined();
const element: DebugElement = fixture.debugElement;
const btns: DebugElement[] = element.queryAll(By.css('a.upper-button'));
testBtnNumberByStrategy(currentButtonConfig.strategy, btns.length);
comp.id = GALLERY_ID;
comp.closeButton.subscribe((res: ButtonEvent) => {
expect(res).toEqual(getButtonEvent(KS_DEFAULT_BTN_CLOSE));
});
comp.delete.subscribe((res: ButtonEvent) => {
expect(res).toEqual(getButtonEvent(KS_DEFAULT_BTN_DELETE));
});
comp.navigate.subscribe((res: ButtonEvent) => {
expect(res).toEqual(getButtonEvent(KS_DEFAULT_BTN_EXTURL));
});
comp.download.subscribe((res: ButtonEvent) => {
expect(res).toEqual(getButtonEvent(KS_DEFAULT_BTN_DOWNLOAD));
});
comp.fullscreen.subscribe((res: ButtonEvent) => {
expect(res).toEqual(getButtonEvent(KS_DEFAULT_BTN_FULL_SCREEN));
});
// testing html elements, attributes and properties
btns.forEach((debugElement: DebugElement, btnIndex: number) => {
testCurrentHtmlBtn(debugElement, btnIndex, KS_DEFAULT_SIZE);
});
// iterate over all buttons from LEFT TO RIGHT
// clicking all of them
btns.forEach((debugElement: DebugElement) => {
debugElement.nativeElement.click();
});
});
});
IGNORE_CUSTOM_CASES.forEach((currentButtonConfig: ButtonsConfig, index: number) => {
it(`should show default buttons ignoring custom ones passed as input, because strategy != CUSTOM. Test i=${index}`, () => {
updateInputs(IMAGE_EXTURL, currentButtonConfig);
// expect a valid ButtonStrategy because passed to this test as input (via currentButtonConfig)
expect(ButtonsStrategy[currentButtonConfig.strategy]).not.toBeUndefined();
const element: DebugElement = fixture.debugElement;
const btns: DebugElement[] = element.queryAll(By.css('a.upper-button'));
testBtnNumberByStrategy(currentButtonConfig.strategy, btns.length);
comp.id = GALLERY_ID;
comp.closeButton.subscribe((res: ButtonEvent) => {
expect(res).toEqual(getButtonEvent(KS_DEFAULT_BTN_CLOSE));
});
comp.delete.subscribe((res: ButtonEvent) => {
expect(res).toEqual(getButtonEvent(KS_DEFAULT_BTN_DELETE));
});
comp.navigate.subscribe((res: ButtonEvent) => {
expect(res).toEqual(getButtonEvent(KS_DEFAULT_BTN_EXTURL));
});
comp.download.subscribe((res: ButtonEvent) => {
expect(res).toEqual(getButtonEvent(KS_DEFAULT_BTN_DOWNLOAD));
});
comp.fullscreen.subscribe((res: ButtonEvent) => {
expect(res).toEqual(getButtonEvent(KS_DEFAULT_BTN_FULL_SCREEN));
});
// testing html elements, attributes and properties
btns.forEach((debugElement: DebugElement, btnIndex: number) => {
testCurrentHtmlBtn(debugElement, btnIndex, KS_DEFAULT_SIZE);
});
// iterate over all buttons from LEFT TO RIGHT
// clicking all of them
btns.forEach((debugElement: DebugElement) => {
debugElement.nativeElement.click();
});
});
});
[DEFAULT_CASES[2], DEFAULT_CASES[3]].forEach((currentButtonConfig: ButtonsConfig, i: number) => {
NO_EXTURL_CASES.forEach((image: Image, j: number) => {
it(`shouldn't catch a navigate event, because either input image isn't valid or extUrl isn't defined. Test i=${i} j=${j}`, () => {
updateInputs(image, currentButtonConfig);
// expect a valid ButtonStrategy because passed to this test as input (via currentButtonConfig)
expect(ButtonsStrategy[currentButtonConfig.strategy]).not.toBeUndefined();
const element: DebugElement = fixture.debugElement;
const btns: DebugElement[] = element.queryAll(By.css('a.upper-button'));
testBtnNumberByStrategy(currentButtonConfig.strategy, btns.length);
comp.id = GALLERY_ID;
comp.navigate.subscribe((res: ButtonEvent) => {
fail('navigate output should be never called, because input image is not valid or extUrl is not defined');
});
comp.closeButton.subscribe((res: ButtonEvent) => {
expect(res).toEqual(getButtonEvent(KS_DEFAULT_BTN_CLOSE));
});
comp.delete.subscribe((res: ButtonEvent) => {
expect(res).toEqual(getButtonEvent(KS_DEFAULT_BTN_DELETE));
});
comp.download.subscribe((res: ButtonEvent) => {
expect(res).toEqual(getButtonEvent(KS_DEFAULT_BTN_DOWNLOAD));
});
comp.fullscreen.subscribe((res: ButtonEvent) => {
expect(res).toEqual(getButtonEvent(KS_DEFAULT_BTN_FULL_SCREEN));
});
// iterate over all buttons from LEFT TO RIGHT
// testing html elements, attributes and properties
btns.forEach((debugElement: DebugElement, btnIndex: number) => {
testCurrentHtmlBtn(debugElement, btnIndex, KS_DEFAULT_SIZE);
});
// iterate over all buttons from LEFT TO RIGHT
// clicking all of them
btns.forEach((debugElement: DebugElement) => {
debugElement.nativeElement.click();
});
});
});
});
CUSTOM_CASES.forEach((currentButtonConfig: ButtonsConfig, index: number) => {
it(`should display custom + default buttons and subscribe to click events. Test i=${index}`, () => {
updateInputs(IMAGE_EXTURL, currentButtonConfig);
// expect a valid ButtonStrategy because passed to this test as input (via currentButtonConfig)
expect(ButtonsStrategy[currentButtonConfig.strategy]).not.toBeUndefined();
const element: DebugElement = fixture.debugElement;
const btns: DebugElement[] = element.queryAll(By.css('a.upper-button'));
comp.id = GALLERY_ID;
comp.closeButton.subscribe((res: ButtonEvent) => {
expect(res).toEqual(getButtonEvent(KS_DEFAULT_BTN_CLOSE));
});
comp.delete.subscribe((res: ButtonEvent) => {
expect(res).toEqual(getButtonEvent(KS_DEFAULT_BTN_DELETE));
});
comp.navigate.subscribe((res: ButtonEvent) => {
expect(res).toEqual(getButtonEvent(KS_DEFAULT_BTN_EXTURL));
});
comp.download.subscribe((res: ButtonEvent) => {
expect(res).toEqual(getButtonEvent(KS_DEFAULT_BTN_DOWNLOAD));
});
comp.customEmit.subscribe((res: ButtonEvent) => {
expect(res).toEqual(getButtonEvent(CUSTOM_BTN));
});
comp.fullscreen.subscribe((res: ButtonEvent) => {
expect(res).toEqual(getButtonEvent(KS_DEFAULT_BTN_FULL_SCREEN));
});
// iterate over all buttons from LEFT TO RIGHT
// testing html elements, attributes and properties
btns.forEach((debugElement: DebugElement, btnIndex: number) => {
testCurrentHtmlBtn(debugElement, btnIndex, KS_DEFAULT_SIZE);
});
// iterate over all buttons from LEFT TO RIGHT
// clicking all of them
btns.forEach((debugElement: DebugElement) => {
debugElement.nativeElement.click();
});
});
});
EXT_URL_IN_A_NEW_TAB_CASES.forEach((currentButtonConfig: ButtonsConfig, index: number) => {
it(`should display buttons where extUrl buttons open extUrl in a new tab and subscribe to click events. Test i=${index}`, () => {
updateInputs(IMAGE_EXTURL, currentButtonConfig);
// expect a valid ButtonStrategy because passed to this test as input (via currentButtonConfig)
expect(ButtonsStrategy[currentButtonConfig.strategy]).not.toBeUndefined();
const element: DebugElement = fixture.debugElement;
const btns: DebugElement[] = element.queryAll(By.css('a.upper-button'));
comp.id = GALLERY_ID;
comp.closeButton.subscribe((res: ButtonEvent) => {
expect(res).toEqual(getButtonEvent(KS_DEFAULT_BTN_CLOSE));
});
comp.delete.subscribe((res: ButtonEvent) => {
expect(res).toEqual(getButtonEvent(KS_DEFAULT_BTN_DELETE));
});
comp.navigate.subscribe((res: ButtonEvent) => {
expect(res).toEqual(getButtonEvent(EXTURL_BTN_NEW_TAB));
});
comp.download.subscribe((res: ButtonEvent) => {
expect(res).toEqual(getButtonEvent(KS_DEFAULT_BTN_DOWNLOAD));
});
comp.customEmit.subscribe((res: ButtonEvent) => {
expect(res).toEqual(getButtonEvent(CUSTOM_BTN));
});
comp.fullscreen.subscribe((res: ButtonEvent) => {
expect(res).toEqual(getButtonEvent(KS_DEFAULT_BTN_FULL_SCREEN));
});
// iterate over all buttons from LEFT TO RIGHT
// testing html elements, attributes and properties
btns.forEach((debugElement: DebugElement, btnIndex: number) => {
testCurrentHtmlBtn(debugElement, btnIndex, KS_DEFAULT_SIZE);
});
// iterate over all buttons from LEFT TO RIGHT
// clicking all of them
btns.forEach((debugElement: DebugElement) => {
debugElement.nativeElement.click();
});
});
});
it(`should display custom buttons (with different types) with FontAwesome and subscribe to click events.`, () => {
updateInputs(IMAGE_EXTURL, CUSTOM_FA_CASE);
// expect a valid ButtonStrategy because passed to this test as input (via currentButtonConfig)
expect(ButtonsStrategy[CUSTOM_FA_CASE.strategy]).not.toBeUndefined();
const element: DebugElement = fixture.debugElement;
const btns: DebugElement[] = element.queryAll(By.css('a.upper-button'));
comp.id = GALLERY_ID;
comp.closeButton.subscribe((res: ButtonEvent) => {
expect(res).toEqual(getButtonEvent(CUSTOM_FA_BUTTONS[2]));
});
comp.delete.subscribe((res: ButtonEvent) => {
expect(res).toEqual(getButtonEvent(CUSTOM_FA_BUTTONS[1]));
});
comp.navigate.subscribe((res: ButtonEvent) => {
expect(res).toEqual(getButtonEvent(CUSTOM_FA_BUTTONS[4]));
});
comp.download.subscribe((res: ButtonEvent) => {
expect(res).toEqual(getButtonEvent(CUSTOM_FA_BUTTONS[3]));
});
comp.customEmit.subscribe((res: ButtonEvent) => {
expect(res).toEqual(getButtonEvent(CUSTOM_FA_BUTTONS[0]));
});
// iterate over all buttons from LEFT TO RIGHT
// testing html elements, attributes and properties
btns.forEach((debugElement: DebugElement, btnIndex: number) => {
testCurrentHtmlBtn(debugElement, btnIndex, KS_DEFAULT_SIZE, true);
});
// iterate over all buttons from LEFT TO RIGHT
// clicking all of them
btns.forEach((debugElement: DebugElement) => {
debugElement.nativeElement.click();
});
});
[CUSTOM_SIZES[0]].forEach((currentButtonConfig: ButtonsConfig, index: number) => {
it(`should display custom buttons (with different types) with custom sizes. Test i=${index}`, () => {
updateInputs(IMAGE_EXTURL, currentButtonConfig);
// expect a valid ButtonStrategy because passed to this test as input (via currentButtonConfig)
expect(ButtonsStrategy[currentButtonConfig.strategy]).not.toBeUndefined();
const element: DebugElement = fixture.debugElement;
const btns: DebugElement[] = element.queryAll(By.css('a.upper-button'));
// iterate over all buttons from LEFT TO RIGHT
// testing html elements, attributes and properties
btns.forEach((debugElement: DebugElement, btnIndex: number) => {
switch (index) {
case 0:
testCurrentHtmlBtn(debugElement, btnIndex, CUSTOM_SIZE);
break;
case 1:
testCurrentHtmlBtn(debugElement, btnIndex, CUSTOM_SIZE_AUTO_HEIGHT);
break;
case 2:
testCurrentHtmlBtn(debugElement, btnIndex, CUSTOM_SIZE_AUTO_WIDTH);
break;
}
});
});
});
});
describe('---NO---', () => {
VISIBILITY_CASES.forEach((currentButtonConfig: ButtonsConfig, index: number) => {
it(`shouldn't find any buttons, because visibility is false. Test i=${index}`, () => {
updateInputs(IMAGE_EXTURL, currentButtonConfig);
// expect a valid ButtonStrategy because passed to this test as input (via currentButtonConfig)
expect(ButtonsStrategy[currentButtonConfig.strategy]).not.toBeUndefined();
const element: DebugElement = fixture.debugElement;
const btnDebugElement: DebugElement = element.query(By.directive(SizeDirective));
expect(btnDebugElement).toBeNull();
const btns: DebugElement[] = element.queryAll(By.css('a.upper-button'));
expect(btns.length).toBe(0);
});
});
UNKNOWN_CASES.forEach((currentButtonConfig: ButtonsConfig, index: number) => {
it(`should display default buttons (DEFAULT strategy), because input strategy is unknown. Test i=${index}`, () => {
updateInputs(IMAGE_EXTURL, currentButtonConfig);
// expect an UNKNOWN ButtonStrategy because passed to this test as input (via currentButtonConfig)
expect(ButtonsStrategy[currentButtonConfig.strategy]).toBeUndefined();
const element: DebugElement = fixture.debugElement;
const btns: DebugElement[] = element.queryAll(By.css('a.upper-button'));
expect(btns.length).toBe(1);
comp.id = GALLERY_ID;
comp.closeButton.subscribe((res: ButtonEvent) => {
expect(res).toEqual(getButtonEvent(KS_DEFAULT_BTN_CLOSE));
});
// iterate over all buttons from LEFT TO RIGHT
// testing html elements, attributes and properties
btns.forEach((debugElement: DebugElement, btnIndex: number) => {
testCurrentHtmlBtn(debugElement, btnIndex, KS_DEFAULT_SIZE);
});
// iterate over all buttons from LEFT TO RIGHT
// clicking all of them
btns.forEach((debugElement: DebugElement) => {
debugElement.nativeElement.click();
});
});
});
CUSTOM_NO_BUTTONS_CASES.forEach((currentButtonConfig: ButtonsConfig, index: number) => {
it(`shouldn't display anything, because custom config requires a buttons array. Test i=${index}`, () => {
updateInputs(IMAGE_EXTURL, currentButtonConfig);
// expect a valid ButtonStrategy because passed to this test as input (via currentButtonConfig)
expect(ButtonsStrategy[currentButtonConfig.strategy]).not.toBeUndefined();
const element: DebugElement = fixture.debugElement;
const btns: DebugElement[] = element.queryAll(By.css('a.upper-button'));
expect(btns.length).toBe(0);
});
});
});
describe('---ERROR---', () => {
NOT_VALID_BTN_TYPE_CASES.forEach((currentButtonConfig: ButtonsConfig, index: number) => {
it(`should throw an error, because all buttons must have valid types. Test i=${index}`, () => {
const ERROR: Error = new Error('Unknown ButtonType. For custom types use ButtonType.CUSTOM');
expect(() => updateInputs(IMAGE_EXTURL, currentButtonConfig)).toThrow(ERROR);
});
});
});
}); | the_stack |
import './setup';
import { StageComponent, ComponentTester } from 'aurelia-testing';
import { PLATFORM } from 'aurelia-pal';
import { bootstrap } from 'aurelia-bootstrapper';
import { validateScrolledState, scrollToEnd, scrollToStart, waitForNextFrame, waitForFrames, waitForTimeout, scrollRepeat } from './utilities';
import { VirtualRepeat } from '../src/virtual-repeat';
import { ITestAppInterface } from './interfaces';
import { eachCartesianJoin } from './lib';
PLATFORM.moduleName('src/virtual-repeat');
PLATFORM.moduleName('test/noop-value-converter');
PLATFORM.moduleName('src/infinite-scroll-next');
describe('vr-integration.infinite-scroll.spec.ts', () => {
const resources = [
'src/virtual-repeat',
'src/infinite-scroll-next',
'test/noop-value-converter',
];
class IdentityValueConverter {
static $resource = {
type: 'valueConverter',
name: 'identity',
};
toView(val: any[]) {
return val;
}
}
class CloneArrayValueConverter {
static $resource = {
type: 'valueConverter',
name: 'cloneArray',
};
toView(val: any[]) {
return Array.isArray(val) ? val.slice() : val;
}
}
let component: ComponentTester<VirtualRepeat>;
let view: string;
let itemHeight = 100;
beforeEach(() => {
component = undefined;
});
afterEach(() => {
try {
if (component) {
component.dispose();
}
} catch (ex) {
console.log('Error disposing component');
console.error(ex);
}
});
const testGroups: ITestCaseGroup[] = [
{
desc: 'div > div',
title: (repeatExpression, scrollNextAttr) =>
`div > div[repeat ${repeatExpression}][${scrollNextAttr}]`,
createView: (repeatExpression, scrollNextAttr) =>
`<div style="height: 500px; overflow-y: scroll">
<div
virtual-repeat.for="item of items ${repeatExpression}"
${scrollNextAttr}
style="height: ${itemHeight}px;">\${item}</div>
</div>`,
},
{
desc: 'ul > li',
title: (repeatExpression, scrollNextAttr) =>
`ul > li[repeat ${repeatExpression}][${scrollNextAttr}]`,
createView: (repeatExpression, scrollNextAttr) =>
`<ul style="height: 500px; overflow-y: scroll; padding: 0; margin: 0;">
<li
virtual-repeat.for="item of items ${repeatExpression}"
${scrollNextAttr}
style="height: ${itemHeight}px;">\${item}</li>
</ul>`,
},
{
desc: 'ol > li',
title: (repeatExpression, scrollNextAttr) =>
`ol > li[repeat ${repeatExpression}][${scrollNextAttr}]`,
createView: (repeatExpression, scrollnextAttr) =>
`<ol style="height: 500px; overflow-y: scroll; padding: 0; margin: 0;">
<li
virtual-repeat.for="item of items ${repeatExpression}"
${scrollnextAttr}
style="height: ${itemHeight}px;">\${item}</li>
</ol>`,
},
{
desc: 'div > table > tr',
title: (repeatExpression: string, scrollNextAttr: string): string => {
return `div > table > tr[repeat ${repeatExpression}][${scrollNextAttr}]`;
},
createView: (repeatExpression: string, scrollNextAttr: string): string => {
return `<div style="height: 500px; overflow-y: scroll; padding: 0; margin: 0;">
<table style="border-spacing: 0">
<tr
virtual-repeat.for="item of items ${repeatExpression}"
${scrollNextAttr}
style="height: ${itemHeight}px;"><td>\${item}</td></tr>
</table>
</div>`;
},
},
{
desc: 'div > table > tbody',
title: (repeatExpression: string, scrollNextAttr: string): string => {
return `div > table > tbody[repeat${repeatExpression}][${scrollNextAttr}]`;
},
createView: (repeatExpression: string, scrollNextAttr: string): string => {
return `<div style="height: 500px; overflow-y: scroll; padding: 0; margin: 0;">
<table style="border-spacing: 0">
<tbody
virtual-repeat.for="item of items ${repeatExpression}"
${scrollNextAttr}>
<tr
style="height: ${itemHeight}px;">
<td>\${item}</td>
</tr>
</tbody>
</table>
</div>`;
},
},
];
const repeatScrollNextCombos: IRepeatScrollNextCombo[] = [
['', 'infinite-scroll-next="getNextPage"'],
['', 'infinite-scroll-next.call="getNextPage($scrollContext)"'],
[' & toView', 'infinite-scroll-next="getNextPage"'],
[' & twoWay', 'infinite-scroll-next="getNextPage"'],
[' & twoWay', 'infinite-scroll-next.call="getNextPage($scrollContext)"'],
[' | cloneArray', 'infinite-scroll-next="getNextPage"', [CloneArrayValueConverter]],
[' | cloneArray', 'infinite-scroll-next.call="getNextPage($scrollContext)"', [CloneArrayValueConverter]],
[' | identity | cloneArray & toView', 'infinite-scroll-next="getNextPage"', [IdentityValueConverter, CloneArrayValueConverter]],
[' | identity | cloneArray & toView', 'infinite-scroll-next.call="getNextPage($scrollContext)"', [IdentityValueConverter, CloneArrayValueConverter]],
[' | cloneArray & toView', 'infinite-scroll-next="getNextPage"', [CloneArrayValueConverter]],
// cloneArray and two way creates infinite loop
// [' | cloneArray & twoWay', 'infinite-scroll-next="getNextPage"', [CloneArrayValueConverter]]
];
eachCartesianJoin(
[repeatScrollNextCombos, testGroups],
([repeatExpression, scrollNextAttr, extraResources], { title, createView }, callIndex) => {
runTestGroup(
title(repeatExpression, scrollNextAttr),
createView(repeatExpression, scrollNextAttr),
extraResources
);
}
);
type IRepeatScrollNextCombo = [/*repeat extra expression*/string, /*infinite-scroll-next attr*/string, /*extraResources*/ any[]?];
interface ITestCaseGroup {
desc?: string;
title: (repeatExpression: string, scrollNextAttr: string) => string;
createView: (repeatExpression: string, scrollNextAttr: string) => string;
}
function runTestGroup(title: string, $view: string, extraResources: any[] = []): void {
it([
title,
'Initial 3 - 4 - 5 - 6 items',
' -- wait',
' -- assert get more',
'',
].join('\n\t'), async () => {
let scrollNextArgs: [number, boolean, boolean];
const spy = jasmine.createSpy('viewModel.getNextPage(): void', function(this: ITestAppInterface<string>, ...args: any[]) {
scrollNextArgs = normalizeScrollNextArgs(args);
let itemLength = this.items.length;
for (let i = 0; i < 100; ++i) {
let itemNum = itemLength + i;
this.items.push('item' + itemNum);
}
}).and.callThrough();
let { component, virtualRepeat, viewModel } = await bootstrapComponent(
{
items: createItems(3),
getNextPage: spy,
},
extraResources,
$view
);
await waitForNextFrame();
expect(virtualRepeat.minViewsRequired).toBe(6, 'repeat.elementsInView');
expect(spy.calls.count()).toBe(1, '3 items getNextPage() calls');
// await waitForNextFrame();
// expect(spy.calls.count()).toBe(1, '3 items - next frame -- getNextPage() calls');
let [firstIndex, isAtBottom, isAtTop] = scrollNextArgs;
expect(firstIndex).toBe(0, 'scrollNextArgs[0] 1');
expect(isAtBottom).toBe(true, 'scrollNextArgs[1] -- isAtBottom 1');
expect(isAtTop).toBe(true, 'scrollNextArgs[2] -- isAtTop 1');
expect(viewModel.items.length).toBe(103, 'items.length 1');
validateScrolledState(virtualRepeat, viewModel, itemHeight);
component.dispose();
spy.calls.reset();
({ component, virtualRepeat, viewModel } = await bootstrapComponent(
{
items: createItems(4),
getNextPage: spy,
},
extraResources,
$view
));
await waitForNextFrame();
expect(virtualRepeat.minViewsRequired * 2).toBe(12, 'repeat._viewsLength');
expect(spy.calls.count()).toBe(1, '4 items getNextPage() calls');
[firstIndex, isAtBottom, isAtTop] = scrollNextArgs;
expect(firstIndex).toBe(0, 'scrollNextArgs[0] 2');
expect(isAtBottom).toBe(true, 'scrollNextArgs[1] -- isAtBottom 2');
expect(isAtTop).toBe(true, 'scrollNextArgs[2] -- isAtTop 2');
expect(viewModel.items.length).toBe(104, 'items.length 2');
validateScrolledState(virtualRepeat, viewModel, itemHeight);
component.dispose();
spy.calls.reset();
({ component, virtualRepeat, viewModel } = await bootstrapComponent(
{
items: createItems(5),
getNextPage: spy,
},
extraResources,
$view
));
await waitForNextFrame();
expect(virtualRepeat.minViewsRequired * 2).toBe(12, 'repeat._viewsLength');
expect(spy.calls.count()).toBe(1, '5 items getNextPage() calls');
[firstIndex, isAtBottom, isAtTop] = scrollNextArgs;
expect(firstIndex).toBe(0, 'scrollNextArgs[0] 3');
expect(isAtBottom).toBe(true, 'scrollNextArgs[1] -- isAtBottom 3');
expect(isAtTop).toBe(true, 'scrollNextArgs[2] -- isAtTop 3');
expect(viewModel.items.length).toBe(105, 'items.length 3');
validateScrolledState(virtualRepeat, viewModel, itemHeight);
component.dispose();
spy.calls.reset();
({ component, virtualRepeat, viewModel } = await bootstrapComponent(
{
items: createItems(6),
getNextPage: spy,
},
extraResources,
$view
));
await waitForNextFrame();
expect(virtualRepeat.minViewsRequired * 2).toBe(12, 'repeat._viewsLength');
expect(spy.calls.count()).toBe(0, '6 items = 0 getNextPage() calls');
[firstIndex, isAtBottom, isAtTop] = scrollNextArgs;
expect(firstIndex).toBe(0, 'scrollNextArgs[0] 4');
expect(isAtBottom).toBe(true, 'scrollNextArgs[1] -- isAtBottom 4');
expect(isAtTop).toBe(true, 'scrollNextArgs[2] -- isAtTop 4');
expect(viewModel.items.length).toBe(6, 'items.length 4');
validateScrolledState(virtualRepeat, viewModel, itemHeight);
});
it([
title,
'Initial 100 items',
' -- scroll down + get 100 more',
' -- wait',
' -- scroll up + get 100 more',
'',
].join('\n\t'), async () => {
const spy = jasmine.createSpy('viewModel.getNextPage(): void', function(this: ITestAppInterface<string>) {
let itemLength = this.items.length;
for (let i = 0; i < 100; ++i) {
let itemNum = itemLength + i;
this.items.push('item' + itemNum);
}
}).and.callThrough();
const { virtualRepeat, viewModel } = await bootstrapComponent(
{
items: createItems(100),
getNextPage: spy,
},
extraResources,
$view
);
expect(virtualRepeat.minViewsRequired * 2).toBe(12, 'repeat._viewsLength');
expect(spy.calls.count()).toBe(0, 'no getNextPage() calls');
expect(viewModel.items.length).toBe(100, 'items.length 1');
validateScrolledState(virtualRepeat, viewModel, itemHeight);
scrollRepeat(virtualRepeat, 'end');
expect(spy.calls.count()).toBe(0, '@scroll 1 start -> end');
await waitForFrames(1);
expect(spy.calls.count()).toBe(0, '@scroll 1 start -> end');
await waitForFrames(2);
expect(spy.calls.count()).toBe(1, '@scroll 1 start -> end');
expect(viewModel.items.length).toBe(200, 'items.length 2');
let firstViewIndex = virtualRepeat.firstViewIndex();
let lastViewIndex = virtualRepeat.lastViewIndex();
expect(firstViewIndex).toBeGreaterThanOrEqual(100 - (5 + 1) * 2, 'repeat._firstViewIndex() 1');
expect(firstViewIndex).toBeLessThan(200 - (5 + 1) * 2, 'repeat._firstViewIndex < bottom');
expect(lastViewIndex).toBeGreaterThanOrEqual(100, 'repeat._lastViewIndex() 1');
validateScrolledState(virtualRepeat, viewModel, itemHeight);
scrollRepeat(virtualRepeat, 'start');
expect(spy.calls.count()).toBe(1, '@scroll 2 end -> start');
await waitForFrames(1);
expect(spy.calls.count()).toBe(1, '@scroll 2 end -> start');
await waitForFrames(2);
expect(spy.calls.count()).toBe(2, '@scroll 2 end -> start');
expect(viewModel.items.length).toBe(300, 'items.length 3');
firstViewIndex = virtualRepeat.firstViewIndex();
lastViewIndex = virtualRepeat.lastViewIndex();
expect(firstViewIndex).toBe(0, 'repeat._firstViewIndex() 2');
expect(lastViewIndex).toBe(11, 'repeat._lastViewIndex() 2');
validateScrolledState(virtualRepeat, viewModel, itemHeight);
});
it([
title,
'passes the current index and location state',
' -- start 100',
' -- jump to end',
' -- wait and assert',
' -- jump to start',
' -- wait and assert',
].join('\n\t'), async () => {
let scrollNextArgs: [number, /*is near bottom*/boolean, /*is near top*/boolean];
const spy = jasmine.createSpy('viewModel.getNextPage(): void', function(this: ITestAppInterface<string>, ...args: any[]) {
scrollNextArgs = normalizeScrollNextArgs(args);
if (scrollNextArgs[2]) {
let itemLength = this.items.length;
for (let i = 0; i < 100; ++i) {
let itemNum = itemLength + i;
this.items.unshift('item' + itemNum);
}
}
}).and.callThrough();
const { virtualRepeat, viewModel } = await bootstrapComponent(
{
items: createItems(100),
getNextPage: spy,
},
extraResources,
$view
);
expect(scrollNextArgs).toBe(undefined, 'getNextPage() args[]');
expect(virtualRepeat.minViewsRequired * 2).toBe(12, 'repeat._viewsLength');
expect(virtualRepeat.viewCount()).toBe(12, 'repeat.viewCount()');
expect(spy.calls.count()).toBe(0, 'no getNextPage() calls');
expect(viewModel.items.length).toBe(100, 'items.length 1');
validateScrolledState(virtualRepeat, viewModel, itemHeight);
scrollRepeat(virtualRepeat, 'end');
expect(spy.calls.count()).toBe(0, '@scroll 1 start -> end');
await waitForFrames(1);
expect(spy.calls.count()).toBe(0, '@scroll 1 start -> end');
await waitForFrames(2);
expect(spy.calls.count()).toBe(1, '@scroll 1 start -> end');
expect(viewModel.items.length).toBe(100, 'items.length 2');
let virtualRepeatFirst = virtualRepeat.$first;
let firstViewIndex = virtualRepeat.firstViewIndex();
let lastViewIndex = virtualRepeat.lastViewIndex();
expect(firstViewIndex).toBe(88, 'repeat._firstViewIndex() 1');
expect(virtualRepeatFirst).toBe(88, 'repeat._first 1 = 88');
// expect(virtualRepeatFirst).toBe(94, 'repeat._first 1 <= 94');
expect(lastViewIndex).toBe(99, 'repeat._lastViewIndex() 1');
validateScrolledState(virtualRepeat, viewModel, itemHeight);
expect(Array.isArray(scrollNextArgs)).toBe(true, 'scrollNextArgs is defined');
let [firstIndex, isAtBottom, isAtTop] = scrollNextArgs;
expect(firstIndex).toBe(88, 'scrollNextArgs[0] 1');
expect(isAtBottom).toBe(true, 'scrollNextArgs[1] -- isAtBottom 1');
expect(isAtTop).toBe(false, 'scrollNextArgs[2] -- isAtTop 1');
scrollRepeat(virtualRepeat, 'start');
expect(spy.calls.count()).toBe(1, '@scroll 2 end -> start');
await waitForFrames(1);
expect(spy.calls.count()).toBe(1, '@scroll 2 end -> start');
await waitForFrames(2);
expect(spy.calls.count()).toBe(2, '@scroll 2 end -> start');
expect(viewModel.items.length).toBe(200, 'items.length 3');
virtualRepeatFirst = virtualRepeat.$first;
firstViewIndex = virtualRepeat.firstViewIndex();
lastViewIndex = virtualRepeat.lastViewIndex();
expect(firstViewIndex).toBe(0, 'repeat._firstViewIndex() 2');
expect(lastViewIndex).toBe(11, 'repeat._lastViewIndex() 2');
validateScrolledState(virtualRepeat, viewModel, itemHeight);
[firstIndex, isAtBottom, isAtTop] = scrollNextArgs;
expect(firstIndex).toBe(virtualRepeatFirst, 'scrollNextArgs[0] 2');
expect(isAtBottom).toBe(false, 'scrollNextArgs[1] -- isAtBottom 2');
expect(isAtTop).toBe(true, 'scrollNextArgs[2] -- isAtTop 2');
});
it([
title,
'passes the current index and location state',
' -- start 100',
' -- scroll down 20',
' -- wait and assert',
' -- scroll up',
' -- wait and assert',
].join('\n\t'), async () => {
let scrollNextArgs: [number, /*is near bottom*/boolean, /*is near top*/boolean];
const spy = jasmine.createSpy('viewModel.getNextPage(): void', function(this: ITestAppInterface<string>, ...args: any[]) {
scrollNextArgs = normalizeScrollNextArgs(args);
if (scrollNextArgs[2]) {
let itemLength = this.items.length;
for (let i = 0; i < 100; ++i) {
let itemNum = itemLength + i;
this.items.unshift('item' + itemNum);
}
}
}).and.callThrough();
const { virtualRepeat, viewModel } = await bootstrapComponent(
{
items: createItems(100),
getNextPage: spy,
},
extraResources,
$view
);
expect(scrollNextArgs).toBe(undefined, 'getNextPage() args[]');
expect(virtualRepeat.minViewsRequired * 2).toBe(12, 'repeat._viewsLength');
expect(virtualRepeat.viewCount()).toBe(12, 'repeat.viewCount()');
expect(spy.calls.count()).toBe(0, 'no getNextPage() calls');
expect(viewModel.items.length).toBe(100, 'items.length 1');
validateScrolledState(virtualRepeat, viewModel, itemHeight);
scrollRepeat(virtualRepeat, 20 * itemHeight);
await waitForFrames(2);
expect(viewModel.items.length).toBe(100, 'items.length 2');
let virtualRepeatFirst = virtualRepeat.$first;
let firstViewIndex = virtualRepeat.firstViewIndex();
let lastViewIndex = virtualRepeat.lastViewIndex();
expect(firstViewIndex).toBe(20, 'repeat._firstViewIndex() 1');
expect(virtualRepeatFirst).toBe(20, 'repeat._first 1 = 88');
expect(lastViewIndex).toBe(20 + virtualRepeat.minViewsRequired * 2 - 1, 'repeat._lastViewIndex() 1');
validateScrolledState(virtualRepeat, viewModel, itemHeight);
expect(scrollNextArgs).toBe(undefined, 'scrollNextArgs is undefined');
for (let i = 0; 15 >= i; ++i) {
scrollRepeat(virtualRepeat, (20 - i) * itemHeight);
await waitForFrames(2);
virtualRepeatFirst = virtualRepeat.$first;
firstViewIndex = virtualRepeat.firstViewIndex();
lastViewIndex = virtualRepeat.lastViewIndex();
expect(firstViewIndex).toBe(20 - i, 'repeat._firstViewIndex() 2');
expect(lastViewIndex).toBe(20 - i + virtualRepeat.minViewsRequired * 2 - 1, 'repeat._lastViewIndex() 2');
}
scrollRepeat(virtualRepeat, 4 * itemHeight);
expect(spy.calls.count()).toBe(0, '@scroll 2 end -> start');
await waitForFrames(1);
expect(spy.calls.count()).toBe(0, '@scroll 2 end -> start');
await waitForFrames(2);
expect(spy.calls.count()).toBe(1, '@scroll 2 end -> start');
expect(viewModel.items.length).toBe(200, 'items.length 3');
let hasValueConverterInExpression = extraResources.length > 0;
virtualRepeatFirst = virtualRepeat.$first;
firstViewIndex = virtualRepeat.firstViewIndex();
lastViewIndex = virtualRepeat.lastViewIndex();
expect(firstViewIndex).toBe(hasValueConverterInExpression ? 4 : 104, 'repeat._firstViewIndex() 3');
expect(lastViewIndex).toBe((hasValueConverterInExpression ? 4 : 104) + virtualRepeat.minViewsRequired * 2 - 1, 'repeat._lastViewIndex() 3');
validateScrolledState(virtualRepeat, viewModel, itemHeight);
let [firstIndex, isAtBottom, isAtTop] = scrollNextArgs;
expect(firstIndex).toBe(4, 'scrollNextArgs[0] 2');
expect(isAtBottom).toBe(false, 'scrollNextArgs[1] -- isAtBottom 2');
expect(isAtTop).toBe(true, 'scrollNextArgs[2] -- isAtTop 2');
});
it([
title,
'handles getting next data set with promises',
' -- sroll to end',
' -- wait',
' -- scroll to top',
].join('\n\t'), async () => {
let scrollNextArgs: [number, boolean, boolean];
let currentPromise: Promise<any>;
const spy = jasmine.createSpy('viewModel.getNextPage(): void', function(this: ITestAppInterface<string>, ...args: any[]) {
let [_, isAtBottom] = scrollNextArgs = normalizeScrollNextArgs(args);
return new Promise(async (resolve) => {
await waitForFrames(2);
let itemLength = this.items.length;
for (let i = 0; i < 100; ++i) {
let itemNum = itemLength + i;
this.items.push('item' + itemNum);
}
resolve();
});
}).and.callThrough();
let { component, virtualRepeat, viewModel } = await bootstrapComponent(
{
items: createItems(100),
getNextPage: spy,
},
extraResources,
$view
);
expect(scrollNextArgs).toBe(undefined, 'getNextPage() args[]');
expect(virtualRepeat.minViewsRequired * 2).toBe(12, 'repeat._viewsLength');
expect(virtualRepeat.viewCount()).toBe(12, 'repeat.viewCount()');
expect(spy.calls.count()).toBe(0, 'no getNextPage() calls 1');
expect(viewModel.items.length).toBe(100, 'items.length 1');
validateScrolledState(virtualRepeat, viewModel, itemHeight);
scrollRepeat(virtualRepeat, 'end');
// assert that nothing changed after
// 1 frame for scroll handler to start working
// 1 frame for getMore to be invoked
await waitForFrames(2);
expect(scrollNextArgs).toEqual([88, true, false], 'scrollNextArgs 1');
expect(spy.calls.count()).toBe(1, '1 getNextPage() calls 2');
// not yet loaded
expect(viewModel.items.length).toBe(100, 'items.length 2 | promise started, not loaded');
await waitForFrames(2);
// loaded
expect(viewModel.items.length).toBe(200, 'items.length 2 | promise resolved, loaded');
});
it([
title,
'handles getting next data set with promises',
' -- start 10 (smaller than min views required: 12)',
' -- sroll 1px (no change in indices)',
].join('\n\t'), async () => {
let scrollNextArgs: [number, boolean, boolean];
let currentPromise: Promise<any>;
const spy = jasmine.createSpy('viewModel.getNextPage(): void', function(this: ITestAppInterface<string>, ...args: any[]) {
let [_, isAtBottom] = scrollNextArgs = normalizeScrollNextArgs(args);
return new Promise(async (resolve) => {
await waitForFrames(2);
let itemLength = this.items.length;
for (let i = 0; i < 1; ++i) {
let itemNum = itemLength + i;
this.items.push('item' + itemNum);
}
resolve();
});
}).and.callThrough();
let { component, virtualRepeat, viewModel } = await bootstrapComponent(
{
items: createItems(10),
getNextPage: spy,
},
extraResources,
$view
);
expect(scrollNextArgs).toBe(undefined, 'getNextPage() args[]');
expect(virtualRepeat.minViewsRequired * 2).toBe(12, 'repeat._viewsLength');
expect(virtualRepeat.viewCount()).toBe(10, 'repeat.viewCount()');
expect(spy.calls.count()).toBe(0, 'no getNextPage() calls 1');
expect(viewModel.items.length).toBe(10, 'items.length 1');
validateScrolledState(virtualRepeat, viewModel, itemHeight);
scrollRepeat(virtualRepeat, 1);
// assert that nothing changed after
// 1 frame for scroll handler to start working
// 1 frame for getMore to be invoked
await waitForFrames(2);
assertScrollNextArgsEqual(scrollNextArgs, [0, true, true], 'scrollnextArgs 1');
// expect(scrollNextArgs).toEqual([/* first view index */0, true, false], 'scrollNextArgs 1');
expect(spy.calls.count()).toBe(1, '1 getNextPage() calls 2');
// not yet loaded
expect(viewModel.items.length).toBe(10, 'items.length 2 | promise started, not loaded');
await waitForFrames(2);
// loaded
expect(viewModel.items.length).toBe(11, 'items.length 2 | promise resolved, loaded');
validateScrolledState(virtualRepeat, viewModel, itemHeight);
// ========================
// try to scroll again, but back to 0 from 1px
scrollRepeat(virtualRepeat, 0);
// assert that nothing changed after
// 1 frame for scroll handler to start working
// 1 frame for getMore to be invoked
await waitForFrames(2);
assertScrollNextArgsEqual(scrollNextArgs, [0, true, true], 'scrollnextArgs 2');
expect(spy.calls.count()).toBe(2, '2 getNextPage() calls 3');
// not yet loaded
expect(viewModel.items.length).toBe(11, 'items.length 3 | promise started, not loaded');
await waitForFrames(2);
// loaded
expect(viewModel.items.length).toBe(12, 'items.length 3 | promise resolved, loaded');
});
}
async function bootstrapComponent<T>($viewModel?: ITestAppInterface<T>, extraResources?: any[], $view = view) {
component = StageComponent
.withResources([
...resources,
...extraResources,
])
.inView($view)
.boundTo($viewModel);
await component.create(bootstrap);
expect(document.body.contains(component.element)).toBe(true, 'repeat is setup in document');
return { virtualRepeat: component.viewModel, viewModel: $viewModel, component: component };
}
function createItems(amount: number, name: string = 'item') {
return Array.from({ length: amount }, (_, index) => name + index);
}
function normalizeScrollNextArgs(args: any[]): [number, boolean, boolean] {
return typeof args[0] === 'number'
? [args[0], args[1], args[2]]
: [args[0].topIndex, args[0].isAtBottom, args[0].isAtTop];
}
function assertScrollNextArgsEqual(scrollnextInfo: [number, boolean, boolean], expectedScrollnextInfo: [number, boolean, boolean], prefixMessage = ''): void {
expect(Array.isArray(scrollnextInfo)).toBe(true, `[${prefixMessage}] scroll next info should have been defined`);
const [actualTopIndex, actualIsNearBottom, actualIsNearTop] = scrollnextInfo;
const [expectedTopIndex, expectedIsNearBottom, expectedIsNearTop] = expectedScrollnextInfo;
expect(actualTopIndex).toBe(expectedTopIndex, `[${prefixMessage}] {top index(${actualTopIndex})} to be ${expectedTopIndex}`);
expect(actualIsNearBottom).toBe(expectedIsNearBottom, `[${prefixMessage}] {is near bottom(${actualIsNearBottom})} to be ${expectedIsNearBottom}`);
expect(actualIsNearTop).toBe(expectedIsNearTop, `[${prefixMessage}] {is near top (${actualIsNearTop})} to be ${expectedIsNearTop}`);
}
}); | the_stack |
import * as ts from "typescript";
import * as lua from "../../../LuaAST";
import { FunctionVisitor, TransformationContext } from "../../context";
import { wrapInToStringForConcat } from "../../utils/lua-ast";
import { LuaLibFeature, transformLuaLibFunction } from "../../utils/lualib";
import { canBeFalsyWhenNotNull, isStandardLibraryType, isStringType } from "../../utils/typescript";
import { transformTypeOfBinaryExpression } from "../typeof";
import { transformAssignmentExpression, transformAssignmentStatement } from "./assignments";
import { BitOperator, isBitOperator, transformBinaryBitOperation } from "./bit";
import {
isCompoundAssignmentToken,
transformCompoundAssignmentExpression,
transformCompoundAssignmentStatement,
unwrapCompoundAssignmentToken,
} from "./compound";
import { assert } from "../../../utils";
import { transformOrderedExpressions } from "../expression-list";
import { transformInPrecedingStatementScope } from "../../utils/preceding-statements";
type ShortCircuitOperator =
| ts.SyntaxKind.AmpersandAmpersandToken
| ts.SyntaxKind.BarBarToken
| ts.SyntaxKind.QuestionQuestionToken;
const isShortCircuitOperator = (value: unknown): value is ShortCircuitOperator =>
value === ts.SyntaxKind.AmpersandAmpersandToken ||
value === ts.SyntaxKind.BarBarToken ||
value === ts.SyntaxKind.QuestionQuestionToken;
type SimpleOperator =
| ts.AdditiveOperatorOrHigher
| Exclude<ts.RelationalOperator, ts.SyntaxKind.InstanceOfKeyword | ts.SyntaxKind.InKeyword>
| ts.EqualityOperator
| ts.LogicalOperator;
const simpleOperatorsToLua: Record<SimpleOperator, lua.BinaryOperator> = {
[ts.SyntaxKind.AmpersandAmpersandToken]: lua.SyntaxKind.AndOperator,
[ts.SyntaxKind.BarBarToken]: lua.SyntaxKind.OrOperator,
[ts.SyntaxKind.PlusToken]: lua.SyntaxKind.AdditionOperator,
[ts.SyntaxKind.MinusToken]: lua.SyntaxKind.SubtractionOperator,
[ts.SyntaxKind.AsteriskToken]: lua.SyntaxKind.MultiplicationOperator,
[ts.SyntaxKind.AsteriskAsteriskToken]: lua.SyntaxKind.PowerOperator,
[ts.SyntaxKind.SlashToken]: lua.SyntaxKind.DivisionOperator,
[ts.SyntaxKind.PercentToken]: lua.SyntaxKind.ModuloOperator,
[ts.SyntaxKind.GreaterThanToken]: lua.SyntaxKind.GreaterThanOperator,
[ts.SyntaxKind.GreaterThanEqualsToken]: lua.SyntaxKind.GreaterEqualOperator,
[ts.SyntaxKind.LessThanToken]: lua.SyntaxKind.LessThanOperator,
[ts.SyntaxKind.LessThanEqualsToken]: lua.SyntaxKind.LessEqualOperator,
[ts.SyntaxKind.EqualsEqualsToken]: lua.SyntaxKind.EqualityOperator,
[ts.SyntaxKind.EqualsEqualsEqualsToken]: lua.SyntaxKind.EqualityOperator,
[ts.SyntaxKind.ExclamationEqualsToken]: lua.SyntaxKind.InequalityOperator,
[ts.SyntaxKind.ExclamationEqualsEqualsToken]: lua.SyntaxKind.InequalityOperator,
};
function transformBinaryOperationWithNoPrecedingStatements(
context: TransformationContext,
left: lua.Expression,
right: lua.Expression,
operator: BitOperator | SimpleOperator | ts.SyntaxKind.QuestionQuestionToken,
node: ts.Node
): lua.Expression {
if (isBitOperator(operator)) {
return transformBinaryBitOperation(context, node, left, right, operator);
}
if (operator === ts.SyntaxKind.QuestionQuestionToken) {
assert(ts.isBinaryExpression(node));
return transformNullishCoalescingOperationNoPrecedingStatements(context, node, left, right);
}
let luaOperator = simpleOperatorsToLua[operator];
// Check if we need to use string concat operator
if (operator === ts.SyntaxKind.PlusToken && ts.isBinaryExpression(node)) {
const typeLeft = context.checker.getTypeAtLocation(node.left);
const typeRight = context.checker.getTypeAtLocation(node.right);
const isLeftString = isStringType(context, typeLeft);
const isRightString = isStringType(context, typeRight);
if (isLeftString || isRightString) {
left = isLeftString ? left : wrapInToStringForConcat(left);
right = isRightString ? right : wrapInToStringForConcat(right);
luaOperator = lua.SyntaxKind.ConcatOperator;
}
}
return lua.createBinaryExpression(left, right, luaOperator, node);
}
export function createShortCircuitBinaryExpressionPrecedingStatements(
context: TransformationContext,
lhs: lua.Expression,
rhs: lua.Expression,
rightPrecedingStatements: lua.Statement[],
operator: ShortCircuitOperator,
node?: ts.BinaryExpression
): [lua.Statement[], lua.Expression] {
const conditionIdentifier = context.createTempNameForLuaExpression(lhs);
const assignmentStatement = lua.createVariableDeclarationStatement(conditionIdentifier, lhs, node?.left);
let condition: lua.Expression;
switch (operator) {
case ts.SyntaxKind.BarBarToken:
condition = lua.createUnaryExpression(
lua.cloneIdentifier(conditionIdentifier),
lua.SyntaxKind.NotOperator,
node
);
break;
case ts.SyntaxKind.AmpersandAmpersandToken:
condition = lua.cloneIdentifier(conditionIdentifier);
break;
case ts.SyntaxKind.QuestionQuestionToken:
condition = lua.createBinaryExpression(
lua.cloneIdentifier(conditionIdentifier),
lua.createNilLiteral(),
lua.SyntaxKind.EqualityOperator,
node
);
break;
}
const ifStatement = lua.createIfStatement(
condition,
lua.createBlock([...rightPrecedingStatements, lua.createAssignmentStatement(conditionIdentifier, rhs)]),
undefined,
node?.left
);
return [[assignmentStatement, ifStatement], conditionIdentifier];
}
function transformShortCircuitBinaryExpression(
context: TransformationContext,
node: ts.BinaryExpression,
operator: ShortCircuitOperator
): [lua.Statement[], lua.Expression] {
const lhs = context.transformExpression(node.left);
const [rightPrecedingStatements, rhs] = transformInPrecedingStatementScope(context, () =>
context.transformExpression(node.right)
);
return transformBinaryOperation(context, lhs, rhs, rightPrecedingStatements, operator, node);
}
export function transformBinaryOperation(
context: TransformationContext,
left: lua.Expression,
right: lua.Expression,
rightPrecedingStatements: lua.Statement[],
operator: BitOperator | SimpleOperator | ts.SyntaxKind.QuestionQuestionToken,
node: ts.Node
): [lua.Statement[], lua.Expression] {
if (rightPrecedingStatements.length > 0 && isShortCircuitOperator(operator)) {
assert(ts.isBinaryExpression(node));
return createShortCircuitBinaryExpressionPrecedingStatements(
context,
left,
right,
rightPrecedingStatements,
operator,
node
);
}
return [
rightPrecedingStatements,
transformBinaryOperationWithNoPrecedingStatements(context, left, right, operator, node),
];
}
export const transformBinaryExpression: FunctionVisitor<ts.BinaryExpression> = (node, context) => {
const operator = node.operatorToken.kind;
const typeOfResult = transformTypeOfBinaryExpression(context, node);
if (typeOfResult) {
return typeOfResult;
}
if (isCompoundAssignmentToken(operator)) {
const token = unwrapCompoundAssignmentToken(operator);
return transformCompoundAssignmentExpression(context, node, node.left, node.right, token, false);
}
switch (operator) {
case ts.SyntaxKind.EqualsToken:
return transformAssignmentExpression(context, node as ts.AssignmentExpression<ts.EqualsToken>);
case ts.SyntaxKind.InKeyword: {
const lhs = context.transformExpression(node.left);
const rhs = context.transformExpression(node.right);
const indexExpression = lua.createTableIndexExpression(rhs, lhs);
return lua.createBinaryExpression(
indexExpression,
lua.createNilLiteral(),
lua.SyntaxKind.InequalityOperator,
node
);
}
case ts.SyntaxKind.InstanceOfKeyword: {
const lhs = context.transformExpression(node.left);
const rhs = context.transformExpression(node.right);
const rhsType = context.checker.getTypeAtLocation(node.right);
if (isStandardLibraryType(context, rhsType, "ObjectConstructor")) {
return transformLuaLibFunction(context, LuaLibFeature.InstanceOfObject, node, lhs);
}
return transformLuaLibFunction(context, LuaLibFeature.InstanceOf, node, lhs, rhs);
}
case ts.SyntaxKind.CommaToken: {
const statements = context.transformStatements(ts.factory.createExpressionStatement(node.left));
const [precedingStatements, result] = transformInPrecedingStatementScope(context, () =>
context.transformExpression(node.right)
);
statements.push(...precedingStatements);
context.addPrecedingStatements(statements);
return result;
}
case ts.SyntaxKind.QuestionQuestionToken:
case ts.SyntaxKind.AmpersandAmpersandToken:
case ts.SyntaxKind.BarBarToken: {
const [precedingStatements, result] = transformShortCircuitBinaryExpression(context, node, operator);
context.addPrecedingStatements(precedingStatements);
return result;
}
}
let [precedingStatements, [lhs, rhs]] = transformInPrecedingStatementScope(context, () =>
transformOrderedExpressions(context, [node.left, node.right])
);
let result: lua.Expression;
[precedingStatements, result] = transformBinaryOperation(context, lhs, rhs, precedingStatements, operator, node);
context.addPrecedingStatements(precedingStatements);
return result;
};
export function transformBinaryExpressionStatement(
context: TransformationContext,
node: ts.ExpressionStatement
): lua.Statement[] | lua.Statement | undefined {
const expression = node.expression;
if (!ts.isBinaryExpression(expression)) return;
const operator = expression.operatorToken.kind;
if (isCompoundAssignmentToken(operator)) {
// +=, -=, etc...
const token = unwrapCompoundAssignmentToken(operator);
return transformCompoundAssignmentStatement(context, expression, expression.left, expression.right, token);
} else if (operator === ts.SyntaxKind.EqualsToken) {
return transformAssignmentStatement(context, expression as ts.AssignmentExpression<ts.EqualsToken>);
} else if (operator === ts.SyntaxKind.CommaToken) {
const statements = [
...context.transformStatements(ts.factory.createExpressionStatement(expression.left)),
...context.transformStatements(ts.factory.createExpressionStatement(expression.right)),
];
return lua.createDoStatement(statements, expression);
}
}
function transformNullishCoalescingOperationNoPrecedingStatements(
context: TransformationContext,
node: ts.BinaryExpression,
transformedLeft: lua.Expression,
transformedRight: lua.Expression
): lua.Expression {
const lhsType = context.checker.getTypeAtLocation(node.left);
// Check if we can take a shortcut to 'lhs or rhs' if the left-hand side cannot be 'false'.
if (canBeFalsyWhenNotNull(context, lhsType)) {
// reuse logic from case with preceding statements
const [precedingStatements, result] = createShortCircuitBinaryExpressionPrecedingStatements(
context,
transformedLeft,
transformedRight,
[],
ts.SyntaxKind.QuestionQuestionToken,
node
);
context.addPrecedingStatements(precedingStatements);
return result;
} else {
// lhs or rhs
return lua.createBinaryExpression(transformedLeft, transformedRight, lua.SyntaxKind.OrOperator, node);
}
} | the_stack |
import React, { Component, Dispatch } from 'react'
import ReactDOM from 'react-dom'
import { createStore } from 'redux'
import { Provider, connect, ReactReduxContext } from '../../src/index'
import * as rtl from '@testing-library/react'
import type { ReactReduxContextValue } from '../../src'
import type { Store } from 'redux'
import '@testing-library/jest-dom/extend-expect'
const createExampleTextReducer =
() =>
(state = 'example text') =>
state
describe('React', () => {
describe('Provider', () => {
afterEach(() => rtl.cleanup())
const createChild = (storeKey = 'store') => {
class Child extends Component {
render() {
return (
<ReactReduxContext.Consumer>
{(props) => {
let { store } = props as ReactReduxContextValue
let text = ''
if (store) {
text = store.getState().toString()
}
return (
<div data-testid="store">
{storeKey} - {text}
</div>
)
}}
</ReactReduxContext.Consumer>
)
}
}
return Child
}
const Child = createChild()
it('should not enforce a single child', () => {
const store = createStore(() => ({}))
const spy = jest.spyOn(console, 'error').mockImplementation(() => {})
expect(() =>
rtl.render(
<Provider store={store}>
<div />
</Provider>
)
).not.toThrow()
//@ts-expect-error
expect(() => rtl.render(<Provider store={store} />)).not.toThrow(
/children with exactly one child/
)
expect(() =>
rtl.render(
<Provider store={store}>
<div />
<div />
</Provider>
)
).not.toThrow(/a single React element child/)
spy.mockRestore()
})
it('should add the store to context', () => {
const store = createStore(createExampleTextReducer())
const spy = jest.spyOn(console, 'error').mockImplementation(() => {})
const tester = rtl.render(
<Provider store={store}>
<Child />
</Provider>
)
expect(spy).toHaveBeenCalledTimes(0)
spy.mockRestore()
expect(tester.getByTestId('store')).toHaveTextContent(
'store - example text'
)
})
it('accepts new store in props', () => {
const store1 = createStore((state: number = 10) => state + 1)
const store2 = createStore((state: number = 10) => state * 2)
const store3 = createStore((state: number = 10) => state * state + 1)
interface StateType {
store: Store
}
let externalSetState: Dispatch<StateType>
class ProviderContainer extends Component<unknown, StateType> {
constructor(props: {}) {
super(props)
this.state = { store: store1 }
externalSetState = this.setState.bind(this)
}
render() {
return (
<Provider store={this.state.store}>
<Child />
</Provider>
)
}
}
const tester = rtl.render(<ProviderContainer />)
expect(tester.getByTestId('store')).toHaveTextContent('store - 11')
rtl.act(() => {
externalSetState({ store: store2 })
})
expect(tester.getByTestId('store')).toHaveTextContent('store - 20')
rtl.act(() => {
store1.dispatch({ type: 'hi' })
})
expect(tester.getByTestId('store')).toHaveTextContent('store - 20')
rtl.act(() => {
store2.dispatch({ type: 'hi' })
})
expect(tester.getByTestId('store')).toHaveTextContent('store - 20')
rtl.act(() => {
externalSetState({ store: store3 })
})
expect(tester.getByTestId('store')).toHaveTextContent('store - 101')
rtl.act(() => {
store1.dispatch({ type: 'hi' })
})
expect(tester.getByTestId('store')).toHaveTextContent('store - 101')
rtl.act(() => {
store2.dispatch({ type: 'hi' })
})
expect(tester.getByTestId('store')).toHaveTextContent('store - 101')
rtl.act(() => {
store3.dispatch({ type: 'hi' })
})
expect(tester.getByTestId('store')).toHaveTextContent('store - 101')
})
it('should handle subscriptions correctly when there is nested Providers', () => {
interface ActionType {
type: string
}
interface TStateProps {
count: number
}
const reducer = (state = 0, action: ActionType) =>
action.type === 'INC' ? state + 1 : state
const innerStore = createStore(reducer)
const innerMapStateToProps = jest.fn<TStateProps, [number]>((state) => ({
count: state,
}))
class Inner extends Component<TStateProps> {
render(): JSX.Element {
return <div>{this.props.count}</div>
}
}
const WrapperInner = connect<TStateProps, unknown, unknown, number>(
innerMapStateToProps
)(Inner)
const outerStore = createStore(reducer)
class Outer extends Component {
render() {
return (
<Provider store={innerStore}>
<WrapperInner />
</Provider>
)
}
}
const WrapperOuter = connect<TStateProps, unknown, unknown, number>(
(state) => ({ count: state })
)(Outer)
rtl.render(
<Provider store={outerStore}>
<WrapperOuter />
</Provider>
)
expect(innerMapStateToProps).toHaveBeenCalledTimes(1)
rtl.act(() => {
innerStore.dispatch({ type: 'INC' })
})
expect(innerMapStateToProps).toHaveBeenCalledTimes(2)
})
it('should pass state consistently to mapState', () => {
interface ActionType {
type: string
body: string
}
function stringBuilder(prev = '', action: ActionType) {
return action.type === 'APPEND' ? prev + action.body : prev
}
const store: Store = createStore(stringBuilder)
rtl.act(() => {
store.dispatch({ type: 'APPEND', body: 'a' })
})
let childMapStateInvokes = 0
const childCalls: Array<Array<string>> = []
interface ChildContainerProps {
parentState: string
}
class ChildContainer extends Component<ChildContainerProps> {
render() {
return <div />
}
}
const WrapperChildrenContainer = connect<
{},
unknown,
ChildContainerProps,
string
>((state, parentProps) => {
childMapStateInvokes++
childCalls.push([state, parentProps.parentState])
// The state from parent props should always be consistent with the current state
return {}
})(ChildContainer)
interface TStateProps {
state: string
}
class Container extends Component<TStateProps> {
emitChange() {
store.dispatch({ type: 'APPEND', body: 'b' })
}
render() {
return (
<div>
<button onClick={this.emitChange.bind(this)}>change</button>
<WrapperChildrenContainer parentState={this.props.state} />
</div>
)
}
}
const WrapperContainer = connect<TStateProps, unknown, unknown, string>(
(state) => ({ state })
)(Container)
const tester = rtl.render(
<Provider store={store}>
<WrapperContainer />
</Provider>
)
expect(childMapStateInvokes).toBe(1)
// The store state stays consistent when setState calls are batched
rtl.act(() => {
store.dispatch({ type: 'APPEND', body: 'c' })
})
expect(childMapStateInvokes).toBe(2)
expect(childCalls).toEqual([
['a', 'a'],
['ac', 'ac'],
])
// setState calls DOM handlers are batched
const button = tester.getByText('change')
rtl.fireEvent.click(button)
expect(childMapStateInvokes).toBe(3)
// Provider uses unstable_batchedUpdates() under the hood
rtl.act(() => {
store.dispatch({ type: 'APPEND', body: 'd' })
})
expect(childCalls).toEqual([
['a', 'a'],
['ac', 'ac'], // then store update is processed
['acb', 'acb'], // then store update is processed
['acbd', 'acbd'], // then store update is processed
])
expect(childMapStateInvokes).toBe(4)
})
it('works in <StrictMode> without warnings (React 16.3+)', () => {
if (!React.StrictMode) {
return
}
const spy = jest.spyOn(console, 'error').mockImplementation(() => {})
const store = createStore(() => ({}))
rtl.render(
<React.StrictMode>
<Provider store={store}>
<div />
</Provider>
</React.StrictMode>
)
expect(spy).not.toHaveBeenCalled()
})
it('should unsubscribe before unmounting', () => {
const store = createStore(createExampleTextReducer())
const subscribe = store.subscribe
// Keep track of unsubscribe by wrapping subscribe()
const spy = jest.fn(() => ({}))
store.subscribe = (listener) => {
const unsubscribe = subscribe(listener)
return () => {
spy()
return unsubscribe()
}
}
const div = document.createElement('div')
ReactDOM.render(
<Provider store={store}>
<div />
</Provider>,
div
)
expect(spy).toHaveBeenCalledTimes(0)
ReactDOM.unmountComponentAtNode(div)
expect(spy).toHaveBeenCalledTimes(1)
})
it('should handle store and children change in a the same render', () => {
interface PropsType {
value: string
}
interface StateType {
nestedA: PropsType
nestedB: PropsType
}
const reducerA = (state = { nestedA: { value: 'expectedA' } }) => state
const reducerB = (state = { nestedB: { value: 'expectedB' } }) => state
const storeA = createStore(reducerA)
const storeB = createStore(reducerB)
class ComponentA extends Component<PropsType> {
render() {
return <div data-testid="value">{this.props.value}</div>
}
}
const WrapperComponentA = connect<PropsType, unknown, unknown, StateType>(
(state) => ({
value: state.nestedA.value,
})
)(ComponentA)
class ComponentB extends Component<PropsType> {
render() {
return <div data-testid="value">{this.props.value}</div>
}
}
const WrapperComponentB = connect<PropsType, unknown, unknown, StateType>(
(state) => ({ value: state.nestedB.value })
)(ComponentB)
const { getByTestId, rerender } = rtl.render(
<Provider store={storeA}>
<WrapperComponentA />
</Provider>
)
expect(getByTestId('value')).toHaveTextContent('expectedA')
rerender(
<Provider store={storeB}>
<WrapperComponentB />
</Provider>
)
expect(getByTestId('value')).toHaveTextContent('expectedB')
})
})
}) | the_stack |
import {
CidrBlock,
cidrMask,
cidrCountIps,
cidrSubnets,
IpSet,
} from "./cidrtools";
interface SubnetRoute {
size: "s"|"m"|"l";
}
const route_size_mask_diff = {
"s": 1,
"m": 0,
"l": -1,
};
export type SubnetRoutes = { [index: string]: SubnetRoute };
interface RegionConfig {
region: string;
zone_count: number;
}
export type RegionsConfig = { [index: string]: RegionConfig };
class FreeCidr extends CidrBlock {
constructor(cidr: string) {
super(cidr);
}
toJSON(): object {
return {
cidr: this.cidr,
};
}
}
/**
* 2 -> 2
* 3 -> 2
* 4 -> 3
*/
const log2ceil = (x: number): number => Math.ceil(Math.log2(x+1));
/**
* number of cidr mask bits inorder to represent given number of subnets + one
* extra reserved spott
*
* 2 bits equals to 4 spots, which means we can have 1 reserved spot and less
* than 4 subnets
*
* 3 bits equals to 9 spots, which means we can have 1 reserved spot and less
* than 9 subnets
*/
const count2CidrMaskBits = log2ceil;
export class Subnet extends CidrBlock {
provider: string;
name: string;
zone: string;
constructor(
provider: string, cidr: string, name: string, zone: string,
) {
super(cidr);
this.provider = provider;
this.name = name;
this.zone = zone;
switch (provider) {
case "aws": {
// From AWS doc: The first 4 IP addresses and the last IP
// address in each subnet // CIDR block are not available for you
// to use and cannot be assigned // to an instance.
this.ip_count -= 5;
break;
}
}
}
toJSON(): object {
return {
name: this.name,
cidr: this.cidr,
};
}
}
interface ZonePlanResult {
subnets: Subnet[];
freeCidrs: FreeCidr[];
}
function planZone(
provider: string, cidr: string, subnet_routes: SubnetRoutes, zone: string,
): ZonePlanResult {
const routes = [];
for (const route_name in subnet_routes) {
routes.push({
name: route_name,
size_mask_diff: route_size_mask_diff[subnet_routes[route_name].size],
});
}
const sorted_routes = routes.sort((x, y) => x.size_mask_diff - y.size_mask_diff);
const subnet_cnt = sorted_routes.length;
const subnet_mask = cidrMask(cidr) + count2CidrMaskBits(subnet_cnt);
const avail_ipset = new IpSet([cidr]);
const subnets = [];
const freeCidrs = [];
for (const route of sorted_routes) {
const subnet_cidr = avail_ipset.nextCidr(subnet_mask + route.size_mask_diff);
avail_ipset.subtract(subnet_cidr);
subnets.push(new Subnet(
provider,
subnet_cidr,
route.name,
zone,
));
if (avail_ipset.ipCount() == 0) {
break;
}
}
for (const avail_cidr of avail_ipset.getCidrs()) {
freeCidrs.push(new FreeCidr(avail_cidr));
}
return {
subnets: subnets,
freeCidrs: freeCidrs,
};
}
export class Zone extends CidrBlock {
// input
provider: string;
subnet_routes: SubnetRoutes;
name: string;
zone: string;
// output
subnets: Subnet[];
freeCidrs: FreeCidr[];
constructor(
provider: string, cidr: string, subnet_routes: SubnetRoutes, name: string | null = null, zone: string,
) {
super(cidr);
this.subnet_routes = subnet_routes;
if (name !== null) {
this.name = name;
} else {
this.name = "unnamed";
}
this.zone = zone;
this.provider = provider;
const re = planZone(provider, cidr, subnet_routes, this.zone);
this.subnets = re.subnets;
this.freeCidrs = re.freeCidrs;
}
toJSON(): object {
const zone = {
name: this.name,
zone: this.zone,
cidr: this.cidr,
subnets: [] as object[],
reserved_cidrs: [] as object[],
};
for (const subnet of this.subnets) {
zone.subnets.push(subnet.toJSON());
}
for (const freecidr of this.freeCidrs) {
zone.reserved_cidrs.push(freecidr.toJSON());
}
return zone
}
}
interface VPCPlanResult {
zones: Zone[];
freeCidrs: FreeCidr[];
}
function planVPC(provider: string, cidr: string, region: string, zone_count: number, subnet_routes: SubnetRoutes): VPCPlanResult {
const zone_mask = cidrMask(cidr) + count2CidrMaskBits(zone_count);
const zones = [];
const freeCidrs = [];
let idx = 0;
for (const zone_cidr of cidrSubnets(cidr, zone_mask)) {
if (idx >= zone_count) {
freeCidrs.push(new FreeCidr(zone_cidr));
} else {
const zone_suffix = String.fromCharCode(97+idx);
zones.push(new Zone(
provider,
zone_cidr,
subnet_routes,
zone_suffix,
`${region}${zone_suffix}`,
));
}
idx += 1;
}
return {
zones: zones,
freeCidrs: freeCidrs,
};
}
export class VPC extends CidrBlock {
// input
provider: string;
subnet_routes: SubnetRoutes;
zone_count: number;
name: string;
region: string;
// output
zones: Zone[];
freeCidrs: FreeCidr[];
constructor(
provider: string,
cidr: string,
region: string,
zone_count: number,
subnet_routes: SubnetRoutes,
name: string | null = null,
) {
super(cidr);
this.zone_count = zone_count;
this.subnet_routes = subnet_routes;
this.region = region;
this.provider = provider;
if (name === null) {
this.name = "unnamed";
} else {
this.name = name;
}
const re = planVPC(provider, cidr, region, zone_count, subnet_routes);
this.zones = re.zones;
this.freeCidrs = re.freeCidrs;
}
toJSON(): object {
const vpc = {
name: this.name,
region: this.region,
cidr: this.cidr,
zones: [] as object[],
reserved_cidrs: [] as object[],
};
for (const zone of this.zones) {
vpc.zones.push(zone.toJSON());
}
for (const freecidr of this.freeCidrs) {
vpc.reserved_cidrs.push(freecidr.toJSON());
}
return vpc;
}
}
interface ClusterPlanResult {
vpcs: VPC[];
freeCidrs: FreeCidr[];
}
function planCluster(provider: string, cidr: string, regions: RegionsConfig, subnet_routes: SubnetRoutes): ClusterPlanResult {
const region_names = Object.keys(regions);
const region_cnt = region_names.length;
const vpcs = [];
const freeCidrs = [];
let region_mask = cidrMask(cidr) + count2CidrMaskBits(region_cnt);
if (provider == "aws") {
// AWS enforces max VPC size of /16 (65536 IPs)
region_mask = Math.max(region_mask, 16);
}
let idx = 0;
const region_cidrs = cidrSubnets(cidr, region_mask);
for (const region_cidr of region_cidrs) {
if (idx >= region_cnt) {
freeCidrs.push(new FreeCidr(region_cidr));
} else {
const vpc_name = region_names[idx];
vpcs.push(new VPC(
provider,
region_cidr,
regions[vpc_name].region,
regions[vpc_name].zone_count,
subnet_routes,
vpc_name,
));
}
idx += 1;
}
return {
vpcs: vpcs,
freeCidrs: freeCidrs,
};
}
export class Cluster {
// input
cidr: string;
regions: RegionsConfig;
subnet_routes: SubnetRoutes;
provider: string;
// output
ip_count: number;
vpcs: VPC[];
freeCidrs: FreeCidr[];
constructor(
provider: string, cidr: string, regions: RegionsConfig, subnet_routes: SubnetRoutes,
) {
this.cidr = cidr;
this.regions = regions;
this.subnet_routes = subnet_routes;
this.provider = provider;
this.ip_count = cidrCountIps(cidr);
const re = planCluster(provider, cidr, regions, subnet_routes);
this.vpcs = re.vpcs;
this.freeCidrs = re.freeCidrs;
}
}
export function AssertValidRoute(
cidr: string, region_count: number, zone_count: number, routes: SubnetRoutes,
): string | null {
// Allocate CIDR ranges using a balanced binary tree
//
// Let total_units = 2^log2ceil(subnet_count) * 2
// constraints:
// l_unit = 4
// m_unit = 2
// s_unit = 1
//
// l_count <= total_units / 4 - 1
// m_count <= total_units / 2 - 4 * l_count - 1
// s_count <= total_units - 2 * m_count - 4 * l_count - 1
//
// Tree view:
//
// L
// M M
// S S S S
const cidr_mask = cidrMask(cidr);
const avail_cidr_mask_bits = 32 - cidr_mask - count2CidrMaskBits(region_count) - count2CidrMaskBits(zone_count);
if (avail_cidr_mask_bits <= 0) {
return "Given CIDR is too small to meet region and zone requirements.";
}
const subnet_route_count = Object.keys(routes).length;
const subnet_cidr_mask_bits = count2CidrMaskBits(subnet_route_count);
const total_units = Math.pow(2, subnet_cidr_mask_bits) * 2;
let avail_units = total_units;
for (const route_name in routes) {
const size = routes[route_name].size;
switch (size) {
case "l": {
avail_units -= 4;
break;
}
case "m": {
avail_units -= 2;
break;
}
case "s": {
avail_units -= 1;
break;
}
default: {
return `invalid size "${size}" for route: ${route_name}`
}
}
if (avail_units <= 0) {
// avail_units == 0 means we don't have space for reserved cidr range
return "Invalid route size configuration, sum of all route size is too large.";
}
}
return null
} | the_stack |
import {
checkAndValidateADR36AminoSignDoc,
makeADR36AminoSignDoc,
verifyADR36Amino,
verifyADR36AminoSignDoc,
} from "./amino";
import { serializeSignDoc } from "@cosmjs/launchpad";
import { PrivKeySecp256k1 } from "@keplr-wallet/crypto";
import { Bech32Address } from "../bech32";
describe("Test ADR-36 Amino Sign Doc", () => {
it("Check not ADR-36 Amino sign doc", () => {
expect(
checkAndValidateADR36AminoSignDoc({
chain_id: "osmosis-1",
account_number: "4287",
sequence: "377",
fee: {
gas: "80000",
amount: [
{
denom: "uosmo",
amount: "0",
},
],
},
msgs: [
{
type: "cosmos-sdk/MsgSend",
value: {
from_address: "osmo1ymk637a7wljvt4w7q9lnrw95mg9sr37yatxd9h",
to_address: "osmo1ymk637a7wljvt4w7q9lnrw95mg9sr37yatxd9h",
amount: [
{
denom: "uosmo",
amount: "1000000",
},
],
},
},
],
memo: "",
})
).toBe(false);
expect(
checkAndValidateADR36AminoSignDoc({
chain_id: "osmosis-1",
account_number: "4287",
sequence: "377",
fee: {
gas: "80000",
amount: [
{
denom: "uosmo",
amount: "0",
},
],
},
msgs: [],
memo: "",
})
).toBe(false);
expect(
checkAndValidateADR36AminoSignDoc({
chain_id: "osmosis-1",
account_number: "4287",
sequence: "377",
fee: {
gas: "80000",
amount: [
{
denom: "uosmo",
amount: "0",
},
],
},
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
msgs: {},
memo: "",
})
).toBe(false);
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
expect(checkAndValidateADR36AminoSignDoc({})).toBe(false);
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
expect(checkAndValidateADR36AminoSignDoc(undefined)).toBe(false);
});
it("Check valid ADR-36 Amino sign doc", () => {
// Without bech32 prefix
expect(
checkAndValidateADR36AminoSignDoc({
chain_id: "",
account_number: "0",
sequence: "0",
fee: {
gas: "0",
amount: [],
},
msgs: [
{
type: "sign/MsgSignData",
value: {
signer: "osmo1ymk637a7wljvt4w7q9lnrw95mg9sr37yatxd9h",
data: "cmFuZG9t",
},
},
],
memo: "",
})
).toBe(true);
// With bech32 prefix
expect(
checkAndValidateADR36AminoSignDoc(
{
chain_id: "",
account_number: "0",
sequence: "0",
fee: {
gas: "0",
amount: [],
},
msgs: [
{
type: "sign/MsgSignData",
value: {
signer: "osmo1ymk637a7wljvt4w7q9lnrw95mg9sr37yatxd9h",
data: "cmFuZG9t",
},
},
],
memo: "",
},
"osmo"
)
).toBe(true);
// With invalid bech32 prefix
expect(() =>
checkAndValidateADR36AminoSignDoc(
{
chain_id: "",
account_number: "0",
sequence: "0",
fee: {
gas: "0",
amount: [],
},
msgs: [
{
type: "sign/MsgSignData",
value: {
signer: "osmo1ymk637a7wljvt4w7q9lnrw95mg9sr37yatxd9h",
data: "cmFuZG9t",
},
},
],
memo: "",
},
"cosmos"
)
).toThrow();
});
it("Check invalid ADR-36 Amino sign doc", () => {
// Chain id should be empty string
expect(() =>
checkAndValidateADR36AminoSignDoc({
chain_id: "haha",
account_number: "0",
sequence: "0",
fee: {
gas: "0",
amount: [],
},
msgs: [
{
type: "sign/MsgSignData",
value: {
signer: "osmo1ymk637a7wljvt4w7q9lnrw95mg9sr37yatxd9h",
data: "cmFuZG9t",
},
},
],
memo: "",
})
).toThrow();
// Account number should be "0"
expect(() =>
checkAndValidateADR36AminoSignDoc({
chain_id: "",
account_number: "1",
sequence: "0",
fee: {
gas: "0",
amount: [],
},
msgs: [
{
type: "sign/MsgSignData",
value: {
signer: "osmo1ymk637a7wljvt4w7q9lnrw95mg9sr37yatxd9h",
data: "cmFuZG9t",
},
},
],
memo: "",
})
).toThrow();
// Sequence should be "0"
expect(() =>
checkAndValidateADR36AminoSignDoc({
chain_id: "",
account_number: "0",
sequence: "1",
fee: {
gas: "0",
amount: [],
},
msgs: [
{
type: "sign/MsgSignData",
value: {
signer: "osmo1ymk637a7wljvt4w7q9lnrw95mg9sr37yatxd9h",
data: "cmFuZG9t",
},
},
],
memo: "",
})
).toThrow();
// Gas should be "0"
expect(() =>
checkAndValidateADR36AminoSignDoc({
chain_id: "",
account_number: "0",
sequence: "0",
fee: {
gas: "1",
amount: [],
},
msgs: [
{
type: "sign/MsgSignData",
value: {
signer: "osmo1ymk637a7wljvt4w7q9lnrw95mg9sr37yatxd9h",
data: "cmFuZG9t",
},
},
],
memo: "",
})
).toThrow();
// Amount should be empty string
expect(() =>
checkAndValidateADR36AminoSignDoc({
chain_id: "",
account_number: "0",
sequence: "0",
fee: {
gas: "0",
amount: [
{
denom: "haha",
amount: "1",
},
],
},
msgs: [
{
type: "sign/MsgSignData",
value: {
signer: "osmo1ymk637a7wljvt4w7q9lnrw95mg9sr37yatxd9h",
data: "cmFuZG9t",
},
},
],
memo: "",
})
).toThrow();
// Memo should be empty string
expect(() =>
checkAndValidateADR36AminoSignDoc({
chain_id: "",
account_number: "0",
sequence: "0",
fee: {
gas: "0",
amount: [],
},
msgs: [
{
type: "sign/MsgSignData",
value: {
signer: "osmo1ymk637a7wljvt4w7q9lnrw95mg9sr37yatxd9h",
data: "cmFuZG9t",
},
},
],
memo: "1",
})
).toThrow();
// Should be value
expect(() =>
checkAndValidateADR36AminoSignDoc({
chain_id: "",
account_number: "0",
sequence: "0",
fee: {
gas: "0",
amount: [],
},
msgs: [
{
type: "sign/MsgSignData",
},
],
memo: "",
} as any)
).toThrow();
// Value should have signer
expect(() =>
checkAndValidateADR36AminoSignDoc({
chain_id: "",
account_number: "0",
sequence: "0",
fee: {
gas: "0",
amount: [],
},
msgs: [
{
type: "sign/MsgSignData",
value: {
data: "cmFuZG9t",
},
},
],
memo: "",
})
).toThrow();
// Value should have valid signer
expect(() =>
checkAndValidateADR36AminoSignDoc({
chain_id: "",
account_number: "0",
sequence: "0",
fee: {
gas: "0",
amount: [],
},
msgs: [
{
type: "sign/MsgSignData",
value: {
signer: "invalid1ymk637a7wljvt4w7q9lnrw95mg9sr37yatxd9h",
data: "cmFuZG9t",
},
},
],
memo: "",
})
).toThrow();
// Value should be data
expect(() =>
checkAndValidateADR36AminoSignDoc({
chain_id: "",
account_number: "0",
sequence: "0",
fee: {
gas: "0",
amount: [],
},
msgs: [
{
type: "sign/MsgSignData",
value: {
signer: "osmo1ymk637a7wljvt4w7q9lnrw95mg9sr37yatxd9h",
},
},
],
memo: "",
})
).toThrow();
// Value should be base64 encoded data
expect(() =>
checkAndValidateADR36AminoSignDoc({
chain_id: "",
account_number: "0",
sequence: "0",
fee: {
gas: "0",
amount: [],
},
msgs: [
{
type: "sign/MsgSignData",
value: {
signer: "osmo1ymk637a7wljvt4w7q9lnrw95mg9sr37yatxd9h",
data: "sc12v",
},
},
],
memo: "",
})
).toThrow();
// Value should not have the empty data
expect(() =>
checkAndValidateADR36AminoSignDoc({
chain_id: "",
account_number: "0",
sequence: "0",
fee: {
gas: "0",
amount: [],
},
msgs: [
{
type: "sign/MsgSignData",
value: {
signer: "osmo1ymk637a7wljvt4w7q9lnrw95mg9sr37yatxd9h",
data: "",
},
},
],
memo: "",
})
).toThrow();
});
it("Make ADR-36 Amino sign doc and validate", () => {
let signDoc = makeADR36AminoSignDoc(
"osmo1ymk637a7wljvt4w7q9lnrw95mg9sr37yatxd9h",
new Uint8Array([1, 2, 3])
);
expect(signDoc.msgs[0].type).toBe("sign/MsgSignData");
expect(signDoc.msgs[0].value.signer).toBe(
"osmo1ymk637a7wljvt4w7q9lnrw95mg9sr37yatxd9h"
);
expect(signDoc.msgs[0].value.data).toBe(
Buffer.from([1, 2, 3]).toString("base64")
);
expect(checkAndValidateADR36AminoSignDoc(signDoc)).toBe(true);
signDoc = makeADR36AminoSignDoc(
"osmo1ymk637a7wljvt4w7q9lnrw95mg9sr37yatxd9h",
"test"
);
expect(signDoc.msgs[0].type).toBe("sign/MsgSignData");
expect(signDoc.msgs[0].value.signer).toBe(
"osmo1ymk637a7wljvt4w7q9lnrw95mg9sr37yatxd9h"
);
expect(signDoc.msgs[0].value.data).toBe(
Buffer.from("test").toString("base64")
);
expect(checkAndValidateADR36AminoSignDoc(signDoc)).toBe(true);
});
it("Verify ADR-36 Amino sign doc", () => {
const privKey = PrivKeySecp256k1.generateRandomKey();
const pubKey = privKey.getPubKey();
const signer = new Bech32Address(pubKey.getAddress()).toBech32("osmo");
const signDoc = makeADR36AminoSignDoc(signer, new Uint8Array([1, 2, 3]));
const msg = serializeSignDoc(signDoc);
const signature = privKey.sign(msg);
expect(
verifyADR36AminoSignDoc("osmo", signDoc, pubKey.toBytes(), signature)
).toBe(true);
expect(() =>
verifyADR36AminoSignDoc(
"osmo",
// Sign doc is not for ADR-36
{
chain_id: "osmosis-1",
account_number: "4287",
sequence: "377",
fee: {
gas: "80000",
amount: [
{
denom: "uosmo",
amount: "0",
},
],
},
msgs: [
{
type: "cosmos-sdk/MsgSend",
value: {
from_address: "osmo1ymk637a7wljvt4w7q9lnrw95mg9sr37yatxd9h",
to_address: "osmo1ymk637a7wljvt4w7q9lnrw95mg9sr37yatxd9h",
amount: [
{
denom: "uosmo",
amount: "1000000",
},
],
},
},
],
memo: "",
},
pubKey.toBytes(),
signature
)
).toThrow();
expect(
verifyADR36Amino(
"osmo",
signer,
new Uint8Array([1, 2, 3]),
pubKey.toBytes(),
signature
)
).toBe(true);
expect(() =>
verifyADR36Amino(
"osmo",
// Unmatched signer
"osmo1ymk637a7wljvt4w7q9lnrw95mg9sr37yatxd9h",
new Uint8Array([1, 2, 3]),
pubKey.toBytes(),
signature
)
).toThrow();
expect(() =>
verifyADR36Amino(
"osmo",
// Invalid signer
"invalid1ymk637a7wljvt4w7q9lnrw95mg9sr37yatxd9h",
new Uint8Array([1, 2, 3]),
pubKey.toBytes(),
signature
)
).toThrow();
expect(
verifyADR36AminoSignDoc(
"osmo",
signDoc,
pubKey.toBytes(),
signature.slice().filter((b) => (Math.random() > 0.5 ? 0 : b))
)
).toBe(false);
expect(
verifyADR36Amino(
"osmo",
signer,
new Uint8Array([1, 2]),
pubKey.toBytes(),
signature
)
).toBe(false);
});
}); | the_stack |
import * as msRest from "@azure/ms-rest-js";
import * as Models from "../models";
import * as Mappers from "../models/policyEventsMappers";
import * as Parameters from "../models/parameters";
import { PolicyInsightsClientContext } from "../policyInsightsClientContext";
/** Class representing a PolicyEvents. */
export class PolicyEvents {
private readonly client: PolicyInsightsClientContext;
/**
* Create a PolicyEvents.
* @param {PolicyInsightsClientContext} client Reference to the service client.
*/
constructor(client: PolicyInsightsClientContext) {
this.client = client;
}
/**
* Queries policy events for the resources under the management group.
* @param managementGroupName Management group name.
* @param [options] The optional parameters
* @returns Promise<Models.PolicyEventsListQueryResultsForManagementGroupResponse>
*/
listQueryResultsForManagementGroup(managementGroupName: string, options?: Models.PolicyEventsListQueryResultsForManagementGroupOptionalParams): Promise<Models.PolicyEventsListQueryResultsForManagementGroupResponse>;
/**
* @param managementGroupName Management group name.
* @param callback The callback
*/
listQueryResultsForManagementGroup(managementGroupName: string, callback: msRest.ServiceCallback<Models.PolicyEventsQueryResults>): void;
/**
* @param managementGroupName Management group name.
* @param options The optional parameters
* @param callback The callback
*/
listQueryResultsForManagementGroup(managementGroupName: string, options: Models.PolicyEventsListQueryResultsForManagementGroupOptionalParams, callback: msRest.ServiceCallback<Models.PolicyEventsQueryResults>): void;
listQueryResultsForManagementGroup(managementGroupName: string, options?: Models.PolicyEventsListQueryResultsForManagementGroupOptionalParams | msRest.ServiceCallback<Models.PolicyEventsQueryResults>, callback?: msRest.ServiceCallback<Models.PolicyEventsQueryResults>): Promise<Models.PolicyEventsListQueryResultsForManagementGroupResponse> {
return this.client.sendOperationRequest(
{
managementGroupName,
options
},
listQueryResultsForManagementGroupOperationSpec,
callback) as Promise<Models.PolicyEventsListQueryResultsForManagementGroupResponse>;
}
/**
* Queries policy events for the resources under the subscription.
* @param subscriptionId Microsoft Azure subscription ID.
* @param [options] The optional parameters
* @returns Promise<Models.PolicyEventsListQueryResultsForSubscriptionResponse>
*/
listQueryResultsForSubscription(subscriptionId: string, options?: Models.PolicyEventsListQueryResultsForSubscriptionOptionalParams): Promise<Models.PolicyEventsListQueryResultsForSubscriptionResponse>;
/**
* @param subscriptionId Microsoft Azure subscription ID.
* @param callback The callback
*/
listQueryResultsForSubscription(subscriptionId: string, callback: msRest.ServiceCallback<Models.PolicyEventsQueryResults>): void;
/**
* @param subscriptionId Microsoft Azure subscription ID.
* @param options The optional parameters
* @param callback The callback
*/
listQueryResultsForSubscription(subscriptionId: string, options: Models.PolicyEventsListQueryResultsForSubscriptionOptionalParams, callback: msRest.ServiceCallback<Models.PolicyEventsQueryResults>): void;
listQueryResultsForSubscription(subscriptionId: string, options?: Models.PolicyEventsListQueryResultsForSubscriptionOptionalParams | msRest.ServiceCallback<Models.PolicyEventsQueryResults>, callback?: msRest.ServiceCallback<Models.PolicyEventsQueryResults>): Promise<Models.PolicyEventsListQueryResultsForSubscriptionResponse> {
return this.client.sendOperationRequest(
{
subscriptionId,
options
},
listQueryResultsForSubscriptionOperationSpec,
callback) as Promise<Models.PolicyEventsListQueryResultsForSubscriptionResponse>;
}
/**
* Queries policy events for the resources under the resource group.
* @param subscriptionId Microsoft Azure subscription ID.
* @param resourceGroupName Resource group name.
* @param [options] The optional parameters
* @returns Promise<Models.PolicyEventsListQueryResultsForResourceGroupResponse>
*/
listQueryResultsForResourceGroup(subscriptionId: string, resourceGroupName: string, options?: Models.PolicyEventsListQueryResultsForResourceGroupOptionalParams): Promise<Models.PolicyEventsListQueryResultsForResourceGroupResponse>;
/**
* @param subscriptionId Microsoft Azure subscription ID.
* @param resourceGroupName Resource group name.
* @param callback The callback
*/
listQueryResultsForResourceGroup(subscriptionId: string, resourceGroupName: string, callback: msRest.ServiceCallback<Models.PolicyEventsQueryResults>): void;
/**
* @param subscriptionId Microsoft Azure subscription ID.
* @param resourceGroupName Resource group name.
* @param options The optional parameters
* @param callback The callback
*/
listQueryResultsForResourceGroup(subscriptionId: string, resourceGroupName: string, options: Models.PolicyEventsListQueryResultsForResourceGroupOptionalParams, callback: msRest.ServiceCallback<Models.PolicyEventsQueryResults>): void;
listQueryResultsForResourceGroup(subscriptionId: string, resourceGroupName: string, options?: Models.PolicyEventsListQueryResultsForResourceGroupOptionalParams | msRest.ServiceCallback<Models.PolicyEventsQueryResults>, callback?: msRest.ServiceCallback<Models.PolicyEventsQueryResults>): Promise<Models.PolicyEventsListQueryResultsForResourceGroupResponse> {
return this.client.sendOperationRequest(
{
subscriptionId,
resourceGroupName,
options
},
listQueryResultsForResourceGroupOperationSpec,
callback) as Promise<Models.PolicyEventsListQueryResultsForResourceGroupResponse>;
}
/**
* Queries policy events for the resource.
* @param resourceId Resource ID.
* @param [options] The optional parameters
* @returns Promise<Models.PolicyEventsListQueryResultsForResourceResponse>
*/
listQueryResultsForResource(resourceId: string, options?: Models.PolicyEventsListQueryResultsForResourceOptionalParams): Promise<Models.PolicyEventsListQueryResultsForResourceResponse>;
/**
* @param resourceId Resource ID.
* @param callback The callback
*/
listQueryResultsForResource(resourceId: string, callback: msRest.ServiceCallback<Models.PolicyEventsQueryResults>): void;
/**
* @param resourceId Resource ID.
* @param options The optional parameters
* @param callback The callback
*/
listQueryResultsForResource(resourceId: string, options: Models.PolicyEventsListQueryResultsForResourceOptionalParams, callback: msRest.ServiceCallback<Models.PolicyEventsQueryResults>): void;
listQueryResultsForResource(resourceId: string, options?: Models.PolicyEventsListQueryResultsForResourceOptionalParams | msRest.ServiceCallback<Models.PolicyEventsQueryResults>, callback?: msRest.ServiceCallback<Models.PolicyEventsQueryResults>): Promise<Models.PolicyEventsListQueryResultsForResourceResponse> {
return this.client.sendOperationRequest(
{
resourceId,
options
},
listQueryResultsForResourceOperationSpec,
callback) as Promise<Models.PolicyEventsListQueryResultsForResourceResponse>;
}
/**
* Queries policy events for the subscription level policy set definition.
* @param subscriptionId Microsoft Azure subscription ID.
* @param policySetDefinitionName Policy set definition name.
* @param [options] The optional parameters
* @returns Promise<Models.PolicyEventsListQueryResultsForPolicySetDefinitionResponse>
*/
listQueryResultsForPolicySetDefinition(subscriptionId: string, policySetDefinitionName: string, options?: Models.PolicyEventsListQueryResultsForPolicySetDefinitionOptionalParams): Promise<Models.PolicyEventsListQueryResultsForPolicySetDefinitionResponse>;
/**
* @param subscriptionId Microsoft Azure subscription ID.
* @param policySetDefinitionName Policy set definition name.
* @param callback The callback
*/
listQueryResultsForPolicySetDefinition(subscriptionId: string, policySetDefinitionName: string, callback: msRest.ServiceCallback<Models.PolicyEventsQueryResults>): void;
/**
* @param subscriptionId Microsoft Azure subscription ID.
* @param policySetDefinitionName Policy set definition name.
* @param options The optional parameters
* @param callback The callback
*/
listQueryResultsForPolicySetDefinition(subscriptionId: string, policySetDefinitionName: string, options: Models.PolicyEventsListQueryResultsForPolicySetDefinitionOptionalParams, callback: msRest.ServiceCallback<Models.PolicyEventsQueryResults>): void;
listQueryResultsForPolicySetDefinition(subscriptionId: string, policySetDefinitionName: string, options?: Models.PolicyEventsListQueryResultsForPolicySetDefinitionOptionalParams | msRest.ServiceCallback<Models.PolicyEventsQueryResults>, callback?: msRest.ServiceCallback<Models.PolicyEventsQueryResults>): Promise<Models.PolicyEventsListQueryResultsForPolicySetDefinitionResponse> {
return this.client.sendOperationRequest(
{
subscriptionId,
policySetDefinitionName,
options
},
listQueryResultsForPolicySetDefinitionOperationSpec,
callback) as Promise<Models.PolicyEventsListQueryResultsForPolicySetDefinitionResponse>;
}
/**
* Queries policy events for the subscription level policy definition.
* @param subscriptionId Microsoft Azure subscription ID.
* @param policyDefinitionName Policy definition name.
* @param [options] The optional parameters
* @returns Promise<Models.PolicyEventsListQueryResultsForPolicyDefinitionResponse>
*/
listQueryResultsForPolicyDefinition(subscriptionId: string, policyDefinitionName: string, options?: Models.PolicyEventsListQueryResultsForPolicyDefinitionOptionalParams): Promise<Models.PolicyEventsListQueryResultsForPolicyDefinitionResponse>;
/**
* @param subscriptionId Microsoft Azure subscription ID.
* @param policyDefinitionName Policy definition name.
* @param callback The callback
*/
listQueryResultsForPolicyDefinition(subscriptionId: string, policyDefinitionName: string, callback: msRest.ServiceCallback<Models.PolicyEventsQueryResults>): void;
/**
* @param subscriptionId Microsoft Azure subscription ID.
* @param policyDefinitionName Policy definition name.
* @param options The optional parameters
* @param callback The callback
*/
listQueryResultsForPolicyDefinition(subscriptionId: string, policyDefinitionName: string, options: Models.PolicyEventsListQueryResultsForPolicyDefinitionOptionalParams, callback: msRest.ServiceCallback<Models.PolicyEventsQueryResults>): void;
listQueryResultsForPolicyDefinition(subscriptionId: string, policyDefinitionName: string, options?: Models.PolicyEventsListQueryResultsForPolicyDefinitionOptionalParams | msRest.ServiceCallback<Models.PolicyEventsQueryResults>, callback?: msRest.ServiceCallback<Models.PolicyEventsQueryResults>): Promise<Models.PolicyEventsListQueryResultsForPolicyDefinitionResponse> {
return this.client.sendOperationRequest(
{
subscriptionId,
policyDefinitionName,
options
},
listQueryResultsForPolicyDefinitionOperationSpec,
callback) as Promise<Models.PolicyEventsListQueryResultsForPolicyDefinitionResponse>;
}
/**
* Queries policy events for the subscription level policy assignment.
* @param subscriptionId Microsoft Azure subscription ID.
* @param policyAssignmentName Policy assignment name.
* @param [options] The optional parameters
* @returns
* Promise<Models.PolicyEventsListQueryResultsForSubscriptionLevelPolicyAssignmentResponse>
*/
listQueryResultsForSubscriptionLevelPolicyAssignment(subscriptionId: string, policyAssignmentName: string, options?: Models.PolicyEventsListQueryResultsForSubscriptionLevelPolicyAssignmentOptionalParams): Promise<Models.PolicyEventsListQueryResultsForSubscriptionLevelPolicyAssignmentResponse>;
/**
* @param subscriptionId Microsoft Azure subscription ID.
* @param policyAssignmentName Policy assignment name.
* @param callback The callback
*/
listQueryResultsForSubscriptionLevelPolicyAssignment(subscriptionId: string, policyAssignmentName: string, callback: msRest.ServiceCallback<Models.PolicyEventsQueryResults>): void;
/**
* @param subscriptionId Microsoft Azure subscription ID.
* @param policyAssignmentName Policy assignment name.
* @param options The optional parameters
* @param callback The callback
*/
listQueryResultsForSubscriptionLevelPolicyAssignment(subscriptionId: string, policyAssignmentName: string, options: Models.PolicyEventsListQueryResultsForSubscriptionLevelPolicyAssignmentOptionalParams, callback: msRest.ServiceCallback<Models.PolicyEventsQueryResults>): void;
listQueryResultsForSubscriptionLevelPolicyAssignment(subscriptionId: string, policyAssignmentName: string, options?: Models.PolicyEventsListQueryResultsForSubscriptionLevelPolicyAssignmentOptionalParams | msRest.ServiceCallback<Models.PolicyEventsQueryResults>, callback?: msRest.ServiceCallback<Models.PolicyEventsQueryResults>): Promise<Models.PolicyEventsListQueryResultsForSubscriptionLevelPolicyAssignmentResponse> {
return this.client.sendOperationRequest(
{
subscriptionId,
policyAssignmentName,
options
},
listQueryResultsForSubscriptionLevelPolicyAssignmentOperationSpec,
callback) as Promise<Models.PolicyEventsListQueryResultsForSubscriptionLevelPolicyAssignmentResponse>;
}
/**
* Queries policy events for the resource group level policy assignment.
* @param subscriptionId Microsoft Azure subscription ID.
* @param resourceGroupName Resource group name.
* @param policyAssignmentName Policy assignment name.
* @param [options] The optional parameters
* @returns
* Promise<Models.PolicyEventsListQueryResultsForResourceGroupLevelPolicyAssignmentResponse>
*/
listQueryResultsForResourceGroupLevelPolicyAssignment(subscriptionId: string, resourceGroupName: string, policyAssignmentName: string, options?: Models.PolicyEventsListQueryResultsForResourceGroupLevelPolicyAssignmentOptionalParams): Promise<Models.PolicyEventsListQueryResultsForResourceGroupLevelPolicyAssignmentResponse>;
/**
* @param subscriptionId Microsoft Azure subscription ID.
* @param resourceGroupName Resource group name.
* @param policyAssignmentName Policy assignment name.
* @param callback The callback
*/
listQueryResultsForResourceGroupLevelPolicyAssignment(subscriptionId: string, resourceGroupName: string, policyAssignmentName: string, callback: msRest.ServiceCallback<Models.PolicyEventsQueryResults>): void;
/**
* @param subscriptionId Microsoft Azure subscription ID.
* @param resourceGroupName Resource group name.
* @param policyAssignmentName Policy assignment name.
* @param options The optional parameters
* @param callback The callback
*/
listQueryResultsForResourceGroupLevelPolicyAssignment(subscriptionId: string, resourceGroupName: string, policyAssignmentName: string, options: Models.PolicyEventsListQueryResultsForResourceGroupLevelPolicyAssignmentOptionalParams, callback: msRest.ServiceCallback<Models.PolicyEventsQueryResults>): void;
listQueryResultsForResourceGroupLevelPolicyAssignment(subscriptionId: string, resourceGroupName: string, policyAssignmentName: string, options?: Models.PolicyEventsListQueryResultsForResourceGroupLevelPolicyAssignmentOptionalParams | msRest.ServiceCallback<Models.PolicyEventsQueryResults>, callback?: msRest.ServiceCallback<Models.PolicyEventsQueryResults>): Promise<Models.PolicyEventsListQueryResultsForResourceGroupLevelPolicyAssignmentResponse> {
return this.client.sendOperationRequest(
{
subscriptionId,
resourceGroupName,
policyAssignmentName,
options
},
listQueryResultsForResourceGroupLevelPolicyAssignmentOperationSpec,
callback) as Promise<Models.PolicyEventsListQueryResultsForResourceGroupLevelPolicyAssignmentResponse>;
}
/**
* Queries policy events for the resources under the management group.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.PolicyEventsListQueryResultsForManagementGroupNextResponse>
*/
listQueryResultsForManagementGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.PolicyEventsListQueryResultsForManagementGroupNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listQueryResultsForManagementGroupNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.PolicyEventsQueryResults>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listQueryResultsForManagementGroupNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.PolicyEventsQueryResults>): void;
listQueryResultsForManagementGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.PolicyEventsQueryResults>, callback?: msRest.ServiceCallback<Models.PolicyEventsQueryResults>): Promise<Models.PolicyEventsListQueryResultsForManagementGroupNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listQueryResultsForManagementGroupNextOperationSpec,
callback) as Promise<Models.PolicyEventsListQueryResultsForManagementGroupNextResponse>;
}
/**
* Queries policy events for the resources under the subscription.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.PolicyEventsListQueryResultsForSubscriptionNextResponse>
*/
listQueryResultsForSubscriptionNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.PolicyEventsListQueryResultsForSubscriptionNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listQueryResultsForSubscriptionNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.PolicyEventsQueryResults>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listQueryResultsForSubscriptionNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.PolicyEventsQueryResults>): void;
listQueryResultsForSubscriptionNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.PolicyEventsQueryResults>, callback?: msRest.ServiceCallback<Models.PolicyEventsQueryResults>): Promise<Models.PolicyEventsListQueryResultsForSubscriptionNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listQueryResultsForSubscriptionNextOperationSpec,
callback) as Promise<Models.PolicyEventsListQueryResultsForSubscriptionNextResponse>;
}
/**
* Queries policy events for the resources under the resource group.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.PolicyEventsListQueryResultsForResourceGroupNextResponse>
*/
listQueryResultsForResourceGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.PolicyEventsListQueryResultsForResourceGroupNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listQueryResultsForResourceGroupNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.PolicyEventsQueryResults>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listQueryResultsForResourceGroupNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.PolicyEventsQueryResults>): void;
listQueryResultsForResourceGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.PolicyEventsQueryResults>, callback?: msRest.ServiceCallback<Models.PolicyEventsQueryResults>): Promise<Models.PolicyEventsListQueryResultsForResourceGroupNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listQueryResultsForResourceGroupNextOperationSpec,
callback) as Promise<Models.PolicyEventsListQueryResultsForResourceGroupNextResponse>;
}
/**
* Queries policy events for the resource.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.PolicyEventsListQueryResultsForResourceNextResponse>
*/
listQueryResultsForResourceNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.PolicyEventsListQueryResultsForResourceNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listQueryResultsForResourceNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.PolicyEventsQueryResults>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listQueryResultsForResourceNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.PolicyEventsQueryResults>): void;
listQueryResultsForResourceNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.PolicyEventsQueryResults>, callback?: msRest.ServiceCallback<Models.PolicyEventsQueryResults>): Promise<Models.PolicyEventsListQueryResultsForResourceNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listQueryResultsForResourceNextOperationSpec,
callback) as Promise<Models.PolicyEventsListQueryResultsForResourceNextResponse>;
}
/**
* Queries policy events for the subscription level policy set definition.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.PolicyEventsListQueryResultsForPolicySetDefinitionNextResponse>
*/
listQueryResultsForPolicySetDefinitionNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.PolicyEventsListQueryResultsForPolicySetDefinitionNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listQueryResultsForPolicySetDefinitionNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.PolicyEventsQueryResults>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listQueryResultsForPolicySetDefinitionNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.PolicyEventsQueryResults>): void;
listQueryResultsForPolicySetDefinitionNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.PolicyEventsQueryResults>, callback?: msRest.ServiceCallback<Models.PolicyEventsQueryResults>): Promise<Models.PolicyEventsListQueryResultsForPolicySetDefinitionNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listQueryResultsForPolicySetDefinitionNextOperationSpec,
callback) as Promise<Models.PolicyEventsListQueryResultsForPolicySetDefinitionNextResponse>;
}
/**
* Queries policy events for the subscription level policy definition.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.PolicyEventsListQueryResultsForPolicyDefinitionNextResponse>
*/
listQueryResultsForPolicyDefinitionNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.PolicyEventsListQueryResultsForPolicyDefinitionNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listQueryResultsForPolicyDefinitionNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.PolicyEventsQueryResults>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listQueryResultsForPolicyDefinitionNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.PolicyEventsQueryResults>): void;
listQueryResultsForPolicyDefinitionNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.PolicyEventsQueryResults>, callback?: msRest.ServiceCallback<Models.PolicyEventsQueryResults>): Promise<Models.PolicyEventsListQueryResultsForPolicyDefinitionNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listQueryResultsForPolicyDefinitionNextOperationSpec,
callback) as Promise<Models.PolicyEventsListQueryResultsForPolicyDefinitionNextResponse>;
}
/**
* Queries policy events for the subscription level policy assignment.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns
* Promise<Models.PolicyEventsListQueryResultsForSubscriptionLevelPolicyAssignmentNextResponse>
*/
listQueryResultsForSubscriptionLevelPolicyAssignmentNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.PolicyEventsListQueryResultsForSubscriptionLevelPolicyAssignmentNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listQueryResultsForSubscriptionLevelPolicyAssignmentNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.PolicyEventsQueryResults>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listQueryResultsForSubscriptionLevelPolicyAssignmentNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.PolicyEventsQueryResults>): void;
listQueryResultsForSubscriptionLevelPolicyAssignmentNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.PolicyEventsQueryResults>, callback?: msRest.ServiceCallback<Models.PolicyEventsQueryResults>): Promise<Models.PolicyEventsListQueryResultsForSubscriptionLevelPolicyAssignmentNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listQueryResultsForSubscriptionLevelPolicyAssignmentNextOperationSpec,
callback) as Promise<Models.PolicyEventsListQueryResultsForSubscriptionLevelPolicyAssignmentNextResponse>;
}
/**
* Queries policy events for the resource group level policy assignment.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns
* Promise<Models.PolicyEventsListQueryResultsForResourceGroupLevelPolicyAssignmentNextResponse>
*/
listQueryResultsForResourceGroupLevelPolicyAssignmentNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.PolicyEventsListQueryResultsForResourceGroupLevelPolicyAssignmentNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listQueryResultsForResourceGroupLevelPolicyAssignmentNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.PolicyEventsQueryResults>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listQueryResultsForResourceGroupLevelPolicyAssignmentNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.PolicyEventsQueryResults>): void;
listQueryResultsForResourceGroupLevelPolicyAssignmentNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.PolicyEventsQueryResults>, callback?: msRest.ServiceCallback<Models.PolicyEventsQueryResults>): Promise<Models.PolicyEventsListQueryResultsForResourceGroupLevelPolicyAssignmentNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listQueryResultsForResourceGroupLevelPolicyAssignmentNextOperationSpec,
callback) as Promise<Models.PolicyEventsListQueryResultsForResourceGroupLevelPolicyAssignmentNextResponse>;
}
}
// Operation Specifications
const serializer = new msRest.Serializer(Mappers);
const listQueryResultsForManagementGroupOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "providers/{managementGroupsNamespace}/managementGroups/{managementGroupName}/providers/Microsoft.PolicyInsights/policyEvents/{policyEventsResource}/queryResults",
urlParameters: [
Parameters.policyEventsResource,
Parameters.managementGroupsNamespace,
Parameters.managementGroupName
],
queryParameters: [
Parameters.apiVersion2,
Parameters.top,
Parameters.orderBy,
Parameters.select,
Parameters.from,
Parameters.to,
Parameters.filter,
Parameters.apply,
Parameters.skipToken
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.PolicyEventsQueryResults
},
default: {
bodyMapper: Mappers.QueryFailure
}
},
serializer
};
const listQueryResultsForSubscriptionOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyEvents/{policyEventsResource}/queryResults",
urlParameters: [
Parameters.policyEventsResource,
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion2,
Parameters.top,
Parameters.orderBy,
Parameters.select,
Parameters.from,
Parameters.to,
Parameters.filter,
Parameters.apply,
Parameters.skipToken
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.PolicyEventsQueryResults
},
default: {
bodyMapper: Mappers.QueryFailure
}
},
serializer
};
const listQueryResultsForResourceGroupOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/policyEvents/{policyEventsResource}/queryResults",
urlParameters: [
Parameters.policyEventsResource,
Parameters.subscriptionId,
Parameters.resourceGroupName
],
queryParameters: [
Parameters.apiVersion2,
Parameters.top,
Parameters.orderBy,
Parameters.select,
Parameters.from,
Parameters.to,
Parameters.filter,
Parameters.apply,
Parameters.skipToken
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.PolicyEventsQueryResults
},
default: {
bodyMapper: Mappers.QueryFailure
}
},
serializer
};
const listQueryResultsForResourceOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "{resourceId}/providers/Microsoft.PolicyInsights/policyEvents/{policyEventsResource}/queryResults",
urlParameters: [
Parameters.policyEventsResource,
Parameters.resourceId
],
queryParameters: [
Parameters.apiVersion2,
Parameters.top,
Parameters.orderBy,
Parameters.select,
Parameters.from,
Parameters.to,
Parameters.filter,
Parameters.apply,
Parameters.expand,
Parameters.skipToken
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.PolicyEventsQueryResults
},
default: {
bodyMapper: Mappers.QueryFailure
}
},
serializer
};
const listQueryResultsForPolicySetDefinitionOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policySetDefinitions/{policySetDefinitionName}/providers/Microsoft.PolicyInsights/policyEvents/{policyEventsResource}/queryResults",
urlParameters: [
Parameters.policyEventsResource,
Parameters.subscriptionId,
Parameters.authorizationNamespace,
Parameters.policySetDefinitionName
],
queryParameters: [
Parameters.apiVersion2,
Parameters.top,
Parameters.orderBy,
Parameters.select,
Parameters.from,
Parameters.to,
Parameters.filter,
Parameters.apply,
Parameters.skipToken
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.PolicyEventsQueryResults
},
default: {
bodyMapper: Mappers.QueryFailure
}
},
serializer
};
const listQueryResultsForPolicyDefinitionOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policyDefinitions/{policyDefinitionName}/providers/Microsoft.PolicyInsights/policyEvents/{policyEventsResource}/queryResults",
urlParameters: [
Parameters.policyEventsResource,
Parameters.subscriptionId,
Parameters.authorizationNamespace,
Parameters.policyDefinitionName
],
queryParameters: [
Parameters.apiVersion2,
Parameters.top,
Parameters.orderBy,
Parameters.select,
Parameters.from,
Parameters.to,
Parameters.filter,
Parameters.apply,
Parameters.skipToken
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.PolicyEventsQueryResults
},
default: {
bodyMapper: Mappers.QueryFailure
}
},
serializer
};
const listQueryResultsForSubscriptionLevelPolicyAssignmentOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policyAssignments/{policyAssignmentName}/providers/Microsoft.PolicyInsights/policyEvents/{policyEventsResource}/queryResults",
urlParameters: [
Parameters.policyEventsResource,
Parameters.subscriptionId,
Parameters.authorizationNamespace,
Parameters.policyAssignmentName
],
queryParameters: [
Parameters.apiVersion2,
Parameters.top,
Parameters.orderBy,
Parameters.select,
Parameters.from,
Parameters.to,
Parameters.filter,
Parameters.apply,
Parameters.skipToken
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.PolicyEventsQueryResults
},
default: {
bodyMapper: Mappers.QueryFailure
}
},
serializer
};
const listQueryResultsForResourceGroupLevelPolicyAssignmentOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{authorizationNamespace}/policyAssignments/{policyAssignmentName}/providers/Microsoft.PolicyInsights/policyEvents/{policyEventsResource}/queryResults",
urlParameters: [
Parameters.policyEventsResource,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.authorizationNamespace,
Parameters.policyAssignmentName
],
queryParameters: [
Parameters.apiVersion2,
Parameters.top,
Parameters.orderBy,
Parameters.select,
Parameters.from,
Parameters.to,
Parameters.filter,
Parameters.apply,
Parameters.skipToken
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.PolicyEventsQueryResults
},
default: {
bodyMapper: Mappers.QueryFailure
}
},
serializer
};
const listQueryResultsForManagementGroupNextOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
queryParameters: [
Parameters.apiVersion2
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.PolicyEventsQueryResults
},
default: {
bodyMapper: Mappers.QueryFailure
}
},
serializer
};
const listQueryResultsForSubscriptionNextOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
queryParameters: [
Parameters.apiVersion2
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.PolicyEventsQueryResults
},
default: {
bodyMapper: Mappers.QueryFailure
}
},
serializer
};
const listQueryResultsForResourceGroupNextOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
queryParameters: [
Parameters.apiVersion2
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.PolicyEventsQueryResults
},
default: {
bodyMapper: Mappers.QueryFailure
}
},
serializer
};
const listQueryResultsForResourceNextOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
queryParameters: [
Parameters.apiVersion2
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.PolicyEventsQueryResults
},
default: {
bodyMapper: Mappers.QueryFailure
}
},
serializer
};
const listQueryResultsForPolicySetDefinitionNextOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
queryParameters: [
Parameters.apiVersion2
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.PolicyEventsQueryResults
},
default: {
bodyMapper: Mappers.QueryFailure
}
},
serializer
};
const listQueryResultsForPolicyDefinitionNextOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
queryParameters: [
Parameters.apiVersion2
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.PolicyEventsQueryResults
},
default: {
bodyMapper: Mappers.QueryFailure
}
},
serializer
};
const listQueryResultsForSubscriptionLevelPolicyAssignmentNextOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
queryParameters: [
Parameters.apiVersion2
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.PolicyEventsQueryResults
},
default: {
bodyMapper: Mappers.QueryFailure
}
},
serializer
};
const listQueryResultsForResourceGroupLevelPolicyAssignmentNextOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
queryParameters: [
Parameters.apiVersion2
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.PolicyEventsQueryResults
},
default: {
bodyMapper: Mappers.QueryFailure
}
},
serializer
}; | the_stack |
import NodeCache = require('node-cache');
import { RosaeContext } from './RosaeContext';
import { PackagedTemplate, RosaeNlgFeatures } from 'rosaenlg-packager';
import * as process from 'process';
interface CacheKey {
user: string;
templateId: string;
}
export interface CacheValue {
templateSha1: string;
rosaeContext: RosaeContext;
}
export interface RosaeContextsManagerParams {
// origin: string;
forgetTemplates?: boolean;
specificTtl?: number;
specificCheckPeriod?: number;
enableCache?: boolean;
sharedTemplatesUser?: string;
sharedTemplatesPath?: string;
}
export interface UserAndTemplateId {
user: string;
templateId: string;
}
export abstract class RosaeContextsManager {
private ttl: number;
private cacheCheckPeriod: number;
private forgetTemplates: boolean;
protected enableCache: boolean;
// protected origin: string;
protected rosaeNlgFeatures: RosaeNlgFeatures;
private rosaeContextsCache: NodeCache;
protected sharedTemplatesUser: string;
constructor(rosaeContextsManagerParams: RosaeContextsManagerParams) {
this.ttl = rosaeContextsManagerParams.specificTtl || 600; // 10 minutes
this.cacheCheckPeriod = rosaeContextsManagerParams.specificCheckPeriod || 60; // 1 minute
this.forgetTemplates = rosaeContextsManagerParams.forgetTemplates;
this.enableCache = rosaeContextsManagerParams.enableCache != null ? rosaeContextsManagerParams.enableCache : true; // enabled by default
// this.origin = rosaeContextsManagerParams.origin;
this.sharedTemplatesUser = rosaeContextsManagerParams.sharedTemplatesUser;
this.rosaeContextsCache = new NodeCache({
checkperiod: this.cacheCheckPeriod,
useClones: false,
deleteOnExpire: true,
});
}
protected abstract getAllFiles(cb: (err: Error, files: string[]) => void): void;
protected abstract getUserAndTemplateId(filename: string): UserAndTemplateId;
public abstract saveOnBackend(user: string, templateId: string, content: string, cb: (err: Error) => void): void;
public abstract deleteFromBackend(user: string, templateId: string, cb: (err: Error) => void): void;
public abstract readTemplateOnBackend(
user: string,
templateId: string,
cb: (err: Error, readContent: any) => void,
): void;
public abstract hasBackend(): boolean;
public abstract checkHealth(cb: (err: Error) => void): void;
public getVersion(): string {
try {
return this.rosaeNlgFeatures.getRosaeNlgVersion();
} catch (e) {
console.log({
action: 'version',
message: `cannot get version: ${e.message}`,
});
const err = new Error();
err.name = '500';
err.message = e.message;
throw err;
}
}
public readTemplateOnBackendAndLoad(
user: string,
templateId: string,
cb: (err: Error, templateSha1: string, rosaeContext: RosaeContext) => void,
): void {
this.readTemplateOnBackend(user, templateId, (err, templateContent) => {
if (err) {
console.warn({
action: 'load',
user: user,
templateId: templateId,
message: `could not reload: ${err}`,
});
cb(err, null, null);
} else {
this.compSaveAndLoad(templateContent, false, (loadErr, templateSha1, rosaeContext) => {
cb(loadErr, templateSha1, rosaeContext);
});
}
});
}
public reloadAllFiles(cb: (err: Error) => void): void {
this.getAllFiles((err, files) => {
if (err) {
cb(err);
} else {
for (let i = 0; i < files.length; i++) {
const file: string = files[i];
const userAndTemplateId = this.getUserAndTemplateId(file);
if (userAndTemplateId && userAndTemplateId.user && userAndTemplateId.templateId) {
this.readTemplateOnBackendAndLoad(
userAndTemplateId.user,
userAndTemplateId.templateId,
(_err, _templateSha1) => {
// do nothing with the error
},
);
} else {
console.warn({
action: 'startup',
message: `invalid file: ${file}`,
});
}
}
cb(null);
}
});
}
public getFromCacheOrLoad(
user: string,
templateId: string,
askedSha1: string,
cb: (err: Error, cacheValue: CacheValue) => void,
): void {
if (
(askedSha1 && this.enableCache && this.isInCacheWithGoodSha1(user, templateId, askedSha1)) ||
(!askedSha1 && this.enableCache && this.isInCache(user, templateId))
) {
// already in cache with the proper sha1?
cb(null, this.getFromCache(user, templateId));
return;
} else {
this.readTemplateOnBackend(user, templateId, (readTemplateErr, templateContent) => {
if (readTemplateErr) {
// does not exist: we don't really care
console.log({
user: user,
templateId: templateId,
action: 'getFromCacheOrLoad',
message: `error: ${readTemplateErr}`,
});
const e = new Error();
e.name = '404';
e.message = `${user} ${templateId} not found on backend: ${readTemplateErr.message}`;
cb(e, null);
return;
} else {
templateContent.user = user;
this.compSaveAndLoad(templateContent, false, (compErr, loadedSha1, rosaeContext) => {
if (compErr) {
const e = new Error();
e.name = '400';
e.message = `no existing compiled content for ${templateId}, and could not compile: ${compErr}`;
cb(e, null);
return;
}
if (askedSha1 && loadedSha1 != askedSha1) {
const e = new Error();
e.name = 'WRONG_SHA1'; // don't put directly a 301 here, as it can be a 301 or a 308 when POST
// leave the <...> as it is parsed for redirection
e.message = `sha1 do not correspond, read sha1 is <${loadedSha1}> while requested is ${askedSha1}`;
cb(e, null);
return;
}
// everything is ok
cb(null, {
templateSha1: loadedSha1,
rosaeContext: rosaeContext,
});
});
}
});
}
}
public deleteFromCacheAndBackend(user: string, templateId: string, cb: (err: Error) => void): void {
if (this.enableCache) {
this.deleteFromCache(user, templateId);
}
if (this.hasBackend()) {
this.deleteFromBackend(user, templateId, (err) => {
if (err) {
console.log({ user: user, templateId: templateId, action: 'delete', message: `failed: ${err}` });
const e = new Error();
//e.name = '500';
e.message = `delete failed: ${err}`;
cb(e);
return;
} else {
console.log({ user: user, templateId: templateId, action: 'delete', message: `done.` });
cb(null);
return;
}
});
} else {
cb(null);
}
}
protected getKindOfUuid(): string {
return `${process.pid}-${Math.floor(Math.random() * 100000)}`; //NOSONAR
}
public compSaveAndLoad(
templateContent: PackagedTemplate,
alwaysSave: boolean,
cb: (err: Error, templateSha1: string, rosaeContext: RosaeContext) => void,
): void {
const user = templateContent.user;
let rosaeContext: RosaeContext;
// if existing we must enrich first
if (templateContent.type == 'existing' && !templateContent.src && !templateContent.comp) {
if (!this.sharedTemplatesUser) {
cb(new Error('shared templates not activated'), null, null);
return;
} else {
this.getFromCacheOrLoad(this.sharedTemplatesUser, templateContent.which, null, (err, cacheValue) => {
if (err) {
cb(new Error(`cannot load shared template: ${templateContent.which}, ${err}`), null, null);
return;
} else {
const sharedRosaeContent = cacheValue.rosaeContext.getFullTemplate();
templateContent.src = sharedRosaeContent.src;
templateContent.comp = sharedRosaeContent.comp;
this.compSaveAndLoad(templateContent, alwaysSave, cb);
// cacheValue.templateSha1
// what could we do with it?
}
});
}
} else {
try {
rosaeContext = new RosaeContext(templateContent, this.rosaeNlgFeatures);
} catch (e) {
console.log({
user: user,
action: 'create',
message: `error creating template: ${e.message}`,
});
const err = new Error();
err.name = '400';
err.message = e.message;
cb(err, null, null);
return;
}
const templateId = rosaeContext.getTemplateId();
if (!templateId) {
const err = new Error();
err.name = '400';
err.message = 'no templateId!';
cb(err, null, null);
console.log({ user: user, action: 'create', message: `no templateId` });
return;
} else {
const templateSha1 = rosaeContext.getSha1();
const cacheValue: CacheValue = {
templateSha1: templateSha1,
rosaeContext: rosaeContext,
};
if (this.enableCache) {
this.setInCache(user, templateId, cacheValue, false);
}
if (this.hasBackend() && (alwaysSave || rosaeContext.hadToCompile)) {
this.saveOnBackend(user, templateId, JSON.stringify(rosaeContext.getFullTemplate()), (err) => {
if (err) {
console.error({
user: user,
action: 'create',
sha1: templateSha1,
message: `could not save to backend: ${err}`,
});
const e = new Error();
e.name = '500';
e.message = 'could not save to backend';
cb(e, null, null);
return;
} else {
console.log({
user: user,
action: 'create',
sha1: templateSha1,
message: `saved to backend`,
});
cb(null, templateSha1, rosaeContext);
return;
}
});
} else {
cb(null, templateSha1, rosaeContext);
return;
}
}
}
}
public getIdsFromBackend(user: string, cb: (err: Error, templates: string[]) => void): void {
this.getAllFiles((err, files) => {
if (err) {
cb(err, null);
} else {
const ids: string[] = [];
for (let i = 0; i < files.length; i++) {
const file: string = files[i];
const userAndTemplateId = this.getUserAndTemplateId(file);
if (userAndTemplateId && userAndTemplateId.user == user && userAndTemplateId.templateId) {
ids.push(userAndTemplateId.templateId);
}
}
cb(null, ids);
}
});
}
protected getUserAndTemplateIdHelper(filename: string, sep: string): UserAndTemplateId {
const splited = filename.split(sep);
if (splited.length != 2) {
console.error({
message: `invalid file: ${splited}`,
});
return null;
}
return { user: splited[0], templateId: splited[1].replace(/\.json$/, '') };
}
private checkCacheEnable(): void {
if (!this.enableCache) {
const err = new Error();
err.name = 'InvalidArgumentError';
err.message = `trying to use cache but enableCache is false`;
throw err;
}
}
private getCacheKey(user: string, templateId: string): string {
this.checkCacheEnable();
const key = JSON.stringify({
user: user,
templateId: templateId,
});
const currTtl = this.rosaeContextsCache.getTtl(key);
if (currTtl == undefined) {
// not in cache yet, don't do anything
} else if (currTtl == 0) {
// no TTl, we don't change it
} else {
// reset ttl
this.rosaeContextsCache.ttl(key, this.ttl);
}
return key;
}
public getFromCache(user: string, templateId: string): CacheValue {
this.checkCacheEnable();
return this.rosaeContextsCache.get(this.getCacheKey(user, templateId));
}
public isInCache(user: string, templateId: string): boolean {
this.checkCacheEnable();
return this.rosaeContextsCache.has(this.getCacheKey(user, templateId));
}
public isInCacheWithGoodSha1(user: string, templateId: string, templateSha1: string): boolean {
this.checkCacheEnable();
const cacheValue = this.getFromCache(user, templateId);
if (!cacheValue) {
return false;
} else {
if (cacheValue.templateSha1 === templateSha1) {
return true;
} else {
return false;
}
}
}
public setInCache(user: string, templateId: string, cacheValue: CacheValue, isTemp: boolean): void {
this.checkCacheEnable();
let ttl: number;
if (isTemp || this.forgetTemplates) {
ttl = this.ttl;
} else {
ttl = 0;
}
this.rosaeContextsCache.set(this.getCacheKey(user, templateId), cacheValue, ttl);
}
public deleteFromCache(user: string, templateId: string): void {
this.checkCacheEnable();
this.rosaeContextsCache.del(this.getCacheKey(user, templateId));
}
public getIdsInCache(user: string): string[] {
this.checkCacheEnable();
const cacheKeys = Array.from(this.rosaeContextsCache.keys());
const ids: string[] = [];
for (let i = 0; i < cacheKeys.length; i++) {
const rawCacheKey = cacheKeys[i];
const cacheKey: CacheKey = JSON.parse(rawCacheKey);
// we don't keep temp ones
if (cacheKey.user == user && this.rosaeContextsCache.getTtl(rawCacheKey) == 0) {
ids.push(cacheKey.templateId);
}
}
return ids;
}
// for debug only
/*
public getAllKeys(): string[] {
return Array.from(this.rosaeContextsCache.keys());
}
*/
} | the_stack |
import {URL} from 'url';
import {compile, compileString, compileStringAsync, Importer} from 'sass';
import {skipForImpl, sandbox} from './utils';
skipForImpl('sass-embedded', () => {
it('uses an importer to resolve an @import', () => {
const result = compileString('@import "orange";', {
importers: [
{
canonicalize: url => new URL(`u:${url}`),
load(url) {
const color = url.pathname;
return {contents: `.${color} {color: ${color}}`, syntax: 'scss'};
},
},
],
});
expect(result.css).toBe('.orange {\n color: orange;\n}');
});
it('passes the canonicalized URL to the importer', () => {
const result = compileString('@import "orange";', {
importers: [
{
canonicalize: () => new URL('u:blue'),
load(url) {
const color = url.pathname;
return {contents: `.${color} {color: ${color}}`, syntax: 'scss'};
},
},
],
});
expect(result.css).toBe('.blue {\n color: blue;\n}');
});
it('only invokes the importer once for a given canonicalization', () => {
const result = compileString(
`
@import "orange";
@import "orange";
`,
{
importers: [
{
canonicalize: () => new URL('u:blue'),
load(url) {
const color = url.pathname;
return {contents: `.${color} {color: ${color}}`, syntax: 'scss'};
},
},
],
}
);
expect(result.css).toBe(`.blue {
color: blue;
}
.blue {
color: blue;
}`);
});
describe('the imported URL', () => {
// Regression test for sass/dart-sass#1137.
it("isn't changed if it's root-relative", () => {
const result = compileString('@import "/orange";', {
importers: [
{
canonicalize(url) {
expect(url).toEqual('/orange');
return new URL(`u:${url}`);
},
load: () => ({contents: 'a {b: c}', syntax: 'scss'}),
},
],
});
expect(result.css).toBe('a {\n b: c;\n}');
});
it("is converted to a file: URL if it's an absolute Windows path", () => {
const result = compileString('@import "C:/orange";', {
importers: [
{
canonicalize(url) {
expect(url).toEqual('file:///C:/orange');
return new URL(`u:${url}`);
},
load: () => ({contents: 'a {b: c}', syntax: 'scss'}),
},
],
});
expect(result.css).toBe('a {\n b: c;\n}');
});
});
it("uses an importer's source map URL", () => {
const result = compileString('@import "orange";', {
importers: [
{
canonicalize: url => new URL(`u:${url}`),
load(url) {
const color = url.pathname;
return {
contents: `.${color} {color: ${color}}`,
syntax: 'scss',
sourceMapUrl: new URL('u:blue'),
};
},
},
],
sourceMap: true,
});
expect(result.sourceMap!.sources).toInclude('u:blue');
});
it('wraps an error in canonicalize()', () => {
expect(() => {
compileString('@import "orange";', {
importers: [
{
canonicalize() {
throw 'this import is bad actually';
},
load() {
fail('load() should not be called');
},
},
],
});
}).toThrowSassException({line: 0});
});
it('wraps an error in load()', () => {
expect(() => {
compileString('@import "orange";', {
importers: [
{
canonicalize: url => new URL(`u:${url}`),
load() {
throw 'this import is bad actually';
},
},
],
});
}).toThrowSassException({line: 0});
});
it('avoids importer when canonicalize() returns null', () =>
sandbox(dir => {
dir.write({'dir/_other.scss': 'a {from: dir}'});
const result = compileString('@import "other";', {
importers: [
{
canonicalize: () => null,
load() {
fail('load() should not be called');
},
},
],
loadPaths: [dir('dir')],
});
expect(result.css).toBe('a {\n from: dir;\n}');
}));
it('fails to import when load() returns null', () =>
sandbox(dir => {
dir.write({'dir/_other.scss': 'a {from: dir}'});
expect(() => {
compileString('@import "other";', {
importers: [
{
canonicalize: url => new URL(`u:${url}`),
load: () => null,
},
],
loadPaths: [dir('dir')],
});
}).toThrowSassException({line: 0});
}));
it('prefers a relative file load to an importer', () =>
sandbox(dir => {
dir.write({
'input.scss': '@import "other"',
'_other.scss': 'a {from: relative}',
});
const result = compile(dir('input.scss'), {
importers: [
{
canonicalize() {
fail('canonicalize() should not be called');
},
load() {
fail('load() should not be called');
},
},
],
});
expect(result.css).toBe('a {\n from: relative;\n}');
}));
it('prefers a relative importer load to an importer', () => {
const result = compileString('@import "other";', {
importers: [
{
canonicalize() {
fail('canonicalize() should not be called');
},
load() {
fail('load() should not be called');
},
},
],
url: new URL('o:style.scss'),
importer: {
canonicalize: url => new URL(url),
load: () => ({contents: 'a {from: relative}', syntax: 'scss'}),
},
});
expect(result.css).toBe('a {\n from: relative;\n}');
});
it('prefers an importer to a load path', () =>
sandbox(dir => {
dir.write({
'input.scss': '@import "other"',
'dir/_other.scss': 'a {from: load-path}',
});
const result = compile(dir('input.scss'), {
importers: [
{
canonicalize: url => new URL(`u:${url}`),
load: () => ({contents: 'a {from: importer}', syntax: 'scss'}),
},
],
loadPaths: [dir('dir')],
});
expect(result.css).toBe('a {\n from: importer;\n}');
}));
describe('with syntax', () => {
it('scss, parses it as SCSS', () => {
const result = compileString('@import "other";', {
importers: [
{
canonicalize: () => new URL('u:other'),
load: () => ({contents: '$a: value; b {c: $a}', syntax: 'scss'}),
},
],
});
expect(result.css).toBe('b {\n c: value;\n}');
});
it('indented, parses it as the indented syntax', () => {
const result = compileString('@import "other";', {
importers: [
{
canonicalize: () => new URL('u:other'),
load: () => ({
contents: '$a: value\nb\n c: $a',
syntax: 'indented',
}),
},
],
});
expect(result.css).toBe('b {\n c: value;\n}');
});
it('css, allows plain CSS', () => {
const result = compileString('@import "other";', {
importers: [
{
canonicalize: () => new URL('u:other'),
load: () => ({contents: 'a {b: c}', syntax: 'css'}),
},
],
});
expect(result.css).toBe('a {\n b: c;\n}');
});
it('css, rejects SCSS', () => {
expect(() => {
compileString('@import "other";', {
importers: [
{
canonicalize: () => new URL('u:other'),
load: () => ({contents: '$a: value\nb\n c: $a', syntax: 'css'}),
},
],
});
}).toThrowSassException({
line: 0,
url: new URL('u:other'),
});
});
});
describe('async', () => {
it('resolves an @import', async () => {
const result = await compileStringAsync('@import "orange";', {
importers: [
{
canonicalize: url => Promise.resolve(new URL(`u:${url}`)),
load(url) {
const color = url.pathname;
return Promise.resolve({
contents: `.${color} {color: ${color}}`,
syntax: 'scss',
});
},
},
],
});
expect(result.css).toBe('.orange {\n color: orange;\n}');
});
it('wraps an asynchronous error in canonicalize', async () => {
await expect(() =>
compileStringAsync('@import "orange";', {
importers: [
{
canonicalize: () => Promise.reject('this import is bad actually'),
load() {
fail('load() should not be called');
},
},
],
})
).toThrowSassException({line: 0});
});
it('wraps a synchronous error in canonicalize', async () => {
await expect(() =>
compileStringAsync('@import "orange";', {
importers: [
{
canonicalize() {
throw 'this import is bad actually';
},
load() {
fail('load() should not be called');
},
},
],
})
).toThrowSassException({line: 0});
});
it('wraps an asynchronous error in load', async () => {
await expect(() =>
compileStringAsync('@import "orange";', {
importers: [
{
canonicalize: url => new URL(`u:${url}`),
load: () => Promise.reject('this import is bad actually'),
},
],
})
).toThrowSassException({line: 0});
});
it('wraps a synchronous error in load', async () => {
await expect(() =>
compileStringAsync('@import "orange";', {
importers: [
{
canonicalize: url => new URL(`u:${url}`),
load() {
throw 'this import is bad actually';
},
},
],
})
).toThrowSassException({line: 0});
});
});
describe('fromImport is', () => {
it('true from an @import', () => {
compileString('@import "foo"', {importers: [expectFromImport(true)]});
});
it('false from a @use', () => {
compileString('@use "foo"', {importers: [expectFromImport(false)]});
});
it('false from a @forward', () => {
compileString('@forward "foo"', {importers: [expectFromImport(false)]});
});
it('false from meta.load-css', () => {
compileString('@use "sass:meta"; @include meta.load-css("")', {
importers: [expectFromImport(false)],
});
});
});
describe('FileImporter', () => {
it('loads a fully canonicalized URL', () =>
sandbox(dir => {
dir.write({'_other.scss': 'a {b: c}'});
const result = compileString('@import "other";', {
importers: [{findFileUrl: () => dir.url('_other.scss')}],
});
expect(result.css).toBe('a {\n b: c;\n}');
}));
it('resolves a non-canonicalized URL', () =>
sandbox(dir => {
dir.write({'other/_index.scss': 'a {b: c}'});
const result = compileString('@import "other";', {
importers: [{findFileUrl: () => dir.url('other')}],
});
expect(result.css).toBe('a {\n b: c;\n}');
}));
it('avoids importer when it returns null', () =>
sandbox(dir => {
dir.write({'_other.scss': 'a {from: dir}'});
const result = compileString('@import "other";', {
importers: [{findFileUrl: () => null}],
loadPaths: [dir.root],
});
expect(result.css).toBe('a {\n from: dir;\n}');
}));
it('avoids importer when it returns an unresolvable URL', () =>
sandbox(dir => {
dir.write({'_other.scss': 'a {from: dir}'});
const result = compileString('@import "other";', {
importers: [{findFileUrl: () => dir.url('nonexistent/other')}],
loadPaths: [dir.root],
});
expect(result.css).toBe('a {\n from: dir;\n}');
}));
it('passes an absolute non-file: URL to the importer', () =>
sandbox(dir => {
dir.write({'dir/_other.scss': 'a {b: c}'});
const result = compileString('@import "u:other";', {
importers: [
{
findFileUrl(url) {
expect(url).toEqual('u:other');
return dir.url('dir/other');
},
},
],
});
expect(result.css).toBe('a {\n b: c;\n}');
}));
it("doesn't pass an absolute file: URL to the importer", () =>
sandbox(dir => {
dir.write({'_other.scss': 'a {b: c}'});
const result = compileString(`@import "${dir.url('other')}";`, {
importers: [
{
findFileUrl() {
fail('findFileUrl() should not be called');
},
},
],
});
expect(result.css).toBe('a {\n b: c;\n}');
}));
it("doesn't pass relative loads to the importer", () =>
sandbox(dir => {
dir.write({'_midstream.scss': '@import "upstream"'});
dir.write({'_upstream.scss': 'a {b: c}'});
let count = 0;
const result = compileString('@import "midstream";', {
importers: [
{
findFileUrl() {
if (count === 0) {
count++;
return dir.url('upstream');
} else {
fail('findFileUrl() should only be called once');
}
},
},
],
});
expect(result.css).toBe('a {\n b: c;\n}');
}));
it('wraps an error', () => {
expect(() => {
compileString('@import "other";', {
importers: [
{
findFileUrl() {
throw 'this import is bad actually';
},
},
],
});
}).toThrowSassException({line: 0});
});
it('rejects a non-file URL', () => {
expect(() => {
compileString('@import "other";', {
importers: [{findFileUrl: () => new URL('u:other.scss')}],
});
}).toThrowSassException({line: 0});
});
describe('when the resolved file has extension', () => {
it('.scss, parses it as SCSS', () =>
sandbox(dir => {
dir.write({'_other.scss': '$a: value; b {c: $a}'});
const result = compileString('@import "other";', {
importers: [{findFileUrl: () => dir.url('other')}],
});
expect(result.css).toBe('b {\n c: value;\n}');
}));
it('.sass, parses it as the indented syntax', () =>
sandbox(dir => {
dir.write({'_other.sass': '$a: value\nb\n c: $a'});
const result = compileString('@import "other";', {
importers: [{findFileUrl: () => dir.url('other')}],
});
expect(result.css).toBe('b {\n c: value;\n}');
}));
it('.css, allows plain CSS', () =>
sandbox(dir => {
dir.write({'_other.css': 'a {b: c}'});
const result = compileString('@import "other";', {
importers: [{findFileUrl: () => dir.url('other')}],
});
expect(result.css).toBe('a {\n b: c;\n}');
}));
it('.css, rejects SCSS', () =>
sandbox(dir => {
dir.write({'_other.css': '$a: value; b {c: $a}'});
expect(() => {
compileString('@import "other";', {
importers: [{findFileUrl: () => dir.url('other')}],
});
}).toThrowSassException({
line: 0,
url: dir.url('_other.css'),
});
}));
});
describe('fromImport is', () => {
it('true from an @import', () =>
sandbox(dir => {
dir.write({'_other.scss': 'a {b: c}'});
compileString('@import "other"', {
importers: [
{
findFileUrl(url, options) {
expect(options.fromImport).toBeTrue();
return dir.url('other');
},
},
],
});
}));
it('false from a @use', () =>
sandbox(dir => {
dir.write({'_other.scss': 'a {b: c}'});
compileString('@use "other"', {
importers: [
{
findFileUrl(url, {fromImport}) {
expect(fromImport).toBeFalse();
return dir.url('other');
},
},
],
});
}));
});
describe('async', () => {
it('resolves an @import', async () =>
sandbox(async dir => {
dir.write({'_other.scss': 'a {b: c}'});
const result = await compileStringAsync('@use "other"', {
importers: [
{
findFileUrl: () => Promise.resolve(dir.url('other')),
},
],
});
expect(result.css).toBe('a {\n b: c;\n}');
}));
it('wraps an error', async () => {
await expect(() =>
compileStringAsync('@import "other";', {
importers: [
{
findFileUrl: () =>
Promise.reject('this import is bad actually'),
},
],
})
).toThrowSassException({line: 0});
});
});
});
it(
"throws an error for an importer that's ambiguous between FileImporter " +
'and Importer',
() =>
sandbox(dir => {
dir.write({'_other.scss': 'a {b: c}'});
const callback = () => {
compileString('', {
importers: [
{
findFileUrl: () => dir.url('other'),
canonicalize: () => new URL('u:other'),
load: () => ({contents: 'a {b: c}', syntax: 'scss'}),
} as unknown as Importer<'sync'>,
],
});
};
expect(callback).toThrow();
expect(callback).not.toThrowSassException();
})
);
});
/**
* Returns an importer that asserts that `fromImport` is `expected`, and
* otherwise imports exclusively empty stylesheets.
*/
function expectFromImport(expected: boolean): Importer<'sync'> {
return {
canonicalize(url, {fromImport}) {
expect(fromImport).toBe(expected);
return new URL(`u:${url}`);
},
load: () => ({contents: '', syntax: 'scss'}),
};
} | the_stack |
import GraphLayout from './GraphLayout';
import { DIRECTION } from '../../util/Constants';
import HierarchicalEdgeStyle from './datatypes/HierarchicalEdgeStyle';
import Dictionary from '../../util/Dictionary';
import GraphHierarchyModel from './hierarchical/GraphHierarchyModel';
import ObjectIdentity from '../../util/ObjectIdentity';
import MinimumCycleRemover from './hierarchical/MinimumCycleRemover';
import MedianHybridCrossingReduction from './hierarchical/MedianHybridCrossingReduction';
import CoordinateAssignment from './hierarchical/CoordinateAssignment';
import { Graph } from '../../view/Graph';
import CellArray from '../../view/cell/CellArray';
import Cell from '../../view/cell/Cell';
import GraphHierarchyNode from './datatypes/GraphHierarchyNode';
/**
* A hierarchical layout algorithm.
*
* Constructor: HierarchicalLayout
*
* Constructs a new hierarchical layout algorithm.
*
* Arguments:
*
* graph - Reference to the enclosing {@link Graph}.
* orientation - Optional constant that defines the orientation of this
* layout.
* deterministic - Optional boolean that specifies if this layout should be
* deterministic. Default is true.
*/
class HierarchicalLayout extends GraphLayout {
constructor(
graph: Graph,
orientation: DIRECTION=DIRECTION.NORTH,
deterministic: boolean=true
) {
super(graph);
this.orientation = orientation;
this.deterministic = deterministic;
}
deterministic: boolean;
parentX: number | null = null;
parentY: number | null = null;
/**
* Holds the array of <Cell> that this layout contains.
*/
roots: CellArray | null = null;
/**
* Specifies if the parent should be resized after the layout so that it
* contains all the child cells. Default is false. See also <parentBorder>.
*/
resizeParent: boolean = false;
/**
* Specifies if the parent location should be maintained, so that the
* top, left corner stays the same before and after execution of
* the layout. Default is false for backwards compatibility.
*/
maintainParentLocation: boolean = false;
/**
* Specifies if the parent should be moved if <resizeParent> is enabled.
* Default is false.
*/
moveParent: boolean = false;
/**
* The border to be added around the children if the parent is to be
* resized using <resizeParent>. Default is 0.
*/
parentBorder: number = 0;
/**
* The spacing buffer added between cells on the same layer. Default is 30.
*/
intraCellSpacing: number = 30;
/**
* The spacing buffer added between cell on adjacent layers. Default is 100.
*/
interRankCellSpacing: number = 100;
/**
* The spacing buffer between unconnected hierarchies. Default is 60.
*/
interHierarchySpacing: number = 60;
/**
* The distance between each parallel edge on each ranks for long edges.
* Default is 10.
*/
parallelEdgeSpacing: number = 10;
/**
* The position of the root node(s) relative to the laid out graph in.
* Default is <mxConstants.DIRECTION.NORTH>.
*/
orientation: DIRECTION = DIRECTION.NORTH;
/**
* Whether or not to perform local optimisations and iterate multiple times
* through the algorithm. Default is true.
*/
fineTuning: boolean = true;
/**
* Whether or not to tighten the assigned ranks of vertices up towards
* the source cells. Default is true.
*/
tightenToSource: boolean = true;
/**
* Specifies if the STYLE_NOEDGESTYLE flag should be set on edges that are
* modified by the result. Default is true.
*/
disableEdgeStyle: boolean = true;
/**
* Whether or not to drill into child cells and layout in reverse
* group order. This also cause the layout to navigate edges whose
* terminal vertices have different parents but are in the same
* ancestry chain. Default is true.
*/
traverseAncestors: boolean = true;
/**
* The internal <GraphHierarchyModel> formed of the layout.
*/
model: GraphHierarchyModel | null = null;
/**
* A cache of edges whose source terminal is the key
*/
edgesCache: Dictionary<Cell, CellArray> = new Dictionary();
/**
* A cache of edges whose source terminal is the key
*/
edgeSourceTermCache: Dictionary<Cell, Cell> = new Dictionary();
/**
* A cache of edges whose source terminal is the key
*/
edgesTargetTermCache: Dictionary<Cell, Cell> = new Dictionary();
/**
* The style to apply between cell layers to edge segments.
* Default is {@link HierarchicalEdgeStyle#POLYLINE}.
*/
edgeStyle = HierarchicalEdgeStyle.POLYLINE;
/**
* Returns the internal <GraphHierarchyModel> for this layout algorithm.
*/
getDataModel(): GraphHierarchyModel | null {
return this.model;
}
/**
* Executes the layout for the children of the specified parent.
*
* @param parent Parent <Cell> that contains the children to be laid out.
* @param roots Optional starting roots of the layout.
*/
execute(parent: Cell, roots: CellArray | null=null): void {
this.parent = parent;
const { model } = this.graph;
this.edgesCache = new Dictionary();
this.edgeSourceTermCache = new Dictionary();
this.edgesTargetTermCache = new Dictionary();
if (roots != null && !(roots instanceof Array)) {
roots = new CellArray(roots);
}
// If the roots are set and the parent is set, only
// use the roots that are some dependent of the that
// parent.
// If just the root are set, use them as-is
// If just the parent is set use it's immediate
// children as the initial set
if (roots == null && parent == null) {
// TODO indicate the problem
return;
}
// Maintaining parent location
this.parentX = null;
this.parentY = null;
if (
parent !== this.graph.getDataModel().root &&
parent.isVertex() != null &&
this.maintainParentLocation
) {
const geo = parent.getGeometry();
if (geo != null) {
this.parentX = geo.x;
this.parentY = geo.y;
}
}
if (roots != null) {
const rootsCopy = new CellArray();
for (let i = 0; i < roots.length; i += 1) {
const ancestor = parent != null ? parent.isAncestor(roots[i]) : true;
if (ancestor && roots[i].isVertex()) {
rootsCopy.push(roots[i]);
}
}
this.roots = rootsCopy;
}
model.beginUpdate();
try {
this.run(parent);
if (this.resizeParent && !parent.isCollapsed()) {
this.graph.updateGroupBounds(new CellArray(parent), this.parentBorder, this.moveParent);
}
// Maintaining parent location
if (this.parentX != null && this.parentY != null) {
let geo = parent.getGeometry();
if (geo != null) {
geo = geo.clone();
geo.x = this.parentX;
geo.y = this.parentY;
model.setGeometry(parent, geo);
}
}
} finally {
model.endUpdate();
}
}
/**
* Returns all visible children in the given parent which do not have
* incoming edges. If the result is empty then the children with the
* maximum difference between incoming and outgoing edges are returned.
* This takes into account edges that are being promoted to the given
* root due to invisible children or collapsed cells.
*
* @param parent <Cell> whose children should be checked.
* @param vertices array of vertices to limit search to
*/
findRoots(parent: Cell, vertices: CellArray): CellArray {
const roots = new CellArray();
if (parent != null && vertices != null) {
const { model } = this.graph;
let best = null;
let maxDiff = -100000;
for (const i in vertices) {
const cell = vertices[i];
if (cell.isVertex() && cell.isVisible()) {
const conns = this.getEdges(cell);
let fanOut = 0;
let fanIn = 0;
for (let k = 0; k < conns.length; k++) {
const src = this.getVisibleTerminal(conns[k], true);
if (src === cell) {
fanOut++;
} else {
fanIn++;
}
}
if (fanIn === 0 && fanOut > 0) {
roots.push(cell);
}
const diff = fanOut - fanIn;
if (diff > maxDiff) {
maxDiff = diff;
best = cell;
}
}
}
if (roots.length === 0 && best != null) {
roots.push(best);
}
}
return roots;
}
/**
* Returns the connected edges for the given cell.
*
* @param cell <Cell> whose edges should be returned.
*/
getEdges(cell: Cell): CellArray {
const cachedEdges = this.edgesCache.get(cell);
if (cachedEdges != null) {
return cachedEdges;
}
const { model } = this.graph;
let edges = new CellArray();
const isCollapsed = cell.isCollapsed();
const childCount = cell.getChildCount();
for (let i = 0; i < childCount; i += 1) {
const child = cell.getChildAt(i);
if (this.isPort(child)) {
edges = edges.concat(child.getEdges(true, true));
} else if (isCollapsed || !child.isVisible()) {
edges = edges.concat(child.getEdges(true, true));
}
}
edges = edges.concat(cell.getEdges(true, true));
const result = new CellArray();
for (let i = 0; i < edges.length; i += 1) {
const source = this.getVisibleTerminal(edges[i], true);
const target = this.getVisibleTerminal(edges[i], false);
if (
source === target ||
(source !== target &&
((target === cell &&
(this.parent == null ||
this.isAncestor(this.parent, source, this.traverseAncestors))) ||
(source === cell &&
(this.parent == null ||
this.isAncestor(this.parent, target, this.traverseAncestors)))))
) {
result.push(edges[i]);
}
}
this.edgesCache.put(cell, result);
return result;
}
/**
* Helper function to return visible terminal for edge allowing for ports
*
* @param edge <Cell> whose edges should be returned.
* @param source Boolean that specifies whether the source or target terminal is to be returned
*/
getVisibleTerminal(edge: Cell, source: boolean) {
let terminalCache;
if (source) {
terminalCache = this.edgeSourceTermCache;
} else {
terminalCache = this.edgesTargetTermCache;
}
const term = terminalCache.get(edge);
if (term != null) {
return term;
}
const state = this.graph.view.getState(edge);
let terminal =
state != null
? state.getVisibleTerminal(source)
: this.graph.view.getVisibleTerminal(edge, source);
if (terminal == null) {
terminal =
state != null
? state.getVisibleTerminal(source)
: this.graph.view.getVisibleTerminal(edge, source);
}
if (terminal != null) {
if (this.isPort(terminal)) {
terminal = <Cell>terminal.getParent();
}
terminalCache.put(edge, terminal);
}
return terminal;
}
/**
* The API method used to exercise the layout upon the graph description
* and produce a separate description of the vertex position and edge
* routing changes made. It runs each stage of the layout that has been
* created.
*/
run(parent: any) {
// Separate out unconnected hierarchies
const hierarchyVertices = [];
const allVertexSet: { [key: string]: Cell } = {};
if (this.roots == null && parent != null) {
const filledVertexSet = Object();
this.filterDescendants(parent, filledVertexSet);
this.roots = new CellArray();
let filledVertexSetEmpty = true;
// Poor man's isSetEmpty
for (var key in filledVertexSet) {
if (filledVertexSet[key] != null) {
filledVertexSetEmpty = false;
break;
}
}
while (!filledVertexSetEmpty) {
const candidateRoots = this.findRoots(parent, filledVertexSet);
// If the candidate root is an unconnected group cell, remove it from
// the layout. We may need a custom set that holds such groups and forces
// them to be processed for resizing and/or moving.
for (let i = 0; i < candidateRoots.length; i += 1) {
const vertexSet = Object();
hierarchyVertices.push(vertexSet);
this.traverse(
candidateRoots[i],
true,
null,
allVertexSet,
vertexSet,
hierarchyVertices,
filledVertexSet
);
}
for (let i = 0; i < candidateRoots.length; i += 1) {
this.roots.push(candidateRoots[i]);
}
filledVertexSetEmpty = true;
// Poor man's isSetEmpty
for (var key in filledVertexSet) {
if (filledVertexSet[key] != null) {
filledVertexSetEmpty = false;
break;
}
}
}
} else {
// Find vertex set as directed traversal from roots
const roots = <CellArray>this.roots;
for (let i = 0; i < roots.length; i += 1) {
const vertexSet = Object();
hierarchyVertices.push(vertexSet);
this.traverse(
roots[i],
true,
null,
allVertexSet,
vertexSet,
hierarchyVertices,
null
);
}
}
// Iterate through the result removing parents who have children in this layout
// Perform a layout for each seperate hierarchy
// Track initial coordinate x-positioning
let initialX = 0;
for (let i = 0; i < hierarchyVertices.length; i += 1) {
const vertexSet = hierarchyVertices[i];
const tmp = new CellArray();
for (var key in vertexSet) {
tmp.push(vertexSet[key]);
}
this.model = new GraphHierarchyModel(
this,
tmp,
<CellArray>this.roots,
parent,
this.tightenToSource
);
this.cycleStage(parent);
this.layeringStage();
this.crossingStage(parent);
initialX = this.placementStage(initialX, parent);
}
}
/**
* Creates an array of descendant cells
*/
filterDescendants(cell: Cell, result: { [key: string]: Cell }): void {
const { model } = this.graph;
if (cell.isVertex() && cell !== this.parent && cell.isVisible()) {
result[<string>ObjectIdentity.get(cell)] = cell;
}
if (this.traverseAncestors || (cell === this.parent && cell.isVisible())) {
const childCount = cell.getChildCount();
for (let i = 0; i < childCount; i += 1) {
const child = cell.getChildAt(i);
// Ignore ports in the layout vertex list, they are dealt with
// in the traversal mechanisms
if (!this.isPort(child)) {
this.filterDescendants(child, result);
}
}
}
}
/**
* Returns true if the given cell is a "port", that is, when connecting to
* it, its parent is the connecting vertex in terms of graph traversal
*
* @param cell <Cell> that represents the port.
*/
isPort(cell: Cell): boolean {
if (cell != null && cell.geometry != null) {
return cell.geometry.relative;
}
return false;
}
/**
* Returns the edges between the given source and target. This takes into
* account collapsed and invisible cells and ports.
*
* source -
* target -
* directed -
*/
getEdgesBetween(source: Cell, target: Cell, directed: boolean): CellArray {
directed = directed != null ? directed : false;
const edges = this.getEdges(source);
const result = new CellArray();
// Checks if the edge is connected to the correct
// cell and returns the first match
for (let i = 0; i < edges.length; i += 1) {
const src = this.getVisibleTerminal(edges[i], true);
const trg = this.getVisibleTerminal(edges[i], false);
if (
(src === source && trg === target) ||
(!directed && src === target && trg === source)
) {
result.push(edges[i]);
}
}
return result;
}
/**
* Traverses the (directed) graph invoking the given function for each
* visited vertex and edge. The function is invoked with the current vertex
* and the incoming edge as a parameter. This implementation makes sure
* each vertex is only visited once. The function may return false if the
* traversal should stop at the given vertex.
*
* @param vertex <Cell> that represents the vertex where the traversal starts.
* @param directed boolean indicating if edges should only be traversed
* from source to target. Default is true.
* @param edge Optional <Cell> that represents the incoming edge. This is
* null for the first step of the traversal.
* @param allVertices Array of cell paths for the visited cells.
*/
// @ts-ignore
traverse(
vertex: Cell,
directed: boolean=false,
edge: Cell | null=null,
allVertices: { [key: string]: Cell } | null=null,
currentComp: { [key: string]: (Cell | null) },
hierarchyVertices: GraphHierarchyNode[],
filledVertexSet: { [key: string]: Cell } | null=null
) {
if (vertex != null && allVertices != null) {
// Has this vertex been seen before in any traversal
// And if the filled vertex set is populated, only
// process vertices in that it contains
const vertexID = <string>ObjectIdentity.get(vertex);
if (
allVertices[vertexID] == null &&
(filledVertexSet == null ? true : filledVertexSet[vertexID] != null)
) {
if (currentComp[vertexID] == null) {
currentComp[vertexID] = vertex;
}
if (allVertices[vertexID] == null) {
allVertices[vertexID] = vertex;
}
if (filledVertexSet !== null) {
delete filledVertexSet[vertexID];
}
const edges = this.getEdges(vertex);
const edgeIsSource = [];
for (let i = 0; i < edges.length; i += 1) {
edgeIsSource[i] = this.getVisibleTerminal(edges[i], true) == vertex;
}
for (let i = 0; i < edges.length; i += 1) {
if (!directed || edgeIsSource[i]) {
const next = this.getVisibleTerminal(edges[i], !edgeIsSource[i]);
// Check whether there are more edges incoming from the target vertex than outgoing
// The hierarchical model treats bi-directional parallel edges as being sourced
// from the more "sourced" terminal. If the directions are equal in number, the direction
// is that of the natural direction from the roots of the layout.
// The checks below are slightly more verbose than need be for performance reasons
let netCount = 1;
for (let j = 0; j < edges.length; j++) {
if (j === i) {
} else {
const isSource2 = edgeIsSource[j];
const otherTerm = this.getVisibleTerminal(edges[j], !isSource2);
if (otherTerm === next) {
if (isSource2) {
netCount++;
} else {
netCount--;
}
}
}
}
if (netCount >= 0) {
currentComp = this.traverse(
<Cell>next,
directed,
edges[i],
allVertices,
currentComp,
hierarchyVertices,
filledVertexSet
);
}
}
}
} else if (currentComp[vertexID] == null) {
// We've seen this vertex before, but not in the current component
// This component and the one it's in need to be merged
for (let i = 0; i < hierarchyVertices.length; i += 1) {
const comp = hierarchyVertices[i];
// @ts-expect-error
if (comp[vertexID] != null) {
for (const key in comp) {
// @ts-expect-error
currentComp[key] = comp[key];
}
// Remove the current component from the hierarchy set
hierarchyVertices.splice(i, 1);
return currentComp;
}
}
}
}
return currentComp;
}
/**
* Executes the cycle stage using mxMinimumCycleRemover.
*/
cycleStage(parent: any): void {
const cycleStage = new MinimumCycleRemover(this);
cycleStage.execute(parent);
}
/**
* Implements first stage of a Sugiyama layout.
*/
layeringStage(): void {
const model = <GraphHierarchyModel>this.model;
model.initialRank();
model.fixRanks();
}
/**
* Executes the crossing stage using mxMedianHybridCrossingReduction.
*/
crossingStage(parent: any): void {
const crossingStage = new MedianHybridCrossingReduction(this);
crossingStage.execute(parent);
}
/**
* Executes the placement stage using mxCoordinateAssignment.
*/
placementStage(initialX: number, parent: any): number {
const placementStage = new CoordinateAssignment(
this,
this.intraCellSpacing,
this.interRankCellSpacing,
this.orientation,
initialX,
this.parallelEdgeSpacing
);
placementStage.fineTuning = this.fineTuning;
placementStage.execute(parent);
return <number>placementStage.limitX + this.interHierarchySpacing;
}
}
export default HierarchicalLayout; | the_stack |
import * as vscode from "vscode";
import * as murmur from "murmurhash-js";
import { Constants } from "./constants";
import { Icon, UserCommand, ArchivedPosition } from "./types";
import { LeoNode } from "./leoNode";
var portfinder = require('portfinder');
/**
* * Unique numeric Id
*/
var uniqueId: number = 0;
/**
* * Get new uniqueID
*/
export function getUniqueId(): string {
const id = uniqueId++;
return id.toString();
}
/**
* * Build a string for representing a number that's 2 digits wide, padding with a zero if needed
* @param p_number Between 0 and 99
* @returns a 2 digit wide string representation of the number, left padded with zeros as needed.
*/
export function padNumber2(p_number: number): string {
return ("0" + p_number).slice(-2);
}
/**
* * Builds a string hash out of of an archived position, default without taking collapsed state into account
* @param p_ap Archived position
* @param p_salt To be added to the hashing process (Change when tree changes)
*/
export function hashNode(p_ap: ArchivedPosition, p_salt: string, p_withCollapse?: boolean): string {
const w_string1: string = p_ap.headline + p_ap.gnx + p_ap.childIndex.toString(36);
const w_string2: string = w_string1 + p_ap.childIndex.toString(36) + JSON.stringify(p_ap.stack);
const w_first: string = murmur.murmur3(w_string2).toString(36);
if (p_withCollapse) {
p_salt += p_ap.expanded ? "1" : "0";
}
return p_salt + w_string1 + w_first + murmur.murmur3(w_first + w_string2).toString(36);
}
/**
* * Performs the actual addition into workspaceState context
* @param p_context Needed to get to vscode workspace storage
* @param p_file path+file name string
* @param p_key A constant string such as RECENT_FILES_KEY or LAST_FILES_KEY
* @returns A promise that resolves when the workspace storage modification is done
*/
export function addFileToWorkspace(p_context: vscode.ExtensionContext, p_file: string, p_key: string): Thenable<void> {
// Just push that string into the context.workspaceState.<something> array
const w_contextEntry: string[] = p_context.workspaceState.get(p_key) || [];
if (w_contextEntry) {
if (!w_contextEntry.includes(p_file)) {
w_contextEntry.push(p_file);
if (w_contextEntry.length > 10) {
w_contextEntry.shift();
}
}
return p_context.workspaceState.update(p_key, w_contextEntry); // Added file
} else {
// First so create key entry with an array of single file
return p_context.workspaceState.update(p_key, [p_file]);
}
}
/**
* * Removes file entry from workspaceState context
* @param p_context Needed to get to vscode workspace storage
* @param p_file path+file name string
* @param p_key A constant string such as RECENT_FILES_KEY or LAST_FILES_KEY
* @returns A promise that resolves when the workspace storage modification is done
*/
export function removeFileFromWorkspace(p_context: vscode.ExtensionContext, p_file: string, p_key: string): Thenable<void> {
// Check if exist in context.workspaceState.<something> and remove if found
const w_files: string[] = p_context.workspaceState.get(p_key) || [];
if (w_files && w_files.includes(p_file)) {
w_files.splice(w_files.indexOf(p_file), 1); // Splice and update
return p_context.workspaceState.update(p_key, w_files);
}
return Promise.resolve(); // not even in list so just resolve
}
/**
* * Build all possible strings for node icons graphic file paths
* @param p_context Needed to get to absolute paths on the system
* @returns An array of the 16 vscode node icons used in this vscode expansion
*/
export function buildNodeIconPaths(p_context: vscode.ExtensionContext): Icon[] {
return Array(16).fill("").map((p_val, p_index) => {
return {
light: p_context.asAbsolutePath(Constants.GUI.ICON_LIGHT_PATH + padNumber2(p_index) + Constants.GUI.ICON_FILE_EXT),
dark: p_context.asAbsolutePath(Constants.GUI.ICON_DARK_PATH + padNumber2(p_index) + Constants.GUI.ICON_FILE_EXT)
};
});
}
/**
* * Build all possible strings for documents icons graphic file paths
* @param p_context Needed to get to absolute paths on the system
* @returns An array containing icons for the documents tree view
*/
export function buildDocumentIconPaths(p_context: vscode.ExtensionContext): Icon[] {
return [
{
light: p_context.asAbsolutePath(Constants.GUI.ICON_LIGHT_DOCUMENT),
dark: p_context.asAbsolutePath(Constants.GUI.ICON_DARK_DOCUMENT)
},
{
light: p_context.asAbsolutePath(Constants.GUI.ICON_LIGHT_DOCUMENT_DIRTY),
dark: p_context.asAbsolutePath(Constants.GUI.ICON_DARK_DOCUMENT_DIRTY)
}
];
}
/**
* * Build all possible strings for buttons icons graphic file paths
* @param p_context Needed to get to absolute paths on the system
* @returns An array containing icons for the documents tree view
*/
export function buildButtonsIconPaths(p_context: vscode.ExtensionContext): Icon[] {
return [
{
light: p_context.asAbsolutePath(Constants.GUI.ICON_LIGHT_BUTTON),
dark: p_context.asAbsolutePath(Constants.GUI.ICON_DARK_BUTTON)
},
{
light: p_context.asAbsolutePath(Constants.GUI.ICON_LIGHT_BUTTON_ADD),
dark: p_context.asAbsolutePath(Constants.GUI.ICON_DARK_BUTTON_ADD)
}
];
}
/**
* * Builds and returns a JSON string with 'node' and 'name' members
* @param p_nodeJson Targeted tree node in the proper JSON format
* @param p_command from which to extract possible name and 'keep selection' flag
* @returns JSON string suitable for being a parameter of a leoBridge action
*/
export function buildNodeCommandJson(p_nodeJson: string, p_command?: UserCommand): string {
let w_json = "{\"ap\":" + p_nodeJson; // already json
if (p_command && p_command.name) {
w_json += ", \"name\": " + JSON.stringify(p_command.name);
}
if (p_command && p_command.keepSelection) {
w_json += ", \"keep\": true";
}
// TODO : Generalize this function to send any other members of p_command / other members
w_json += "}";
return w_json;
}
/**
* * Shows dialog for choosing the Leo Editor installation folder path
* @returns A promise that resolves to the selected resources or undefined
*/
export function chooseLeoFolderDialog(): Thenable<vscode.Uri[] | undefined> {
return vscode.window.showOpenDialog(
{
title: "Locate Leo-Editor Installation Folder",
canSelectMany: false,
openLabel: "Choose Folder",
canSelectFiles: false,
canSelectFolders: true
}
);
}
/**
* * Returns the milliseconds between a given starting process.hrtime tuple and the current call to process.hrtime
* @param p_start starting process.hrtime to subtract from current immediate time
* @returns number of milliseconds passed since the given start hrtime
*/
export function getDurationMs(p_start: [number, number]): number {
const [w_secs, w_nanosecs] = process.hrtime(p_start);
return w_secs * 1000 + Math.floor(w_nanosecs / 1000000);
}
/**
* * Extracts the file name from a full path, such as "foo.bar" from "/abc/def/foo.bar"
* @param p_path Full path such as "/var/drop/foo/boo/moo.js" or "C:\Documents and Settings\img\recycled log.jpg"
* @returns file name string such as "moo.js" or "recycled log.jpg""
*/
export function getFileFromPath(p_path: string): string {
return p_path.replace(/^.*[\\\/]/, '');
}
/**
* * Checks if a node would become dirty if it were to now have body content at all
* @param p_node LeoNode from vscode's outline
* @param p_newHasBody Flag to signify presence of body content, to be compared with its current state
* @returns True if it would change the icon with actual body content, false otherwise
*/
export function isIconChangedByEdit(p_node: LeoNode, p_newHasBody: boolean): boolean {
if (!p_node.dirty || (p_node.hasBody === !p_newHasBody)) {
return true;
}
return false;
}
/**
* * Checks if a string is formatted as a valid rrggbb color code.
* @param p_hexString hexadecimal 6 digits string, without leading '0x'
* @returns True if the string is a valid representation of an hexadecimal 6 digit number
*/
export function isHexColor(p_hexString: string): boolean {
return typeof p_hexString === 'string'
&& p_hexString.length === 6
&& !isNaN(Number('0x' + p_hexString));
}
/**
* * Builds a 'Leo Scheme' vscode.Uri from a gnx (or strings like 'LEO BODY' or empty strings to decorate breadcrumbs)
* with a scheme header like "leo:/" or 'more:/'
* @param p_str leo node gnx strings are used to build Uri
* @returns A vscode 'Uri' object
*/
export function strToLeoUri(p_str: string): vscode.Uri {
return vscode.Uri.parse(Constants.URI_SCHEME_HEADER + p_str);
}
/**
* * Gets the gnx, (or another string like 'LEO BODY' or other), from a vscode.Uri object
* @param p_uri Source uri to extract from
* @returns The string source that was used to build this Uri
*/
export function leoUriToStr(p_uri: vscode.Uri): string {
// TODO : Use length of a constant or something other than 'fsPath'
// For now, just remove the '/' (or backslash on Windows) before the path string
return p_uri.fsPath.substr(1);
}
/**
* * Sets a vscode context variable with 'vscode.commands.executeCommand' & 'setContext'
* @param p_key Key string name such as constants 'bridgeReady' or 'treeOpened', etc.
* @param p_value Value to be assigned to the p_key 'key'
* @returns A Thenable that is returned by the executeCommand call
*/
export function setContext(p_key: string, p_value: any): Thenable<unknown> {
return vscode.commands.executeCommand(Constants.VSCODE_COMMANDS.SET_CONTEXT, p_key, p_value);
}
/**
* * Find next available port starting with p_startingPort inclusively,
* * check next (max 5) additional ports and return port number, or 0 if none.
* @param p_startingPort the port number at which to start looking for a free port
* @returns a promise of an opened port number
*/
export function findNextAvailablePort(p_startingPort: number): Promise<number> {
return portfinder.getPortPromise({
port: p_startingPort,
startPort: p_startingPort,
stopPort: p_startingPort + 5
});
}
/**
* * Check for unique port #
* @param p_port the port number at which to look for
* @returns a promise of an opened port number - or rejection if busy port
*/
export function findSingleAvailablePort(p_port: number): Promise<number> {
return portfinder.getPortPromise({
port: p_port,
startPort: p_port,
stopPort: p_port
});
} | the_stack |
import type {Class} from "@swim/util";
import type {MemberFastenerClass} from "@swim/component";
import type {Trait} from "@swim/model";
import type {GraphicsView} from "@swim/graphics";
import {Controller, TraitViewRef, TraitViewControllerSet} from "@swim/controller";
import type {DataPointView} from "../data/DataPointView";
import type {DataPointTrait} from "../data/DataPointTrait";
import type {DataPointController} from "../data/DataPointController";
import type {DataSetTrait} from "../data/DataSetTrait";
import type {PlotView} from "../plot/PlotView";
import type {PlotTrait} from "../plot/PlotTrait";
import {PlotController} from "../plot/PlotController";
import {GraphView} from "./GraphView";
import {GraphTrait} from "./GraphTrait";
import type {GraphControllerObserver} from "./GraphControllerObserver";
/** @public */
export interface GraphControllerPlotExt<X = unknown, Y = unknown> {
attachPlotTrait(plotTrait: PlotTrait<X, Y>, plotController: PlotController<X, Y>): void;
detachPlotTrait(plotTrait: PlotTrait<X, Y>, plotController: PlotController<X, Y>): void;
attachPlotView(plotView: PlotView<X, Y>, plotController: PlotController<X, Y>): void;
detachPlotView(plotView: PlotView<X, Y>, plotController: PlotController<X, Y>): void;
attachDataSetTrait(dataSetTrait: DataSetTrait<X, Y>, plotController: PlotController<X, Y>): void;
detachDataSetTrait(dataSetTrait: DataSetTrait<X, Y>, plotController: PlotController<X, Y>): void;
attachDataPoint(dataPointController: DataPointController<X, Y>, plotController: PlotController<X, Y>): void;
detachDataPoint(dataPointController: DataPointController<X, Y>, plotController: PlotController<X, Y>): void;
attachDataPointTrait(dataPointTrait: DataPointTrait<X, Y>, dataPointController: DataPointController<X, Y>, plotController: PlotController<X, Y>): void;
detachDataPointTrait(dataPointTrait: DataPointTrait<X, Y>, dataPointController: DataPointController<X, Y>, plotController: PlotController<X, Y>): void;
attachDataPointView(dataPointView: DataPointView<X, Y>, dataPointController: DataPointController<X, Y>, plotController: PlotController<X, Y>): void;
detachDataPointView(dataPointView: DataPointView<X, Y>, dataPointController: DataPointController<X, Y>, plotController: PlotController<X, Y>): void;
attachDataPointLabelView(dataPointLabelView: GraphicsView, dataPointController: DataPointController<X, Y>, plotController: PlotController<X, Y>): void;
detachDataPointLabelView(dataPointLabelView: GraphicsView, dataPointController: DataPointController<X, Y>, plotController: PlotController<X, Y>): void;
}
/** @public */
export class GraphController<X = unknown, Y = unknown> extends Controller {
override readonly observerType?: Class<GraphControllerObserver<X, Y>>;
@TraitViewRef<GraphController<X, Y>, GraphTrait<X, Y>, GraphView<X, Y>>({
traitType: GraphTrait,
observesTrait: true,
willAttachTrait(graphTrait: GraphTrait<X, Y>): void {
this.owner.callObservers("controllerWillAttachGraphTrait", graphTrait, this.owner);
},
didAttachTrait(graphTrait: GraphTrait<X, Y>): void {
const plotTraits = graphTrait.plots.traits;
for (const traitId in plotTraits) {
const plotTrait = plotTraits[traitId]!;
this.owner.plots.addTraitController(plotTrait);
}
},
willDetachTrait(graphTrait: GraphTrait<X, Y>): void {
const plotTraits = graphTrait.plots.traits;
for (const traitId in plotTraits) {
const plotTrait = plotTraits[traitId]!;
this.owner.plots.deleteTraitController(plotTrait);
}
},
didDetachTrait(graphTrait: GraphTrait<X, Y>): void {
this.owner.callObservers("controllerDidDetachGraphTrait", graphTrait, this.owner);
},
traitWillAttachPlot(plotTrait: PlotTrait<X, Y>, targetTrait: Trait): void {
this.owner.plots.addTraitController(plotTrait, targetTrait);
},
traitDidDetachPlot(plotTrait: PlotTrait<X, Y>): void {
this.owner.plots.deleteTraitController(plotTrait);
},
viewType: GraphView,
initView(graphView: GraphView<X, Y>): void {
const plotControllers = this.owner.plots.controllers;
for (const controllerId in plotControllers) {
const plotController = plotControllers[controllerId]!;
const plotView = plotController.plot.view;
if (plotView !== null && plotView.parent === null) {
plotController.plot.insertView(graphView);
}
}
},
willAttachView(newGraphView: GraphView<X, Y>): void {
this.owner.callObservers("controllerWillAttachGraphView", newGraphView, this.owner);
},
didDetachView(newGraphView: GraphView<X, Y>): void {
this.owner.callObservers("controllerDidDetachGraphView", newGraphView, this.owner);
},
})
readonly graph!: TraitViewRef<this, GraphTrait<X, Y>, GraphView<X, Y>>;
static readonly graph: MemberFastenerClass<GraphController, "graph">;
@TraitViewControllerSet<GraphController<X, Y>, PlotTrait<X, Y>, PlotView<X, Y>, PlotController<X, Y>, GraphControllerPlotExt<X, Y>>({
implements: true,
type: PlotController,
binds: true,
observes: true,
get parentView(): GraphView<X, Y> | null {
return this.owner.graph.view;
},
getTraitViewRef(plotController: PlotController<X, Y>): TraitViewRef<unknown, PlotTrait<X, Y>, PlotView<X, Y>> {
return plotController.plot;
},
willAttachController(plotController: PlotController<X, Y>): void {
this.owner.callObservers("controllerWillAttachPlot", plotController, this.owner);
},
didAttachController(plotController: PlotController<X, Y>): void {
const plotTrait = plotController.plot.trait;
if (plotTrait !== null) {
this.attachPlotTrait(plotTrait, plotController);
}
const plotView = plotController.plot.view;
if (plotView !== null) {
this.attachPlotView(plotView, plotController);
}
const dataSetTrait = plotController.dataSet.trait;
if (dataSetTrait !== null) {
this.attachDataSetTrait(dataSetTrait, plotController);
}
},
willDetachController(plotController: PlotController<X, Y>): void {
const dataSetTrait = plotController.dataSet.trait;
if (dataSetTrait !== null) {
this.detachDataSetTrait(dataSetTrait, plotController);
}
const plotView = plotController.plot.view;
if (plotView !== null) {
this.detachPlotView(plotView, plotController);
}
const plotTrait = plotController.plot.trait;
if (plotTrait !== null) {
this.detachPlotTrait(plotTrait, plotController);
}
},
didDetachController(plotController: PlotController<X, Y>): void {
this.owner.callObservers("controllerDidDetachPlot", plotController, this.owner);
},
controllerWillAttachPlotTrait(plotTrait: PlotTrait<X, Y>, plotController: PlotController<X, Y>): void {
this.owner.callObservers("controllerWillAttachPlotTrait", plotTrait, plotController, this.owner);
this.attachPlotTrait(plotTrait, plotController);
},
controllerDidDetachPlotTrait(plotTrait: PlotTrait<X, Y>, plotController: PlotController<X, Y>): void {
this.detachPlotTrait(plotTrait, plotController);
this.owner.callObservers("controllerDidDetachPlotTrait", plotTrait, plotController, this.owner);
},
attachPlotTrait(plotTrait: PlotTrait<X, Y>, plotController: PlotController<X, Y>): void {
// hook
},
detachPlotTrait(plotTrait: PlotTrait<X, Y>, plotController: PlotController<X, Y>): void {
// hook
},
controllerWillAttachPlotView(plotView: PlotView<X, Y>, plotController: PlotController<X, Y>): void {
this.owner.callObservers("controllerWillAttachPlotView", plotView, plotController, this.owner);
this.attachPlotView(plotView, plotController);
},
controllerDidDetachPlotView(plotView: PlotView<X, Y>, plotController: PlotController<X, Y>): void {
this.detachPlotView(plotView, plotController);
this.owner.callObservers("controllerDidDetachPlotView", plotView, plotController, this.owner);
},
attachPlotView(plotView: PlotView<X, Y>, plotController: PlotController<X, Y>): void {
// hook
},
detachPlotView(plotView: PlotView<X, Y>, plotController: PlotController<X, Y>): void {
plotView.remove();
},
controllerWillAttachDataSetTrait(dataSetTrait: DataSetTrait<X, Y>, plotController: PlotController<X, Y>): void {
this.owner.callObservers("controllerWillAttachDataSetTrait", dataSetTrait, plotController, this.owner);
this.attachDataSetTrait(dataSetTrait, plotController);
},
controllerDidDetachDataSetTrait(dataSetTrait: DataSetTrait<X, Y>, plotController: PlotController<X, Y>): void {
this.detachDataSetTrait(dataSetTrait, plotController);
this.owner.callObservers("controllerDidDetachDataSetTrait", dataSetTrait, plotController, this.owner);
},
attachDataSetTrait(dataSetTrait: DataSetTrait<X, Y>, plotController: PlotController<X, Y>): void {
// hook
},
detachDataSetTrait(dataSetTrait: DataSetTrait<X, Y>, plotController: PlotController<X, Y>): void {
// hook
},
controllerWillAttachDataPoint(dataPointController: DataPointController<X, Y>, plotController: PlotController<X, Y>): void {
this.owner.callObservers("controllerWillAttachDataPoint", dataPointController, plotController, this.owner);
this.attachDataPoint(dataPointController, plotController);
},
controllerDidDetachDataPoint(dataPointController: DataPointController<X, Y>, plotController: PlotController<X, Y>): void {
this.detachDataPoint(dataPointController, plotController);
this.owner.callObservers("controllerDidDetachDataPoint", dataPointController, plotController, this.owner);
},
attachDataPoint(dataPointController: DataPointController<X, Y>, plotController: PlotController<X, Y>): void {
const dataPointTrait = dataPointController.dataPoint.trait;
if (dataPointTrait !== null) {
this.attachDataPointTrait(dataPointTrait, dataPointController, plotController);
}
const dataPointView = dataPointController.dataPoint.view;
if (dataPointView !== null) {
this.attachDataPointView(dataPointView, dataPointController, plotController);
}
},
detachDataPoint(dataPointController: DataPointController<X, Y>, plotController: PlotController<X, Y>): void {
const dataPointTrait = dataPointController.dataPoint.trait;
if (dataPointTrait !== null) {
this.detachDataPointTrait(dataPointTrait, dataPointController, plotController);
}
const dataPointView = dataPointController.dataPoint.view;
if (dataPointView !== null) {
this.detachDataPointView(dataPointView, dataPointController, plotController);
}
},
controllerWillAttachDataPointTrait(dataPointTrait: DataPointTrait<X, Y>, dataPointController: DataPointController<X, Y>, plotController: PlotController<X, Y>): void {
this.owner.callObservers("controllerWillAttachDataPointTrait", dataPointTrait, dataPointController, plotController, this.owner);
this.attachDataPointTrait(dataPointTrait, dataPointController, plotController);
},
controllerDidDetachDataPointTrait(dataPointTrait: DataPointTrait<X, Y>, dataPointController: DataPointController<X, Y>, plotController: PlotController<X, Y>): void {
this.detachDataPointTrait(dataPointTrait, dataPointController, plotController);
this.owner.callObservers("controllerDidDetachDataPointTrait", dataPointTrait, dataPointController, plotController, this.owner);
},
attachDataPointTrait(dataPointTrait: DataPointTrait<X, Y>, dataPointController: DataPointController<X, Y>, plotController: PlotController<X, Y>): void {
// hook
},
detachDataPointTrait(dataPointTrait: DataPointTrait<X, Y>, dataPointController: DataPointController<X, Y>, plotController: PlotController<X, Y>): void {
// hook
},
controllerWillAttachDataPointView(dataPointView: DataPointView<X, Y>, dataPointController: DataPointController<X, Y>, plotController: PlotController<X, Y>): void {
this.owner.callObservers("controllerWillAttachDataPointView", dataPointView, dataPointController, plotController, this.owner);
this.attachDataPointView(dataPointView, dataPointController, plotController);
},
controllerDidDetachDataPointView(dataPointView: DataPointView<X, Y>, dataPointController: DataPointController<X, Y>, plotController: PlotController<X, Y>): void {
this.detachDataPointView(dataPointView, dataPointController, plotController);
this.owner.callObservers("controllerDidDetachDataPointView", dataPointView, dataPointController, plotController, this.owner);
},
attachDataPointView(dataPointView: DataPointView<X, Y>, dataPointController: DataPointController<X, Y>, plotController: PlotController<X, Y>): void {
const labelView = dataPointView.label.view;
if (labelView !== null) {
this.attachDataPointLabelView(labelView, dataPointController, plotController);
}
},
detachDataPointView(dataPointView: DataPointView<X, Y>, dataPointController: DataPointController<X, Y>, plotController: PlotController<X, Y>): void {
const labelView = dataPointView.label.view;
if (labelView !== null) {
this.detachDataPointLabelView(labelView, dataPointController, plotController);
}
},
controllerWillAttachDataPointLabelView(labelView: GraphicsView, dataPointController: DataPointController<X, Y>, plotController: PlotController<X, Y>): void {
this.owner.callObservers("controllerWillAttachDataPointLabelView", labelView, dataPointController, plotController, this.owner);
this.attachDataPointLabelView(labelView, dataPointController, plotController);
},
controllerDidDetachDataPointLabelView(labelView: GraphicsView, dataPointController: DataPointController<X, Y>, plotController: PlotController<X, Y>): void {
this.detachDataPointLabelView(labelView, dataPointController, plotController);
this.owner.callObservers("controllerDidDetachDataPointLabelView", labelView, dataPointController, plotController, this.owner);
},
attachDataPointLabelView(dataPointLabelView: GraphicsView, dataPointController: DataPointController<X, Y>, plotController: PlotController<X, Y>): void {
// hook
},
detachDataPointLabelView(dataPointLabelView: GraphicsView, dataPointController: DataPointController<X, Y>, plotController: PlotController<X, Y>): void {
// hook
},
createController(plotTrait?: PlotTrait<X, Y>): PlotController<X, Y> {
if (plotTrait !== void 0) {
return PlotController.fromTrait(plotTrait);
} else {
return TraitViewControllerSet.prototype.createController.call(this);
}
},
})
readonly plots!: TraitViewControllerSet<this, PlotTrait<X, Y>, PlotView<X, Y>, PlotController<X, Y>>;
static readonly plots: MemberFastenerClass<GraphController, "plots">;
} | the_stack |
import React, { Component, useLayoutEffect } from 'react'
import { View, Button, Text, unstable_batchedUpdates } from 'react-native'
import { createStore, applyMiddleware } from 'redux'
import {
Provider as ProviderMock,
connect,
batch,
useSelector,
useDispatch,
} from '../../src/index'
import { useIsomorphicLayoutEffect } from '../../src/utils/useIsomorphicLayoutEffect'
import * as rtl from '@testing-library/react-native'
import '@testing-library/jest-native/extend-expect'
import type { MiddlewareAPI, Dispatch as ReduxDispatch } from 'redux'
describe('React Native', () => {
const propMapper = (prop: any) => {
switch (typeof prop) {
case 'object':
case 'boolean':
return JSON.stringify(prop)
case 'function':
return '[function ' + prop.name + ']'
default:
return prop
}
}
interface PassthroughPropsType {
[x: string]: any
}
class Passthrough extends Component<PassthroughPropsType> {
render() {
return (
<View>
{Object.keys(this.props).map((prop) => (
<View testID={prop} key={prop}>
{propMapper(this.props[prop])}
</View>
))}
</View>
)
}
}
interface ActionType {
type: string
body?: string
}
function stringBuilder(prev = '', action: ActionType) {
return action.type === 'APPEND' ? prev + action.body : prev
}
afterEach(() => rtl.cleanup())
describe('batch', () => {
it('batch should be RN unstable_batchedUpdates', () => {
expect(batch).toBe(unstable_batchedUpdates)
})
})
describe('useIsomorphicLayoutEffect', () => {
it('useIsomorphicLayoutEffect should be useLayoutEffect', () => {
expect(useIsomorphicLayoutEffect).toBe(useLayoutEffect)
})
})
describe('Subscription and update timing correctness', () => {
it('should pass state consistently to mapState', () => {
type RootStateType = string
type NoDispatch = {}
const store = createStore(stringBuilder)
rtl.act(() => {
store.dispatch({ type: 'APPEND', body: 'a' })
})
let childMapStateInvokes = 0
interface ContainerTStatePropsType {
state: RootStateType
}
type ContainerOwnOwnPropsType = {}
class Container extends Component<ContainerTStatePropsType> {
emitChange() {
store.dispatch({ type: 'APPEND', body: 'b' })
}
render() {
return (
<View>
<Button
title="change"
testID="change-button"
onPress={this.emitChange.bind(this)}
/>
<ConnectedChildrenContainer parentState={this.props.state} />
</View>
)
}
}
const ConnectedContainer = connect<
ContainerTStatePropsType,
NoDispatch,
ContainerOwnOwnPropsType,
RootStateType
>((state) => ({ state }))(Container)
const childCalls: Array<[string, string]> = []
type ChildrenTStatePropsType = {}
type ChildrenOwnPropsType = {
parentState: string
}
class ChildContainer extends Component {
render() {
return <Passthrough {...this.props} />
}
}
const ConnectedChildrenContainer = connect<
ChildrenTStatePropsType,
NoDispatch,
ChildrenOwnPropsType,
RootStateType
>((state, parentProps) => {
childMapStateInvokes++
childCalls.push([state, parentProps.parentState])
// The state from parent props should always be consistent with the current state
expect(state).toEqual(parentProps.parentState)
return {}
})(ChildContainer)
const tester = rtl.render(
<ProviderMock store={store}>
<ConnectedContainer />
</ProviderMock>
)
expect(childMapStateInvokes).toBe(1)
expect(childCalls).toEqual([['a', 'a']])
rtl.act(() => {
store.dispatch({ type: 'APPEND', body: 'c' })
})
expect(childMapStateInvokes).toBe(2)
expect(childCalls).toEqual([
['a', 'a'],
['ac', 'ac'],
])
// setState calls DOM handlers are batched
const button = tester.getByTestId('change-button')
rtl.fireEvent.press(button)
expect(childMapStateInvokes).toBe(3)
rtl.act(() => {
store.dispatch({ type: 'APPEND', body: 'd' })
})
expect(childMapStateInvokes).toBe(4)
expect(childCalls).toEqual([
['a', 'a'],
['ac', 'ac'],
['acb', 'acb'],
['acbd', 'acbd'],
])
})
it('should invoke mapState always with latest props', () => {
// Explicitly silence "not wrapped in act()" messages for this test
const spy = jest.spyOn(console, 'error')
spy.mockImplementation(() => {})
type RootStateType = number
type NoDispatch = {}
const store = createStore((state: RootStateType = 0) => state + 1)
interface TStatePropsType {
reduxCount: number
}
interface OwnPropsType {
count: number
}
let propsPassedIn: TStatePropsType & OwnPropsType
class InnerComponent extends Component<TStatePropsType & OwnPropsType> {
render() {
propsPassedIn = this.props
return <Passthrough {...this.props} />
}
}
const ConnectedInner = connect<
TStatePropsType,
NoDispatch,
OwnPropsType,
RootStateType
>((reduxCount) => {
return { reduxCount }
})(InnerComponent)
type OutStateType = {
count: number
}
class OuterComponent extends Component<{}, OutStateType> {
constructor(props: {}) {
super(props)
this.state = { count: 0 }
}
render() {
return <ConnectedInner {...this.state} />
}
}
let outerComponent = React.createRef<OuterComponent>()
rtl.render(
<ProviderMock store={store}>
<OuterComponent ref={outerComponent} />
</ProviderMock>
)
outerComponent.current!.setState(({ count }) => ({ count: count + 1 }))
store.dispatch({ type: '' })
//@ts-ignore
expect(propsPassedIn.count).toEqual(1)
//@ts-ignore
expect(propsPassedIn.reduxCount).toEqual(2)
spy.mockRestore()
})
it('should use the latest props when updated between actions', () => {
// Explicitly silence "not wrapped in act()" messages for this test
const spy = jest.spyOn(console, 'error')
spy.mockImplementation(() => {})
type ActionType = {
type: string
payload?: () => void
}
const reactCallbackMiddleware = (store: MiddlewareAPI) => {
let callback: () => void
return (next: ReduxDispatch) => (action: ActionType) => {
if (action.type === 'SET_COMPONENT_CALLBACK') {
callback = action.payload!
}
if (callback && action.type === 'INC1') {
// Deliberately create multiple updates of different types in a row:
// 1) Store update causes subscriber notifications
next(action)
// 2) React setState outside batching causes a sync re-render.
// Because we're not using `act()`, this won't flush pending passive effects,
// simulating
callback()
// 3) Second dispatch causes subscriber notifications again. If `connect` is working
// correctly, nested subscriptions won't execute until the parents have rendered,
// to ensure that the subscriptions have access to the latest wrapper props.
store.dispatch({ type: 'INC2' })
return
}
next(action)
}
}
type RootStateType = number
const counter = (state: RootStateType = 0, action: ActionType) => {
if (action.type === 'INC1') {
return state + 1
} else if (action.type === 'INC2') {
return state + 2
}
return state
}
const store = createStore(
counter,
applyMiddleware(reactCallbackMiddleware)
)
interface ChildrenTStatePropsType {
count: RootStateType
}
type NoDispatch = {}
type OwnPropsType = {
prop: string
}
const Child = connect<
ChildrenTStatePropsType,
NoDispatch,
OwnPropsType,
RootStateType
>((count) => ({ count }))(function (
props: OwnPropsType & ChildrenTStatePropsType
) {
return (
<View>
<Text testID="child-prop">{props.prop}</Text>
<Text testID="child-count">{props.count}</Text>
</View>
)
})
interface ParentPropsType {
prop: string
}
class Parent extends Component<{}, ParentPropsType> {
inc1: () => void
constructor(props: {}) {
super(props)
this.state = {
prop: 'a',
}
this.inc1 = () => store.dispatch({ type: 'INC1' })
store.dispatch({
type: 'SET_COMPONENT_CALLBACK',
payload: () => this.setState({ prop: 'b' }),
})
}
render() {
return (
<ProviderMock store={store}>
<Child prop={this.state.prop} />
</ProviderMock>
)
}
}
let parent = React.createRef<Parent>()
const rendered = rtl.render(<Parent ref={parent} />)
expect(rendered.getByTestId('child-count').children).toEqual(['0'])
expect(rendered.getByTestId('child-prop').children).toEqual(['a'])
// Force the multi-update sequence by running this bound action creator
parent.current!.inc1()
// The connected child component _should_ have rendered with the latest Redux
// store value (3) _and_ the latest wrapper prop ('b').
expect(rendered.getByTestId('child-count')).toHaveTextContent('3')
expect(rendered.getByTestId('child-prop')).toHaveTextContent('b')
spy.mockRestore()
})
it('should invoke mapState always with latest store state', () => {
// Explicitly silence "not wrapped in act()" messages for this test
const spy = jest.spyOn(console, 'error')
spy.mockImplementation(() => {})
type RootStateType = number
const store = createStore((state: RootStateType = 0) => state + 1)
let reduxCountPassedToMapState
class InnerComponent extends Component {
render() {
return <Passthrough {...this.props} />
}
}
interface InnerTStatePropsType {
a: string
}
type NoDispatch = {}
type InnerOwnPropsType = {
count: number
}
const ConnectedInner = connect<
InnerTStatePropsType,
NoDispatch,
InnerOwnPropsType,
RootStateType
>((reduxCount) => {
reduxCountPassedToMapState = reduxCount
return reduxCount < 2 ? { a: 'a' } : { a: 'b' }
})(InnerComponent)
interface OuterState {
count: number
}
class OuterComponent extends Component<{}, OuterState> {
constructor(props: {}) {
super(props)
this.state = { count: 0 }
}
render() {
return <ConnectedInner {...this.state} />
}
}
let outerComponent = React.createRef<OuterComponent>()
rtl.render(
<ProviderMock store={store}>
<OuterComponent ref={outerComponent} />
</ProviderMock>
)
store.dispatch({ type: '' })
store.dispatch({ type: '' })
outerComponent.current!.setState(({ count }) => ({ count: count + 1 }))
expect(reduxCountPassedToMapState).toEqual(3)
spy.mockRestore()
})
it('1should ensure top-down updates for consecutive batched updates', () => {
const INC = 'INC'
type ActionType = {
type: string
}
type RootStateType = number
const reducer = (c: RootStateType = 0, { type }: ActionType) =>
type === INC ? c + 1 : c
const store = createStore(reducer)
let executionOrder: string[] = []
let expectedExecutionOrder = [
'parent map',
'parent render',
'child map',
'child render',
]
const ChildImpl = () => {
executionOrder.push('child render')
return <View>child</View>
}
const Child = connect((state) => {
executionOrder.push('child map')
return { state }
})(ChildImpl)
const ParentImpl = () => {
executionOrder.push('parent render')
return <Child />
}
const Parent = connect((state) => {
executionOrder.push('parent map')
return { state }
})(ParentImpl)
rtl.render(
<ProviderMock store={store}>
<Parent />
</ProviderMock>
)
executionOrder = []
rtl.act(() => {
store.dispatch({ type: INC })
store.dispatch({ type: '' })
})
expect(executionOrder).toEqual(expectedExecutionOrder)
})
})
describe('useSelector', () => {
it('should stay in sync with the store', () => {
// https://github.com/reduxjs/react-redux/issues/1437
jest.useFakeTimers()
// Explicitly silence "not wrapped in act()" messages for this test
const spy = jest.spyOn(console, 'error')
spy.mockImplementation(() => {})
const INIT_STATE = { bool: false }
type ActionType = {
type: string
}
interface RootStateType {
bool: boolean
}
const reducer = (
state: RootStateType = INIT_STATE,
action: ActionType
) => {
switch (action.type) {
case 'TOGGLE':
return { bool: !state.bool }
default:
return state
}
}
const store = createStore(reducer, INIT_STATE)
const selector = (state: RootStateType) => ({
bool: state.bool,
})
const ReduxBugParent = () => {
const dispatch = useDispatch()
const { bool } = useSelector(selector)
const boolFromStore = store.getState().bool
expect(boolFromStore).toBe(bool)
return (
<>
<Button
title="Click Me"
testID="standardBatching"
onPress={() => {
dispatch({ type: 'NOOP' })
dispatch({ type: 'TOGGLE' })
}}
/>
<Button
title="[BUG] Click Me (setTimeout)"
testID="setTimeout"
onPress={() => {
setTimeout(() => {
dispatch({ type: 'NOOP' })
dispatch({ type: 'TOGGLE' })
}, 0)
}}
/>
<Button
title="Click Me (setTimeout & batched from react-native)"
testID="unstableBatched"
onPress={() => {
setTimeout(() => {
unstable_batchedUpdates(() => {
dispatch({ type: 'NOOP' })
dispatch({ type: 'TOGGLE' })
})
}, 0)
}}
/>
<Button
title="Click Me (setTimeout & batched from react-redux)"
testID="reactReduxBatch"
onPress={() => {
setTimeout(() => {
batch(() => {
dispatch({ type: 'NOOP' })
dispatch({ type: 'TOGGLE' })
})
}, 0)
}}
/>
<Text testID="boolFromSelector">
bool from useSelector is {JSON.stringify(bool)}
</Text>
<Text testID="boolFromStore">
bool from store.getState is {JSON.stringify(boolFromStore)}
</Text>
{bool !== boolFromStore && <Text>They are not same!</Text>}
</>
)
}
const ReduxBugDemo = () => {
return (
<ProviderMock store={store}>
<ReduxBugParent />
</ProviderMock>
)
}
const rendered = rtl.render(<ReduxBugDemo />)
type RenderedType = typeof rendered
const assertValuesMatch = (rendered: RenderedType) => {
const [, boolFromSelector] =
rendered.getByTestId('boolFromSelector').children
const [, boolFromStore] = rendered.getByTestId('boolFromStore').children
expect(boolFromSelector).toBe(boolFromStore)
}
const clickButton = (rendered: RenderedType, testID: string) => {
const button = rendered.getByTestId(testID)
rtl.fireEvent.press(button)
}
const clickAndRender = (rendered: RenderedType, testId: string) => {
// Note: Normally we'd wrap this all in act(), but that automatically
// wraps your code in batchedUpdates(). The point of this bug is that it
// specifically occurs when you are _not_ batching updates!
clickButton(rendered, testId)
jest.advanceTimersByTime(100)
assertValuesMatch(rendered)
}
assertValuesMatch(rendered)
clickAndRender(rendered, 'setTimeout')
clickAndRender(rendered, 'standardBatching')
clickAndRender(rendered, 'unstableBatched')
clickAndRender(rendered, 'reactReduxBatch')
spy.mockRestore()
})
})
}) | the_stack |
import * as Configuration from "../Configuration";
import * as Meta from "../Meta";
import * as Utils from "../Utils/Utils-Index";
// NOTE:
// We wrote our own custom JSON serialization rather than using an existing npm package (like https://www.npmjs.com/package/json2typescript) because we
// wanted to retain control over serialization for performance, interoperability (with LB's in other languages), and because of the close relationship
// between serialization and code-gen (for example, deciding what TS language elements are publishable and therefore must be serializable).
// We also wanted to avoid the risks involved in taking a third-party dependency after this burned the original C# LB (to enable Async methods).
// If a developer wants to use a third-party serializer, they can still do this (albeit in a compromised way) by "tunnelling" the serialized data
// through a 'raw byte' Uint8Array (for method parameters and appState) and foregoing the use of published types.
const CUSTOM_SERIALIZATION_PREFIX: string = "{__ACSv1__}"; // Note: This MUST start with "{" in order for the produced JSON to not be treated as 'raw' bytes by the IncomingRPC constructor
const BYTE_HEX_VALUES: string[] = [...Array(256)].map((v, i) => (i < 16 ? "0" : "") + i.toString(16)); // ["00".."FF"] Used for fast number-to-hex conversion of a byte value (0..255)
/** Returns true if the specified value requires custom serialization. */
function requiresCustomJSON(value: any): boolean
{
const _value: any = (value instanceof Object) ? value.valueOf() : value;
const requiresCustomJSON: boolean =
(typeof _value === "bigint") ||
((typeof _value === "number") && (isNaN(value) || !isFinite(value))) || // NaN, Infinity or -Infinity
(value instanceof Date) ||
(value instanceof Int8Array) ||
(value instanceof Uint8Array) ||
(value instanceof Uint8ClampedArray) ||
(value instanceof Int16Array) ||
(value instanceof Uint16Array) ||
(value instanceof Int32Array) ||
(value instanceof Uint32Array) ||
(value instanceof Float32Array) ||
(value instanceof Float64Array) ||
(value instanceof BigInt64Array) ||
(value instanceof BigUint64Array) ||
(value instanceof Set) ||
(value instanceof Map) ||
(value instanceof Error);
return (requiresCustomJSON);
}
let _jsonStringifyRecursionDepth: number = 0; // Flag used to prevent running checkForCircularReferences() more than once when using jsonStringify(); safe to use because JS is single-threaded
/**
* Converts the supplied Uint8Array into a string made up of 2-character hexidecimal values (for example, [3, 127] becomes "037f").
* To decode the produced string, use Uint8ArrayFromHexString().\
* Note: This is up to 30% slower than Uint8Array.toString(), but the string it produces is up to 50% smaller (44% smaller on average).
*/
export function Uint8ArrayToHexString(byteArray: Uint8Array): string
{
const hexValues: string[] = [];
for (let i = 0; i < byteArray.length; i++)
{
hexValues.push(BYTE_HEX_VALUES[byteArray[i]]);
}
return (hexValues.join(""));
}
/**
* Converts the supplied hexidecimal string (eg. "037f"), produced by Uint8ArrayToHexString(), back into a Uint8Array.
* This is up to 40% faster than decoding from a JSON encoded array, ie. Uint8Array.from(JSON.parse(encoded)).
*/
export function Uint8ArrayFromHexString(hex: string): Uint8Array
{
if (!hex || (hex.length === 0))
{
return (new Uint8Array());
}
if (hex.length % 2 !== 0)
{
throw new Error(`The supplied 'hex' string is of length ${hex.length} when an even number was expected`);
}
const byteArray: Uint8Array = new Uint8Array(hex.length / 2);
for (let i = 0; i < byteArray.length; i++)
{
const pos = i * 2;
byteArray[i] = parseInt(hex[pos] + hex[pos + 1], 16);
}
return (byteArray);
}
/**
* Custom JSON serializer that preserves the type of typed-arrays (eg. Uint8Array) and BigInt, Set, Map, Date, RegExp and Error objects.\
* Objects with literal forms will be converted to those literal forms (eg. new String("Test") will become "Test", BigInt("123") will become 123n).\
* For non-built-in objects, any object property descriptors (eg. 'writable') will be lost.\
* Note: Typed-arrays, BigInt, Set, Map, Date, RegExp and Error objects will only be preserved between JS language bindings (not cross-language), but only if 'allowCustomSerialization' is true.\
* Note: Array element with the value 'undefined' will become null. Members with the value 'undefined' will be removed.\
* Note: Properties named using Symbols, and any prototype-inherited properties, will not be serialized (which is standard JSON.stringify() behavior
* [see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#symbols_and_json.stringify
* and https://stackoverflow.com/questions/8779249/how-to-stringify-inherited-objects-to-json])
*/
export function jsonStringify(value: any, objectExpected: boolean = true, allowCustomSerialization: boolean = Configuration.loadedConfig().lbOptions.allowCustomJSONSerialization): string
{
/** [Local function] Returns either a custom serialization string for the supplied value (based on its type), or the unaltered value. */
function replacer(key: string, value: any): any
{
let typedArrayName: string = "";
if (value instanceof Int8Array) { typedArrayName = "##Int8Array##"; } else
if (value instanceof Uint8Array) { typedArrayName = "##Uint8Array##"; } else
if (value instanceof Uint8ClampedArray) { typedArrayName = "##Uint8ClampedArray##"; } else
if (value instanceof Int16Array) { typedArrayName = "##Int16Array##"; } else
if (value instanceof Uint16Array) { typedArrayName = "##Uint16Array##"; } else
if (value instanceof Int32Array) { typedArrayName = "##Int32Array##"; } else
if (value instanceof Uint32Array) { typedArrayName = "##Uint32Array##"; } else
if (value instanceof Float32Array) { typedArrayName = "##Float32Array##"; } else
if (value instanceof Float64Array) { typedArrayName = "##Float64Array##"; } else
if (value instanceof BigInt64Array) { typedArrayName = "##BigInt64Array##"; } else
if (value instanceof BigUint64Array) { typedArrayName = "##BigUint64Array##"; }
if (typedArrayName)
{
if (value instanceof Uint8Array)
{
// Special case: optimized for both smaller string size (up to 50% smaller), and lower total [encode/decode] execution time (~15% faster)
return (`${typedArrayName}${Utils.Uint8ArrayToHexString(value)}`); // Note: No square brackets around the value
}
else
{
return (`${typedArrayName}[${value.toString()}]`);
}
}
else
{
switch (typeof ((value instanceof Object) ? value.valueOf() : value))
{
case "bigint":
return (`${value.toString()}n`);
case "number":
// Note: Without this, NaN, Infinity and -Infinity would all serialize to null
if (isNaN(value)) { return ("##NaN##"); };
if (!isFinite(value)) { return (value > 0 ? "##Infinity##" : "##-Infinity##"); }
break;
case "string":
// Note: We can't simply check "value instanceof Date" because JSON.stringify() has already converted the Date to a string
if ((value.length === 24) && value.endsWith("Z") && !isNaN(new Date(value).valueOf()))
{
return (`##Date##${value}`);
}
break;
case "object":
// Note: WeakSet objects are not supported because they are not iterable
if (value instanceof Set)
{
return (`##Set##${jsonStringify([...value], false)}`);
}
// Note: WeakMap objects are not supported because they are not iterable
if (value instanceof Map)
{
return (`##Map##${jsonStringify([...value], false)}`);
}
if (value instanceof RegExp)
{
return (`##RegExp##${value.toString()}`);
}
if (value instanceof Error)
{
return (`##Error##${jsonStringify({name: value.name, message: value.message, stack: value.stack})}`);
}
break;
}
// Note: We cannot preserve undefined (either as an array element value or as a property value) because JSON.parse() ALWAYS removes all undefined values.
// So undefined array elements will become null (which is the default JSON.stringify() behavior); if we tried to preserve them using a "##undefined##"
// token, the parsed array would end up with "holes" [missing indicies] where the undefined elements previously were.
return (value);
}
}
/** [Local function] Returns true if any member [including array element values] is of a type that requires custom JSON serialization. */
function checkObjectTree(o: Utils.SimpleObject): boolean
{
if (requiresCustomJSON(o))
{
return (true);
}
// Note: When o is an array (including Uint8Array, etc.), propName will be the index, so - in the worst case - we will end up walking ALL array elements
for (let propName in o)
{
// JSON.stringify() doesn't serialize prototype-inherited properties, so we can skip those [see: https://stackoverflow.com/questions/8779249/how-to-stringify-inherited-objects-to-json]
if (!Object.prototype.hasOwnProperty.call(o, propName)) // Using Object.prototype because o.hasOwnProperty() can be redefined (shadowed)
{
continue;
}
const value: any = o[propName];
if (value !== null)
{
// Note: A simple "if (checkObjectTree(value)) { return (true); }" would suffice here, but we include an optimization for
// the common case of a homogenous array of non-objects, eg. string[], by not calling checkObjectTree() for every
// element and instead calling requiresCustomJSON() directly (thus skipping an extra function call for each element).
if (typeof value === "object")
{
if (checkObjectTree(value))
{
return (true);
}
}
else
{
if (requiresCustomJSON(value))
{
return (true);
}
}
}
}
return (false);
}
try
{
// Any object (like NodeJS.Timeout) that has circular references between members will result in a 'RangeError: Maximum call stack size exceeded' in checkObjectTree().
// So to prevent this we first explicitly check for circular references.
try
{
// checkForCircularReferences() is exhaustive, so we don't need to run it more than once. Further, by only calling
// it once at the start, any reported error will have the context of the root object, not some nested object.
if (_jsonStringifyRecursionDepth++ === 0)
{
// This will throw if it finds a circular reference or an unsupported object type (eg. WeakSet)
checkForCircularReferences(value, true);
}
}
catch (error: unknown)
{
throw new Error(`Unable to serialize object to JSON (reason: ${Utils.makeError(error).message})`);
}
// Using a 'replacer' function in JSON.stringify() is expensive (eg. ~5x slower) because it's called not only for each property, but also for EACH item in any array.
// Consequently, we check whether the object contains any properties [or array items] that are of a type that requires using the 'replacer' at all.
// This check itself is expensive, but - thanks to early termination and fewer total function calls - it's usually considerably less expensive (2 to 3x) than [unnecessarily] using 'replacer'.
let customSerializerRequired: boolean = allowCustomSerialization && checkObjectTree(value);
let json: string = JSON.stringify(value, customSerializerRequired ? replacer : undefined);
if (objectExpected && ((json === undefined) || (json[0] !== "{")))
{
// Note: When serializing method parameters, the generated JSON MUST start with "{" in order for it to NOT be treated as 'raw' bytes by the IncomingRPC constructor
throw new Error("The value to be serialized to JSON is not an object; either supply an object, or set 'objectExpected' to false");
}
if (customSerializerRequired)
{
return (CUSTOM_SERIALIZATION_PREFIX + json);
}
return (json);
}
finally
{
_jsonStringifyRecursionDepth--;
}
}
/**
* Custom JSON deserializer that re-creates an object (or primitive value) from the supplied serialization string [produced by jsonStringify()].\
* See jsonStringify() for the serialization capabilities and limitations.
*/
export function jsonParse(text: string): any
{
function reviver(key: string, value: any): any
{
let isString = (o: any): o is string => ((typeof value === "string") || (value instanceof String)); // Local 'type guard' function
if (isString(value) && /^##[A-Za-z0-9]+Array##\[?/.test(value)) // Note: 'value' can be a complex type string that includes, for example, "Int8Array[" at a location other than the start
{
if (value.indexOf("##Int8Array##[") === 0) { return (Int8Array.from(JSON.parse(value.substring(13)))) } else
if (value.indexOf("##Uint8Array##") === 0) { return (Utils.Uint8ArrayFromHexString(value.substring(14))) } else // Note: No square brackets around the value
if (value.indexOf("##Uint8ClampedArray##[") === 0) { return (Uint8ClampedArray.from(JSON.parse(value.substring(21)))) } else
if (value.indexOf("##Int16Array##[") === 0) { return (Int16Array.from(JSON.parse(value.substring(14)))) } else
if (value.indexOf("##Uint16Array##[") === 0) { return (Uint16Array.from(JSON.parse(value.substring(15)))) } else
if (value.indexOf("##Int32Array##[") === 0) { return (Int32Array.from(JSON.parse(value.substring(14)))) } else
if (value.indexOf("##Uint32Array##[") === 0) { return (Uint32Array.from(JSON.parse(value.substring(15)))) } else
if (value.indexOf("##Float32Array##[") === 0) { return (Float32Array.from(JSON.parse(value.substring(16)))) } else
if (value.indexOf("##Float64Array##[") === 0) { return (Float64Array.from(JSON.parse(value.substring(16)))) } else
if (value.indexOf("##BigInt64Array##[") === 0) { return (BigInt64Array.from(value.substring(18, value.length - 1).split(",").map(BigInt))) } else
if (value.indexOf("##BigUint64Array##[") === 0) { return (BigUint64Array.from(value.substring(19, value.length - 1).split(",").map(BigInt))) }
return (value);
}
else
{
if (isString(value))
{
if ((value[value.length - 1] === "n") && /^-?\d+n$/.test(value))
{
return (BigInt(value.substring(0, value.length - 1)));
}
if (value.startsWith("##"))
{
switch (value)
{
case "##NaN##":
return (NaN);
case "##Infinity##":
return (Infinity);
case "##-Infinity##":
return (-Infinity);
}
if (value.startsWith("##Date##") && (value.length > 8))
{
return (new Date(value.substring(8, value.length)));
}
if (value.startsWith("##Set##") && (value.length > 7))
{
const elementArray: string = value.substring(7, value.length);
return (new Set(jsonParse(elementArray)));
}
if (value.startsWith("##Map##") && (value.length > 7))
{
const kvElementsArray: string = value.substring(7, value.length);
return (new Map(jsonParse(kvElementsArray)));
}
if (value.startsWith("##RegExp##") && (value.length > 10))
{
const re: string = value.substring(10, value.length);
const matchResults: RegExpMatchArray | null = re.match(/\/(.*)\/(.*)?/);
if (!matchResults)
{
throw new Error(`Malformed serialized RegExp ("${re}")`);
}
const body: string = matchResults[1];
const flags: string = matchResults[2] || "";
return (new RegExp(body, flags));
}
if (value.startsWith("##Error##") && (value.length > 9))
{
const error: Error = jsonParse(value.substring(9, value.length));
const newError = new Error(error.message);
newError.name = error.name;
newError.stack = error.stack;
return (newError);
}
}
}
return (value);
}
}
if (text === undefined)
{
return (undefined);
}
// Note: Only if 'text' comes from jsonStringify() will it start with CUSTOM_SERIALIZATION_PREFIX [so, for example, if 'text' comes from the C# LB it will never have this prefix]
let customDeserializerRequired: boolean = (text.substr(0, CUSTOM_SERIALIZATION_PREFIX.length) === CUSTOM_SERIALIZATION_PREFIX);
return (JSON.parse(customDeserializerRequired ? text.substr(CUSTOM_SERIALIZATION_PREFIX.length) : text, customDeserializerRequired ? reviver : undefined));
}
/** The names of all types that we support serialization for (cached for speed). */
const _supportedTypes: string[] = [...Meta.Type.getSupportedNativeTypes()];
/** [Internal] All the strings that can be used (in the serialization format) as a token for either a built-in constructed object or a special value. */
export const _serializationTokens: string[] =
[
"##Map##", "##Set##", "##Date##", "##Error##", "##RegExp##", "##NaN##", "##Infinity##", "##-Infinity##",
"##Int8Array##", "##Uint8Array##", "##Uint8ClampedArray##", "##Int16Array##", "##Uint16Array##",
"##Int32Array##", "##Uint32Array##", "##Float32Array##", "##Float64Array##", "##BigInt64Array##", "##BigUint64Array##"
];
/**
* [Internal] Throws if the specified object has members [or array elements] that form a circular reference.
* If 'checkForSerializability' is true, also throws if a type is encountered which Ambrosia doesn't serialize.
*/
// Adapted from https://stackoverflow.com/questions/14962018/detecting-and-fixing-circular-references-in-javascript
// Preliminary testing indicates that this is about 20% slower than JSON.stringify() to detect circular references.
export function checkForCircularReferences(obj: object, checkForSerializability: boolean = false): void
{
const supportedTypes: string[] = !checkForSerializability? [] : _supportedTypes;
const keyStack: string[] = [];
const objectStack: Set<object> = new Set<object>();
let errorMsg: string = "";
/** [Local function] Returns the path (and description) of 'key'. */
function getKeyPath(key: string): { path: string, keyDescription: string }
{
let objectChain: object[] = [...objectStack];
let keyPath: string = keyStack.join(".") + (keyStack.length > 0 ? "." : "") + key;
let keyName: string = (keyStack.length > 0) ? "a property" : "a value";
if (objectChain[objectChain.length - 1] instanceof Set)
{
keyPath = `${keyStack.join(".")}[${key}]`;
keyName = "a Set entry";
}
else
{
// Note: We must check for Map before checking for Array because a Map's members are always 2-element [key, value] arrays
if ((objectChain.length >= 2) && (objectChain[objectChain.length - 2] instanceof Map))
{
const mapPart: string = (key === "0") ? "key" : "value";
keyPath = `${keyStack.slice(0, -1).join(".")}[${keyStack[keyStack.length - 1]}].${mapPart}`;
keyName = `a Map ${mapPart}`;
}
else
{
if (objectChain[objectChain.length - 1] instanceof Array)
{
keyPath = `${keyStack.join(".")}[${key}]`;
keyName = "an array element";
}
}
}
return ({ path: keyPath, keyDescription: keyName });
}
/** [Local function] Returns true if 'obj' appears anywhere up the current objectStack chain. */
function detectCircularReference(obj: object, key: string): boolean
{
if ((obj !== null) && (typeof obj !== "object")) // Note: If obj is an array, 'typeof obj' will still return "object"
{
return (false);
}
if (objectStack.has(obj)) // A Set object has O(1) lookup speed compared to O(N) for an array [Set.has() is about 5000x faster than Array.indexOf(), and Object[key] is 2x faster that Set.has()]
{
// We found a [circular] reference to something earlier in the chain
let objectChain: object[] = [...objectStack];
let keyPath: { path: string, keyDescription: string } = getKeyPath(key);
let referencerName: string = keyPath.path;
let referencerDescription: string = keyPath.keyDescription;
let referencedObjectIndex: number = objectChain.indexOf(obj);
let referencedObjectName: string = keyStack.slice(0, referencedObjectIndex + 1).join(".");
let referencedObjectType: string = obj.constructor.name;
errorMsg = `${referencedObjectName} [${referencedObjectType}] has ${referencerDescription} (${referencerName}) that points back to ${referencedObjectName}, creating a circular reference`;
return (true);
}
keyStack.push(key);
objectStack.add(obj);
// Recurse through the object's children [Note: 'obj' can also be an array, Set or Map], but don't check typed arrays (eg. Uint8Array) because they cannot contain values
// that cause circular references.
// Aside: For an object - but NOT an array [!(obj instanceof Array)] - we could sort the property names so that it matches what the [VS Code] debugger shows, like this:
// for (const k of [...Object.keys(obj)].sort()) { ... }
// But this would have 2 downsides: 1) It would be slower, and 2) It would potentially yield an error mesasage that refers to different elements than the JSON.stringify()
// error message would refer to [which, evidently, does no such sorting] making it harder to verify the correctness of checkForCircularReferences().
if (!Meta.Type.isTypedArray(obj))
{
const targetObj: Utils.SimpleObject = ((obj instanceof Set) || (obj instanceof Map)) ? [...obj] : obj;
for (const k in targetObj)
{
// JSON.stringify() doesn't serialize prototype-inherited properties, so we can skip those [see: https://stackoverflow.com/questions/8779249/how-to-stringify-inherited-objects-to-json]
if (Object.prototype.hasOwnProperty.call(targetObj, k)) // Using Object.prototype because obj.hasOwnProperty() can be redefined (shadowed)
{
if (checkForSerializability)
{
checkCanSerialize(targetObj[k], k);
}
if (detectCircularReference(targetObj[k], k))
{
return (true);
}
}
}
}
keyStack.pop();
objectStack.delete(obj);
return (false);
}
/** [Local function] Throws if the supplied obj is not of a type that can be serialized, or if it has a [string] value that overlaps with any of our custom serialization tokens (##xxx##). */
// Note: JSON.stringify() typically returns "{}" for objects that it doesn't serialize, but this "silent failure"
// approach makes it harder to find serialization issues, so we "fail fast" instead (at a performance cost).
function checkCanSerialize(obj: object, currentKey: string): void
{
if (obj !== undefined)
{
const typeName: string = Meta.Type.getNativeType(obj);
if (supportedTypes.indexOf(typeName) === -1)
{
const keyPath: { path: string, keyDescription: string } = getKeyPath(currentKey);
throw new Error(`${keyPath.path} (${keyPath.keyDescription}) is of type '${typeName}' which is not supported for serialization`);
}
// Check if this is a string that's one of our "reserved" internal tokens (either a specifier for a built-in constructed object (eg. "##Map##"),
// or a special value placeholder (eg. "##NaN##")).
// Note: Technically this check is applied too liberally, but limiting it to apply only when truly needed would add unwanted complexity.
// Further, checking "greedily" allows us to more easily identify serialization problems (ie. a token being used in the wrong place).
if ((typeName === "string") && ((obj as unknown) as string).startsWith("##"))
{
const value: string = (obj as unknown) as string;
for (const token of _serializationTokens)
{
if (value.startsWith(token))
{
const keyPath: { path: string, keyDescription: string } = getKeyPath(currentKey);
throw new Error(`Found ${keyPath.keyDescription} (${keyPath.path}) with a value ('${value}') which cannot be serialized because it's used as an internal token`);
}
}
}
}
}
const startingObjName: string = `(${Meta.Type.getNativeType(obj)})`;
if (checkForSerializability)
{
checkCanSerialize(obj, startingObjName);
}
if (detectCircularReference(obj, startingObjName))
{
throw new Error(errorMsg);
}
}
/** This is for testing the performance of our custom JSON serialization [jsonStringify()/jsonParse()], including vs native JSON serialization. */
function testJsonSerializationPerf()
{
interface IIndexable { [index: number]: any; length: number };
/** [Local function] Throws if the supplied arrays are either different lengths, or contain elements that don't match when compared using '==='. */
function compareArrays(arr1: IIndexable, arr2: IIndexable): void
{
if (arr1.length !== arr2.length)
{
throw new Error(`Arrays are not of the same length (${arr1.length} vs. ${arr2.length})`);
}
for (let i: number = 0; i < arr1.length; i++)
{
if (arr1[i] !== arr2[i])
{
throw new Error(`Array element ${i} does not match (${arr1[i]} vs. ${arr2[i]})`);
}
}
}
Utils.log("Starting JSON serialization/deserialization perf tests...");
// let o: object = { p1: BigInt(1), p2: 123, p3: "Hello!", p4: true };
// let d: object = jsonParse(jsonStringify(o));
let itemCount: number = 1000 * 1000;
let numArray: number[] = new Array(itemCount);
let biArray: bigint[] = new Array(itemCount);
let strArray: string[] = new Array(itemCount);
for (let i = 0; i < itemCount; i++)
{
numArray[i] = Math.floor(Math.random() * itemCount);
biArray[i] = BigInt(numArray[i]);
strArray[i] = "*".repeat(Math.floor(Math.random() * 10))
}
let bi64Array: BigInt64Array = BigInt64Array.from(biArray as bigint[]);
let startTime: number = Date.now();
let o1: number[] = jsonParse(jsonStringify(numArray, false));
let elapsedMs1 = Date.now() - startTime;
compareArrays(numArray, o1);
startTime = Date.now();
let o2: bigint[] = jsonParse(jsonStringify(biArray, false));
let elapsedMs2 = Date.now() - startTime;
let percent2: number = (elapsedMs2 / elapsedMs1) * 100;
compareArrays(biArray, o2);
startTime = Date.now();
let o3: BigInt64Array = jsonParse(jsonStringify(bi64Array, false));
let elapsedMs3 = Date.now() - startTime;
let percent3: number = (elapsedMs3 / elapsedMs1) * 100;
compareArrays(bi64Array, o3);
startTime = Date.now();
let o4: string[] = JSON.parse(JSON.stringify(strArray));
let elapsedMs4 = Date.now() - startTime;
compareArrays(strArray, o4);
startTime = Date.now();
let o5: string[] = jsonParse(jsonStringify(strArray, false));
let elapsedMs5 = Date.now() - startTime;
let percent5: number = (elapsedMs5 / elapsedMs4) * 100;
compareArrays(strArray, o5);
startTime = Date.now();
let o6: string[] = JSON.parse(JSON.stringify(numArray));
let elapsedMs6 = Date.now() - startTime;
let percent7: number = (elapsedMs1 / elapsedMs6) * 100;
compareArrays(numArray, o6);
Utils.log(`1) Number type perf test finished (${itemCount.toLocaleString()} items): ` +
`${elapsedMs1}ms for number[] (1x), ` +
`${elapsedMs2}ms for bigint[] (${(percent2 / 100).toFixed(2)}x), ` +
`${elapsedMs3}ms for BigInt64Array (${(percent3 / 100).toFixed(2)}x)`);
Utils.log(`2) String serialization comparision perf test finished (${itemCount.toLocaleString()} items): ` +
`${elapsedMs4}ms for string[] using native JSON serialization (1x), ` +
`${elapsedMs5}ms for string[] using custom JSON serialization (${(percent5 / 100).toFixed(2)}x)`);
Utils.log(`3) Number serialization comparision perf test finished (${itemCount.toLocaleString()} items): ` +
`${elapsedMs6}ms for number[] using native JSON serialization (1x), ` +
`${elapsedMs1}ms for number[] using custom JSON serialization (${(percent7 / 100).toFixed(2)}x)`);
Utils.log("JSON serialization/deserialization perf tests finished.");
} | the_stack |
import { ComponentType, createElement, ReactNode } from 'react';
import {
GetServerSidePropsContext,
GetStaticPropsContext,
NextPageContext,
} from 'next';
export interface LayoutBaseProps {
// Children should always be supplied in layouts, but loosening this since pages are also layouts.
children?: ReactNode;
}
export interface BaseLayoutParams<
TProps extends LayoutBaseProps,
TInitialProps extends Partial<TProps>,
TParent extends Layout<any, any, any> | undefined
> {
// Unique key generated to identify the layout - needed e.g. in LayoutRenderer.
key: string;
isLayout: true;
parent?: TParent;
useParentProps: (props: {
initialProps: InitialProps<TInitialProps>;
layoutProps: InitialProps<
LayoutSelfProps<TProps, TInitialProps> & Partial<TInitialProps>
>;
// The require functions are escape hatches which allow you to pass a loading/error state to the parent while still preserving type safety and inference.
// If you need initialProps (data loaded) or layoutProps (passed by downstream layout) resolved before rendering the parent layout, use these.
requireInitialProps: (
callback: (initialProps: TInitialProps) => LayoutProps<TParent>
) => any;
requireLayoutProps: (
callback: (
layoutProps: LayoutSelfProps<TProps, TInitialProps> &
Partial<TInitialProps>
) => LayoutProps<TParent>
) => any;
requireProps: (
callback: (props: {
initialProps: TInitialProps;
layoutProps: LayoutSelfProps<TProps, TInitialProps> &
Partial<TInitialProps>;
}) => LayoutProps<TParent>
) => any;
}) => LayoutProps<TParent>;
}
interface ServerLayoutParams<
TProps extends LayoutBaseProps,
TInitialProps extends Partial<TProps>,
TParent extends Layout<any, any, any> | undefined
> extends BaseLayoutParams<TProps, TInitialProps, TParent> {
getInitialProps?: (context: NextPageContext) => Promise<TInitialProps>;
getStaticProps?: (context: GetStaticPropsContext) => Promise<TInitialProps>;
getServerSideProps?: (
context: GetServerSidePropsContext
) => Promise<TInitialProps>;
}
export type ServerLayout<
TProps extends LayoutBaseProps,
TInitialProps extends Partial<TProps>,
TParent extends Layout<any, any, any> | undefined
> = ServerLayoutParams<TProps, TInitialProps, TParent> & ComponentType<TProps>;
interface ClientLayoutParams<
TProps extends LayoutBaseProps,
TInitialProps extends Partial<TProps>,
TParent extends Layout<any, any, any> | undefined
> extends BaseLayoutParams<TProps, TInitialProps, TParent> {
useInitialProps: () => InitialProps<TInitialProps>;
loadingComponent?: ComponentType;
}
export type ClientLayout<
TProps extends LayoutBaseProps,
TInitialProps extends Partial<TProps>,
TParent extends Layout<any, any, any> | undefined
> = ClientLayoutParams<TProps, TInitialProps, TParent> & ComponentType<TProps>;
export type Layout<
TProps extends LayoutBaseProps,
TInitialProps extends Partial<TProps>,
TParent extends Layout<any, any, any> | undefined
> =
| ServerLayout<TProps, TInitialProps, TParent>
| ClientLayout<TProps, TInitialProps, TParent>;
export const isServerLayout = <
TProps extends LayoutBaseProps,
TInitialProps extends Partial<TProps>,
TParent extends Layout<any, any, any> | undefined
>(
layout: Layout<TProps, TInitialProps, TParent>
): layout is ServerLayout<TProps, TInitialProps, TParent> => {
return !(layout as ClientLayout<any, any, any>).useInitialProps;
};
export const isClientLayout = <
TProps extends LayoutBaseProps,
TInitialProps extends Partial<TProps>,
TParent extends Layout<any, any, any> | undefined
>(
layout: Layout<TProps, TInitialProps, TParent>
): layout is ClientLayout<TProps, TInitialProps, TParent> => {
return !isServerLayout(layout);
};
export type MakeServerLayoutInitialParams<TInitialProps> = Pick<
ServerLayoutParams<any, TInitialProps, any>,
'getInitialProps' | 'getStaticProps' | 'getServerSideProps'
>;
export type MakeClientLayoutInitialParams<TInitialProps> = Pick<
ClientLayoutParams<any, TInitialProps, any>,
'useInitialProps'
>;
export type MakeLayoutInitialParams<TInitialProps> =
| MakeServerLayoutInitialParams<TInitialProps>
| MakeClientLayoutInitialParams<TInitialProps>;
type MakeServerLayoutParams<
TProps extends LayoutBaseProps,
TInitialProps extends Partial<TProps>,
TParent extends Layout<any, any, any> | undefined
> = Omit<
ServerLayoutParams<TProps, TInitialProps, TParent>,
| 'key'
| 'isLayout'
| 'getInitialProps'
| 'getStaticProps'
| 'getServerSideProps'
> & {
component: ComponentType<TProps>;
};
type MakeClientLayoutParams<
TProps extends LayoutBaseProps,
TInitialProps extends Partial<TProps>,
TParent extends Layout<any, any, any> | undefined
> = Omit<
ClientLayoutParams<TProps, TInitialProps, TParent>,
'key' | 'isLayout' | 'useInitialProps'
> & {
component: ComponentType<TProps>;
};
type MakeLayoutParams<
TProps extends LayoutBaseProps,
TInitialProps extends Partial<TProps>,
TParent extends Layout<any, any, any> | undefined
> =
| MakeServerLayoutParams<TProps, TInitialProps, TParent>
| MakeClientLayoutParams<TProps, TInitialProps, TParent>;
let keyCount = 0;
export const makeLayout = <
TProps extends LayoutBaseProps,
TInitialProps extends Partial<TProps> = object,
TParent extends Layout<any, any, any> | undefined = undefined
>(
initialParams: MakeLayoutInitialParams<TInitialProps> | undefined,
params: MakeLayoutParams<TProps, TInitialProps, TParent>
): Layout<TProps, TInitialProps, TParent> => {
keyCount++;
const layout: Layout<TProps, TInitialProps, TParent> = (props) => {
return createElement(params.component, props);
};
layout.isLayout = true;
layout.key = `${layout.displayName}:${keyCount}`;
layout.parent = params.parent;
layout.useParentProps = params.useParentProps;
(layout as ServerLayout<TProps, TInitialProps, TParent>).getInitialProps = (
initialParams as MakeServerLayoutInitialParams<TInitialProps>
)?.getInitialProps;
(layout as ServerLayout<TProps, TInitialProps, TParent>).getStaticProps = (
initialParams as MakeServerLayoutInitialParams<TInitialProps>
)?.getStaticProps;
(layout as ServerLayout<TProps, TInitialProps, TParent>).getServerSideProps =
(
initialParams as MakeServerLayoutInitialParams<TInitialProps>
)?.getServerSideProps;
(layout as ClientLayout<TProps, TInitialProps, TParent>).useInitialProps = (
initialParams as MakeClientLayoutInitialParams<TInitialProps>
)?.useInitialProps;
return layout;
};
export type LayoutParent<TLayout extends Layout<any, any, any> | undefined> =
TLayout extends Layout<any, any, infer TParent> ? TParent : never;
export type LayoutProps<TLayout extends Layout<any, any, any> | undefined> =
TLayout extends Layout<infer TProps, infer TInitialProps, any>
? LayoutSelfProps<TProps, TInitialProps> & Partial<TInitialProps>
: Record<string, never>;
type LayoutSelfProps<TProps, TInitialProps extends Partial<TProps>> = Omit<
TProps,
(TInitialProps extends never ? never : keyof TInitialProps) | 'children'
>;
export type InitialProps<TInitialProps> = {
data: TInitialProps | undefined;
loading?: boolean;
error?: Error;
};
type LayoutRawInitialProps<TLayout extends Layout<any, any, any> | undefined> =
TLayout extends Layout<any, infer TInitialProps, any> ? TInitialProps : never;
export type LayoutInitialProps<
TLayout extends Layout<any, any, any> | undefined
> = InitialProps<LayoutRawInitialProps<TLayout>>;
type Recursion = [never, 0, 1, 2, 3, 4, 5];
export type LayoutInitialPropsStack<
TLayout extends Layout<any, any, any> | undefined,
TRecursion extends number = 6
> = [TRecursion] extends [0]
? []
: TLayout extends Layout<infer TProps, infer TInitialProps, infer TParent>
? [
LayoutInitialProps<TLayout>,
...LayoutInitialPropsStack<TParent, Recursion[TRecursion]>
]
: [];
export const layoutHasGetInitialProps = <
TLayout extends Layout<any, any, any> | undefined
>(
layout: TLayout
): boolean => {
let hasInitialProps = false;
let loopLayout: any = layout;
while (!!loopLayout) {
if (isServerLayout(loopLayout) && loopLayout.getInitialProps) {
hasInitialProps = true;
break;
}
loopLayout = loopLayout.parent;
}
return hasInitialProps;
};
export const _fetchGetInitialProps = async <
TLayout extends Layout<any, any, any>
>(
layout: TLayout,
getInitialProps: <TLayout2 extends ServerLayout<any, any, any>>(
layout: TLayout2
) => Promise<LayoutRawInitialProps<TLayout2>> | undefined
): Promise<LayoutInitialPropsStack<TLayout>> => {
const promises: Promise<any>[] = [];
let loopLayout: Layout<any, any, any> = layout;
while (!!loopLayout) {
promises.push(
(isServerLayout(loopLayout) ? getInitialProps(loopLayout) : undefined) ??
Promise.resolve({})
);
loopLayout = loopLayout.parent;
}
const result = await Promise.allSettled(promises);
return result.map((promise) => {
if (promise.status === 'fulfilled') {
return {
data: promise.value,
};
}
return {
error: wrapError(promise.reason),
};
}) as LayoutInitialPropsStack<TLayout>;
};
export const fetchGetInitialProps = <TLayout extends Layout<any, any, any>>(
layout: TLayout,
context: NextPageContext
) => {
return _fetchGetInitialProps(layout, (l) => {
return l.getInitialProps?.(context);
});
};
export const fetchGetStaticProps = <TLayout extends Layout<any, any, any>>(
layout: TLayout,
context: GetStaticPropsContext
) => {
return _fetchGetInitialProps(layout, (l) => {
return l.getStaticProps?.(context);
});
};
export const fetchGetServerSideProps = <TLayout extends Layout<any, any, any>>(
layout: TLayout,
context: GetServerSidePropsContext
) => {
return _fetchGetInitialProps(layout, (l) => {
return l.getServerSideProps?.(context);
});
};
export const useLayoutInitialProps = <
TLayout extends Layout<any, any, any> | undefined
>(
layout: TLayout
): LayoutInitialPropsStack<TLayout> => {
const initialProps: any[] = [];
let loopLayout: any = layout;
while (!!loopLayout) {
initialProps.push(
!isServerLayout(loopLayout) && loopLayout.useInitialProps
? loopLayout.useInitialProps()
: {}
);
loopLayout = loopLayout.parent;
}
return initialProps as LayoutInitialPropsStack<TLayout>;
};
export const isLayout = (
component: ComponentType<any>
): component is Layout<any, any, any> => {
return 'isLayout' in component;
};
// TODO: This is not a safe way to ensure Error.
export const wrapError = (e: unknown): Error =>
e instanceof Error ? e : new Error('' + e); | the_stack |
export type ConnectionDisconnectReason = 'clientDisconnected' | 'forceDisconnected' | 'networkDisconnected';
/**
* Error object
*
* {@link https://tokbox.com/developer/sdks/js/reference/Error.html}
*/
export interface Error {
code?: number;
name: string;
preventDefault(): void;
isDefaultPrevented(): boolean;
}
/**
* Base interface for all OpenTok events
*
* {@link https://tokbox.com/developer/sdks/js/reference/Event.html}
*/
export interface Event<ET extends string = string, T = unknown> {
type: ET;
cancelable: boolean;
target: T;
preventDefault(): void;
isDefaultPrevented(): boolean;
}
/**
* ArchiveEvent
*
* {@link https://tokbox.com/developer/sdks/js/reference/ArchiveEvent.html}
*/
export interface ArchiveEvent extends Event<'archiveStarted' | 'archiveStopped'> {
id: string;
name: string;
}
/**
* AudioLevelUpdatedEvent
*
* {@link https://tokbox.com/developer/sdks/js/reference/AudioLevelUpdatedEvent.html}
*/
export interface AudioLevelUpdatedEvent extends Event<'audioLevelUpdated'> {
audioLevel: number;
}
/**
* ConnectionEvent, a common interface for {@link ConnectionCreatedEvent} and {@link ConnectionDestroyedEvent}
*
* {@link https://tokbox.com/developer/sdks/js/reference/ConnectionEvent.html}
*/
export interface ConnectionEvent<T extends 'connectionCreated' | 'connectionDestroyed'> extends Event<T> {
connection: Connection;
connections?: Connection[];
}
/**
* ConnectionCreatedEvent
*
* {@link https://tokbox.com/developer/sdks/js/reference/ConnectionEvent.html}
*/
export interface ConnectionCreatedEvent extends ConnectionEvent<'connectionCreated'> {
reason: undefined;
}
/**
* ConnectionDestroyedEvent
*
* {@link https://tokbox.com/developer/sdks/js/reference/ConnectionEvent.html}
*/
export interface ConnectionDestroyedEvent extends ConnectionEvent<'connectionDestroyed'> {
reason: ConnectionDisconnectReason;
}
/**
* ExceptionEvent
*
* {@link https://tokbox.com/developer/sdks/js/reference/ExceptionEvent.html}
*/
export interface ExceptionEvent extends Event<'exception'> {
code: number;
message: string;
title: string;
}
/**
* MediaStoppedEvent
*
* {@link https://tokbox.com/developer/sdks/js/reference/MediaStoppedEvent.html}
*/
export interface MediaStoppedEvent extends Event<'mediaStopped'> {
track: MediaStreamTrack;
}
/**
* SessionEvent, a common interface for {@link SessionConnectEvent} and {@link SessionDisconnectEvent}
*/
export interface SessionEvent<T extends 'sessionConnected' | 'sessionDisconnected'> extends Event<T> {
connections?: Connection[];
streams?: Stream[];
}
/**
* SessionConnectEvent
*
* {@link https://tokbox.com/developer/sdks/js/reference/SessionConnectEvent.html}
*/
export interface SessionConnectEvent extends SessionEvent<'sessionConnected'> {
reason: undefined;
}
/**
* SessionDisconnectEvent
*
* {@link https://tokbox.com/developer/sdks/js/reference/SessionDisconnectEvent.html}
*/
export interface SessionDisconnectEvent extends SessionEvent<'sessionDisconnected'> {
reason: ConnectionDisconnectReason;
}
/**
* SessionReconnectEvent
*
* {@link https://tokbox.com/developer/sdks/js/reference/Event.html}
*/
export type SessionReconnectEvent = Event<'sessionReconnected'>;
/**
* SessionReconnectingEvent
*
* {@link https://tokbox.com/developer/sdks/js/reference/Event.html}
*/
export type SessionReconnectingEvent = Event<'sessionReconnecting'>;
/**
* SignalEvent
*
* {@link https://tokbox.com/developer/sdks/js/reference/SignalEvent.html}
*/
export interface SignalEvent extends Event<'signal' | string> {
data: string;
from: Connection;
}
/**
* StreamEvent, a common interface for {@link StreamCreatedEvent} and {@link StreamDestroyedEvent}
*
* {@link https://tokbox.com/developer/sdks/js/reference/StreamEvent.html}
*/
export interface StreamEvent<T extends 'streamCreated' | 'streamDestroyed' | 'streamPropertyChanged'> extends Event<T> {
stream: Stream;
streams?: Stream[];
}
/**
* StreamCreatedEvent
*
* {@link https://tokbox.com/developer/sdks/js/reference/StreamEvent.html}
*/
export interface StreamCreatedEvent extends StreamEvent<'streamCreated'> {
reason: undefined;
}
/**
* StreamDestroyedEvent
*
* {@link https://tokbox.com/developer/sdks/js/reference/StreamEvent.html}
*/
export interface StreamDestroyedEvent extends StreamEvent<'streamDestroyed'> {
reason: 'clientDisconnected' | 'forceDisconnected' | 'forceUnpublished' | 'mediaStopped' | 'networkDisconnected';
}
/**
* StreamPropertyChangedEvent
*
* {@link https://tokbox.com/developer/sdks/js/reference/StreamPropertyChangedEvent.html}
*/
export interface StreamPropertyChangedEvent<V = unknown> extends StreamEvent<'streamPropertyChanged'> {
changedProperty: string;
newValue: V;
oldValue: V;
}
/**
* VideoDimensionsChangedEvent
*
* {@link https://tokbox.com/developer/sdks/js/reference/VideoDimensionsChangedEvent.html}
*/
export interface VideoDimensionsChangedEvent extends Event<'videoDimensionsChanged'> {
newValue: Dimensions;
oldValue: Dimensions;
}
/**
* VideoEnabledChangedEvent
*
* {@link https://tokbox.com/developer/sdks/js/reference/VideoEnabledChangedEvent.html}
*/
export interface VideoEnabledChangedEvent<T extends 'videoDisabled' | 'videoEnabled'> extends Event<T> {
reason: 'publishVideo' | 'quality' | 'subscribeToVideo' | 'codecNotSupported' | 'codecChanged';
}
/**
* VideoElementCreatedEvent
*
* {@link https://tokbox.com/developer/sdks/js/reference/VideoElementCreatedEvent.html}
*/
export interface VideoElementCreatedEvent extends Event<'videoElementCreated'> {
element: HTMLElement;
}
export type CompletionHandler = (error?: Error) => void;
export type EventHandler<E extends Event<string> = Event<string>> = (event: E) => void;
/**
* Base interface for all objects that emit events:
*
* {@link Session}
*/
export interface EventEmitter<EventHandlers extends {}> {
/**
* @deprecated Use on
*/
addEventListener<T extends keyof EventHandlers & string>(type: T, listener: EventHandlers[T], context?: any): void;
/**
* @deprecated Use on
*/
addEventListener(type: string, listener: EventHandler, context?: any): void;
/**
* @deprecated Use off
*/
removeEventListener<T extends keyof EventHandlers & string>(type: T, listener: EventHandlers[T], context?: any): void;
/**
* @deprecated Use off
*/
removeEventListener(type: string, listener: EventHandler, context?: any): void;
off(handlers?: Partial<EventHandlers>): this;
off<T extends keyof EventHandlers & string>(type: T, handler?: EventHandlers[T]): this;
off(type: string, handler?: EventHandler): this;
on(handlers: Partial<EventHandlers>, context?: any): this;
on<T extends keyof EventHandlers & string>(type: T, handler: EventHandlers[T], context?: any): this;
on(type: string, handler: EventHandler, context?: any): this;
once(handlers: Partial<EventHandlers>, context?: any): this;
once<T extends keyof EventHandlers & string>(type: T, handler: EventHandler<Event<T>>, context?: any): this;
}
/**
* Signal object
*
* {@link https://tokbox.com/developer/sdks/js/reference/Session.html#signal}
*/
export interface Signal {
data?: string;
retryAfterReconnect?: boolean;
to?: Connection;
type?: string;
}
export type SessionEventHandlers =
| {
archiveStarted?: EventHandler<ArchiveEvent>;
archiveStopped?: EventHandler<ArchiveEvent>;
connectionCreated?: EventHandler<ConnectionCreatedEvent>;
connectionDestroyed?: EventHandler<ConnectionDestroyedEvent>;
sessionConnected?: EventHandler<SessionConnectEvent>;
sessionDisconnected?: EventHandler<SessionDisconnectEvent>;
sessionReconnected?: EventHandler<SessionReconnectEvent>;
sessionReconnecting?: EventHandler<SessionReconnectingEvent>;
signal?: EventHandler<SignalEvent>;
streamCreated?: EventHandler<StreamCreatedEvent>;
streamDestroyed?: EventHandler<StreamDestroyedEvent>;
streamPropertyChanged?: EventHandler<StreamPropertyChangedEvent>;
}
| Record<string, EventHandler<Event>>;
/**
* Session object
*
* {@link https://tokbox.com/developer/sdks/js/reference/Session.html}
*/
export interface Session extends EventEmitter<SessionEventHandlers> {
capabilities: Capabilities;
connection: Connection;
sessionId: string;
connect(token: string, completionHandler?: CompletionHandler): void;
disconnect(): void;
forceDisconnect(connection: Connection, completionHandler?: CompletionHandler): void;
forceUnpublish(stream: Stream, completionHandler?: CompletionHandler): void;
getPublisherForStream(stream: Stream): Publisher;
getSubscribersForStream(stream: Stream): Subscriber[];
isConnected(): boolean;
publish(publisher: Publisher, completionHandler?: CompletionHandler): void;
signal(signal: Signal, completionHandler?: CompletionHandler): void;
subscribe(
stream: Stream,
targetElement: HTMLElement | string | undefined,
properties: SubscriberProperties,
completionHandler?: CompletionHandler,
): Subscriber;
unpublish(publisher: Publisher): void;
unsubscribe(subscriber: Subscriber): void;
}
/**
* Dimensions object
*
* Passed in Session.subscribe properties {@link SubscriberProperties#preferredResolution}
*
* {@link https://tokbox.com/developer/sdks/js/reference/Session.html#subscribe}
*/
export interface Dimensions {
height: number;
width: number;
}
export type StyleToggle = 'on' | 'off' | 'auto';
export interface Style {
audioLevelDisplayMode?: StyleToggle;
backgroundImageURI?: string;
buttonDisplayMode?: StyleToggle;
nameDisplayMode?: StyleToggle;
videoDisabledDisplayMode?: StyleToggle;
}
/**
* Style object passed in Session.subscribe properties {@link SubscriberProperties#style}
*
* {@link https://tokbox.com/developer/sdks/js/reference/Session.html#subscribe}
*/
export interface SubscriberStyle extends Style {
audioBlockedDisplayMode?: StyleToggle;
videoDisabledDisplayMode?: StyleToggle;
}
/**
* Properties object passed to Session.subscribe
*
* {@link https://tokbox.com/developer/sdks/js/reference/Session.html#subscribe}
*/
export interface SubscriberProperties {
audioVolume?: number;
fitMode?: 'cover' | 'contain';
height?: string | number;
insertDefaultUI?: boolean;
insertMode?: 'replace' | 'after' | 'before' | 'append';
preferredFrameRate?: number;
preferredResolution?: Dimensions;
showControls?: boolean;
style?: SubscriberStyle;
subscribeToAudio?: boolean;
subscribeToVideo?: boolean;
testNetwork?: boolean;
width?: string | number;
}
export type SubscriberEventHandlers = {
audioBlocked?: EventHandler<Event<'audioBlocked'>>;
audioLevelUpdated?: EventHandler<AudioLevelUpdatedEvent>;
audioUnblocked?: EventHandler<Event<'audioUnblocked'>>;
connected?: EventHandler<Event<'connected'>>;
destroyed?: EventHandler<Event<'destroyed'>>;
disconnected?: EventHandler<Event<'disconnected'>>;
videoDimensionsChanged?: EventHandler<VideoDimensionsChangedEvent>;
videoDisabled?: EventHandler<VideoEnabledChangedEvent<'videoDisabled'>>;
videoDisableWarning?: EventHandler<Event<'videoDisableWarning'>>;
videoDisableWarningLifted?: EventHandler<Event<'videoDisableWarningLifted'>>;
videoElementCreated?: EventHandler<VideoElementCreatedEvent>;
videoEnabled?: EventHandler<VideoEnabledChangedEvent<'videoEnabled'>>;
};
/**
* Subscriber object
*
* {@link https://tokbox.com/developer/sdks/js/reference/Subscriber.html}
*/
export interface Subscriber extends EventEmitter<SubscriberEventHandlers> {
element: HTMLElement;
id: string;
stream: Stream;
getAudioVolume(): number;
getImgData(): string;
getStats(completionHandler: (error: Error | undefined, stats: SubscriberStats) => void): void;
getStyle(): SubscriberStyle;
isAudioBlocked(): boolean;
restrictFrameRate(value: boolean): this;
setAudioVolume(value: number): this;
setPreferredFrameRate(value: number): void;
setPreferredResolution(value: number): void;
setStyle(style: SubscriberStyle): this;
setStyle<K extends keyof SubscriberStyle>(style: K, value: SubscriberStyle[K]): this;
subscribeToAudio(value: boolean): this;
subscribeToVideo(value: boolean): this;
videoHeight(): number;
videoWidth(): number;
}
/**
* Capabilities object
*
* {@link https://tokbox.com/developer/sdks/js/reference/Capabilities.html}
*/
export interface Capabilities {
forceDisconnect?: 0 | 1;
forceUnpublish?: 0 | 1;
publish?: 0 | 1;
subscribe?: 0 | 1;
}
/**
* Connection object
*
* {@link https://tokbox.com/developer/sdks/js/reference/Connection.html}
*/
export interface Connection {
connectionId: string;
creationTime: number;
data: string;
}
/**
* Publisher style object
*
* {@link https://tokbox.com/developer/sdks/js/reference/Publisher.html#setStyle}
*/
export interface PublisherStyle extends Style {
archiveStatusDisplayMode: StyleToggle;
}
export interface PublisherEventHandlers {
accessAllowed?: EventHandler<Event<'accessAllowed'>>;
accessDenied?: EventHandler<Event<'accessDenied'>>;
accessDialogClosed?: EventHandler<Event<'accessDialogClosed'>>;
accessDialogOpened?: EventHandler<Event<'accessDialogOpened'>>;
audioLevelUpdated?: EventHandler<AudioLevelUpdatedEvent>;
destroyed?: EventHandler<Event<'destroyed'>>;
mediaStopped?: EventHandler<MediaStoppedEvent>;
streamCreated?: EventHandler<StreamCreatedEvent>;
streamDestroyed?: EventHandler<StreamDestroyedEvent>;
videoDimensionsChanged?: EventHandler<VideoDimensionsChangedEvent>;
videoElementCreated?: EventHandler<VideoElementCreatedEvent>;
}
/**
* Publisher object
*
* {@link https://tokbox.com/developer/sdks/js/reference/Publisher.html}
*/
export interface Publisher extends EventEmitter<PublisherEventHandlers> {
accessAllowed: boolean;
element?: HTMLElement;
id: string;
stream: Stream;
session: Session;
cycleVideo(): Promise<void>;
destroy(): this;
getAudioSource(): MediaStreamTrack;
getImgData(): string;
getStats(completionHandler: (error: Error | undefined, stats: PublisherStats[]) => void): void;
getStyle(): PublisherStyle;
publishAudio(value: boolean): void;
publishVideo(value: boolean): void;
setAudioSource(value: string | MediaStreamTrack): void;
setStyle(style: PublisherStyle): this;
setStyle<K extends keyof PublisherStyle>(style: K, value: PublisherStyle[K]): this;
videoHeight(): number;
videoWidth(): number;
}
/**
* Stream object
*
* {@link https://tokbox.com/developer/sdks/js/reference/Stream.html}
*/
export interface Stream {
connection: Connection;
creationTime: number;
frameRate: number;
hasAudio: boolean;
hasVideo: boolean;
name: string;
streamId: string;
videoDimensions: Dimensions;
videoType: 'camera' | 'screen' | 'custom';
}
/**
* Publisher stats object
*
* {@link https://tokbox.com/developer/sdks/js/reference/Publisher.html#getStats}
*/
export interface PublisherStats {
connectionId?: string;
subscriberId?: string;
stats: {
'audio.bytesSent': number;
'audio.packetsLost': number;
'audio.packetsSent': number;
timestamp: number;
'video.bytesSent': number;
'video.packetsLost': number;
'video.packetsSent': number;
'video.frameRate': number;
};
}
/**
* SubscriberStats stats object
*
* {@link https://tokbox.com/developer/sdks/js/reference/Subscribe.html#getStats}
*/
export interface SubscriberStats {
'audio.bytesReceived': number;
'audio.packetsLost': number;
'audio.packetsReceived': number;
timestamp: number;
'video.bytesReceived': number;
'video.packetsLost': number;
'video.packetsReceived': number;
'video.frameRate': number;
}
/**
* Publisher properties object
*
* {@link https://tokbox.com/developer/sdks/js/reference/OT.html#initPublisher}
*/
export interface PublisherProperties {
audioBitrate?: number;
audioFallbackEnabled?: boolean;
audioSource?: string | MediaStreamTrack | boolean | null;
disableAudioProcessing?: boolean;
enableStereo?: boolean;
facingMode?: 'user' | 'environment' | 'left' | 'right';
fitMode?: 'cover' | 'contain';
frameRate?: number;
height?: number | string;
insertDefaultUI?: boolean;
insertMode?: 'replace' | 'after' | 'before' | 'append';
maxResolution?: Dimensions;
mirror?: boolean;
name?: string;
publishAudio?: boolean;
publishVideo?: boolean;
resolution?: string;
showControls?: boolean;
style?: PublisherStyle;
usePreviousDeviceSelection?: boolean;
videoSource?: string | MediaStreamTrack | boolean | null;
width?: number | string;
}
export interface ScreenSharingCapabilities {
/**
* In older versions of Chrome and Opera, this is set to true if the extension is installed and registered. In Chrome 72+, Firefox 52+, Opera 59+, Edge 79+, and Internet Explorer, this property is undefined.
*/
extensionInstalled: boolean;
/**
* Set to true if screen sharing is supported in the browser. Check the extensionRequired property to see if the browser requires an extension for screen sharing.
*/
supported: boolean;
/**
* In older browser versions, you could select a type of screen-sharing source (such as "application", "screen", or "window" by setting the videoSource property of the options passed into the OT.initPublisher() method. However, in current browsers that support screen sharing, passing in any of these values results in the same behavior โ the browser displays a dialog box in which the end user selects the screen-sharing source (which can be the entire screen or a specific window).
*
* @deprecated
*/
supportedSources: {};
/**
* Set to "chrome" in older versions of Chrome and Opera, which require a screen-sharing extension to be installed. This property is undefined in other browsers.
*/
extensionRequired?: string;
/**
* In older versions of Chrome and Opera, this property is set to true if a screen-sharing extension is registered; otherwise it is set to false. In other browsers (which do not require an extension), this property is undefined. Use the OT.registerScreenSharingExtension() method to register a screen-sharing extension in older versions of Chrome or Opera.
*/
extensionRegistered?: boolean;
}
export interface Device {
kind: 'videoInput' | 'audioInput';
/**
* You can pass the deviceId in as the audioSource or videoSource property of the options parameter of the OT.initPublisher() method.
*/
deviceId: string;
/**
* The label property identifies the device. The label property is set to an empty string if the user has not previously granted access to a camera and microphone. In HTTP, the user must have granted access to a camera and microphone in the current page (for example, in response to a call to OT.initPublisher()). In HTTPS, the user must have previously granted access to the camera and microphone in the current page or in a page previously loaded from the domain.
*/
label: string;
}
export interface SupportedCodecs {
videoDecoders: string[];
videoEncoders: string[];
}
export interface SessionInitOptions {
connectionEventsSuppressed?: boolean;
ipWhitelist?: boolean;
iceConfig?: {};
}
export interface OTInterfaceEvents {
exception?: EventHandler<ExceptionEvent>;
}
export interface OTInterface extends EventEmitter<OTInterfaceEvents> {
/**
* Checks for support for publishing screen-sharing streams on the client browser.
*
* @param callback
*/
checkScreenSharingCapability(callback: (capabilities: ScreenSharingCapabilities) => void): void;
/**
* Checks if the system supports OpenTok for WebRTC (1) or not (0).
*/
checkSystemRequirements(): 1 | 0;
/**
* Enumerates the audio input devices (such as microphones) and video input devices (cameras) available to the browser.
*
* @param callback
*/
getDevices(callback: (error: Error | null | undefined, devices: Device[]) => void): void;
getSupportedCodecs(): Promise<SupportedCodecs>;
getUserMedia(options?: PublisherProperties): Promise<void>;
initPublisher(
targetElement: HTMLElement | undefined,
properties: PublisherProperties,
completionHandler?: CompletionHandler,
): Publisher;
initSession(apiKey: string, sessionId: string, options?: SessionInitOptions): Session;
/**
* Sends a string to the debugger console.
*
* @param {String} message
*/
log(message: string): void;
/**
* Register an extension for screen-sharing support in an older version of Chrome or Opera.
*
* @param kind Set this parameter to "chrome". Currently, you can only register a screen-sharing extension for older versions of Chrome and Opera.
* @param {String} id The ID for your screen-sharing extension. You can find this ID at chrome://extensions.
* @param {Number} version The version of the screen-sharing extension from the screensharing-extensions repo. Set this if you are using version 2 or later. For example, if you are using version 2, set this to 2. With version 2, the client can use the extension immediately after installing it, without reloading the page.
*/
registerScreenSharingExtension(kind: 'chrome', id: string, version: number): void;
/**
* Report that your app experienced an issue.
*
* @param {Function} completionHandler
*/
reportIssue(completionHandler: (error: Error | null | undefined, reportId: string) => void): void;
/**
* Sets the API log level.
*
* @param logLevel
*/
setLogLevel(logLevel: string): void;
/**
* Causes subscribers' audio to play back in browsers where audio is blocked.
*/
unblockAudio(): void;
/**
* Displays information about system requirements for OpenTok for WebRTC.
*/
upgradeSystemRequirements(): void;
}
declare global {
const OT: OTInterface;
} | the_stack |
import cn from 'classnames'
import PropTypes from 'prop-types'
import React, { useImperativeHandle, useRef, useCallback } from 'react'
import { useUncontrolled } from 'uncontrollable'
import Calendar, { CalendarProps } from './Calendar'
import DatePickerInput, { DatePickerInputProps } from './DatePickerInput'
import { calendar } from './Icon'
import { useLocalizer, DateFormats } from './Localization'
import BasePopup, { PopupProps } from './Popup'
import TimeInput, { TimeInputProps } from './TimeInput'
import Widget, { WidgetProps } from './Widget'
import WidgetPicker from './WidgetPicker'
import dates from './dates'
import useDropdownToggle from './useDropdownToggle'
import useTabTrap from './useTabTrap'
import useFocusManager from './useFocusManager'
import { notify, useFirstFocusedRender, useInstanceId } from './WidgetHelpers'
import { TransitionProps } from 'react-transition-group/Transition'
import { WidgetHTMLProps, InferFormat } from './shared'
import useEventCallback from '@restart/hooks/useEventCallback'
import InputAddon from './InputAddon'
let propTypes = {
/**
* @example ['valuePicker', [ ['new Date()', null] ]]
*/
value: PropTypes.instanceOf(Date),
/**
* @example ['onChangePicker', [ ['new Date()', null] ]]
*/
onChange: PropTypes.func,
/**
* @example ['openDate']
*/
open: PropTypes.bool,
onToggle: PropTypes.func,
/**
* Default current date at which the calendar opens. If none is provided, opens at today's date or the `value` date (if any).
*/
currentDate: PropTypes.instanceOf(Date),
/**
* Change event Handler that is called when the currentDate is changed. The handler is called with the currentDate object.
*/
onCurrentDateChange: PropTypes.func,
onSelect: PropTypes.func,
/**
* The minimum Date that can be selected. Min only limits selection, it doesn't constrain the date values that
* can be typed or pasted into the widget. If you need this behavior you can constrain values via
* the `onChange` handler.
*
* @example ['prop', ['min', 'new Date()']]
*/
min: PropTypes.instanceOf(Date),
/**
* The maximum Date that can be selected. Max only limits selection, it doesn't constrain the date values that
* can be typed or pasted into the widget. If you need this behavior you can constrain values via
* the `onChange` handler.
*
* @example ['prop', ['max', 'new Date()']]
*/
max: PropTypes.instanceOf(Date),
/**
* A formatting options used to display the date value. This is a shorthand for
* setting both `valueDisplayFormat` and `valueEditFormat`.
*/
valueFormat: PropTypes.any,
/**
* A formatting options used to display the date value. For more information about formats
* visit the [Localization page](./localization)
*
* ```tsx live
* import { DatePicker } from 'react-widgets';
*
* <DatePicker
* defaultValue={new Date()}
* valueDisplayFormat={{ dateStyle: "medium" }}
* />
* ```
*/
valueDisplayFormat: PropTypes.any,
/**
* A formatting options used while the date input has focus. Useful for showing a simpler format for inputing.
* For more information about formats visit the [Localization page](./localization)
*
* ```tsx live
* import { DatePicker } from 'react-widgets';
*
* <DatePicker
* defaultValue={new Date()}
* valueEditFormat={{ dateStyle: "short" }}
* valueDisplayFormat={{ dateStyle: "medium" }}
* />
* ```
*/
valueEditFormat: PropTypes.any,
/**
* Enable the time list component of the picker.
*/
includeTime: PropTypes.bool,
timePrecision: PropTypes.oneOf(['minutes', 'seconds', 'milliseconds']),
timeInputProps: PropTypes.object,
/** Specify the element used to render the calendar dropdown icon. */
selectIcon: PropTypes.node,
dropUp: PropTypes.bool,
popupTransition: PropTypes.elementType,
placeholder: PropTypes.string,
name: PropTypes.string,
autoFocus: PropTypes.bool,
/**
* @example ['disabled', ['new Date()']]
*/
disabled: PropTypes.bool,
/**
* @example ['readOnly', ['new Date()']]
*/
readOnly: PropTypes.bool,
/**
* Determines how the widget parses the typed date string into a Date object. You can provide an array of formats to try,
* or provide a function that returns a date to handle parsing yourself. When `parse` is unspecified and
* the `format` prop is a `string` parse will automatically use that format as its default.
*/
parse: PropTypes.oneOfType([PropTypes.any, PropTypes.func]),
/** @ignore */
tabIndex: PropTypes.any,
/** @ignore */
'aria-labelledby': PropTypes.string,
/** @ignore */
'aria-describedby': PropTypes.string,
/** @ignore */
localizer: PropTypes.any,
onKeyDown: PropTypes.func,
onKeyPress: PropTypes.func,
onBlur: PropTypes.func,
onFocus: PropTypes.func,
/** Adds a css class to the input container element. */
containerClassName: PropTypes.string,
calendarProps: PropTypes.object,
inputProps: PropTypes.object,
messages: PropTypes.shape({
dateButton: PropTypes.string,
}),
}
const defaultProps = {
...(Calendar as any).defaultProps,
min: new Date(1900, 0, 1),
max: new Date(2099, 11, 31),
selectIcon: calendar,
formats: {},
}
export interface DatePickerProps<TLocalizer = unknown>
extends Omit<WidgetHTMLProps, 'onChange' | 'defaultValue'>,
Omit<WidgetProps, 'onChange' | 'onSelect' | 'defaultValue'> {
/**
* @example ['valuePicker', [ ['new Date()', null] ]]
*/
value?: Date | null
defaultValue?: Date | null
/**
* @example ['onChangePicker', [ ['new Date()', null] ]]
*/
onChange?: (date: Date | null | undefined, rawValue: string) => void
/**
* @example ['openDateTime']
*/
open?: boolean
onToggle?: (isOpen: boolean) => void
/**
* Default current date at which the calendar opens. If none is provided, opens at today's date or the `value` date (if any).
*/
currentDate?: Date
/**
* Change event Handler that is called when the currentDate is changed. The handler is called with the currentDate object.
*/
onCurrentDateChange?: () => void
onSelect?: (date: Date | null, rawValue: string) => void
/**
* The minimum Date that can be selected. Min only limits selection, it doesn't constrain the date values that
* can be typed or pasted into the widget. If you need this behavior you can constrain values via
* the `onChange` handler.
*
* @example ['prop', ['min', 'new Date()']]
*/
min?: Date
/**
* The maximum Date that can be selected. Max only limits selection, it doesn't constrain the date values that
* can be typed or pasted into the widget. If you need this behavior you can constrain values via
* the `onChange` handler.
*
* @example ['prop', ['max', 'new Date()']]
*/
max?: Date
/**
* The amount of minutes between each entry in the time list.
*
* @example ['prop', { step: 90 }]
*/
step?: number
/**
* Enable the time list component of the picker.
*/
includeTime?: boolean
timePrecision?: 'minutes' | 'seconds' | 'milliseconds'
timeInputProps?: Partial<TimeInputProps>
/** Specify the element used to render the calendar dropdown icon. */
selectIcon?: React.ReactNode
/**
* @example ['prop', { dropUp: true }]
*/
dropUp?: boolean
popupTransition?: React.ComponentType<TransitionProps>
popupComponent?: React.ComponentType<PopupProps>
placeholder?: string
name?: string
autoFocus?: boolean
/**
* @example ['disabled', ['new Date()']]
*/
disabled?: boolean
/**
* @example ['readOnly', ['new Date()']]
*/
readOnly?: boolean
/**
* Determines how the widget parses the typed date string into a Date object. You can provide a date format
* or a function that returns a date to handle parsing yourself. When `parse` is unspecified and
* the default `localizer.parse` is used and passed the string as well as `valueDisplayFormat` or `valueEditFormat`.
*/
parse?: string | ((str: string, localizer?: TLocalizer) => Date | undefined)
onKeyDown?: (e: React.KeyboardEvent<HTMLDivElement>) => void
onKeyPress?: (e: React.KeyboardEvent<HTMLDivElement>) => void
onBlur?: () => void
onFocus?: () => void
/** Adds a css class to the input container element. */
containerClassName?: string
calendarProps?: Partial<CalendarProps>
inputProps?: Partial<DatePickerInputProps>
valueFormat?: InferFormat<TLocalizer>
valueDisplayFormat?: InferFormat<TLocalizer>
valueEditFormat?: InferFormat<TLocalizer>
formats?: DateFormats<InferFormat<TLocalizer>>
messages?: CalendarProps['messages'] & {
dateButton?: string
}
}
export interface DatePickerHandle {
focus(): void
}
/**
* ---
* subtitle: DatePicker, TimePicker
* localized: true
* shortcuts:
* - { key: alt + down arrow, label: open calendar or time }
* - { key: alt + up arrow, label: close calendar or time }
* - { key: down arrow, label: move focus to next item }
* - { key: up arrow, label: move focus to previous item }
* - { key: home, label: move focus to first item }
* - { key: end, label: move focus to last item }
* - { key: enter, label: select focused item }
* - { key: any key, label: search list for item starting with key }
* ---
*
* @public
* @extends Calendar
*/
const DatePicker = React.forwardRef(
(
uncontrolledProps: DatePickerProps,
outerRef: React.Ref<DatePickerHandle>,
) => {
const {
id,
value,
onChange,
onSelect,
onToggle,
onKeyDown,
onKeyPress,
onCurrentDateChange,
inputProps,
calendarProps,
timeInputProps,
autoFocus,
tabIndex,
disabled,
readOnly,
className,
// @ts-ignore
valueFormat,
valueDisplayFormat = valueFormat,
valueEditFormat = valueFormat,
containerClassName,
name,
selectIcon,
placeholder,
includeTime = false,
min,
max,
open,
dropUp,
parse,
messages,
formats,
currentDate,
popupTransition,
popupComponent: Popup = BasePopup,
timePrecision,
'aria-labelledby': ariaLabelledby,
'aria-describedby': ariaDescribedby,
...elementProps
} = useUncontrolled(uncontrolledProps, {
open: 'onToggle',
value: 'onChange',
currentDate: 'onCurrentDateChange',
})
const localizer = useLocalizer(messages, formats)
const ref = useRef<HTMLInputElement>(null)
const calRef = useRef<HTMLDivElement>(null)
const tabTrap = useTabTrap(calRef)
const inputId = useInstanceId(id, '_input')
const dateId = useInstanceId(id, '_date')
const currentFormat = includeTime ? 'datetime' : 'date'
const toggle = useDropdownToggle(open, onToggle!)
const [focusEvents, focused] = useFocusManager(ref, uncontrolledProps, {
didHandle(focused) {
if (!focused) {
toggle.close()
tabTrap.stop()
} else if (open) {
tabTrap.focus()
}
},
})
const dateParser = useCallback(
(str: string) => {
if (typeof parse == 'function') {
return parse(str, localizer) ?? null
}
return (
localizer.parseDate(
str,
parse ?? valueEditFormat ?? valueDisplayFormat,
) ?? null
)
},
[localizer, parse, valueDisplayFormat, valueEditFormat],
)
/**
* Handlers
*/
const handleChange = useEventCallback(
(date: Date | null | undefined, str: string, constrain?: boolean) => {
if (readOnly || disabled) return
if (constrain) date = inRangeValue(date)
if (onChange) {
if (date == null || value == null) {
if (
date != value //eslint-disable-line eqeqeq
)
onChange(date, str)
} else if (!dates.eq(date, value)) {
onChange(date, str)
}
}
},
)
const handleKeyDown = useEventCallback(
(e: React.KeyboardEvent<HTMLDivElement>) => {
if (readOnly) return
notify(onKeyDown, [e])
if (e.defaultPrevented) return
if (e.key === 'Escape' && open) {
toggle.close()
} else if (e.altKey) {
if (e.key === 'ArrowDown') {
e.preventDefault()
toggle.open()
} else if (e.key === 'ArrowUp') {
e.preventDefault()
toggle.close()
}
}
},
)
const handleKeyPress = useEventCallback(
(e: React.KeyboardEvent<HTMLDivElement>) => {
notify(onKeyPress, [e])
if (e.defaultPrevented) return
},
)
const handleDateSelect = useEventCallback((date) => {
let dateTime = dates.merge(date, value, currentDate)
let dateStr = formatDate(date)
if (!includeTime) toggle.close()
notify(onSelect, [dateTime, dateStr])
handleChange(dateTime, dateStr, true)
ref.current?.focus()
})
const handleTimeChange = useEventCallback((date) => {
handleChange(date, formatDate(date), true)
})
const handleCalendarClick = useEventCallback((e: React.MouseEvent) => {
if (readOnly || disabled) return
// prevents double clicks when in a <label>
e.preventDefault()
toggle()
})
const handleOpening = () => {
tabTrap.start()
requestAnimationFrame(() => {
tabTrap.focus()
})
}
const handleClosing = () => {
tabTrap.stop()
if (focused) focus()
}
/**
* Methods
*/
function focus() {
if (open) calRef.current?.focus()
else ref.current?.focus()
}
function inRangeValue(value: Date | null | undefined) {
if (value == null) return value
return dates.max(dates.min(value, max!), min!)
}
function formatDate(date: Date) {
return date instanceof Date && !isNaN(date.getTime())
? localizer.formatDate(date, currentFormat)
: ''
}
useImperativeHandle(outerRef, () => ({
focus,
}))
let shouldRenderList = useFirstFocusedRender(focused, open!)
const inputReadOnly =
inputProps?.readOnly != null ? inputProps?.readOnly : readOnly
return (
<Widget
{...elementProps}
defaultValue={undefined}
open={!!open}
dropUp={dropUp}
focused={focused}
disabled={disabled}
readOnly={readOnly}
onKeyDown={handleKeyDown}
onKeyPress={handleKeyPress}
{...focusEvents}
className={cn(className, 'rw-date-picker')}
>
<WidgetPicker className={containerClassName}>
<DatePickerInput
{...inputProps}
id={inputId}
ref={ref}
role="combobox"
name={name}
value={value}
tabIndex={tabIndex}
autoFocus={autoFocus}
placeholder={placeholder}
disabled={disabled}
readOnly={inputReadOnly}
formatter={currentFormat}
displayFormat={valueDisplayFormat}
editFormat={valueEditFormat}
editing={focused}
localizer={localizer}
parse={dateParser}
onChange={handleChange}
aria-haspopup
aria-labelledby={ariaLabelledby}
aria-describedby={ariaDescribedby}
aria-expanded={!!open}
aria-owns={dateId}
/>
<InputAddon
icon={selectIcon}
label={localizer.messages.dateButton()}
disabled={disabled || readOnly}
onClick={handleCalendarClick}
/>
</WidgetPicker>
{!!shouldRenderList && (
<Popup
dropUp={dropUp}
open={open}
role="dialog"
ref={calRef}
id={dateId}
className="rw-calendar-popup"
transition={popupTransition}
onEntering={handleOpening}
onExited={handleClosing}
>
<Calendar
min={min}
max={max}
bordered={false}
{...calendarProps}
messages={{
...messages,
...calendarProps?.messages,
}}
tabIndex={-1}
value={value}
autoFocus={false}
onChange={handleDateSelect}
currentDate={currentDate}
onCurrentDateChange={onCurrentDateChange}
aria-hidden={!open}
aria-live="polite"
aria-labelledby={inputId}
/>
{includeTime && (
<TimeInput
{...timeInputProps}
value={value}
precision={timePrecision}
onChange={handleTimeChange}
datePart={currentDate}
/>
)}
</Popup>
)}
</Widget>
)
},
)
DatePicker.displayName = 'DatePicker'
DatePicker.propTypes = propTypes as any
DatePicker.defaultProps = defaultProps
export default DatePicker | the_stack |
export interface Info {
error_code: string;
error_message: string;
}
export interface CallbackResultNoData {
info: Info;
}
export interface CallbackResult {
info: Info;
data: any;
}
export interface Native {
/**
* ้่ฟ็ฝ้กตjs่ทๅๅฎขๆท็ซฏๅบๆฌไฟกๆฏ
*
* @param params - ๆฅๅฃๅ
ฅๅ
* @param cb ๅ่ฝๅค็ๅ็ๅ่ฐๅฝๆฐ
*/
getSystemInfo(params: any, cb: (res: CallbackResult) => void): void;
/**
* ้่ฟjsๆฅๅฃ่ทๅๅฝๅ็ฝ็ป็ถๆ
* @param params - ๆฅๅฃๅ
ฅๅ
* @param cb ๅ่ฝๅค็ๅ็ๅ่ฐๅฝๆฐ
*/
getNetworkStatus(params: any, cb: (res: CallbackResult) => void): void;
/**
* ้่ฟjsๆฅๅฃ่ทๅ่ฎพๅคๅฏไธๆ ่ฏ็
* @param params - ๆฅๅฃๅ
ฅๅ
* @param cb ๅ่ฝๅค็ๅ็ๅ่ฐๅฝๆฐ
*/
getUDID(params: any, cb: (res: CallbackResult) => void): void;
/**
* ้่ฟ็ฝ้กตjs่ทๅๅฎขๆท็ซฏ็ๆฌไฟกๆฏ
*
* @param params - ๆฅๅฃๅ
ฅๅ
* @param cb ๅ่ฝๅค็ๅ็ๅ่ฐๅฝๆฐ
*/
getVersion(params: any, cb: (res: CallbackResult) => void): void;
/**
* ๆๅผnative็ณป็ป็นๆฎ็ๅค้จ้พๆฅ ๅฆ็ต่ฏ๏ผ้ฎ็ฎฑ๏ผ็ญไฟก๏ผ็ฝ้กต๏ผๅ
ถไปAPP็ญใ
* @param params - ๆฅๅฃๅ
ฅๅ
* @param url - ็ต่ฏ: tel:10086 ้ฎ็ฎฑ: mailto:abc@163.com ็ญไฟก: sms:10086 ็ฝ้กต:https://www.baidu.com App: weixin://
* @param cb ๅ่ฝๅค็ๅ็ๅ่ฐๅฝๆฐ
*/
openURL(params: any, cb: () => void): void;
/**
* ้่ฟjsๆฅๅฃ่ฎฐๅฝๆฅๅฟไฟกๆฏ
* @param params - ๆฅๅฃๅ
ฅๅ
* @param params.level -ๆฅๅฟ็บงๅซ๏ผๅๅผๆinfo,error,debug,warn,verbose
* @param params.content -ๆฅๅฟๅ
ๅฎน
* @param cb ๅ่ฝๅค็ๅ็ๅ่ฐๅฝๆฐ
*/
log(params: any, cb: (res: CallbackResultNoData) => void): void;
/**
* ้่ฟjsๆทปๅ ๅฏผ่ชๆ ๆ้ฎ๏ผ็ฎๅๅ
่ฎธๅจๅทฆๅณไธค่พนๅๅ ไธคไธชๆฉๅฑๆ้ฎ
* @param params - ๆฅๅฃๅ
ฅๅ
* @param params.title ๆๆฌๆ้ฎๆ ้ข
* @param params.icon "ๅพ็ๆ้ฎ็ๅพๆ ๏ผๅฏๆฏๆๆ ผๅผ๏ผ
* 1. ่ฟ็จๅพ็url๏ผๅฟ
้กปไปฅhttp://ๆhttps://ๅผๅคด
* 2. ๅพ็Base64็ผ็ ๏ผไปฅbase64://ๅผๅคด
* 3. gmu๏ผgmu_icon็ฎๅฝไธ็ๆฌๅฐๆไปถ๏ผ็ธๅฏน่ทฏๅพไธไธๅ
ๆฌๆไปถๅ็ผ๏ผๅฆไฝฟ็จๅพ็gmu/gmu_icon/test.png, ๅๆฌกๆญคๅๆฐไธบtest"
* @param params.action "็จๆท็นๅปๆ้ฎ่งฆๅ็ไบไปถ๏ผๅฏๆฏๆๆ ผๅผ๏ผ
* 1. ๆ ๅhttpๆhttps url
* 2. ๆ ๅgmuๅ่ฎฎurl
* 3. JavaScript๏ผไปฅjavascript๏ผๅผๅคด"
* @param params.position ่ฅไธบโleftโ๏ผๆ้ฎๆทปๅ ๅจๅทฆไพง๏ผ่ฅไธบโrightโ๏ผๆ้ฎๆทปๅ ๅจๅณไพง๏ผ้ป่ฎคไธบโrightโ
* @param params.tag ๅฏผ่ชๆ ๆ้ฎ็บข็น็ๆ ่ฏไฝ๏ผ็จไบๆงๅถๆฏๅฆ้่็บข็น๏ผๆณจๆ๏ผไฝฟ็จ็บข็นๅ่ฝๆถ่ฏฅๅญๆฎตไธบๅฟ
้ๅญๆฎต
* @param params.badges ็บข็นjsonๆฐๆฎ๏ผๅฆ{ type: โnumโ, badge: 12,backgroundColor:โ#ff6c00โ}
* 1. typeๅญๆฎต{string}๏ผๅไธบnum๏ผdotไธค็ง๏ผnumไธบ็บข็นๆฐๆฎ็ฑปๅ๏ผdotไธบๅ็บฏๅฐ็บข็น็ฑปๅ๏ผๅณๅณไธ่งๅฐฑๅชๆ็บข่ฒ็ๅ็น๏ผnum็บข็นๆฐๆฎ็ฑปๅ๏ผๅณไธ่งๆ็บข่ฒ็ๅ็นไธๅ็นไธญๆๆฐๅญๆพ็คบ
* 2. badgeๅญๆฎต{number}๏ผ็บข็นๆพ็คบ็ๆฐๅญ
* 3. backgroundColorๅญๆฎต ๏ผ่ฎพ็ฝฎ็บข็น็่ๆฏ้ข่ฒ
* @param cb ๅ่ฝๅค็ๅ็ๅ่ฐๅฝๆฐ
*/
addButton(params: any, cb: () => void): void;
/**
* ๆงๅถๅฏผ่ชๆ ็บข็นๆ้ฎๆฏๅฆ้่
* @param params - ๆฅๅฃๅ
ฅๅ
* @param params.type -ๆงๅถๅฏผ่ชๆ ๆ้ฎ็บข็นๆฏๅฆ้่๏ผ่ฅไธบshow ๅๆพ็คบ็บข็น,ๅฆๅ้่็บข็นใ
* @param params.badgeId -็บข็นId,ไพๆฅ่ฏข็บข็นไฟกๆฏไฝฟ็จใๆณจๆ:่ฆ่ทไฝ ๅๅปบๅฏผ่ชๆ ็บข็นๆถIdไฟๆไธ่ดใ
* @param cb ๅ่ฝๅค็ๅ็ๅ่ฐๅฝๆฐ
*/
showNativeBadge(params: any, cb: () => void): void;
/**
* ไฟฎๆนๅฏผ่ชๆ ้ๆๅบฆ
* @param params - ๆฅๅฃๅ
ฅๅ
* @param params.alpha -่ฎพ็ฝฎ้ๆๅบฆ๏ผ้ๆๅบฆ่ฎพ็ฝฎ่ถๅฐ่ถ้ๆ
* @param cb ๅ่ฝๅค็ๅ็ๅ่ฐๅฝๆฐ
*/
headSetAlpha(params: any, cb: (res: CallbackResultNoData) => void): void;
/**
* ้่ฟjsๅ ้คๅทฒๆทปๅ ็ๅฏผ่ชๆ ๆ้ฎ
* @param params - ๆฅๅฃๅ
ฅๅ
* @param params.string -่ฅไธบโleftโ๏ผๅๅ ้คๅทฆไพงๆ้ฎ๏ผ่ฅไธบโrightโ๏ผๅๅ ้คๅณไพงๆ้ฎ๏ผ้ป่ฎคไธบโrightโ
* @param cb ๅ่ฝๅค็ๅ็ๅ่ฐๅฝๆฐ
*/
removeButton(params: any, cb: (res: CallbackResultNoData) => void): void;
/**
* ้่ฟjsไฟฎๆนๅฏผ่ชๆ ่ๆฏ่ฒ
* @param params - ๆฅๅฃๅ
ฅๅ
* @param params.color -้ข่ฒ๏ผๆ ผๅผไธบ #ffffff
* @param cb ๅ่ฝๅค็ๅ็ๅ่ฐๅฝๆฐ
*/
setBackgroundColor(params: any, cb: (res: CallbackResultNoData) => void): void;
/**
* ้่ฟjsๆฅๅฃๆงๅถๅฏผ่ชๆ ๆ ้ข
* @param params - ๆฅๅฃๅ
ฅๅ
* @param params.title -ๆ ้ข
* @param cb ๅ่ฝๅค็ๅ็ๅ่ฐๅฝๆฐ
*/
setTitle(params: any, cb: (res: CallbackResultNoData) => void): void;
/**
* ้่ฟjsๆฅๅฃ่ฎพ็ฝฎๅฏผ่ชๆ ไธไธๆ ้ขๆ ทๅผ
* @param params - ๆฅๅฃๅ
ฅๅ
* @param params.title -ๆ ้ข
* @param params.subtitle -ๅฏๆ ้ข
* @param cb ๅ่ฝๅค็ๅ็ๅ่ฐๅฝๆฐ
*/
setSubtitle(params: any, cb: (res: CallbackResultNoData) => void): void;
/**
* ้่ฟjs่ฎพ็ฝฎๅฏผ่ชๆ ๆ็ดข่งๅพ
* @param params - ๆฅๅฃๅ
ฅๅ
* @param params.icon -ๆ็ดขๆกๅพๆ ็ๆไปถๅ๏ผnative/res/icon็ฎๅฝไธ็ๆฌๅฐๆไปถ๏ผ็ธๅฏน่ทฏๅพไธไธๅ
ๆฌๆไปถๅ็ผ๏ผๅฆไฝฟ็จๅพ็native/res/icon/test.png๏ผ ๅๆฌกๆญคๅๆฐไธบtest
* @param params.backgroundColor -ๆ็ดขๆก่ๆฏ้ข่ฒ๏ผๆ ผๅผไธบ #ffffff๏ผ้ป่ฎคไธบ็ฝ่ฒ
* @param params.placeholderText -ๆ็ดขๆกๆๅญ๏ผ้ป่ฎคไธบ็ฉบ
* @param params.type -ๆ็ดขๆก็่พๅ
ฅ็ฑปๅ๏ผ่ฅtypeไธบinputๅไธบๅฏไปฅ่พๅ
ฅๆๅญ๏ผๅฆๅๅชๆง่กtouch ่ทณ่ฝฌไบไปถ
* @param params.placeholderTextColor -ๆ็ดขๆกๆๅญ้ข่ฒ๏ผๆ ผๅผไธบ #ffffff๏ผ้ป่ฎค็ฐ่ฒ
* @param cb ๅ่ฝๅค็ๅ็ๅ่ฐๅฝๆฐ
*/
headSetSearchView(params: any, cb: (res: CallbackResult) => void): void;
/**
* ้่ฟjs่ฐ็จ้กต้ข่ฟๅไบไปถ
* @param params - ๆฅๅฃๅ
ฅๅ
* @param params.number - ่ฟๅ็ๅฑๆฐใๅฆไธบ1๏ผๅ่ฟๅไธไธๅฑใๅคงไบ็ญไบ้กต้ขๆ ๆฐ้๏ผๅ่ฟๅ้ฆ้กต๏ผๅฐไบ็ญไบ0๏ผๅๆ ๆใไธ้
็ฝฎ่ฏฅๅญๆฎต๏ผๅ้ป่ฎค่ฟๅไธไธๅฑ
* @param cb ๅ่ฝๅค็ๅ็ๅ่ฐๅฝๆฐ
*/
back(params: any, cb: (res: CallbackResultNoData) => void): void;
/**
* ้่ฟjs่ฐ็จๅ
ณ้ญ้กต้ข
*/
close(params: null, cb: (res: CallbackResultNoData) => void): void;
/**
* ้่ฟjsๆฅๅฃๅจ็ฝ้กตๆJsNative้กต้ขไธญๅๆขๅบ้จtab
*
* @param params - ๆฅๅฃๅ
ฅๅ
* @param params.index - ๅๆข่ณไธๆ ไธบindexไฝ็ฝฎ็tab
* @param cb ๅ่ฝๅค็ๅ็ๅ่ฐๅฝๆฐ
*/
switchTab(params: any, cb: (res: CallbackResultNoData) => void): void;
/**
* ่ฎพ็ฝฎ้ฆ้กตtabๅฐ็บข็น
* @param params - ๆฅๅฃๅ
ฅๅ
* @param params.index -tab็index๏ผๅผไป0ๅผๅง่ฎกๆฐ๏ผ้กปๅจtabไธชๆฐ่ๅดๅ
* @param params.type -0่กจ็คบ็บข็น๏ผ1่กจ็คบๆๆฌ๏ผ้ป่ฎคไธบ0
* @param params.value -typeไธบ0ๆถ๏ผๅฟฝ็ฅvalueๅญๆฎตๅผไธบ""ไปฅๅค็ๆๆๅผใ่ฅvalueไธบ"",ๅๆธ
้ค็บข็นใtypeไธบ1ๆถ๏ผvalueไธบๅฟ
้กปๅญๆฎต๏ผๆพ็คบๅจ็บข็นไธญๅฟ็ๆๆฌ,่ฅvalueไธบ"",ๅๆธ
้คๆๆฌ
* @param cb ๅ่ฝๅค็ๅ็ๅ่ฐๅฝๆฐ
*/
setTabBarBadge(params: any, cb: (res: CallbackResultNoData) => void): void;
/**
* ้่ฟJSๅ้็ป่ฎกๅๆๅ็นไบไปถ
* @param params - ๆฅๅฃๅ
ฅๅ
* @param params.event -ไบไปถID๏ผ่ขซ็ป่ฎกไบไปถ็ๅฏไธๆ ่ฏ๏ผ็จๆท้่ฆๅ
ๅจ่กไธบๅๆ็ฝ็ซๅๅฐๆณจๅไบไปถID ๏ผ็ถๅๅฎขๆท็ซฏ้้็ไบไปถๆ่ฝๅจ็ฝ็ซๅๅฐๅฑ็คบ๏ผ
* @param params.attributes -ไบไปถ้ๅ ๅฑๆง๏ผ็จๆทๅฏๆ นๆฎไธๅก้ๆฑไธบไบไปถๆทปๅ ้ๅ ๅฑๆง๏ผ้ป่ฎคๅผไธบ{}
* @param params.duration -ไบไปถๆถ้ฟ๏ผๆฏซ็ง๏ผ๏ผ่ฏฅๅญๆฎตๅฏไปฅไธบๆ็ปญๆงไบไปถๆ ่ฏไบไปถๆ็ปญ็ๆถ้ฟ๏ผ้ป่ฎคๅผไธบ0
* @param cb ๅ่ฝๅค็ๅ็ๅ่ฐๅฝๆฐ
*/
analyticsSendEvent(params: any, cb: () => void): void;
/**
* ้่ฟjsๆฅๅฃ่ทๅพๅฝๅๆกๆถ้กต้ขๅ ๆ ไฟกๆฏ
* @param params
* @param cb
*/
getCurrentPages(params: any, cb: (res: CallbackResult) => void): void;
/**
* ็จไบๅฎ็ฐ็ฝ็ป่ฏทๆฑ
* @param params - ๆฅๅฃๅ
ฅๅ
* @param params.url - ่ฏทๆฑ็ URL
* @param params.method - HTTP ๆนๆณ GET ๆ POST ๏ผ้ป่ฎคGET
* @param params.headers - HTTP ่ฏทๆฑๅคด
* @param params.type - ๅๅบ็ฑปๅ๏ผ json๏ผtext ๆๆฏ jsonp ๏ผๅจๅ็ๅฎ็ฐไธญๅ
ถๅฎไธ json ็ธๅ๏ผ
* @param params.body - HTTP ่ฏทๆฑไฝ
* @param params.timeout - ่ฏทๆฑ่ถ
ๆถๆถ้ด๏ผๅไฝms,้ป่ฎค30000ms
*/
streamFetch(params: any, cb: (res: CallbackResult) => void): void;
/**
* ๆพ็คบ่ๅฑ
* @param params - ๆฅๅฃๅ
ฅๅ
* @param params.data - ๅ ่ฝฝๅฐ่ๅฑWebViewไธญ้กต้ขๆฐๆฎ๏ผๅฏไปฅๆฏๅญ็ฌฆไธฒๆ ผๅผ็HTMLๆURL๏ผURLไธบ่ฟ็จๅฐๅๆๆฌๅฐwwwไธ็HTML๏ผ
* @param params.dataType -data็็ฑปๅ strh5 ๆ url ๏ผ้ป่ฎคstrh5 ๏ผstrh5: ๅ ่ฝฝๅญ็ฌฆไธฒๆ ผๅผHTML, url: ่ฟ็จๅฐๅๆๆฌๅฐwwwไธ็HTML๏ผ
* @param params.callbackDataType - ่ฟๅ็dataๅญๆฎต็ฑปๅ json ๆ text๏ผ้ป่ฎคๆฏtext
*/
showOverlay(params: any, cb: (res: CallbackResult) => void): void;
/**
* ้่ฟjsๆฅๅฃ่ฎพ็ฝฎๅฑๅนๆนๅ
* @param params - ๆฅๅฃๅ
ฅๅ
* @param params.screenOrientation - landscape_left:ๅทฆๆจชๅฑ landscape_right๏ผๅณๆจชๅฑ portrait๏ผ็ซๅฑ
* @param cb ๅ่ฝๅค็ๅ็ๅ่ฐๅฝๆฐ
*/
setScreenOrientation(params: any, cb: (res: CallbackResultNoData) => void): void;
/**
* ้่ฟjsๆฅๅฃ่ฎพ็ฝฎๅฑๅนๅฏๆ่ฝฌๆนๅ
* @param params - ๆฅๅฃๅ
ฅๅ
* @param params.supportScreenOrientation - ไปฅๆฐ็ปๅฝขๅผ๏ผๆทปๅ ๅฏ่ฎพ็ฝฎๆนๅใ
* @param cb ๅ่ฝๅค็ๅ็ๅ่ฐๅฝๆฐ
*/
setSupportScreenOrientation(params: any, cb: (res: CallbackResult) => void): void;
/**
* ้่ฟjsๆฅๅฃๆงๅถๆฏๅฆ้่็ถๆๆ
* @param params - ๆฅๅฃๅ
ฅๅ
* @param params.hidden -ๆฏๅฆ้่
* @param cb ๅ่ฝๅค็ๅ็ๅ่ฐๅฝๆฐ
*/
setSystemStatusBar(params: any, cb: (res: CallbackResultNoData) => void): void;
/**
* ้่ฟjsๆฅๅฃ่ทๅAPP็ถๆๆ ้ซๅบฆ
* @param params - ๆฅๅฃๅ
ฅๅ
*/
getStatusBarHeight(params: any, cb: (res: CallbackResult) => void): void;
/**
* ้่ฟjs็ปๅฝ็จๆท
* @param params - ๆฅๅฃๅ
ฅๅ
* @param params.uid -็จๆทhsid
* @param params.mobile -็จๆทๆๆบๅท็
* @param params.token -็จๆทไปค็
* @param params.nickname -็จๆทๆต็งฐ
* @param params.photoURL -็จๆทๅคดๅๅฐๅ
* @param params.logoutWhenExit -app้ๅบๅๆฏๅฆๆณจ้ๅฝๅ็จๆท
* @param cb ๅ่ฝๅค็ๅ็ๅ่ฐๅฝๆฐ
*/
userLogin(params: any, cb: any): void;
/**
* ้่ฟJS่ทๅ็ปๅฝ็จๆทไฟกๆฏ
* @param cb
*/
userGetInfo(cb: (res: CallbackResult) => void): void;
/**
* ้่ฟjs่ฎพ็ฝฎ็ปๅฝ็จๆทไฟกๆฏ
* @param params - ๆฅๅฃๅ
ฅๅ
* @param params.uid -็จๆทhsid
* @param params.mobile -็จๆทๆๆบๅท็
* @param params.token -็จๆทไปค็
* @param params.nickname -็จๆทๆต็งฐ
* @param params.photoURL -็จๆทๅคดๅๅฐๅ
* @param params.logoutWhenExit -app้ๅบๅๆฏๅฆๆณจ้ๅฝๅ็จๆท
* @param params.extraInfo -็จๆท้ขๅคไฟกๆฏ
* @param cb ๅ่ฝๅค็ๅ็ๅ่ฐๅฝๆฐ
*/
userSetInfo(params: any, cb: (res: CallbackResult) => void): void;
/**
* ้่ฟJS้ๅบ็จๆท็ปๅฝ
* @param cb
*/
userlogout(cb: (res: CallbackResult) => void): void;
/**
* ็จไบๅ็ณป็ปๆฅๅๅขๅ ไบไปถ
* @param params - ๆฅๅฃๅ
ฅๅ
* @param params.startDate - ๅผๅงๆถ้ด๏ผๆ ผๅผ๏ผyyyy-MM-dd hh:mm:ss ๏ผ็คบไพ๏ผ"2019-6-12 15:05:00"
* @param params.endDate - ็ปๆๆถ้ด๏ผๆ ผๅผๅๅผๅงๆถ้ด๏ผ้ป่ฎคๅผไธบๅผๅงๆถ้ด๏ผไธๅกซๆๆๅกซๆถ้ดๅฐไบๅผๅงๆถ้ด๏ผๅไธบ้ป่ฎคๅผ
* @param params.title - ๆ ้ข
* @param params.location - ไฝ็ฝฎไฟกๆฏ
* @param params.notes - ๅคๆณจไฟกๆฏ
* @param params.alarmOffset - ๆๅๆ้ๆถ้ด๏ผๅไฝ๏ผๅ ๏ผ้ป่ฎคๅผไธบ0๏ผๅณไบไปถๅผๅงๆถ้ดๆ้.ๆณจๆไบ้กน๏ผ็ฑปๅๅฟ
้กปไธบๆดๆฐ๏ผๅ
ฅๅๅฐไบ0ๆถไธบ้ป่ฎคๅผ
* @param cb ๅ่ฝๅค็ๅ็ๅ่ฐๅฝๆฐ
*/
createCalendar(params: any, cb: (res: CallbackResult) => void): void;
/**
* ็จไบๅ็ณป็ปๆฅๅๆดๆฐ็ธๅบไบไปถไฟกๆฏ
* @param params - ๆฅๅฃๅ
ฅๅ
* @param params.id - ไบไปถid
* @param params.startDate - ๅผๅงๆถ้ด๏ผๆ ผๅผ๏ผyyyy-MM-dd hh:mm:ss ๏ผ็คบไพ๏ผ"2019-6-12 15:05:00"
* @param params.endDate - ็ปๆๆถ้ด๏ผๆ ผๅผๅๅผๅงๆถ้ด๏ผ้ป่ฎคๅผไธบๅผๅงๆถ้ด๏ผไธๅกซๆๆๅกซๆถ้ดๅฐไบๅผๅงๆถ้ด๏ผๅไธบ้ป่ฎคๅผ
* @param params.title - ๆ ้ข
* @param params.location - ไฝ็ฝฎไฟกๆฏ
* @param params.notes - ๅคๆณจไฟกๆฏ
* @param params.alarmOffset - ๆๅๆ้ๆถ้ด๏ผๅไฝ๏ผๅ ๏ผ้ป่ฎคๅผไธบ0๏ผๅณไบไปถๅผๅงๆถ้ดๆ้.ๆณจๆไบ้กน๏ผ็ฑปๅๅฟ
้กปไธบๆดๆฐ๏ผๅ
ฅๅๅฐไบ0ๆถไธบ้ป่ฎคๅผ
* @param cb ๅ่ฝๅค็ๅ็ๅ่ฐๅฝๆฐ
*/
updateCalendar(params: any, cb: (res: CallbackResult) => void): void;
/**
* ็จไบๅ็ณป็ปๆฅๅๅ ้คไบไปถ
* @param params - ๆฅๅฃๅ
ฅๅ
* @param params.startDate - ๅผๅงๆถ้ด๏ผๆ ผๅผ๏ผyyyy-MM-dd hh:mm:ss ๏ผ็คบไพ๏ผ"2019-6-12 15:05:00"
* @param params.endDate - ็ปๆๆถ้ด๏ผๆ ผๅผๅๅผๅงๆถ้ด๏ผ้ป่ฎคๅผไธบๅผๅงๆถ้ด๏ผไธๅกซๆๆๅกซๆถ้ดๅฐไบๅผๅงๆถ้ด๏ผๅไธบ้ป่ฎคๅผ
* @param params.id - ไบไปถid
* @param cb ๅ่ฝๅค็ๅ็ๅ่ฐๅฝๆฐ
*/
deleteCalendar(params: any, cb: (res: CallbackResultNoData) => void): void;
/**
* ็จไบๅ็ณป็ปๆฅๅๆฅ่ฏขไบไปถ
* @param params - ๆฅๅฃๅ
ฅๅ
* @param params.startDate - ๅผๅงๆถ้ด๏ผๆ ผๅผ๏ผyyyy-MM-dd hh:mm:ss ๏ผ็คบไพ๏ผ"2019-6-12 15:05:00"
* @param params.endDate - ็ปๆๆถ้ด๏ผๆ ผๅผๅๅผๅงๆถ้ด๏ผ้ป่ฎคๅผไธบๅผๅงๆถ้ด๏ผไธๅกซๆๆๅกซๆถ้ดๅฐไบๅผๅงๆถ้ด๏ผๅไธบ้ป่ฎคๅผ
* @param params.id - ไบไปถid
* @param cb ๅ่ฝๅค็ๅ็ๅ่ฐๅฝๆฐ
*/
queryCalendar(params: any, cb: (res: CallbackResult) => void): void;
/**
* ้่ฟjsๆฅๅฃๅจ็ฝ้กตไธญๆฅ่ฏขๅญๅจๅจnative็ๅฑๆง
* @param params - ๆฅๅฃๅ
ฅๅ
* @param params.key - nativeๅญๅจๆฐๆฎ็key
* @param params.keepType - ไผ true๏ผvalueๅฏไปฅๆฏๆstringใobjectใarrayใbooleanใnumber็ญ็ฑปๅ็ๆฐๆฎใ้ป่ฎคfalse๏ผๅณๅชๆฏๆstringๆobject็ฑปๅ็ๆฐๆฎ
* @param params.multi_param - ไธๆฌกๆง่ฏปๅๅคไธชๅผๅฆ[{key:key1},{key:key2}]
* @param params.scope - nativeๅญๅจๅ
* @param cb ๅ่ฝๅค็ๅ็ๅ่ฐๅฝๆฐ
*/
readData(params: any, cb: (res: CallbackResult) => void): void;
/**
* ้่ฟjsๆฅๅฃๅจ็ฝ้กตไธญๅnativeไฟๅญๆฐๆฎ
* @param params - ๆฅๅฃๅ
ฅๅ
* @param params.key - nativeๅญๅจๆฐๆฎ็key
* @param params.value - ๅnativeไฟๅญ็ๆฐๆฎ
* @param params.keepType - ไผ true๏ผvalueๅฏไปฅๆฏๆstringใobjectใarrayใbooleanใnumber็ญ็ฑปๅ็ๆฐๆฎใ้ป่ฎคfalse๏ผๅณๅชๆฏๆstringๆobject็ฑปๅ็ๆฐๆฎ
* @param params.multi_param - ไธๆฌกๆงๅญๅจๅคไธชๅผๅฆ[{key:key1,value:value1},{key:key2,value:value1}]
* @param params.scope - nativeๅญๅจๅ
* @param cb ๅ่ฝๅค็ๅ็ๅ่ฐๅฝๆฐ
*/
writeData(params: any, cb: (res: CallbackResult) => void): void;
/**
* ้่ฟjsๆฅๅฃๅจ็ฝ้กตไธญๅ ้คๅญๅจๅจnative็ๅฑๆง
* @param params - ๆฅๅฃๅ
ฅๅ
* @param params.key - nativeๅญๅจๆฐๆฎ็key
* @param params.multi_param - ไธๆฌกๆงๅ ้คๅคไธชๅผๅฆ[{key:key1},{key:key2}]
* @param params.scope - nativeๅญๅจๅ
* @param cb ๅ่ฝๅค็ๅ็ๅ่ฐๅฝๆฐ
*/
deleteData(params: any, cb: (res: CallbackResult) => void): void;
/**
* ้่ฟjsๆฅๅฃ่ทๅๅฎขๆท็ซฏ็ณป็ปๅช่ดดๆฟๅ
ๅฎน
* @param params - ๆฅๅฃๅ
ฅๅ
* @param cb ๅ่ฝๅค็ๅ็ๅ่ฐๅฝๆฐ
*/
getClipBoardContent(params: null, cb: (res: CallbackResult) => void): void;
/**
* ้่ฟjsๆฅๅฃๅจwebๆ่
JSNative้กต้ขไธญๅคๅถๅ
ๅฎนๅฐๅช่ดดๆฟ
* @param params - ๆฅๅฃๅ
ฅๅ
* @param params.value - ้่ฆๅคๅถๅฐๅช่ดดๆฟ็ๅ
ๅฎน๏ผ็ฎๅๅชๆฏๆๅญ็ฌฆไธฒ
* @param cb ๅ่ฝๅค็ๅ็ๅ่ฐๅฝๆฐ
*/
setClipBoardContent(params: any, cb: any): void;
/**
* ้่ฟjs่ทๅๆๆบ้่ฎฏๅฝไฟกๆฏ
* @param params - ๆฅๅฃๅ
ฅๅ
* @param cb ๅ่ฝๅค็ๅ็ๅ่ฐๅฝๆฐ
*/
getContactInfo(params: null, cb: (res: CallbackResult) => void): void;
/**
* ้่ฟjsๆฅๅฃ่ฟๅๆๅฎๅญ็ฌฆไธฒๅ
ๅฎน็ไบ็ปด็ ๅพ็็base64็ผ็ ๅญ็ฌฆไธฒ
*
* @param params - ๆฅๅฃๅ
ฅๅ
* @param params.desc - ้่ฆ่ขซ็ผ็ ๆไบ็ปด็ ็ๅ
ๅฎน
* @param params.size - ไบ็ปด็ ๅฐบๅฏธ,้ป่ฎคไธบ300x300๏ผ
* @param cb ๅ่ฝๅค็ๅ็ๅ่ฐๅฝๆฐ
*/
genCode(params: any, cb: (res: CallbackResult) => void): void;
/**
* ้่ฟjsๆฅๅฃๆๅผๆฌๅฐไบ็ปด็ ๆซๆ้กต้ข๏ผๆซ็ ๆๅๅๅจ็ฝ้กตไธญ่ฟๅๆซ็ ็ปๆไฟกๆฏ
*
* @param params - ๆฅๅฃๅ
ฅๅ
* @param params.sideLength - ๆซๆๅบๅ่พน้ฟ็ธๅฏนไบๅฑๅน่พ็ญ่พน้ฟ็็พๅๆฏ๏ผๅๅผ่ๅด(0,1]
* @param params.offsetX - ๆซๆๅบๅ็ธๅฏนไบๅฑๅนๅทฆไพง็ๅ็งป็พๅๆฏ๏ผๅๅผ่ๅด[0,1]
* @param params.offsetY - ๆซๆๅบๅ็ธๅฏนไบๅฑๅน้กถ้จ็ๅ็งป็พๅๆฏ๏ผๅๅผ่ๅด[0,1]
* @param params.type - ๆซไธๆซ่ฏๅซ็ฑปๅใๅๆฐๅผๆ2็งๅฏ้๏ผqrcode๏ผไบ็ปด็ ๏ผ barcode๏ผๆกๅฝข็ ๏ผไธไผ ๆๅๆฐ้่ฏฏๆถ้ป่ฎคไธบไบ็ปด็ ๆๆ
* @param cb ๅ่ฝๅค็ๅ็ๅ่ฐๅฝๆฐ
*/
scanCode(params: any, cb: (res: CallbackResult) => void): void;
/**
* ้่ฟjs่ฐ็จ่ทๅ็ป็บฌๅบฆ
* @param params - ๆฅๅฃๅ
ฅๅ
* @param params.scanSpan - ๅฎไฝๅทๆฐ้ด้๏ผๅไฝๆฏซ็ง๏ผ
* @param cb ๅ่ฝๅค็ๅ็ๅ่ฐๅฝๆฐ
*/
getLocation(params: any, cb: (res: CallbackResult) => void): void;
/**
* ้่ฟjs่ฐ็จๅ
ณ้ญๅฎไฝๆๅก
* @deprecated
* @param params - ๆฅๅฃๅ
ฅๅ
* @param cb
*/
stopLocation(params: any, cb: (res: CallbackResult) => void): void;
/**
* ่ทๅๅฝๅๆฏๅฆๅฏ่ทๅๅฎไฝ็ถๆ
* @param params - ๆฅๅฃๅ
ฅๅ
* @param cb ๅ่ฝๅค็ๅ็ๅ่ฐๅฝๆฐ
*/
getLocationStatus(params: any, cb: (res: CallbackResult) => void): void;
/**
* ้่ฟJS่ทๅๆจ้registrationID
* @deprecated
* @param params - ๆฅๅฃๅ
ฅๅ
* @param cb
*/
pushGetRegistrationID(params: null, cb: (res: CallbackResult) => void): void;
/**
* ๅฝๅ็จๆทๆทปๅ ๆ ็ญพ
* @deprecated
* @param params - ๆฅๅฃๅ
ฅๅ
* @param params.tags -็จๆทๆไผ ็ๆ ็ญพ้ๅ
* @param cb
*/
pushAddTags(params: any, cb: (res: CallbackResultNoData) => void): void;
/**
* ๅฝๅ็จๆทๅ ้คๆ ็ญพ
* @deprecated
* @param params - ๆฅๅฃๅ
ฅๅ
* @param params.tags -็จๆทๆไผ ็ๆ ็ญพ้ๅ
* @param cb
*/
pushDeleteTags(params: any, cb: (res: CallbackResultNoData) => void): void;
/**
* ่ทๅๅฝๅ็จๆท็ๆๆๆ ็ญพ
* @deprecated
* @param params
* @param cb
*/
pushGetTags(params: any, cb: (res: CallbackResult) => void): void;
/**
* ้่ฟJSๅๅฎขๆท็ซฏไผ ้ๆจ้alias๏ผ็จไบๆจ้ๆๅกๅจๅฎ็นๆจ้
* @param params - ๆฅๅฃๅ
ฅๅ
* @param params.alias -ๆจ้alias๏ผไธบ็ฉบๅญ็ฌฆไธฒๆถไธบๆธ
้คๅทฒๆalias
* @param cb ๅ่ฝๅค็ๅ็ๅ่ฐๅฝๆฐ
*/
pushSetAlias(params: any, cb: (res: CallbackResultNoData) => void): void;
/**
* ้่ฟJS่ทๅๆจ้ๆถๆฏ
* @param params - ๆฅๅฃๅ
ฅๅ
* @param cb ๅ่ฝๅค็ๅ็ๅ่ฐๅฝๆฐ
*/
pushAddEventListener(params: null, cb: (res: CallbackResult) => void): void;
/**
* ้่ฟjsๆฅๅฃๅจ็ฝ้กตไธญ่ฟๅๆๅฎๅพ็็ๆไปถID๏ผๅ่ฎฎๆ ผๅผไธบLightResource://xxx.image
* @param params - ๆฅๅฃๅ
ฅๅ
* @param params.count - ๆๅคงๅฏ้็
ง็ๆฐ๏ผ้ป่ฎค 9 ๅผ ๏ผๅๅผ่ๅด๏ผ1-9
* @param params.sizeType -originalๅๅพ๏ผcompressed ๅ็ผฉๅพ๏ผ้ป่ฎค ['original','compressed']
* @param params.sourceType - ็ธๅ้ๅๆ่
ๆ็
ง๏ผ้ป่ฎค ['camera','album']
*/
imagePicker(params: any, cb: (res: CallbackResult) => void): void;
/**
* ้่ฟjsๆฅๅฃๅจ็ฝ้กตไธญ่ฟๅๆๅฎๆไปถIDๅฏนๅบ็base64็ผ็ ๅญ็ฌฆไธฒ
* @param params - ๆฅๅฃๅ
ฅๅ
* @param params.path - ๆไปถID,ๅ่ฎฎไธบLightResource://xxx.็ฑปๅ
*/
getBase64(params: any, cb: (res: CallbackResult) => void): void;
/**
* ้่ฟjsๆฅๅฃ้กต้ขไธญ่ฟๅๆๅฎๅพ็็base64็ผ็ ๅญ็ฌฆไธฒ
*
* @param params - ๆฅๅฃๅ
ฅๅ
* @param params.imagePickType - ้ๆฉ็จๆๅๅคด่ฟๆฏ็ธๅ่ฟ่ก้ๆฉ๏ผ้ป่ฎค2็ง้ฝๆพ็คบ(carmer,album)ๅ้ๅพ็๏ผๅค้ๅพ็ไผ ๅ
ฅtypeไธบ๏ผ(CAMERA_MUTIL-ALBUM)
* @param params.cropPhoto - ๆฏๅฆๅช่ฃ
* @param params.maxWidth - ๆๅคงๅฎฝๅบฆ
* @param params.aspectXY - ๅฎฝ้ซๆฏ
* @param params.maxCount - ๅฎฝ้ซๆฏ
* @param params.allowTakePicture - ๅค้ๅพ็(ๅณtypeไธบCAMERA_MUTIL-ALBUMๆMUTIL-ALBUM)ๆ
ๅตไธๅฏ้็ๆๅคง็
ง็ๆฐ๏ผ้ป่ฎคไธบ9ใ
* @param params.reverselyOrdered - ๅค้ๅพ็(ๅณtypeไธบCAMERA_MUTIL-ALBUMๆMUTIL-ALBUM)ๆ
ๅตไธ็ธๅ้ๆฉๅจๆฏๅฆๅๅบๆพ็คบ๏ผ้ป่ฎคๆญฃๅบๆพ็คบ๏ผไป
ๆฏๆiOS
* @param cb ๅ่ฝๅค็ๅ็ๅ่ฐๅฝๆฐ
*/
chooseImage(params: any, cb: (res: CallbackResult) => void): void;
/**
* ้่ฟjsๅฏนweb้กตๆJSNative้กต้ขไธ็ๅพ็่ฟ่กๆฌๅฐๅๅค็๏ผไฟๅญ่ณๆฌๅฐ็ธๅ
* @param params - ๆฅๅฃๅ
ฅๅ
* @param params.image -ๅพ็ๆฐๆฎ๏ผๆฏๆไปฅไธๆ ผๅผ๏ผ1. ๆ ๅhttpๆhttpsๅพ็้พๆฅ 2. ๅพ็base64็ผ็ ๏ผไปฅdata:image/png;base64, //ๅผๅคด
* @param cb ๅ่ฝๅค็ๅ็ๅ่ฐๅฝๆฐ
*/
saveImage(params: any, cb: (res: CallbackResultNoData) => void): void;
/**
* ๅพ็้ข่งๅ่ฝ๏ผๆฏๆ้ข่งๅคๅผ ๅพ็ใ
* @param params - ๆฅๅฃๅ
ฅๅ
* @param params.images -ๅพ็ๅฐๅ
* @param params.selectedIndex -้ข่งๆถ็ๅพ็ๆฐ็ปไธๆ (ไป0ๅผๅง)๏ผ่กจ็คบๅฑ็คบๅฝๅ้ไธญ็ๅพ็ใ้ป่ฎคๆ
ๅตไธบ0
* @param cb ๅ่ฝๅค็ๅ็ๅ่ฐๅฝๆฐ
*/
imagePreview(params: any, cb: (res: CallbackResultNoData) => void): void;
/**
* ้่ฟjsๆฅๅฃๅฝๅถ้ณ้ข
* @param params - ๆฅๅฃๅ
ฅๅ
* @param params.duration -้ณ้ขๅฝๅถ็ๆ้ฟๆถ้ด๏ผไปฅ็งไธบๅไฝ
* @param cb ๅ่ฝๅค็ๅ็ๅ่ฐๅฝๆฐ
*/
startRecord(params: any, cb: (res: CallbackResultNoData) => void): void;
/**
* ้่ฟjsๆฅๅฃ็ปๆๅฝๅถ้ณ้ข
* @param cb
*/
stopRecord(cb: (res: CallbackResult) => void): void;
/**
* ๆไปถ้ข่ง๏ผๆฏๆdoc๏ผdocx ๏ผxls๏ผxlsx๏ผpdf๏ผtxt๏ผppt ๏ผpptXใ
* @param params - ๆฅๅฃๅ
ฅๅ
* @param params.url -้่ฆๆๅผ็ๆไปถๅฐๅ
* @param params.title -้ข่ง้กต้ขๆ ้ข๏ผๅฆๆไธไผ title๏ผ้ป่ฎคไธบๆไปถๅ๏ผๅ่งๆณจๆไบ้กน
* @param cb ๅ่ฝๅค็ๅ็ๅ่ฐๅฝๆฐ
*/
filePreview(params: any, cb: (res: CallbackResult) => void): void;
/**
* ๆไปถไธ่ฝฝไฟๅญๅ่ฝใๆไปถๆฏๆdoc๏ผdocx ๏ผxls๏ผxlsx๏ผpdf๏ผtxt๏ผppt ๏ผpptXใ
* @param params - ๆฅๅฃๅ
ฅๅ
* @param params.path -ๆไปถๅญๆพ็็ธๅฏน่ทฏๅพ๏ผไปฅโ/โๅผๅคด๏ผไพโ/aaa/bbb.docxโ
* @param params.url -ๆไปถ็่ฟ็จๅฐๅ
* @param params.data -ๆไปถๆฐๆฎ็base64็ผ็ ๅญ็ฌฆไธฒ๏ผurlไธdata่ณๅฐๆไธไธชไธไธบ็ฉบ๏ผไผๅ
ๅurl็ๅผ
* @param params.overwrite -ๆฏๅฆ่ฆ็๏ผ้ป่ฎคไธ่ฆ็๏ผ
* @param cb ๅ่ฝๅค็ๅ็ๅ่ฐๅฝๆฐ
*/
fileSave(params: any, cb: (res: CallbackResult) => void): void;
/**
* ้่ฟjs่ทๅๆฏๅฆๅซๆๆๅฟๆๆ็บน้ช่ฏไฟกๆฏ
* @param params - ๆฅๅฃๅ
ฅๅ
* @param params.verifyType -้ช่ฏๆนๅผ๏ผFP:ๆ็บน GL:ๆๅฟ๏ผ
* @param cb ๅ่ฝๅค็ๅ็ๅ่ฐๅฝๆฐ
*/
preVerifyOpeation(params: any, cb: (res: CallbackResult) => void): void;
/**
* ้่ฟjs่ฐ็จๆๅฟๆๆ็บน้ช่ฏ
* @param params - ๆฅๅฃๅ
ฅๅ
* @param params.verifyType -้ช่ฏๆนๅผ๏ผFP:ๆ็บน GL:ๆๅฟ๏ผ
* @param params.GLOpeationType -ๅชๆverifyTypeไธบGLๆๅฏ็จ๏ผๅญๆฎต่ฏดๆ(verify:ๆๅฟ้ช่ฏ set:ๆๅฟ่ฎพ็ฝฎ update:ๆๅฟๆดๆฐ close:ๆธ
้คๆๅฟ)
* @param params.otherTitle -ๅ
ถไปๆนๅผ็นๅปๆ้ฎtitle
* @param params.additionalTitle -้ๅ ๆนๅผ็นๅปๆ้ฎtitle
* @param cb ๅ่ฝๅค็ๅ็ๅ่ฐๅฝๆฐ
*/
verifyOpeation(params: any, cb: (res: CallbackResult) => void): void;
/**
* ้่ฟjsๅฑ็ฐๅฎๅ
จ้ฎ็
* @deprecated
* @param params - ๆฅๅฃๅ
ฅๅ
* @param params.textshow -Plain:ๆๆๆพ็คบ๏ผไธๅ ๅฏ๏ผๅฝtextShow่ฎพ็ฝฎไธบPlainๆถ๏ผencryptModeๆ ่ฎบ่ฎพ็ฝฎๆไปไน้ฝไธๅ ๅฏ๏ผใDelayAsterisk:ๅญ็ฌฆ0.5็งๅๅไธบๆๅทใInstantAsterisk:ๅญ็ฌฆ่พๅ
ฅๅ็ดๆฅๅไธบๆๅทใ้ป่ฎคไธบInstantAsterisk้
็ฝฎ๏ผๅคงๅฐๅไธๆๆ๏ผๅ้ข็ฑปๅไธบstring็้
็ฝฎ้กนไธๆ ท๏ผ
* @param params.disorderEffect -appear:้ฆๆฌกๆๅผ้ฎ็ๆถๅฐฑไนฑๅบ click:็นๅปๆ้ฎๆถๆไนฑๅบ๏ผappearandclick:ๆๅผ้ฎ็ๅฐฑไนฑๅบไธ็นๅปๆ้ฎไนไนฑๅบใ่ฅๆ ้
็ฝฎๆ้
็ฝฎๅญ็ฌฆไธฒไธ็ฌฆๅ่ฟไธไธช๏ผๅ้ป่ฎคไธบclickๆๆใๆณจๆ:่ฏฅๅญๆฎต้กป้
ๅdisorderๅญๆฎตไธ่ตทไฝฟ็จใ
* @param params.disorder -none:ไธไนฑๅบใnumber:ๅชๆๆฐๅญไนฑๅบใnumberAndAlpha:ๆฐๅญๅญๆฏ้ฝไนฑๅบใ่ฅๆ ้
็ฝฎๆ้
็ฝฎๅญ็ฌฆไธฒไธ็ฌฆๅ่ฟไธไธช๏ผๅ้ป่ฎคไธบnoneใ
* @param params.pressEffect -default:ๆ้ฎ็นๅปๅๆ็นๅปๆๆ๏ผnone:ๆฒกๆ็นๅปๆๆใ้ป่ฎคไธบdefaultใ
* @param params.keyboardType -number:ๆฐๅญ้ฎ็,alpha:ๅญๆฏ้ฎ็,symbol:็ฌฆๅท้ฎ็ใ้
็ฝฎ็ปๅๆฏๆๅ็ง๏ผnumber|alphaใalpha|symbolใnumberใalpha|number|symbolใไธ่
ไน้ด้
็ฝฎ้กบๅบๅฏๆนๅใ้ป่ฎคไธบalpha|number|symbol
* @param params.maxLength -่ฎพ็ฝฎๆๅคง่พๅ
ฅ้ฟๅบฆ๏ผ้ป่ฎคไธบ16
* @param params.encryptMode -่ฎพ็ฝฎๅ ๅฏๆนๅผ๏ผๅฏ้้กนๆ:AES๏ผ16ไธชๅๆฐ็ไปปๆๅญ็ฌฆ๏ผใRSA๏ผไธๅคงไธฒๅญ็ฌฆ๏ผใMD5ใSM2๏ผx&y๏ผใSM3(ๆ )ใSM4๏ผ16ไธชไปปๆๅญ็ฌฆ๏ผใไธ้
็ฝฎ้ป่ฎคไธบMD5ๅ ๅฏใ
* @param params.secretKey -ๅฏ้ฅ๏ผ่ฅๆๅฎๅ ๅฏๆนๅผ้่ฆๅฏ้ฅๅๅฟ
้กปไผ ้๏ผๅฆๅไธ้่ฆไผ ้ใ่ฅๅ ๅฏๆนๅผไธบSM2ๅไผ ๅ
ฅ็x,yๅฏ้ฅไน้ด็จโ&โ็ฌฆๅท่ฟๆฅ๏ผไพๅฆ: "aaaaaaa&bbbbbb"
* @param params.titleText -่ฎพ็ฝฎ้ฎ็้กถ้จ่ชๅฎไนๆๆก๏ผไธ้
็ฝฎๆ่
้
็ฝฎๅญ็ฌฆไธฒไธบ็ฉบ้ป่ฎคไธบโๆ็ๅฎๅ
จ่พๅ
ฅ้ฎ็โใๆณจๆ:ไธ้
็ฝฎๅญๆฎตๆถ๏ผๅฎๅ
จ้ฎ็้กถ้จๆๆก้ป่ฎคๆพ็คบไธบsafekeyboard.gmuไธญ็้
็ฝฎใๅฆๆgmuไธญๅๆฒกๆ็่ฏ๏ผๅ้ป่ฎคๆพ็คบไธบโๆ็ๅฎๅ
จ่พๅ
ฅ้ฎ็โใ
* @param cb
*/
safekeyboardShow(params: any, cb: (res: CallbackResult) => void): void;
/**
* ้่ฟjsๅ
ณ้ญๅฎๅ
จ้ฎ็
* @deprecated
* @param params - ๆฅๅฃๅ
ฅๅ
* @param cb
*/
safekeyboardHide(params: null, cb: (res: CallbackResult) => void): void;
/**
* ้่ฟjsๅฑ็ฐไบคๆ้ฎ็
* @deprecated
* @param params - ๆฅๅฃๅ
ฅๅ
* @param params.type -้ช่ฏๆนๅผ๏ผprice:ไบคๆไปทๆ ผ้ฎ็ volume:ไบคๆ้้ฎ็ search:่ก็ฅจไปฃ็ ๆ็ดข้ฎ็๏ผ
* @param params.buttons -้ฎ็ๅทฅๅ
ทๆ ๆ้ฎ
* @param params.funcKey -้ฎ็ๅทฅๅ
ทๆ ๆ้ฎ ๆณจๆ:ๆฌๅญๆฎตๅชๆsearch็ฑปๅๆๆฏๆ๏ผvolumeๅprice็ฑปๅไธๆฏๆ
* @param params.describe -้ฎ็ๅทฅๅ
ท็ฑปๆ่ฟฐ
* @param cb
*/
tradekeyboardShow(params: any, cb: (res: CallbackResult) => void): void;
/**
* t้่ฟjsๅ
ณ้ญไบคๆ้ฎ็
* @deprecated
* @param params - ๆฅๅฃๅ
ฅๅ
* @param params.type -ๅ
ณ้ญ็้ฎ็็ฑปๅ๏ผprice:ไบคๆไปทๆ ผ้ฎ็ volume:ไบคๆ้้ฎ็ search:่ก็ฅจไปฃ็ ๆ็ดข้ฎ็๏ผ
* @param cb
*/
tradekeyboardHide(params: any, cb: (res: CallbackResultNoData) => void): void;
/**
* ้่ฟjsๅไบซๅ
ๅฎนๅฐๅๅนณๅฐ
* @param params - ๆฅๅฃๅ
ฅๅ
* @param params.title ๅไบซๆ ้ข
* @param params.content ๅไบซ็ๆ่ฟฐไฟกๆฏ
* @param params.url ็จๆท็นๅปๅไบซๅๆๅผ็้พๆฅๅฐๅ๏ผ
* @param params.image ไธ่ฌๆฏๆ ๅhttpๆhttps่ฏทๆฑ,ๅฏๆฏๆๆ ผๅผ
* 1.่ฟ็จๅพ็url๏ผๅฟ
้กปไปฅhttp://ๆhttps://ๅผๅคด
* 2. ๅพ็Base64็ผ็ ๏ผไปฅbase64://ๅผๅคด
* 3. gmu๏ผgmu_icon็ฎๅฝไธ็ๆฌๅฐๆไปถ๏ผ็ธๅฏน่ทฏๅพไธไธๅ
ๆฌๆไปถๅ็ผ๏ผๅฆไฝฟ็จๅพ็gmu/gmu_icon/test.png, ๅๆฌกๆญคๅๆฐไธบtest"
* @param params.type ๅฏ้ๅผ๏ผ
* โwebpageโ๏ผๅไบซ็ฝ้กต)
* โimageโ๏ผๅไบซๅพ็) (ๆณจๆ:ๅไบซๅพ็็ฎๅๆฏๆๅพฎไฟก๏ผๅพฎๅ๏ผqq๏ผ้้ใๅ
ถไปๅไธๆฏๆๅไบซๅพ็ๅ่ฝ๏ผ
* โfileโ๏ผๅไบซๆไปถ) (ๆณจๆ:ๆฌๅฐๅฐๅ้่ฆไธบๆไปถ้ข่งๆๆไปถไธ่ฝฝๆฅๅฃๆไผ ็ๆไปถๅญๆพ็็ธๅฏน่ทฏๅพๅฐๅใๆไปถๅไบซ็ฎๅๅชๆฏๆๅพฎไฟก๏ผๅ
ถไปๅฆqq๏ผๅพฎๅ๏ผ้้ๅไธๆฏๆๆไปถๅไบซๅ่ฝใๆณจๆ:ๅพฎไฟกๆๅๅไธๆฏๆๆไปถๅไบซๅ่ฝ๏ผ
* (้ป่ฎคๅผ๏ผโwebpageโ)
* @param params.channel ่ฎพ็ฝฎๅไบซๆธ ้๏ผ็จๆทๅฏๆๅฎๅฐไฟกๆฏๅไบซๅฐๅชไธชๆธ ้ไธ ๏ผๆณจๆ๏ผ่ฅ้
็ฝฎไบๆญคๅๆฐ๏ผๅๆ ๅไบซๅฏน่ฏๆกๅผนๅบUI๏ผไธ้
็ฝฎๅไผๆ นๆฎๅผๅ่
็share.gmuไธญ็้
็ฝฎ็ๆๅจๆ็ๆๅไบซๅฏน่ฏๆกๅผนๅบ๏ผไพ็จๆท้ๆฉๅไบซๆธ ้ใ
* ๅฏ้ๅผ๏ผ
* โweixinโ ๏ผๅพฎไฟก๏ผ
* โweixin_timelineโ๏ผๅพฎไฟกๆๅๅ๏ผ
* โqqโ๏ผQQ๏ผ
* โweiboโ(ๅพฎๅ)
* โdingtalkโ๏ผ้้๏ผ
* โsystemโ(็ณป็ปๅไบซ)โ
* @param cb ๅ่ฝๅค็ๅ็ๅ่ฐๅฝๆฐ
*/
socialShare(params: any, cb: (res: CallbackResultNoData) => void): void;
/**
* ไธๆน็ปๅฝๆฅๅฃ
* @param params - ๆฅๅฃๅ
ฅๅ
* @param params.type ็ปๅฝๅนณๅฐ็ฑปๅซ,ๅชๆฏๆqq,weibo,weixinไธไธชtype
* @param cb ๅ่ฝๅค็ๅ็ๅ่ฐๅฝๆฐ
*/
socialLogin(params: any, cb: (res: CallbackResult) => void): void;
/**
* ้่ฟjsๅคๆญๅไธชๅนณๅฐappๅจ่ฎพๅคไธๆฏๅฆๅทฒๅฎ่ฃ
* @param params - ๆฅๅฃๅ
ฅๅ
* @param params.type -ๅนณๅฐ็ฑปๅ๏ผ็ฎๅtypeๅผๅชๆฏๆ'qq'๏ผ'weibo'๏ผ'weixin'ไธไธช
* @param cb ๅ่ฝๅค็ๅ็ๅ่ฐๅฝๆฐ
*/
socialAppInstalled(params: any, cb: (res: CallbackResult) => void): void;
/**
* ่นๆๅ
่ดญๆฅๅฃ
* @param params - ๆฅๅฃๅ
ฅๅ
* @param params.apple_product_id -่นๆๅๅID(้่ฆๅจ่นๆitunes connectๅนณๅฐๅๅปบๅๅ)
* @param params.orderId -ๅๆท่ฎขๅๅท(ๆญค่ฎขๅๅทไธบๅฎขๆท่ชๅทฑไธๅก็ๆ็่ฎขๅๅท๏ผ็จไบๆๅไธๆญฅๆ ก้ช่นๆๆถๆฎๆถๅๆฃๆตๅฏไธๆงไฝฟ็จ๏ผไฟ่ฏๅ
่ดญ้พ่ทฏๅฎๆดๆง)
* @param cb ๅ่ฝๅค็ๅ็ๅ่ฐๅฝๆฐ
*/
iapPurchase(params: any, cb: (res: CallbackResult) => void): void;
/**
* ้่ฟjsไผ ๅ
ฅ็ปๆๅกๅจๅ ็ญพๅ็่ฎขๅไฟกๆฏ(orderInfo)ๅนถ่ฐ็จ็ธๅบๆฏไปๆธ ้SDK็ๆฏไปๆฅๅฃ
* @param params - ๆฅๅฃๅ
ฅๅ
* @param params.channel_id -021:ๆฏไปๅฎ้ฑๅ
022:ๅพฎไฟก้ฑๅ
* @param params.orderInfo - ๅ
ทไฝๅ
ๅฎน่งไธๆน็โๅ
ถไป(ๅฝๆฏไปๆธ ้ไธบๅพฎไฟก้ฑๅ
ๆถ/ๅฝๆฏไปๆธ ้ไธบๅพฎไฟก้ฑๅ
ๆถ)โ้กน
* @param params.isSandBox -ๆฏๅฆ่ฟๅ
ฅๆฒ็ฎฑ็ฏๅข๏ผๅชๅฏนๆฏไปๅฎๆๆ๏ผ
* @param cb ๅ่ฝๅค็ๅ็ๅ่ฐๅฝๆฐ
*/
tradePay(params: any, cb: (res: CallbackResult) => void): void;
}
export function register(options: any): void;
export const config: any;
export const native: Native;
export const net: any;
export const openAPI: any; | the_stack |
import {
MockERC20Instance,
MockAddressBookInstance,
WETH9Instance,
MarginPoolInstance,
MockDumbERC20Instance,
} from '../../build/types/truffle-types'
import BigNumber from 'bignumber.js'
const { expectRevert, ether } = require('@openzeppelin/test-helpers')
const MockERC20 = artifacts.require('MockERC20.sol')
const MockDumbERC20 = artifacts.require('MockDumbERC20.sol')
const MockAddressBook = artifacts.require('MockAddressBook.sol')
const WETH9 = artifacts.require('WETH9.sol')
const MarginPool = artifacts.require('MarginPool.sol')
// address(0)
const ZERO_ADDR = '0x0000000000000000000000000000000000000000'
contract('MarginPool', ([owner, controllerAddress, farmer, user1, random]) => {
const usdcToMint = ether('1000')
const wethToMint = ether('50')
// ERC20 mocks
let usdc: MockERC20Instance
let weth: WETH9Instance
// DumbER20: Return false when transfer fail.
let dumbToken: MockDumbERC20Instance
// addressbook module mock
let addressBook: MockAddressBookInstance
// margin pool
let marginPool: MarginPoolInstance
before('Deployment', async () => {
// deploy USDC token
usdc = await MockERC20.new('USDC', 'USDC', 6)
// deploy WETH token for testing
weth = await WETH9.new()
// deploy dumb erc20
dumbToken = await MockDumbERC20.new('DUSDC', 'DUSDC', 6)
// deploy AddressBook mock
addressBook = await MockAddressBook.new()
// set Controller module address
await addressBook.setController(controllerAddress)
// deploy MarginPool module
marginPool = await MarginPool.new(addressBook.address)
// mint usdc
await usdc.mint(user1, usdcToMint)
// wrap ETH in Controller module level
await weth.deposit({ from: controllerAddress, value: wethToMint })
// controller approving infinite amount of WETH to pool
await weth.approve(marginPool.address, wethToMint, { from: controllerAddress })
})
describe('MarginPool initialization', () => {
it('should revert if initilized with 0 addressBook address', async () => {
await expectRevert(MarginPool.new(ZERO_ADDR), 'Invalid address book')
})
})
describe('Transfer to pool', () => {
const usdcToTransfer = ether('250')
const wethToTransfer = ether('25')
it('should revert transfering to pool from caller other than controller address', async () => {
// user approve USDC transfer
await usdc.approve(marginPool.address, usdcToTransfer, { from: user1 })
await expectRevert(
marginPool.transferToPool(usdc.address, user1, usdcToTransfer, { from: random }),
'MarginPool: Sender is not Controller',
)
})
it('should revert transfering to pool an amount equal to zero', async () => {
// user approve USDC transfer
await usdc.approve(marginPool.address, usdcToTransfer, { from: user1 })
await expectRevert(
marginPool.transferToPool(usdc.address, user1, ether('0'), { from: controllerAddress }),
'MarginPool: transferToPool amount is equal to 0',
)
})
it('should revert transfering to pool if the address of the sender is the margin pool', async () => {
// user approve USDC transfer
await usdc.approve(marginPool.address, usdcToTransfer, { from: user1 })
await expectRevert(
marginPool.transferToPool(usdc.address, marginPool.address, ether('1'), { from: controllerAddress }),
'ERC20: transfer amount exceeds balance',
)
})
it('should transfer to pool from user when called by the controller address', async () => {
const userBalanceBefore = new BigNumber(await usdc.balanceOf(user1))
const poolBalanceBefore = new BigNumber(await usdc.balanceOf(marginPool.address))
// user approve USDC transfer
await usdc.approve(marginPool.address, usdcToTransfer, { from: user1 })
await marginPool.transferToPool(usdc.address, user1, usdcToTransfer, { from: controllerAddress })
const userBalanceAfter = new BigNumber(await usdc.balanceOf(user1))
const poolBalanceAfter = new BigNumber(await usdc.balanceOf(marginPool.address))
assert.equal(
new BigNumber(usdcToTransfer).toString(),
userBalanceBefore.minus(userBalanceAfter).toString(),
'USDC value transfered from user mismatch',
)
assert.equal(
new BigNumber(usdcToTransfer).toString(),
poolBalanceAfter.minus(poolBalanceBefore).toString(),
'USDC value transfered into pool mismatch',
)
})
it('should transfer WETH to pool from controller when called by the controller address', async () => {
const controllerBalanceBefore = new BigNumber(await weth.balanceOf(controllerAddress))
const poolBalanceBefore = new BigNumber(await weth.balanceOf(marginPool.address))
await marginPool.transferToPool(weth.address, controllerAddress, wethToTransfer, { from: controllerAddress })
const controllerBalanceAfter = new BigNumber(await weth.balanceOf(controllerAddress))
const poolBalanceAfter = new BigNumber(await weth.balanceOf(marginPool.address))
assert.equal(
new BigNumber(wethToTransfer).toString(),
controllerBalanceBefore.minus(controllerBalanceAfter).toString(),
'WETH value transfered from controller mismatch',
)
assert.equal(
new BigNumber(wethToTransfer).toString(),
poolBalanceAfter.minus(poolBalanceBefore).toString(),
'WETH value transfered into pool mismatch',
)
})
it('should revert when transferFrom return false on dumbERC20', async () => {
await expectRevert(
marginPool.transferToPool(dumbToken.address, user1, ether('1'), { from: controllerAddress }),
'SafeERC20: ERC20 operation did not succeed',
)
})
})
describe('Transfer to user', () => {
const usdcToTransfer = ether('250')
const wethToTransfer = ether('25')
it('should revert transfering to user from caller other than controller address', async () => {
await expectRevert(
marginPool.transferToUser(usdc.address, user1, usdcToTransfer, { from: random }),
'MarginPool: Sender is not Controller',
)
})
it('should revert transfering to user if the user address is the margin pool addres', async () => {
await expectRevert(
marginPool.transferToUser(usdc.address, marginPool.address, usdcToTransfer, { from: controllerAddress }),
'MarginPool: cannot transfer assets to oneself',
)
})
it('should transfer an ERC-20 to user from pool when called by the controller address', async () => {
const userBalanceBefore = new BigNumber(await usdc.balanceOf(user1))
const poolBalanceBefore = new BigNumber(await usdc.balanceOf(marginPool.address))
await marginPool.transferToUser(usdc.address, user1, usdcToTransfer, { from: controllerAddress })
const userBalanceAfter = new BigNumber(await usdc.balanceOf(user1))
const poolBalanceAfter = new BigNumber(await usdc.balanceOf(marginPool.address))
assert.equal(
new BigNumber(usdcToTransfer).toString(),
userBalanceAfter.minus(userBalanceBefore).toString(),
'USDC value transfered to user mismatch',
)
assert.equal(
new BigNumber(usdcToTransfer).toString(),
poolBalanceBefore.minus(poolBalanceAfter).toString(),
'USDC value transfered from pool mismatch',
)
})
it('should transfer WETH to controller from pool, unwrap it and transfer ETH to user when called by the controller address', async () => {
const poolBalanceBefore = new BigNumber(await weth.balanceOf(marginPool.address))
const userBalanceBefore = new BigNumber(await web3.eth.getBalance(user1))
// transfer to controller
await marginPool.transferToUser(weth.address, controllerAddress, wethToTransfer, { from: controllerAddress })
// unwrap WETH to ETH
await weth.withdraw(wethToTransfer, { from: controllerAddress })
// send ETH to user
await web3.eth.sendTransaction({ from: controllerAddress, to: user1, value: wethToTransfer })
const poolBalanceAfter = new BigNumber(await weth.balanceOf(marginPool.address))
const userBalanceAfter = new BigNumber(await web3.eth.getBalance(user1))
assert.equal(
new BigNumber(wethToTransfer).toString(),
poolBalanceBefore.minus(poolBalanceAfter).toString(),
'WETH value un-wrapped from pool mismatch',
)
assert.equal(
new BigNumber(wethToTransfer).toString(),
userBalanceAfter.minus(userBalanceBefore).toString(),
'ETH value transfered to user mismatch',
)
})
it('should revert when transfer return false on dumbERC20', async () => {
await dumbToken.mint(user1, ether('1'))
await dumbToken.approve(marginPool.address, ether('1'), { from: user1 })
await marginPool.transferToPool(dumbToken.address, user1, ether('1'), { from: controllerAddress })
// let the transfer failed
await dumbToken.setLocked(true)
await expectRevert(
marginPool.transferToUser(dumbToken.address, user1, ether('1'), { from: controllerAddress }),
'SafeERC20: ERC20 operation did not succeed',
)
await dumbToken.setLocked(false)
})
})
describe('Transfer multiple assets to pool', () => {
const usdcToTransfer = ether('250')
const wethToTransfer = ether('25')
it('should revert transfering an array to pool from caller other than controller address', async () => {
// user approve USDC and WETH transfer
await usdc.approve(marginPool.address, usdcToTransfer, { from: user1 })
await weth.approve(marginPool.address, wethToTransfer, { from: user1 })
await expectRevert(
marginPool.batchTransferToPool([usdc.address, weth.address], [user1, user1], [usdcToTransfer, wethToTransfer], {
from: random,
}),
'MarginPool: Sender is not Controller',
)
})
it('should revert transfering to pool an array with an amount equal to zero', async () => {
// user approve USDC transfer
await usdc.approve(marginPool.address, usdcToTransfer, { from: user1 })
await weth.approve(marginPool.address, wethToTransfer, { from: user1 })
await expectRevert(
marginPool.batchTransferToPool([usdc.address, weth.address], [user1, user1], [ether('0'), wethToTransfer], {
from: controllerAddress,
}),
'MarginPool: transferToPool amount is equal to 0',
)
})
it('should revert with different size arrays', async () => {
await expectRevert(
marginPool.batchTransferToPool(
[usdc.address, weth.address],
[user1, user1],
[usdcToTransfer, usdcToTransfer, usdcToTransfer],
{ from: controllerAddress },
),
'MarginPool: batchTransferToPool array lengths are not equal',
)
})
it('should transfer an array including weth and usdc to pool from user/controller when called by the controller address', async () => {
const userUsdcBalanceBefore = new BigNumber(await usdc.balanceOf(user1))
const poolUsdcBalanceBefore = new BigNumber(await usdc.balanceOf(marginPool.address))
const controllerWethBalanceBefore = new BigNumber(await weth.balanceOf(controllerAddress))
const poolWethBalanceBefore = new BigNumber(await weth.balanceOf(marginPool.address))
// user approve USDC and WETH transfer
await usdc.approve(marginPool.address, usdcToTransfer, { from: user1 })
await weth.approve(marginPool.address, wethToTransfer, { from: user1 })
await marginPool.batchTransferToPool(
[usdc.address, weth.address],
[user1, controllerAddress],
[usdcToTransfer, wethToTransfer],
{ from: controllerAddress },
)
const userUsdcBalanceAfter = new BigNumber(await usdc.balanceOf(user1))
const poolUsdcBalanceAfter = new BigNumber(await usdc.balanceOf(marginPool.address))
const controllerWethBalanceAfter = new BigNumber(await weth.balanceOf(controllerAddress))
const poolWethBalanceAfter = new BigNumber(await weth.balanceOf(marginPool.address))
assert.equal(
new BigNumber(usdcToTransfer).toString(),
userUsdcBalanceBefore.minus(userUsdcBalanceAfter).toString(),
'USDC value transfered from user mismatch',
)
assert.equal(
new BigNumber(usdcToTransfer).toString(),
poolUsdcBalanceAfter.minus(poolUsdcBalanceBefore).toString(),
'USDC value transfered into pool mismatch',
)
assert.equal(
new BigNumber(wethToTransfer).toString(),
controllerWethBalanceBefore.minus(controllerWethBalanceAfter).toString(),
'WETH value transfered from controller mismatch',
)
assert.equal(
new BigNumber(wethToTransfer).toString(),
poolWethBalanceAfter.minus(poolWethBalanceBefore).toString(),
'WETH value transfered into pool mismatch',
)
})
})
describe('Transfer multiple assets to user', () => {
const usdcToTransfer = ether('250')
const wethToTransfer = ether('25')
it('should revert transfering to user from caller other than controller address', async () => {
await expectRevert(
marginPool.batchTransferToUser([usdc.address, weth.address], [user1, user1], [usdcToTransfer, wethToTransfer], {
from: random,
}),
'MarginPool: Sender is not Controller',
)
})
it('should revert with different size arrays', async () => {
await expectRevert(
marginPool.batchTransferToUser(
[usdc.address, weth.address],
[user1, user1],
[usdcToTransfer, usdcToTransfer, usdcToTransfer],
{ from: controllerAddress },
),
'MarginPool: batchTransferToUser array lengths are not equal',
)
})
it('should batch transfer to users when called from controller', async () => {
const userUsdcBalanceBefore = new BigNumber(await usdc.balanceOf(user1))
const poolUsdcBalanceBefore = new BigNumber(await usdc.balanceOf(marginPool.address))
const controllerWethBalanceBefore = new BigNumber(await weth.balanceOf(controllerAddress))
const poolWethBalanceBefore = new BigNumber(await weth.balanceOf(marginPool.address))
await marginPool.batchTransferToUser(
[usdc.address, weth.address],
[user1, controllerAddress],
[poolUsdcBalanceBefore, poolWethBalanceBefore],
{ from: controllerAddress },
)
const userUsdcBalanceAfter = new BigNumber(await usdc.balanceOf(user1))
const poolUsdcBalanceAfter = new BigNumber(await usdc.balanceOf(marginPool.address))
const controllerWethBalanceAfter = new BigNumber(await weth.balanceOf(controllerAddress))
const poolWethBalanceAfter = new BigNumber(await weth.balanceOf(marginPool.address))
assert.equal(
poolUsdcBalanceBefore.toString(),
userUsdcBalanceAfter.minus(userUsdcBalanceBefore).toString(),
'USDC value transfered to user mismatch',
)
assert.equal(
poolUsdcBalanceBefore.toString(),
poolUsdcBalanceBefore.minus(poolUsdcBalanceAfter).toString(),
'USDC value transfered from pool mismatch',
)
assert.equal(
poolWethBalanceBefore.toString(),
controllerWethBalanceAfter.minus(controllerWethBalanceBefore).toString(),
'WETH value transfered to controller mismatch',
)
assert.equal(
poolWethBalanceBefore.toString(),
poolWethBalanceBefore.minus(poolWethBalanceAfter).toString(),
'WETH value transfered from pool mismatch',
)
})
})
describe('Farming', () => {
before(async () => {
// send more usdc to pool
await usdc.mint(marginPool.address, new BigNumber('100'))
})
it('should revert setting farmer address from non-owner', async () => {
await expectRevert(marginPool.setFarmer(farmer, { from: random }), 'Ownable: caller is not the owner')
})
it('should set farmer address when called from owner', async () => {
await marginPool.setFarmer(farmer, { from: owner })
assert.equal(await marginPool.farmer(), farmer, 'farmer address mismatch')
})
it('should revert farming when receiver address is equal to zero', async () => {
const poolStoredBalanceBefore = new BigNumber(await marginPool.getStoredBalance(usdc.address))
const poolBlanaceBefore = new BigNumber(await usdc.balanceOf(marginPool.address))
const amountToFarm = poolBlanaceBefore.minus(poolStoredBalanceBefore)
await expectRevert(
marginPool.farm(usdc.address, ZERO_ADDR, amountToFarm, { from: farmer }),
'MarginPool: invalid receiver address',
)
})
it('should revert farming when sender is not farmer address', async () => {
const poolStoredBalanceBefore = new BigNumber(await marginPool.getStoredBalance(usdc.address))
const poolBlanaceBefore = new BigNumber(await usdc.balanceOf(marginPool.address))
const amountToFarm = poolBlanaceBefore.minus(poolStoredBalanceBefore)
await expectRevert(
marginPool.farm(usdc.address, random, amountToFarm, { from: random }),
'MarginPool: Sender is not farmer',
)
})
it('should farm additional USDC', async () => {
const poolStoredBalanceBefore = new BigNumber(await marginPool.getStoredBalance(usdc.address))
const poolBlanaceBefore = new BigNumber(await usdc.balanceOf(marginPool.address))
const farmerBalanceBefore = new BigNumber(await usdc.balanceOf(farmer))
const amountToFarm = poolBlanaceBefore.minus(poolStoredBalanceBefore)
await marginPool.farm(usdc.address, farmer, amountToFarm, { from: farmer })
const poolStoredBalanceAfter = new BigNumber(await marginPool.getStoredBalance(usdc.address))
const poolBlanaceAfter = new BigNumber(await usdc.balanceOf(marginPool.address))
const farmerBalanceAfter = new BigNumber(await usdc.balanceOf(farmer))
assert.equal(
poolStoredBalanceBefore.toString(),
poolStoredBalanceAfter.toString(),
'Pool stored balance mismatch',
)
assert.equal(
poolBlanaceBefore.minus(poolBlanaceAfter).toString(),
amountToFarm.toString(),
'Pool balance mismatch',
)
assert.equal(
farmerBalanceAfter.minus(farmerBalanceBefore).toString(),
amountToFarm.toString(),
'Farmer balance mismatch',
)
})
it('should revert farming when amount is greater than available balance to farm', async () => {
const amountToFarm = new BigNumber('100000000000')
await expectRevert(
marginPool.farm(usdc.address, farmer, amountToFarm, { from: farmer }),
'MarginPool: amount to farm exceeds limit',
)
})
it('should revert farming when transfer return false for dumbERC20', async () => {
const amountExcess = ether('1')
await dumbToken.mint(marginPool.address, amountExcess)
await dumbToken.setLocked(true)
await expectRevert(
marginPool.farm(dumbToken.address, farmer, amountExcess, { from: farmer }),
'SafeERC20: ERC20 operation did not succeed',
)
})
})
}) | the_stack |
module android.text {
import System = java.lang.System;
/**
* PackedIntVector stores a two-dimensional array of integers,
* optimized for inserting and deleting rows and for
* offsetting the values in segments of a given column.
*/
export class PackedIntVector {
private mColumns:number = 0;
private mRows:number = 0;
private mRowGapStart:number = 0;
private mRowGapLength:number = 0;
private mValues:number[];
// starts, followed by lengths
private mValueGap:number[];
/**
* Creates a new PackedIntVector with the specified width and
* a height of 0.
*
* @param columns the width of the PackedIntVector.
*/
constructor( columns:number) {
this.mColumns = columns;
this.mRows = 0;
this.mRowGapStart = 0;
this.mRowGapLength = this.mRows;
this.mValues = null;
this.mValueGap = androidui.util.ArrayCreator.newNumberArray(2 * columns);
}
/**
* Returns the value at the specified row and column.
*
* @param row the index of the row to return.
* @param column the index of the column to return.
*
* @return the value stored at the specified position.
*
* @throws IndexOutOfBoundsException if the row is out of range
* (row < 0 || row >= size()) or the column is out of range
* (column < 0 || column >= width()).
*/
getValue(row:number, column:number):number {
const columns:number = this.mColumns;
if (((row | column) < 0) || (row >= this.size()) || (column >= columns)) {
throw Error(`new IndexOutOfBoundsException(row + ", " + column)`);
}
if (row >= this.mRowGapStart) {
row += this.mRowGapLength;
}
let value:number = this.mValues[row * columns + column];
let valuegap:number[] = this.mValueGap;
if (row >= valuegap[column]) {
value += valuegap[column + columns];
}
return value;
}
/**
* Sets the value at the specified row and column.
*
* @param row the index of the row to set.
* @param column the index of the column to set.
*
* @throws IndexOutOfBoundsException if the row is out of range
* (row < 0 || row >= size()) or the column is out of range
* (column < 0 || column >= width()).
*/
setValue(row:number, column:number, value:number):void {
if (((row | column) < 0) || (row >= this.size()) || (column >= this.mColumns)) {
throw Error(`new IndexOutOfBoundsException(row + ", " + column)`);
}
if (row >= this.mRowGapStart) {
row += this.mRowGapLength;
}
let valuegap:number[] = this.mValueGap;
if (row >= valuegap[column]) {
value -= valuegap[column + this.mColumns];
}
this.mValues[row * this.mColumns + column] = value;
}
/**
* Sets the value at the specified row and column.
* Private internal version: does not check args.
*
* @param row the index of the row to set.
* @param column the index of the column to set.
*
*/
private setValueInternal(row:number, column:number, value:number):void {
if (row >= this.mRowGapStart) {
row += this.mRowGapLength;
}
let valuegap:number[] = this.mValueGap;
if (row >= valuegap[column]) {
value -= valuegap[column + this.mColumns];
}
this.mValues[row * this.mColumns + column] = value;
}
/**
* Increments all values in the specified column whose row >= the
* specified row by the specified delta.
*
* @param startRow the row at which to begin incrementing.
* This may be == size(), which case there is no effect.
* @param column the index of the column to set.
*
* @throws IndexOutOfBoundsException if the row is out of range
* (startRow < 0 || startRow > size()) or the column
* is out of range (column < 0 || column >= width()).
*/
adjustValuesBelow(startRow:number, column:number, delta:number):void {
if (((startRow | column) < 0) || (startRow > this.size()) || (column >= this.width())) {
throw Error(`new IndexOutOfBoundsException(startRow + ", " + column)`);
}
if (startRow >= this.mRowGapStart) {
startRow += this.mRowGapLength;
}
this.moveValueGapTo(column, startRow);
this.mValueGap[column + this.mColumns] += delta;
}
/**
* Inserts a new row of values at the specified row offset.
*
* @param row the row above which to insert the new row.
* This may be == size(), which case the new row is added
* at the end.
* @param values the new values to be added. If this is null,
* a row of zeroes is added.
*
* @throws IndexOutOfBoundsException if the row is out of range
* (row < 0 || row > size()) or if the length of the
* values array is too small (values.length < width()).
*/
insertAt(row:number, values:number[]):void {
if ((row < 0) || (row > this.size())) {
throw Error(`new IndexOutOfBoundsException("row " + row)`);
}
if ((values != null) && (values.length < this.width())) {
throw Error(`new IndexOutOfBoundsException("value count " + values.length)`);
}
this.moveRowGapTo(row);
if (this.mRowGapLength == 0) {
this.growBuffer();
}
this.mRowGapStart++;
this.mRowGapLength--;
if (values == null) {
for (let i:number = this.mColumns - 1; i >= 0; i--) {
this.setValueInternal(row, i, 0);
}
} else {
for (let i:number = this.mColumns - 1; i >= 0; i--) {
this.setValueInternal(row, i, values[i]);
}
}
}
/**
* Deletes the specified number of rows starting with the specified
* row.
*
* @param row the index of the first row to be deleted.
* @param count the number of rows to delete.
*
* @throws IndexOutOfBoundsException if any of the rows to be deleted
* are out of range (row < 0 || count < 0 ||
* row + count > size()).
*/
deleteAt(row:number, count:number):void {
if (((row | count) < 0) || (row + count > this.size())) {
throw Error(`new IndexOutOfBoundsException(row + ", " + count)`);
}
this.moveRowGapTo(row + count);
this.mRowGapStart -= count;
this.mRowGapLength += count;
// TODO: Reclaim memory when the new height is much smaller
// than the allocated size.
}
/**
* Returns the number of rows in the PackedIntVector. This number
* will change as rows are inserted and deleted.
*
* @return the number of rows.
*/
size():number {
return this.mRows - this.mRowGapLength;
}
/**
* Returns the width of the PackedIntVector. This number is set
* at construction and will not change.
*
* @return the number of columns.
*/
width():number {
return this.mColumns;
}
/**
* Grows the value and gap arrays to be large enough to store at least
* one more than the current number of rows.
*/
private growBuffer():void {
const columns:number = this.mColumns;
let newsize:number = this.size() + 1;
newsize = (newsize * columns) / columns;
let newvalues:number[] = androidui.util.ArrayCreator.newNumberArray(newsize * columns);
const valuegap:number[] = this.mValueGap;
const rowgapstart:number = this.mRowGapStart;
let after:number = this.mRows - (rowgapstart + this.mRowGapLength);
if (this.mValues != null) {
System.arraycopy(this.mValues, 0, newvalues, 0, columns * rowgapstart);
System.arraycopy(this.mValues, (this.mRows - after) * columns, newvalues, (newsize - after) * columns, after * columns);
}
for (let i:number = 0; i < columns; i++) {
if (valuegap[i] >= rowgapstart) {
valuegap[i] += newsize - this.mRows;
if (valuegap[i] < rowgapstart) {
valuegap[i] = rowgapstart;
}
}
}
this.mRowGapLength += newsize - this.mRows;
this.mRows = newsize;
this.mValues = newvalues;
}
/**
* Moves the gap in the values of the specified column to begin at
* the specified row.
*/
private moveValueGapTo(column:number, where:number):void {
const valuegap:number[] = this.mValueGap;
const values:number[] = this.mValues;
const columns:number = this.mColumns;
if (where == valuegap[column]) {
return;
} else if (where > valuegap[column]) {
for (let i:number = valuegap[column]; i < where; i++) {
values[i * columns + column] += valuegap[column + columns];
}
} else /* where < valuegap[column] */
{
for (let i:number = where; i < valuegap[column]; i++) {
values[i * columns + column] -= valuegap[column + columns];
}
}
valuegap[column] = where;
}
/**
* Moves the gap in the row indices to begin at the specified row.
*/
private moveRowGapTo(where:number):void {
if (where == this.mRowGapStart) {
return;
} else if (where > this.mRowGapStart) {
let moving:number = where + this.mRowGapLength - (this.mRowGapStart + this.mRowGapLength);
const columns:number = this.mColumns;
const valuegap:number[] = this.mValueGap;
const values:number[] = this.mValues;
const gapend:number = this.mRowGapStart + this.mRowGapLength;
for (let i:number = gapend; i < gapend + moving; i++) {
let destrow:number = i - gapend + this.mRowGapStart;
for (let j:number = 0; j < columns; j++) {
let val:number = values[i * columns + j];
if (i >= valuegap[j]) {
val += valuegap[j + columns];
}
if (destrow >= valuegap[j]) {
val -= valuegap[j + columns];
}
values[destrow * columns + j] = val;
}
}
} else /* where < mRowGapStart */
{
let moving:number = this.mRowGapStart - where;
const columns:number = this.mColumns;
const valuegap:number[] = this.mValueGap;
const values:number[] = this.mValues;
const gapend:number = this.mRowGapStart + this.mRowGapLength;
for (let i:number = where + moving - 1; i >= where; i--) {
let destrow:number = i - where + gapend - moving;
for (let j:number = 0; j < columns; j++) {
let val:number = values[i * columns + j];
if (i >= valuegap[j]) {
val += valuegap[j + columns];
}
if (destrow >= valuegap[j]) {
val -= valuegap[j + columns];
}
values[destrow * columns + j] = val;
}
}
}
this.mRowGapStart = where;
}
}
} | the_stack |
import { INvModule, IComponent } from '../types';
import { getService, NvInstanceFactory, rootInjector, Type } from '@indiv/di';
import { NvModuleFactory } from '../nv-module';
import { Renderer, Vnode } from '../vnode';
import { ElementRef } from '../component';
import { lifecycleCaller } from '../lifecycle';
export interface IPlugin {
bootstrap(vm: InDiv): void;
}
/**
* main: for new InDiv
*
* @class InDiv
*/
export class InDiv {
public static globalApplication: InDiv;
private readonly pluginList: IPlugin[] = [];
private rootElement: any;
private routeDOMKey: string = 'router-render';
private rootModule: INvModule = null;
private declarations: Function[];
private bootstrapComponent: IComponent;
private renderer: Renderer;
private isServerRendering: boolean = false;
private indivEnv: string = 'browser';
private templateRootPath?: string;
/**
* create an instance of InDiv
*
* set provider and instance in rootInjector
*
* @memberof InDiv
*/
constructor() {
rootInjector.setProviderAndInstance(InDiv, InDiv, this);
}
/**
* static method for bootstrap an InDiv application
*
* options:
* 1. plugins?: Type<IPlugin>[] indiv plugins
* 2. ssrTemplateRootPath?: string for ssr env to set templateRootPath
*
* @static
* @param {Type<INvModule>} Nvmodule
* @param {{
* plugins?: Type<IPlugin>[],
* ssrTemplateRootPath?: string,
* }} [options={}]
* @returns {Promise<InDiv>}
* @memberof InDiv
*/
public static async bootstrapFactory(Nvmodule: Type<INvModule>, options: {
plugins?: Type<IPlugin>[],
ssrTemplateRootPath?: string,
} = {}): Promise<InDiv> {
if (!InDiv.globalApplication) InDiv.globalApplication = new InDiv();
else return InDiv.globalApplication;
InDiv.globalApplication.bootstrapModule(Nvmodule);
if (options.plugins) options.plugins.forEach(plugin => InDiv.globalApplication.use(plugin));
if (options.ssrTemplateRootPath) InDiv.globalApplication.setTemplateRootPath(options.ssrTemplateRootPath);
await InDiv.globalApplication.init();
return InDiv.globalApplication;
}
/**
* for using plugin class, use bootstrap method of plugin instance and return plugin's id in this.pluginList
*
* @param {Type<IPlugin>} Modal
* @returns {number}
* @memberof InDiv
*/
public use(Plugin: Type<IPlugin>): number {
const newPlugin = new Plugin();
newPlugin.bootstrap(this);
return this.pluginList.push(newPlugin) - 1;
}
/**
* set component Renderer
*
* @param {*} NewRenderer
* @memberof InDiv
*/
public setRenderer(NewRenderer: any): void {
const _renderer = new NewRenderer();
if (_renderer instanceof Renderer) {
this.renderer = _renderer;
rootInjector.setProvider(Renderer, NewRenderer);
rootInjector.setInstance(Renderer, this.renderer);
} else throw new Error('Custom Renderer must extend class Renderer!');
}
/**
* get global application instance of InDiv
*
* @readonly
* @type {InDiv}
* @memberof InDiv
*/
public get getGlobalApplication(): InDiv {
return InDiv.globalApplication;
}
/**
* get component Renderer
*
* @readonly
* @type {Renderer}
* @memberof InDiv
*/
public get getRenderer(): Renderer {
return this.renderer;
}
/**
* return component instance of root module's bootstrap
*
* @readonly
* @type {IComponent}
* @memberof InDiv
*/
public get getBootstrapComponent(): IComponent {
return this.bootstrapComponent;
}
/**
* set route's DOM tag name
*
* @param {string} routeDOMKey
* @memberof InDiv
*/
public setRouteDOMKey(routeDOMKey: string): void {
this.routeDOMKey = routeDOMKey;
}
/**
* get route's DOM tag name
*
* @readonly
* @type {string}
* @memberof InDiv
*/
public get getRouteDOMKey(): string {
return this.routeDOMKey;
}
/**
* get root module in InDiv
*
* @readonly
* @type {INvModule}
* @memberof InDiv
*/
public get getRootModule(): INvModule {
return this.rootModule;
}
/**
* get root module in root module
*
* @readonly
* @type {Function[]}
* @memberof InDiv
*/
public get getDeclarations(): Function[] {
return this.declarations;
}
/**
* set rootElement which InDiv application can be mounted
*
* this method can be used in cross platform architecture
*
* @param {*} node
* @memberof InDiv
*/
public setRootElement(node: any): void {
this.rootElement = node;
}
/**
* get rootElement which InDiv application can be mounted
*
* this method can be used in cross platform architecture
*
* @readonly
* @type {*}
* @memberof InDiv
*/
public get getRootElement(): any {
return this.rootElement;
}
/**
* set env and isServerRendering for indiv env
*
* @param {string} env
* @param {boolean} [isServerRendering]
* @memberof InDiv
*/
public setIndivEnv(env: string, isServerRendering?: boolean): void {
this.indivEnv = env;
if (arguments.length === 2) this.isServerRendering = isServerRendering;
}
/**
* get env and isServerRendering for indiv env
*
* @readonly
* @type {{ isServerRendering: boolean; indivEnv: string; }}
* @memberof InDiv
*/
public get getIndivEnv(): { isServerRendering: boolean; indivEnv: string; } {
return { isServerRendering: this.isServerRendering, indivEnv: this.indivEnv };
}
/**
* set templateRootPath for SSR
*
* @param {string} templateRootPath
* @memberof InDiv
*/
public setTemplateRootPath(templateRootPath: string): void {
if (!this.isServerRendering) return;
this.templateRootPath = templateRootPath;
}
/**
* get templateRootPath for SSR
*
* @readonly
* @type {string}
* @memberof InDiv
*/
public get getTemplateRootPath(): string {
return this.templateRootPath;
}
/**
* for SSR to build templateUrl
*
* @param {IComponent} component
* @memberof InDiv
*/
public templateChecker(component: IComponent): void { }
/**
* set templateChecker
*
* used in @Indiv/platform-browser
*
* @param {(component: IComponent) => void} checker
* @memberof InDiv
*/
public setTemplateChecker(checker: (component: IComponent) => void): void {
this.templateChecker = checker;
}
/**
* bootstrap NvModule
*
* if not use Route it will be used
*
* @param {Function} Nvmodule
* @returns {INvModule}
* @memberof InDiv
*/
public bootstrapModule(Nvmodule: Function): INvModule {
if (!Nvmodule) throw new Error('must send a root module');
this.rootModule = NvModuleFactory(Nvmodule, true);
this.declarations = [...this.rootModule.$declarations];
return this.rootModule;
}
/**
* init InDiv and renderModuleBootstrap()
*
* @template R
* @returns {Promise<void>}
* @memberof InDiv
*/
public async init<R = Element>(): Promise<IComponent> {
if (!this.rootModule) throw new Error('must use bootstrapModule to declare a root NvModule before init');
if (!this.renderer) throw new Error('must use plugin of platform to set a renderer in InDiv!');
return await this.renderModuleBootstrap<R>();
}
/**
* method of Component's initialization
*
* init component and watch data
*
* @template R
* @param {Function} BootstrapComponent
* @param {R} nativeElement
* @param {INvModule} [otherModule]
* @returns {IComponent}
* @memberof InDiv
*/
public initComponent<R = Element>(BootstrapComponent: Function, nativeElement: R, otherModule?: INvModule): IComponent {
const injector = otherModule ? otherModule.$privateInjector.fork() : this.rootModule.$privateInjector.fork();
injector.setProviderAndInstance(ElementRef, ElementRef, new ElementRef<R>(nativeElement));
const component: IComponent = NvInstanceFactory(BootstrapComponent, null, injector);
component.$indivInstance = this;
if (otherModule) {
otherModule.$declarations.forEach((findDeclaration: Function) => {
if (!component.$declarationMap.has((findDeclaration as any).selector)) component.$declarationMap.set((findDeclaration as any).selector, findDeclaration);
});
} else {
this.rootModule.$declarations.forEach((findDeclaration: Function) => {
if (!component.$declarationMap.has((findDeclaration as any).selector)) component.$declarationMap.set((findDeclaration as any).selector, findDeclaration);
});
}
lifecycleCaller(component, 'nvOnInit');
lifecycleCaller(component, 'watchData');
if (!component.$template && !component.$templateUrl) throw new Error('must set template or templateUrl in bootstrap component');
return component;
}
/**
* run renderer of Component by async
*
* will call lifecycle nvBeforeMount, nvHasRender, nvAfterMount
*
* @template R
* @param {IComponent} component
* @param {R} nativeElement
* @param {Vnode[]} [initVnode]
* @returns {Promise<IComponent>}
* @memberof InDiv
*/
public async runComponentRenderer<R = Element>(component: IComponent, nativeElement: R, initVnode?: Vnode[]): Promise<IComponent> {
if ((component.$template || component.$templateUrl) && nativeElement) {
lifecycleCaller(component, 'nvBeforeMount');
await this.render<R>(component, nativeElement, initVnode);
if (!this.isServerRendering) lifecycleCaller(component, 'nvAfterMount');
return component;
} else {
throw new Error('renderBootstrap failed: template or rootDom is not exit');
}
}
/**
* expose function for render Component
*
* if otherModule don't has use rootModule
* if has otherModule, build component will use injector from loadModule instead of rootInjector
* if has initVnode, it will use initVnode for new Component
*
* @template R
* @param {Function} BootstrapComponent
* @param {R} nativeElement
* @param {INvModule} [otherModule]
* @param {Vnode[]} [initVnode]
* @returns {Promise<IComponent>}
* @memberof InDiv
*/
public renderComponent<R = Element>(BootstrapComponent: Function, nativeElement: R, otherModule?: INvModule, initVnode?: Vnode[]): Promise<IComponent> {
const component = this.initComponent(BootstrapComponent, nativeElement, otherModule);
return this.runComponentRenderer(component, nativeElement, initVnode);
}
/**
* render NvModule Bootstrap
*
* @private
* @template R
* @returns {Promise<IComponent>}
* @memberof InDiv
*/
private async renderModuleBootstrap<R = Element>(): Promise<IComponent> {
if (!this.rootModule.$bootstrap) throw new Error('need bootstrap for render Module Bootstrap');
const BootstrapComponent = this.rootModule.$bootstrap;
this.bootstrapComponent = await this.renderComponent<R>(BootstrapComponent, this.rootElement);
return this.bootstrapComponent;
}
/**
* render and replace DOM
*
* @private
* @template R
* @param {IComponent} component
* @param {R} nativeElement
* @param {Vnode[]} [initVnode]
* @returns {Promise<void>}
* @memberof InDiv
*/
private async render<R = Element>(component: IComponent, nativeElement: R, initVnode?: Vnode[]): Promise<void> {
// if has initVnode, assign initVnode for component.$saveVnode
if (initVnode) component.$saveVnode = initVnode;
component.$nativeElement = nativeElement;
await component.render();
}
} | the_stack |
import {
BlueprintWriter,
IBlueprintWriterSession,
} from "@bluelibs/terminal-bundle";
import { FSOperator, XElements, XSession, XElementType, FSUtils } from "..";
import * as Studio from ".";
import { Models, Writers } from "..";
import * as fs from "fs";
import * as path from "path";
import { UICollectionWriter } from "../writers/UICollectionWriter";
import { UICollectionModel } from "../models/UICollectionModel";
import { UICRUDModel } from "../models/UICrudModel";
import { UICollectionCRUDWriter } from "../writers/UICollectionCRUDWriter";
import { XBridge } from "./bridge/XBridge";
import { Fixturizer } from "./bridge/Fixturizer";
import { XElementClassSuffix } from "../utils/XElements";
import { CollectionReducerWriter } from "../writers/CollectionReducerWriter";
import { CollectionReducerModel } from "../models/CollectionReducerModel";
import { chalk } from "@bluelibs/terminal-bundle";
import {
ALL_GENERATORS,
GenerateProjectOptionsType,
GeneratorKind,
StudioWritersType,
} from "./defs";
import { ContainerInstance } from "@bluelibs/core";
import {
EnumConfigType,
FrontendReactMicroserviceModel,
ModelRaceEnum,
} from "../models";
import { execSync, spawnSync } from "child_process";
import { GenericModelEnumWriter } from "../writers/GenericModelEnumWriter";
import { GraphQLEnumWriter } from "../writers/GraphQLEnumWriter";
const ADMIN_FOLDER = "admin";
const API_FOLDER = "api";
export class StudioWriter {
public readonly session: XSession;
public readonly options: GenerateProjectOptionsType;
constructor(
protected readonly container: ContainerInstance,
protected readonly model: Studio.App,
options: Partial<GenerateProjectOptionsType>
) {
options = options || {};
options.writers = options.writers || {};
options.writers = Object.assign(
{},
this.getWriterDefaults(),
options.writers
);
if (!options.generators) {
options.generators = ALL_GENERATORS;
}
this.options = options as GenerateProjectOptionsType;
this.session = container.get(XSession);
if (options.override) {
this.session.isOverrideMode = true;
}
}
protected getWriterDefaults(): StudioWritersType {
return {
microservice: this.container.get(Writers.MicroserviceWriter),
collection: this.container.get(Writers.CollectionWriter),
graphQLCRUD: this.container.get(Writers.GraphQLCRUDWriter),
graphQLEntity: this.container.get(Writers.GraphQLEntityWriter),
graphQLInput: this.container.get(Writers.GraphQLInputWriter),
collectionLink: this.container.get(Writers.CollectionLinkWriter),
uiCollection: this.container.get(UICollectionWriter),
uiCollectionCRUD: this.container.get(UICollectionCRUDWriter),
fixture: this.container.get(Writers.FixtureWriter),
genericModel: this.container.get(Writers.GenericModelWriter),
};
}
get writers(): StudioWritersType {
return this.options.writers as StudioWritersType;
}
hasGenerator(kind: GeneratorKind) {
return this.options.generators.includes(kind);
}
async write() {
const session = this.session;
const studioApp = this.model;
this.model.clean();
const commit = () =>
this.session.commit({ verbose: false, skipInstructions: true });
if (!this.model.find.collection("Users")) {
throw new Error(
'You do not have a "Users" collection added. We cannot continue without one.'
);
return;
}
const projectPath = process.cwd();
let firstTimeGeneration = false;
session.setProjectPath(projectPath);
// BACKEND
const backendMicroservicePath = path.join(
projectPath,
"microservices",
API_FOLDER
);
session.setMicroservicePath(backendMicroservicePath);
if (!fs.existsSync(backendMicroservicePath)) {
firstTimeGeneration = true;
await this.createBackendMicroservice(studioApp, session, commit);
} else {
this.skipping(`Backend microservice already exists.`);
}
if (this.hasGenerator(GeneratorKind.BACKEND_COLLECTIONS)) {
await this.createCollections(studioApp, session, commit);
await this.createSharedModels(studioApp, session, commit);
await this.addReducersToUsers(session);
await this.createRelations(studioApp, session, commit);
await this.createReducers(studioApp, session, commit);
}
if (this.hasGenerator(GeneratorKind.BACKEND_CRUDS)) {
await this.createGraphQLCRUDs(studioApp, session, commit);
}
if (this.hasGenerator(GeneratorKind.BACKEND_FIXTURES)) {
await this.createFixtures(studioApp, session, commit);
}
// FRONTEND
const frontendMicroservicePath = path.join(
projectPath,
"microservices",
ADMIN_FOLDER
);
session.setMicroservicePath(frontendMicroservicePath);
const hasExistingFrontendMicroservice = fs.existsSync(
frontendMicroservicePath
);
if (!hasExistingFrontendMicroservice) {
await this.createFrontendMicroservice(studioApp, session, commit);
} else {
this.skipping(`Frontend microservice already exists.`);
}
session.setMicroservicePath(frontendMicroservicePath);
if (this.hasGenerator(GeneratorKind.FRONTEND_COLLECTIONS)) {
await this.createUICollections(studioApp, session, commit);
}
if (this.hasGenerator(GeneratorKind.FRONTEND_CRUDS)) {
await this.createUICRUDs(studioApp, session, commit);
}
if (
!hasExistingFrontendMicroservice &&
this.hasGenerator(GeneratorKind.FRONTEND_BOILERPLATE_COMPONENTS)
) {
await this.createBoilerplateUIComponents(studioApp, session, commit);
}
await this.setupI18NGenerics(studioApp, session, commit);
this.ensureNpmDependencies(firstTimeGeneration);
}
/**
* Install all dependencies necessary
*/
protected ensureNpmDependencies(firstTimeGeneration: boolean) {
console.log("");
this.loading("Installing npm dependencies for api");
execSync("npm install", { cwd: "microservices/api", stdio: "inherit" });
this.loading("Installing npm dependencies for admin");
execSync("npm install", { cwd: "microservices/admin", stdio: "inherit" });
console.log("");
this.success("Done. Now you can use:");
console.log("");
console.log("$ npm run start:api");
console.log("$ npm run start:admin");
if (firstTimeGeneration) {
console.log(
"Note: wait for the `api` to start before running the `admin` microservice to ensure GraphQL types are in-sync."
);
}
console.log("");
}
async setupI18NGenerics(
model: Studio.App,
session: XSession,
commit: () => Promise<void>
) {
const operator = new FSOperator(session, {});
const tpl = operator.getTemplatePathCreator("blueprint");
const bundleDir = FSUtils.bundlePath(
session.getMicroservicePath(),
"UIAppBundle"
);
// I18N
operator.sessionCopy(
tpl("ui/i18n/generics.json"),
path.join(bundleDir, "i18n", "generics.json")
);
operator.sessionPrependFile(
path.join(bundleDir, "i18n", "store.ts"),
`import generics from "./generics.json";`
);
operator.sessionAppendFile(
path.join(bundleDir, "i18n", "store.ts"),
`i18n.push(generics);`
);
await commit();
}
async createBoilerplateUIComponents(
model: Studio.App,
session: XSession,
commit: () => Promise<void>
) {
this.success(`Performing final UI Preparations ...`);
const operator = new FSOperator(session, {});
const tpl = operator.getTemplatePathCreator("blueprint");
const bundleDir = FSUtils.bundlePath(
session.getMicroservicePath(),
"UIAppBundle"
);
const pagesDir = path.join(bundleDir, "pages");
// CUSTOM HOME
// TODO: Change the way we perform this extension
operator.sessionCopy(
tpl("ui/components/Home.tsx"),
path.join(pagesDir, "Home", "Home.tsx"),
{
ignoreIfContains: "This is your application",
}
);
operator.sessionCopy(
tpl("ui/components/routes.tsx"),
path.join(pagesDir, "Home", "routes.tsx"),
{
ignoreIfExists: true,
}
);
this.success(`Added custom home page.`);
// OVERRIDES
const overridesDir = path.join(bundleDir, "overrides");
operator.sessionCopy(tpl("ui/overrides"), overridesDir, {
ignoreIfExists: true,
});
["AdminTopHeader", "NotAuthorized", "Loading", "NotFound"].forEach(
(componentName) => {
operator.sessionAppendFile(
path.join(overridesDir, "index.ts"),
`export * from "./${componentName}"`
);
this.success(`Added override for ${componentName}`);
}
);
// DASHBOARD & AUTH
operator.sessionCopy(
tpl("ui/dashboard"),
path.join(pagesDir, "Dashboard"),
{
ignoreIfExists: true,
}
);
this.success(`Added custom dashboard.`);
operator.sessionCopy(tpl("ui/authentication"), pagesDir, {
ignoreIfExists: true,
});
this.success(`Added authentication components`);
operator.sessionPrependFile(
path.join(pagesDir, "styles.scss"),
`@import "./Authentication/styles.scss";`
);
operator.sessionAppendFile(
path.join(pagesDir, "routes.tsx"),
`export * from "./Dashboard/routes";`
);
operator.sessionAppendFile(
path.join(pagesDir, "routes.tsx"),
`export * from "./Home/routes";`
);
operator.sessionAppendFile(
path.join(pagesDir, "routes.tsx"),
`export * from "./Authentication/routes";`
);
operator.sessionCopy(
tpl("ui/styles/style.scss"),
path.join(bundleDir, "styles", "admin.scss"),
{ ignoreIfExists: true }
);
operator.sessionAppendFile(
path.join(bundleDir, "styles", "styles.scss"),
`@import "./admin.scss";`
);
await commit();
}
async createUICRUDs(
studioApp: Studio.App,
session: XSession,
commit: () => Promise<void>
) {
const writer = this.writers.uiCollectionCRUD;
studioApp.collections.forEach((collection) => {
if (collection.ui === false) {
return;
}
if (collection.isExternal()) {
return;
}
const model = new UICRUDModel();
model.bundleName = "UIAppBundle";
model.studioCollection = collection;
model.features = collection.ui;
writer.write(model, session);
this.success(`(UI) Created CRUD interfaces for: "${collection.id}"`);
});
await commit();
}
async createUICollections(
studioApp: Studio.App,
session: XSession,
commit: () => Promise<void>
) {
const writer = this.writers.uiCollection;
studioApp.collections
.filter((c) => c.hasGraphQL("entity"))
.forEach((collection) => {
if (collection.isExternal()) {
return;
}
const model = new UICollectionModel();
model.bundleName = "UIAppBundle";
model.hasCustomInputs = true;
model.studioCollection = collection;
model.collectionName = collection.id;
model.collectionEndpoint = collection.id;
model.entityName = collection.entityName;
writer.write(model, session);
this.success(`(UI) Created client-side collection: "${collection.id}"`);
});
await commit();
}
private async createFixtures(
studioApp: Studio.App,
session: XSession,
commit: () => Promise<void>
) {
const fixturesWriter = this.writers.fixture;
const fixturesModel = new Models.FixtureModel();
const fixturizer = new Fixturizer(studioApp);
fixturesModel.bundleName = "AppBundle";
fixturesModel.fixtureName = "app";
fixturesModel.dataMapMode = true;
fixturesModel.dataMap = fixturizer.getDataSet();
fixturesWriter.write(fixturesModel, session);
await commit();
this.success(`Successfully created fixtures for data set.`);
}
private async createGraphQLCRUDs(
studioApp: Studio.App,
session: XSession,
commit: () => Promise<void>
) {
const microservicePath = session.getMicroservicePath();
const crudWriter = this.writers.graphQLCRUD;
for (const collection of studioApp.collections) {
if (!collection.hasGraphQL("crud")) {
continue;
}
if (collection.isExternal()) {
continue;
}
const model = new Models.GraphQLCRUDModel();
model.bundleName = "AppBundle";
model.checkLoggedIn = false;
model.hasSubscriptions = true;
model.crudName = collection.id;
model.collectionElement = XElements.emulateElement(
microservicePath,
"AppBundle",
XElementType.COLLECTION,
collection.id
);
model.graphqlEntityElement = XElements.emulateElement(
microservicePath,
"AppBundle",
XElementType.GRAPHQL_ENTITY,
collection.entityName
);
// TODO: maybe allow-opt-in somehow?
model.hasCustomInputs = true;
// Shorthand function to eliminate code-repetition below
function createModel(ui: "edit" | "create") {
return XBridge.collectionToGenericModel(collection, {
graphql: true,
// skipRelations: true,
ui,
isInput: true,
});
}
model.insertInputModelDefinition = createModel("create");
model.updateInputModelDefinition = createModel("edit");
// Make all fields optional for the update. We want to enable atomic-size updates from day 0.
model.updateInputModelDefinition.fields.forEach((field) => {
field.isOptional = true;
field.defaultValue = undefined;
});
crudWriter.write(model, session);
await commit();
this.success(
`Created complete GraphQL CRUD interface for ${collection.id}`
);
}
}
private async createRelations(
studioApp: Studio.App,
session: XSession,
commit: () => Promise<void>
) {
const microservicePath = session.getMicroservicePath();
const linkWriter = this.writers.collectionLink;
for (const collection of studioApp.collections) {
for (const _relation of collection.relations) {
const relation = _relation.cleaned;
const model = new Models.CollectionLinkModel();
// For inversed links
model.fieldName = relation.field && relation.field.id;
model.type = relation.isMany ? "manyToMany" : "manyToOne";
if (relation.unique) {
model.type = "oneToOne";
}
model.collectionAElement = XElements.emulateElement(
microservicePath,
"AppBundle",
XElementType.COLLECTION,
collection.id
);
if (relation.to.isExternal()) {
model.collectionBElement = {
type: XElementType.COLLECTION,
identityNameRaw: relation.to.id,
identityName:
relation.to.id + XElementClassSuffix[XElementType.COLLECTION],
isExternal: true,
absolutePath: relation.to.externalPackage,
importablePath: relation.to.externalPackage,
};
} else {
model.collectionBElement = XElements.emulateElement(
microservicePath,
"AppBundle",
XElementType.COLLECTION,
relation.to.id
);
}
model.whereIsTheLinkStored = relation.isDirect ? "A" : "B";
model.linkFromA = relation.id;
model.linkFromB = relation.inversedBy;
model.shouldProcessB = false;
linkWriter.write(model, session);
this.success(
`Linked collection: "${collection.id}:${relation.id}" to -> "${relation.to.id}"`
);
await commit();
}
}
await commit();
}
protected async createReducers(
studioApp: Studio.App,
session: XSession,
commit: () => Promise<void>
) {
const microservicePath = session.getMicroservicePath();
const reducerWriter = this.container.get(CollectionReducerWriter);
for (const collection of studioApp.collections) {
collection.fields
.filter((f) => f.isReducer)
.forEach((field) => {
const reducerModel = new CollectionReducerModel();
reducerModel.bundleName = "AppBundle";
reducerModel.collectionName = collection.id;
reducerModel.dependency = field.reducerDependency;
reducerModel.name = field.id;
reducerWriter.write(reducerModel, session);
});
}
await commit();
}
protected async createSharedModels(
studioApp: Studio.App,
session: XSession,
commit: () => Promise<void>
) {
const pathsInfo = XBridge.getPathInfos();
const genericModelWriter = this.writers.genericModel;
const graphqlEntityWriter = this.writers.graphQLEntity;
const graphqlInputWriter = this.writers.graphQLInput;
const genericModelEnumWriter = this.container.get(GenericModelEnumWriter);
const bundleDir = FSUtils.bundlePath(
session.getMicroservicePath(),
"AppBundle"
);
const sharedModelsPath = path.join(
bundleDir,
...pathsInfo.sharedModelPathInBundle.split("/")
);
for (const model of studioApp.sharedModels) {
if (model.isEnum()) {
genericModelEnumWriter.write(
{
className: model.id,
elements: model.enumValues as EnumConfigType[],
targetPath: sharedModelsPath,
},
session
);
const fsOperator = new FSOperator(session, model);
fsOperator.sessionAppendFile(
path.join(sharedModelsPath, "index.ts"),
`export * from "./${model.id}"`
);
fsOperator.sessionAppendFile(
path.join(bundleDir, "collections", "index.ts"),
`export * from "./shared"`
);
const graphqlEnumWriter = this.container.get(GraphQLEnumWriter);
graphqlEnumWriter.write(
{
className: model.id,
description: model.description,
elements: model.enumValues as EnumConfigType[],
targetPath: path.join(bundleDir, "graphql", "entities", model.id),
},
session
);
// STOP AND CONTINUE
continue;
}
const genericModel = new Models.GenericModel(model.id);
genericModel.name = model.id;
genericModel.yupValidation = true;
model.fields.forEach((field) => {
genericModel.addField(XBridge.fieldToGenericField(field));
});
genericModel.targetPath = path.join(sharedModelsPath, `${model.id}.ts`);
genericModelWriter.write(genericModel, session);
await commit();
const fsOperator = new FSOperator(session, model);
fsOperator.sessionAppendFile(
path.join(sharedModelsPath, "index.ts"),
`export * from "./${genericModel.name}"`
);
fsOperator.sessionAppendFile(
path.join(bundleDir, "collections", "index.ts"),
`export * from "./shared"`
);
if (model.enableGraphQL) {
const genericTypeModel = new Models.GenericModel(model.id);
const genericInputModel = new Models.GenericModel(model.id);
genericTypeModel.name = model.id;
genericInputModel.name = model.id;
genericTypeModel.yupValidation = true;
genericInputModel.yupValidation = true;
model.fields.forEach((field) => {
genericInputModel.addField(
XBridge.fieldToGenericField(field, true, model.id)
);
genericTypeModel.addField(
XBridge.fieldToGenericField(field, false, model.id)
);
});
const graphqlTypeModel = new Models.GraphQLInputModel();
graphqlTypeModel.bundleName = "AppBundle";
graphqlTypeModel.genericModel =
Models.GenericModel.clone(genericTypeModel);
graphqlTypeModel.genericModel.race = ModelRaceEnum.GRAPHQL_TYPE;
graphqlEntityWriter.write(graphqlTypeModel, session);
const graphqlInputModel = new Models.GraphQLInputModel();
graphqlInputModel.bundleName = "AppBundle";
graphqlInputModel.genericModel = genericInputModel;
graphqlInputModel.genericModel.race = ModelRaceEnum.GRAPHQL_INPUT;
graphqlInputModel.genericModel.isBaseExtendMode = true;
graphqlInputModel.genericModel.reuseEnums = true;
graphqlInputModel.genericModel.isInputMode = true;
graphqlInputWriter.write(graphqlInputModel, session);
}
}
await commit();
}
protected async createCollections(
studioApp: Studio.App,
session: XSession,
commit: () => Promise<void>
) {
const collectionWriter = this.writers.collection;
// Create collections on the backend.
for (const collection of studioApp.collections) {
// Ignore external collections
if (collection.isExternal()) {
continue;
}
const collectionModel = new Models.CollectionModel();
const genericModel = XBridge.collectionToGenericModel(collection);
genericModel.ensureIdField();
if (collection.id === "Users") {
collectionModel.customCollectionImport =
"@bluelibs/security-mongo-bundle";
collectionModel.customCollectionName = "UsersCollection";
this.prepareUserModel(genericModel);
}
collectionModel.modelDefinition = genericModel;
collectionModel.hasSubscriptions = true;
collectionModel.isTimestampable = collection.behaviors.timestampable;
collectionModel.isSoftdeletable = collection.behaviors.softdeletable;
collectionModel.isBlameable = collection.behaviors.blameable;
collectionModel.isEntitySameAsModel = false;
collectionModel.collectionName = collection.id;
collectionModel.bundleName = "AppBundle";
collectionModel.createEntity = false;
collectionModel.overrideCollectionIfExists = false;
if (collection.hasGraphQL("entity")) {
const graphQLModel = XBridge.collectionToGenericModel(collection, {
graphql: true,
});
collectionModel.createEntity = true;
collectionModel.entityDefinition = graphQLModel;
}
collectionWriter.write(collectionModel, session);
await commit();
this.success(
`Created collection, model and GraphQL entity for: ${collection.id}`
);
}
await commit();
}
private prepareUserModel(genericModel: Models.GenericModel) {
if (!genericModel.hasField("isEnabled")) {
genericModel.addField({
name: "isEnabled",
type: Models.GenericFieldTypeEnum.BOOLEAN,
});
}
if (!genericModel.hasField("createdAt")) {
genericModel.addField({
name: "createdAt",
type: Models.GenericFieldTypeEnum.DATE,
});
}
}
protected addReducersToUsers(session: XSession) {
const fsOperator = new FSOperator(session, {});
const reducersPath = fsOperator.getTemplatePath(
path.join("blueprint", "users", "reducers.ts.tpl")
);
const targetPath = path.join(
session.getMicroservicePath(),
"src",
"bundles",
"AppBundle",
"collections",
"Users",
"Users.reducers.ts"
);
fsOperator.sessionCopy(reducersPath, targetPath, {
ignoreIfContains: "fullName",
});
}
private async createFrontendMicroservice(
model: Studio.App,
session: XSession,
commit: () => Promise<void>
) {
FrontendReactMicroserviceModel;
const frontendMicroservice = new Models.FrontendReactMicroserviceModel();
frontendMicroservice.name = ADMIN_FOLDER;
frontendMicroservice.projectName = model.id + "-admin-ui";
frontendMicroservice.adminMode = true;
frontendMicroservice.hasCustomGuardian = true;
frontendMicroservice.type = Models.MicroserviceTypeEnum.FRONTEND_REACT;
this.writers.microservice.write(frontendMicroservice, session);
await commit();
// NPM
const npmPackages = {
"@bluelibs/x-ui-admin": "^1.0.0",
antd: "^4.12.3",
"@ant-design/icons": "^4.5.0",
};
for (const pack in npmPackages) {
session.installNpmPackage(pack, npmPackages[pack], {
rootDir: session.getMicroservicePath(),
});
}
await commit();
this.success(
`Successfully setup the frontend microservice in "./microservices/${ADMIN_FOLDER}"`
);
}
private async createBackendMicroservice(
model: Studio.App,
session: XSession,
commit: () => Promise<void>
) {
const backendMicroservice = new Models.BackendMicroserviceModel();
backendMicroservice.hasUsers = true;
backendMicroservice.hasUploads = true;
backendMicroservice.createUsersCollection = false;
backendMicroservice.name = "api";
backendMicroservice.projectName = model.id;
backendMicroservice.type = Models.MicroserviceTypeEnum.BACKEND;
this.writers.microservice.write(backendMicroservice, session);
const operator = new FSOperator(session, {});
await commit();
const bundleDir = FSUtils.bundlePath(
session.getMicroservicePath(),
"AppBundle"
);
const tpl = operator.getTemplatePathCreator("blueprint");
operator.sessionCopy(
tpl("uploads/graphql"),
path.join(bundleDir, "graphql", "modules", "Uploads"),
{
ignoreIfExists: true,
}
);
// NPM
const npmPackages = {
"aws-sdk": "^2.948.0",
"graphql-upload": "^12.0.0",
"@bluelibs/x-s3-bundle": "^1.0.0",
};
for (const pack in npmPackages) {
session.installNpmPackage(pack, npmPackages[pack], {
rootDir: session.getMicroservicePath(),
});
}
this.success(
`Successfully setup the backend microservice in "./microservices/api"`
);
}
public skipping(message) {
console.log(`${chalk.magentaBright("โค")} ${message} (skipping)`);
}
public success(message) {
console.log(`${chalk.greenBright("โ")} ${message}`);
}
public loading(message) {
console.log(`${chalk.redBright("โฆ")} ${message}...`);
}
} | the_stack |
import { XmlWriter } from '../src/xml-writer';
/**
* Xml Writer Spec
*/
describe('Create XmlWriter instance', (): void => {
beforeEach((): void => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 500;
});
it('Validate constructor', (done): void => {
/**
* instantiate XmlWriter class
*/
let xmlWriter: XmlWriter = new XmlWriter();
setTimeout((): void => {
expect('').toBe('');
done();
}, 50);
});
});
describe('Create single empty element without start document', (): void => {
let xmlWriter: XmlWriter;
let fileReader: FileReader;
let xmlText: string | ArrayBuffer;
beforeEach((): void => {
/**
* instantiate XmlWriter class
*/
xmlWriter = new XmlWriter();
/**
* creates instance of FileReader class
*/
fileReader = new FileReader();
fileReader.onload = (): void => {
/**
* gets xml text from bolb
*/
xmlText = fileReader.result;
};
jasmine.DEFAULT_TIMEOUT_INTERVAL = 500;
});
afterEach((): void => {
xmlWriter.destroy();
xmlWriter = undefined;
fileReader = undefined;
xmlText = '';
});
it('Prefix and namespace as null', (done): void => {
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root />');
done();
}, 50);
});
it('Prefix and namespace as empty', (done): void => {
xmlWriter.writeStartElement('', 'root', '');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root />');
done();
}, 50);
});
it('Prefix and namespace as valid string', (done): void => {
xmlWriter.writeStartElement('w', 'root', 'xmlns');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><w:root xmlns:w="xmlns" />');
done();
}, 50);
});
it('Prefix as null and namespace as valid string', (done): void => {
xmlWriter.writeStartElement(null, 'root', 'xmlns');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root xmlns="xmlns" />');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string', (done): void => {
xmlWriter.writeStartElement('', 'root', 'xmlns');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root xmlns="xmlns" />');
done();
}, 50);
});
it('Prefix as valid string and namespace as null', (done): void => {
setTimeout((): void => {
expect((): void => { xmlWriter.writeStartElement('w', 'root', null); }).toThrow(new Error('ArgumentException: Cannot use a prefix with an empty namespace'));
done();
}, 50);
});
it('Prefix, namespace as null ,localName with valid special character', (done): void => {
xmlWriter.writeStartElement(null, 'root_-.', null)
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root_-. />');
done();
}, 50);
});
it('Prefix, namespace, localName as null', (done): void => {
setTimeout((): void => {
expect((): void => { xmlWriter.writeStartElement(null, null, null); }).toThrow(new Error('ArgumentException: localName cannot be undefined, null or empty'));
done();
}, 50);
});
it('Prefix, namespace, localName as null empty', (done): void => {
setTimeout((): void => {
expect((): void => { xmlWriter.writeStartElement('', '', ''); }).toThrow(new Error('ArgumentException: localName cannot be undefined, null or empty'));
done();
}, 50);
});
it('Prefix,localName as valid String and namespace as empty', (done): void => {
setTimeout((): void => {
expect((): void => { xmlWriter.writeStartElement('w', 'root', ''); }).toThrow(new Error('ArgumentException: Cannot use a prefix with an empty namespace'));
done();
}, 50);
});
it('Prefix,localName as valid String and namespace as null', (done): void => {
setTimeout((): void => {
expect((): void => { xmlWriter.writeStartElement('w', 'root', null); }).toThrow(new Error('ArgumentException: Cannot use a prefix with an empty namespace'));
done();
}, 50);
});
it('Prefix = xmlns, namespace, localName as valid string', (done): void => {
setTimeout((): void => {
expect((): void => { xmlWriter.writeStartElement('xmlns', 'root', 'element'); }).toThrow(new Error('InvalidArgumentException: Prefix "xmlns" is reserved for use by XML.'));
done();
}, 50);
});
it('Prefix =xmlns, and namespace aa valid string', (done): void => {
setTimeout((): void => {
expect((): void => { xmlWriter.writeStartElement('xmlns', 'root', 'element'); }).toThrow(new Error('InvalidArgumentException: Prefix "xmlns" is reserved for use by XML.'));
done();
}, 50);
});
it('Prefix,localName with invalid special character @ and namespace as null', (done): void => {
setTimeout((): void => {
expect((): void => { xmlWriter.writeStartElement('w', 'ro@ot', null); }).toThrow(new Error('InvalidArgumentException: invalid name character'));
done();
}, 50);
});
it('Prefix,localName with invalid special character \'(\' and namespace as null', (done): void => {
setTimeout((): void => {
expect((): void => { xmlWriter.writeStartElement('w', 'ro(ot', null); }).toThrow(new Error('InvalidArgumentException: invalid name character'));
done();
}, 50);
});
it('Prefix,localName with invalid special character \')\' and namespace as null', (done): void => {
setTimeout((): void => {
expect((): void => { xmlWriter.writeStartElement('w', 'ro)ot', null); }).toThrow(new Error('InvalidArgumentException: invalid name character'));
done();
}, 50);
});
it('Prefix,localName with invalid special character \' \' and namespace as null', (done): void => {
setTimeout((): void => {
expect((): void => { xmlWriter.writeStartElement('w', 'ro ot', null); }).toThrow(new Error('InvalidArgumentException: invalid name character'));
done();
}, 50);
});
it('Prefix,localName with invalid special character \'$\' and namespace as null', (done): void => {
setTimeout((): void => {
expect((): void => { xmlWriter.writeStartElement('w', 'ro$ot', null); }).toThrow(new Error('InvalidArgumentException: invalid name character'));
done();
}, 50);
});
it('Prefix,localName with invalid special character \':\' and namespace as null', (done): void => {
setTimeout((): void => {
expect((): void => { xmlWriter.writeStartElement('w', 'ro:ot', null); }).toThrow(new Error('InvalidArgumentException: invalid name character'));
done();
}, 50);
});
it('Prefix,localName with invalid special character \'#\' and namespace as null', (done): void => {
setTimeout((): void => {
expect((): void => { xmlWriter.writeStartElement('w', 'ro#ot', null); }).toThrow(new Error('InvalidArgumentException: invalid name character'));
done();
}, 50);
});
it('Prefix,localName with invalid special character \'*\' and namespace as null', (done): void => {
setTimeout((): void => {
expect((): void => { xmlWriter.writeStartElement('w', 'ro**ot', null); }).toThrow(new Error('InvalidArgumentException: invalid name character'));
done();
}, 50);
});
it('Prefix and namespace as null,localName with invalid special character \'<\' ', (done): void => {
setTimeout((): void => {
expect((): void => { xmlWriter.writeStartElement('w', 'ro<ot', null); }).toThrow(new Error('InvalidArgumentException: invalid name character'));
done();
}, 50);
});
it('Element\'s prefix=xmlns ,ns=http://www.w3.org/2000/xmlns/ ', (done): void => {
setTimeout((): void => {
expect((): void => { xmlWriter.writeStartElement('xmlns', "book", 'http://www.w3.org/2000/xmlns/'); }).toThrow(new Error('InvalidArgumentException: Prefix "xmlns" is reserved for use by XML.'));
done();
}, 50);
});
it('Element\'s prefix=xml ,ns=http://www.w3.org/2000/xmlns/ ', (done): void => {
setTimeout((): void => {
expect((): void => { xmlWriter.writeStartElement('xml', "book", 'http://www.w3.org/2000/xmlns/'); }).toThrow(new Error('InvalidArgumentException: Xml String'));
done();
}, 50);
});
it('Element\'s prefix as valid string ,ns=http://www.w3.org/XML/1998/namespace ', (done): void => {
setTimeout((): void => {
expect((): void => { xmlWriter.writeStartElement('w', "book", 'http://www.w3.org/XML/1998/namespace'); }).toThrow(new Error('InvalidArgumentException'));
done();
}, 50);
});
it('Element\'s prefix as valid string,ns=http://www.w3.org/2000/xmlns/ ', (done): void => {
setTimeout((): void => {
expect((): void => { xmlWriter.writeStartElement('w', "book", 'http://www.w3.org/2000/xmlns/'); }).toThrow(new Error('InvalidArgumentException'));
done();
}, 50);
});
});
describe('Create single empty element with start document', (): void => {
let xmlWriter: XmlWriter;
let fileReader: FileReader;
let xmlText: string | ArrayBuffer;
beforeEach((): void => {
/**
* instantiate XmlWriter class
*/
xmlWriter = new XmlWriter();
/**
* creates instance of FileReader class
*/
fileReader = new FileReader();
fileReader.onload = (): void => {
/**
* gets xml text from bolb
*/
xmlText = fileReader.result;
};
jasmine.DEFAULT_TIMEOUT_INTERVAL = 500;
});
afterEach((): void => {
xmlWriter.destroy();
xmlWriter = undefined;
fileReader = undefined;
xmlText = '';
});
it('Prefix and namespace as null with start Document standalone true', (done): void => {
xmlWriter.writeStartDocument(true);
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="yes"?><root />');
done();
}, 50);
});
it('Prefix and namespace as null with start Document standalone false', (done): void => {
xmlWriter.writeStartDocument(false);
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="no"?><root />');
done();
}, 50);
});
it('Prefix and namespace as null with start Document standalone empty', (done): void => {
xmlWriter.writeStartDocument();
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root />');
done();
}, 50);
});
it('Prefix and namespace as empty with start Document standalone true', (done): void => {
xmlWriter.writeStartDocument(true);
xmlWriter.writeStartElement('', 'root', '');
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="yes"?><root />');
done();
}, 50);
});
it('Prefix and namespace as empty with start Document standalone false', (done): void => {
xmlWriter.writeStartDocument(false);
xmlWriter.writeStartElement('', 'root', '');
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="no"?><root />');
done();
}, 50);
});
it('Prefix and namespace as empty with start Document standalone empty', (done): void => {
xmlWriter.writeStartDocument();
xmlWriter.writeStartElement('', 'root', '');
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root />');
done();
}, 50);
});
it('Prefix and namespace as valid string with start document standalone true', (done): void => {
xmlWriter.writeStartDocument(true);
xmlWriter.writeStartElement('w', 'root', 'xmlns');
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="yes"?><w:root xmlns:w="xmlns" />');
done();
}, 50);
});
it('Prefix and namespace as valid string with start document standalone false', (done): void => {
xmlWriter.writeStartDocument(false);
xmlWriter.writeStartElement('w', 'root', 'xmlns');
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="no"?><w:root xmlns:w="xmlns" />');
done();
}, 50);
});
it('Prefix and namespace as valid string with start document standalone empty', (done): void => {
xmlWriter.writeStartDocument();
xmlWriter.writeStartElement('w', 'root', 'xmlns');
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><w:root xmlns:w="xmlns" />');
done();
}, 50);
});
it('Prefix as null and namespace as valid string with start document standalone true', (done): void => {
xmlWriter.writeStartDocument(true);
xmlWriter.writeStartElement(null, 'root', 'xmlns');
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="yes"?><root xmlns="xmlns" />');
done();
}, 50);
});
it('Prefix as null and namespace as valid string with start document standalone false', (done): void => {
xmlWriter.writeStartDocument(false);
xmlWriter.writeStartElement(null, 'root', 'xmlns');
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="no"?><root xmlns="xmlns" />');
done();
}, 50);
});
it('Prefix as null and namespace as valid string with start document standalone empty', (done): void => {
xmlWriter.writeStartDocument();
xmlWriter.writeStartElement(null, 'root', 'xmlns');
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root xmlns="xmlns" />');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string with start document standalone true', (done): void => {
xmlWriter.writeStartDocument(true);
xmlWriter.writeStartElement('', 'root', "xmlns");
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="yes"?><root xmlns="xmlns" />');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string with start document standalone false', (done): void => {
xmlWriter.writeStartDocument(false);
xmlWriter.writeStartElement('', 'root', "xmlns");
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="no"?><root xmlns="xmlns" />');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string with start document standalone false', (done): void => {
xmlWriter.writeStartDocument();
xmlWriter.writeStartElement('', 'root', "xmlns");
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root xmlns="xmlns" />');
done();
}, 50);
});
it('Empty start Document without child element', (done): void => {
xmlWriter.writeStartElement('', 'book', '');
setTimeout((): void => {
expect((): void => { xmlWriter.writeStartDocument(); }).toThrow(new Error('InvalidOperationException: Wrong Token'));
done();
}, 50);
});
it('Prefix as empty and namespace as valid string with start document standalone false,end document befor end element', (done): void => {
xmlWriter.writeStartDocument();
xmlWriter.writeStartElement('', 'root', "xmlns");
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root xmlns="xmlns" />');
done();
}, 50);
});
});
describe('create single non empty element without start document', (): void => {
let xmlWriter: XmlWriter;
let fileReader: FileReader;
let xmlText: string | ArrayBuffer;
beforeEach((): void => {
/**
* instantiate XmlWriter class
*/
xmlWriter = new XmlWriter();
/**
* creates instance of FileReader class
*/
fileReader = new FileReader();
fileReader.onload = (): void => {
/**
* gets xml text from bolb
*/
xmlText = fileReader.result;
};
jasmine.DEFAULT_TIMEOUT_INTERVAL = 500;
});
afterEach((): void => {
xmlWriter.destroy();
xmlWriter = undefined;
fileReader = undefined;
xmlText = '';
});
it('Prefix and namespace as null & value as valid string ', (done): void => {
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeString('value');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root>value</root>');
done();
}, 50);
});
it('Prefix and namespace as null & value as empty ', (done): void => {
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeString('');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root></root>');
done();
}, 50);
});
it('Prefix and namespace as null & value as null ', (done): void => {
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeString(null);
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root />');
done();
}, 50);
});
it('Prefix and namespace as empty & value as valid string ', (done): void => {
xmlWriter.writeStartElement('', 'root', '');
xmlWriter.writeString('value');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root>value</root>');
done();
}, 50);
});
it('Prefix and namespace as empty & value as empty ', (done): void => {
xmlWriter.writeStartElement('', 'root', '');
xmlWriter.writeString('');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root></root>');
done();
}, 50);
});
it('Prefix and namespace as empty & value as null', (done): void => {
xmlWriter.writeStartElement('', 'root', '');
xmlWriter.writeString(null);
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root />');
done();
}, 50);
});
it('Prefix and namespace as valid string & value as valid string ', (done): void => {
xmlWriter.writeStartElement('w', 'root', 'xmlns');
xmlWriter.writeString('value');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><w:root xmlns:w="xmlns">value</w:root>');
done();
}, 50);
});
it('Prefix and namespace as valid string & value as empty ', (done): void => {
xmlWriter.writeStartElement('w', 'root', 'xmlns');
xmlWriter.writeString('');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><w:root xmlns:w="xmlns"></w:root>');
done();
}, 50);
});
it('Prefix and namespace as valid string & value as null ', (done): void => {
xmlWriter.writeStartElement('w', 'root', 'xmlns');
xmlWriter.writeString(null);
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><w:root xmlns:w="xmlns" />');
done();
}, 50);
});
it('Prefix as null and namespace as valid string & value as valid string ', (done): void => {
xmlWriter.writeStartElement(null, 'root', 'xmlns');
xmlWriter.writeString('value');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root xmlns="xmlns">value</root>');
done();
}, 50);
});
it('Prefix as null and namespace as valid string & value as empty string ', (done): void => {
xmlWriter.writeStartElement(null, 'root', 'xmlns');
xmlWriter.writeString('');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root xmlns="xmlns"></root>');
done();
}, 50);
});
it('Prefix as null and namespace as valid string & value as null', (done): void => {
xmlWriter.writeStartElement(null, 'root', 'xmlns');
xmlWriter.writeString(null);
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root xmlns="xmlns" />');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string & value as valid string ', (done): void => {
xmlWriter.writeStartElement('', 'root', "xmlns");
xmlWriter.writeString('value');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root xmlns="xmlns">value</root>');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string & value as empty string ', (done): void => {
xmlWriter.writeStartElement('', 'root', "xmlns");
xmlWriter.writeString('');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root xmlns="xmlns"></root>');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string & value as null ', (done): void => {
xmlWriter.writeStartElement('', 'root', "xmlns");
xmlWriter.writeString(null);
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root xmlns="xmlns" />');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string & value as valid string with special char & ', (done): void => {
xmlWriter.writeStartElement('', 'root', "xmlns");
xmlWriter.writeString('value&');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root xmlns="xmlns">value&</root>');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string & value as valid string with special char < ', (done): void => {
xmlWriter.writeStartElement('', 'root', "xmlns");
xmlWriter.writeString('value<');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root xmlns="xmlns">value<</root>');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string & value as valid string with special char > ', (done): void => {
xmlWriter.writeStartElement('', 'root', "xmlns");
xmlWriter.writeString('value>');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root xmlns="xmlns">value></root>');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string & value as valid string with special char \" ', (done): void => {
xmlWriter.writeStartElement('', 'root', "xmlns");
xmlWriter.writeString('value\"');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root xmlns="xmlns">value\"</root>');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string & value as valid string with special char \' ', (done): void => {
xmlWriter.writeStartElement('', 'root', "xmlns");
xmlWriter.writeString('value\'');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root xmlns="xmlns">value\'</root>');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string & value as valid string with multiple special character', (done): void => {
xmlWriter.writeStartElement('', 'root', "xmlns");
xmlWriter.writeString('value&&<\"');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root xmlns="xmlns">value&&<\"</root>');
done();
}, 50);
});
it('writeString at XmlWriteStart initial', (done): void => {
setTimeout((): void => {
expect((): void => { xmlWriter.writeString('value&&<\"'); }).toThrow(new Error('InvalidOperationException: Wrong Token'));
done();
}, 50);
});
it('writeString at XmlWriteStart initial', (done): void => {
xmlWriter.writeStartElement('', 'root', '');
xmlWriter.writeString('parent');
xmlWriter.writeEndElement();
xmlWriter.destroy();
setTimeout((): void => {
expect((): void => { xmlWriter.writeStartElement('', 'root', ''); }).toThrow(new Error('InvalidOperationException: Wrong Token'));
done();
}, 50);
});
});
describe('create single non empty element with start document', (): void => {
let xmlWriter: XmlWriter;
let fileReader: FileReader;
let xmlText: string | ArrayBuffer;
beforeEach((): void => {
/**
* instantiate XmlWriter class
*/
xmlWriter = new XmlWriter();
/**
* creates instance of FileReader class
*/
fileReader = new FileReader();
fileReader.onload = (): void => {
/**
* gets xml text from bolb
*/
xmlText = fileReader.result;
};
jasmine.DEFAULT_TIMEOUT_INTERVAL = 500;
});
afterEach((): void => {
xmlWriter.destroy();
xmlWriter = undefined;
fileReader = undefined;
xmlText = '';
});
it('Prefix and namespace as null & value as valid string,start document empty ', (done): void => {
xmlWriter.writeStartDocument();
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeString('value');
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root>value</root>');
done();
}, 50);
});
it('Prefix and namespace as null & value as valid string,start document true ', (done): void => {
xmlWriter.writeStartDocument(true);
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeString('value');
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="yes"?><root>value</root>');
done();
}, 50);
});
it('Prefix and namespace as null & value as valid string,start document false ', (done): void => {
xmlWriter.writeStartDocument(false);
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeString('value');
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="no"?><root>value</root>');
done();
}, 50);
});
it('Prefix and namespace as null & value as empty,start document empty ', (done): void => {
xmlWriter.writeStartDocument();
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeString('');
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root></root>');
done();
}, 50);
});
it('Prefix and namespace as null & value as empty,start document true ', (done): void => {
xmlWriter.writeStartDocument(true);
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeString('');
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="yes"?><root></root>');
done();
}, 50);
});
it('Prefix and namespace as null & value as empty,start document false ', (done): void => {
xmlWriter.writeStartDocument(false);
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeString('');
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="no"?><root></root>');
done();
}, 50);
});
it('Prefix and namespace as null & value as null,start document empty ', (done): void => {
xmlWriter.writeStartDocument();
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeString(null);
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root />');
done();
}, 50);
});
it('Prefix and namespace as null & value as null,start document true ', (done): void => {
xmlWriter.writeStartDocument(true);
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeString(null);
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="yes"?><root />');
done();
}, 50);
});
it('Prefix and namespace as null & value as null,start document false ', (done): void => {
xmlWriter.writeStartDocument(false);
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeString(null);
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="no"?><root />');
done();
}, 50);
});
it('Prefix and namespace as empty & value as valid string,start document empty ', (done): void => {
xmlWriter.writeStartDocument();
xmlWriter.writeStartElement('', 'root', '');
xmlWriter.writeString('value');
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root>value</root>');
done();
}, 50);
});
it('Prefix and namespace as empty & value as valid string,start document true ', (done): void => {
xmlWriter.writeStartDocument(true);
xmlWriter.writeStartElement('', 'root', '');
xmlWriter.writeString('value');
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="yes"?><root>value</root>');
done();
}, 50);
});
it('Prefix and namespace as empty & value as valid string,start document false ', (done): void => {
xmlWriter.writeStartDocument(false);
xmlWriter.writeStartElement('', 'root', '');
xmlWriter.writeString('value');
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="no"?><root>value</root>');
done();
}, 50);
});
it('Prefix and namespace as empty & value as null,start document empty', (done): void => {
xmlWriter.writeStartDocument();
xmlWriter.writeStartElement('', 'root', '');
xmlWriter.writeString(null);
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root />');
done();
}, 50);
});
it('Prefix and namespace as empty & value as null,start document true', (done): void => {
xmlWriter.writeStartDocument(true);
xmlWriter.writeStartElement('', 'root', '');
xmlWriter.writeString(null);
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="yes"?><root />');
done();
}, 50);
});
it('Prefix and namespace as empty & value as null,start document false', (done): void => {
xmlWriter.writeStartDocument(false);
xmlWriter.writeStartElement('', 'root', '');
xmlWriter.writeString(null);
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="no"?><root />');
done();
}, 50);
});
it('Prefix and namespace as valid string & value as valid string,start document empty ', (done): void => {
xmlWriter.writeStartDocument();
xmlWriter.writeStartElement('w', 'root', 'xmlns');
xmlWriter.writeString('value');
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><w:root xmlns:w="xmlns">value</w:root>');
done();
}, 50);
});
it('Prefix,namespace,value as valid string with two writeString method ', (done): void => {
xmlWriter.writeStartDocument();
xmlWriter.writeStartElement('w', 'root', 'xmlns');
xmlWriter.writeString('value');
xmlWriter.writeString(' data');
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><w:root xmlns:w="xmlns">value data</w:root>');
done();
}, 50);
});
it('Prefix and namespace as valid string & value as valid string,start document true ', (done): void => {
xmlWriter.writeStartDocument(true);
xmlWriter.writeStartElement('w', 'root', 'xmlns');
xmlWriter.writeString('value');
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="yes"?><w:root xmlns:w="xmlns">value</w:root>');
done();
}, 50);
});
it('Prefix and namespace as valid string & value as valid string,start document false ', (done): void => {
xmlWriter.writeStartDocument(false);
xmlWriter.writeStartElement('w', 'root', 'xmlns');
xmlWriter.writeString('value');
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="no"?><w:root xmlns:w="xmlns">value</w:root>');
done();
}, 50);
});
it('Prefix and namespace as valid string & value as empty,start document empty ', (done): void => {
xmlWriter.writeStartDocument();
xmlWriter.writeStartElement('w', 'root', 'xmlns');
xmlWriter.writeString('');
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><w:root xmlns:w="xmlns"></w:root>');
done();
}, 50);
});
it('Prefix and namespace as valid string & value as empty,start document true ', (done): void => {
xmlWriter.writeStartDocument(true);
xmlWriter.writeStartElement('w', 'root', 'xmlns');
xmlWriter.writeString('');
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="yes"?><w:root xmlns:w="xmlns"></w:root>');
done();
}, 50);
});
it('Prefix and namespace as valid string & value as empty,start document false ', (done): void => {
xmlWriter.writeStartDocument(false);
xmlWriter.writeStartElement('w', 'root', 'xmlns');
xmlWriter.writeString('');
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="no"?><w:root xmlns:w="xmlns"></w:root>');
done();
}, 50);
});
it('Prefix and namespace as valid string & value as null,start document empty ', (done): void => {
xmlWriter.writeStartDocument();
xmlWriter.writeStartElement('w', 'root', 'xmlns');
xmlWriter.writeString(null);
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><w:root xmlns:w="xmlns" />');
done();
}, 50);
});
it('Prefix and namespace as valid string & value as null,start document true ', (done): void => {
xmlWriter.writeStartDocument(true);
xmlWriter.writeStartElement('w', 'root', 'xmlns');
xmlWriter.writeString(null);
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="yes"?><w:root xmlns:w="xmlns" />');
done();
}, 50);
});
it('Prefix and namespace as valid string & value as null,start document false ', (done): void => {
xmlWriter.writeStartDocument(false);
xmlWriter.writeStartElement('w', 'root', 'xmlns');
xmlWriter.writeString(null);
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="no"?><w:root xmlns:w="xmlns" />');
done();
}, 50);
});
it('Prefix as null and namespace as valid string & value as valid string ,start document empty', (done): void => {
xmlWriter.writeStartDocument();
xmlWriter.writeStartElement(null, 'root', 'xmlns');
xmlWriter.writeString('value');
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root xmlns="xmlns">value</root>');
done();
}, 50);
});
it('Prefix as null and namespace as valid string & value as valid string ,start document false', (done): void => {
xmlWriter.writeStartDocument(false);
xmlWriter.writeStartElement(null, 'root', 'xmlns');
xmlWriter.writeString('value');
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="no"?><root xmlns="xmlns">value</root>');
done();
}, 50);
});
it('Prefix as null and namespace as valid string & value as valid string ,start document true', (done): void => {
xmlWriter.writeStartDocument(true);
xmlWriter.writeStartElement(null, 'root', 'xmlns');
xmlWriter.writeString('value');
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="yes"?><root xmlns="xmlns">value</root>');
done();
}, 50);
});
it('Prefix as null and namespace as valid string & value as empty string,start document empty ', (done): void => {
xmlWriter.writeStartDocument();
xmlWriter.writeStartElement(null, 'root', 'xmlns');
xmlWriter.writeString('');
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root xmlns="xmlns"></root>');
done();
}, 50);
});
it('Prefix as null and namespace as valid string & value as empty string,start document false ', (done): void => {
xmlWriter.writeStartDocument(false);
xmlWriter.writeStartElement(null, 'root', 'xmlns');
xmlWriter.writeString('');
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="no"?><root xmlns="xmlns"></root>');
done();
}, 50);
});
it('Prefix as null and namespace as valid string & value as empty string,start document true ', (done): void => {
xmlWriter.writeStartDocument(true);
xmlWriter.writeStartElement(null, 'root', 'xmlns');
xmlWriter.writeString('');
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="yes"?><root xmlns="xmlns"></root>');
done();
}, 50);
});
it('Prefix as null and namespace as valid string & value as null,start document empty', (done): void => {
xmlWriter.writeStartDocument();
xmlWriter.writeStartElement(null, 'root', 'xmlns');
xmlWriter.writeString(null);
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root xmlns="xmlns" />');
done();
}, 50);
});
it('Prefix as null and namespace as valid string & value as null,start document false', (done): void => {
xmlWriter.writeStartDocument(false);
xmlWriter.writeStartElement(null, 'root', 'xmlns');
xmlWriter.writeString(null);
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="no"?><root xmlns="xmlns" />');
done();
}, 50);
});
it('Prefix as null and namespace as valid string & value as null,start document true', (done): void => {
xmlWriter.writeStartDocument(true);
xmlWriter.writeStartElement(null, 'root', 'xmlns');
xmlWriter.writeString(null);
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="yes"?><root xmlns="xmlns" />');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string & value as valid string,start document empty ', (done): void => {
xmlWriter.writeStartDocument();
xmlWriter.writeStartElement('', 'root', "xmlns");
xmlWriter.writeString('value');
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root xmlns="xmlns">value</root>');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string & value as valid string,start document false ', (done): void => {
xmlWriter.writeStartDocument(false);
xmlWriter.writeStartElement('', 'root', "xmlns");
xmlWriter.writeString('value');
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="no"?><root xmlns="xmlns">value</root>');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string & value as valid string,start document true ', (done): void => {
xmlWriter.writeStartDocument(true);
xmlWriter.writeStartElement('', 'root', "xmlns");
xmlWriter.writeString('value');
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="yes"?><root xmlns="xmlns">value</root>');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string & value as empty string,start document empty ', (done): void => {
xmlWriter.writeStartDocument();
xmlWriter.writeStartElement('', 'root', "xmlns");
xmlWriter.writeString('');
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root xmlns="xmlns"></root>');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string & value as empty string,start document false ', (done): void => {
xmlWriter.writeStartDocument(false);
xmlWriter.writeStartElement('', 'root', "xmlns");
xmlWriter.writeString('');
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="no"?><root xmlns="xmlns"></root>');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string & value as empty string,start document true ', (done): void => {
xmlWriter.writeStartDocument(true);
xmlWriter.writeStartElement('', 'root', "xmlns");
xmlWriter.writeString('');
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="yes"?><root xmlns="xmlns"></root>');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string & value as null,start document empty ', (done): void => {
xmlWriter.writeStartDocument();
xmlWriter.writeStartElement('', 'root', "xmlns");
xmlWriter.writeString(null);
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root xmlns="xmlns" />');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string & value as null,start document false ', (done): void => {
xmlWriter.writeStartDocument(false);
xmlWriter.writeStartElement('', 'root', "xmlns");
xmlWriter.writeString(null);
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="no"?><root xmlns="xmlns" />');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string & value as null,start document true ', (done): void => {
xmlWriter.writeStartDocument(true);
xmlWriter.writeStartElement('', 'root', "xmlns");
xmlWriter.writeString(null);
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="yes"?><root xmlns="xmlns" />');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string & value as valid string with special char &,start document empty ', (done): void => {
xmlWriter.writeStartDocument();
xmlWriter.writeStartElement('', 'root', "xmlns");
xmlWriter.writeString('value&');
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root xmlns="xmlns">value&</root>');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string & value as valid string with special char &,start document false ', (done): void => {
xmlWriter.writeStartDocument(false);
xmlWriter.writeStartElement('', 'root', "xmlns");
xmlWriter.writeString('value&');
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="no"?><root xmlns="xmlns">value&</root>');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string & value as valid string with special char &,start document true ', (done): void => {
xmlWriter.writeStartDocument(true);
xmlWriter.writeStartElement('', 'root', "xmlns");
xmlWriter.writeString('value&');
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="yes"?><root xmlns="xmlns">value&</root>');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string & value as valid string with special char <,start document empty ', (done): void => {
xmlWriter.writeStartDocument();
xmlWriter.writeStartElement('', 'root', "xmlns");
xmlWriter.writeString('value<');
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root xmlns="xmlns">value<</root>');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string & value as valid string with special char <,start document false ', (done): void => {
xmlWriter.writeStartDocument(false);
xmlWriter.writeStartElement('', 'root', "xmlns");
xmlWriter.writeString('value<');
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="no"?><root xmlns="xmlns">value<</root>');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string & value as valid string with special char <,start document true ', (done): void => {
xmlWriter.writeStartDocument(true);
xmlWriter.writeStartElement('', 'root', "xmlns");
xmlWriter.writeString('value<');
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="yes"?><root xmlns="xmlns">value<</root>');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string & value as valid string with special char >,start document empty ', (done): void => {
xmlWriter.writeStartDocument();
xmlWriter.writeStartElement('', 'root', "xmlns");
xmlWriter.writeString('value>');
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root xmlns="xmlns">value></root>');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string & value as valid string with special char >,start document empty ', (done): void => {
xmlWriter.writeStartDocument(false);
xmlWriter.writeStartElement('', 'root', "xmlns");
xmlWriter.writeString('value>');
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="no"?><root xmlns="xmlns">value></root>');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string & value as valid string with special char >,start document empty ', (done): void => {
xmlWriter.writeStartDocument(true);
xmlWriter.writeStartElement('', 'root', "xmlns");
xmlWriter.writeString('value>');
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="yes"?><root xmlns="xmlns">value></root>');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string & value as valid string with special char \" ,start document empty', (done): void => {
xmlWriter.writeStartDocument();
xmlWriter.writeStartElement('', 'root', "xmlns");
xmlWriter.writeString('value\"');
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root xmlns="xmlns">value\"</root>');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string & value as valid string with special char \" ,start document false', (done): void => {
xmlWriter.writeStartDocument(false);
xmlWriter.writeStartElement('', 'root', "xmlns");
xmlWriter.writeString('value\"');
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="no"?><root xmlns="xmlns">value\"</root>');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string & value as valid string with special char \" ,start document true', (done): void => {
xmlWriter.writeStartDocument(true);
xmlWriter.writeStartElement('', 'root', "xmlns");
xmlWriter.writeString('value\"');
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="yes"?><root xmlns="xmlns">value\"</root>');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string & value as valid string with special char \',start document empty ', (done): void => {
xmlWriter.writeStartDocument();
xmlWriter.writeStartElement('', 'root', "xmlns");
xmlWriter.writeString('value\'');
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root xmlns="xmlns">value\'</root>');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string & value as valid string with special char \',start document flase ', (done): void => {
xmlWriter.writeStartDocument(false);
xmlWriter.writeStartElement('', 'root', "xmlns");
xmlWriter.writeString('value\'');
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="no"?><root xmlns="xmlns">value\'</root>');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string & value as valid string with special char \',start document true ', (done): void => {
xmlWriter.writeStartDocument(true);
xmlWriter.writeStartElement('', 'root', "xmlns");
xmlWriter.writeString('value\'');
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="yes"?><root xmlns="xmlns">value\'</root>');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string & value as valid string with multiple special character,start document empty', (done): void => {
xmlWriter.writeStartDocument();
xmlWriter.writeStartElement('', 'root', "xmlns");
xmlWriter.writeString('value&&<\"');
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument()
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root xmlns="xmlns">value&&<\"</root>');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string & value as valid string with multiple special character,start document false', (done): void => {
xmlWriter.writeStartDocument(false);
xmlWriter.writeStartElement('', 'root', "xmlns");
xmlWriter.writeString('value&&<\"');
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument()
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="no"?><root xmlns="xmlns">value&&<\"</root>');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string & value as valid string with multiple special character,start document true', (done): void => {
xmlWriter.writeStartDocument(true);
xmlWriter.writeStartElement('', 'root', "xmlns");
xmlWriter.writeString('value&&<\"');
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument()
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="yes"?><root xmlns="xmlns">value&&<\"</root>');
done();
}, 50);
});
});
describe('create single non empty element with writeElementString', (): void => {
let xmlWriter: XmlWriter;
let fileReader: FileReader;
let xmlText: string | ArrayBuffer;
beforeEach((): void => {
/**
* instantiate XmlWriter class
*/
xmlWriter = new XmlWriter();
/**
* creates instance of FileReader class
*/
fileReader = new FileReader();
fileReader.onload = (): void => {
/**
* gets xml text from bolb
*/
xmlText = fileReader.result;
};
jasmine.DEFAULT_TIMEOUT_INTERVAL = 500;
});
afterEach((): void => {
xmlWriter.destroy();
xmlWriter = undefined;
fileReader = undefined;
xmlText = '';
});
it('Prefix,namespace,value as valid string', (done): void => {
xmlWriter.writeElementString(null, 'root', null, 'value');
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root>value</root>');
done();
}, 50);
});
it('Prefix and namespace as null & value as valid string,start document true ', (done): void => {
xmlWriter.writeStartDocument(true);
xmlWriter.writeElementString(null, 'root', null, 'value');
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="yes"?><root>value</root>');
done();
}, 50);
});
it('Prefix and namespace as null & value as valid string,start document false ', (done): void => {
xmlWriter.writeStartDocument(false);
xmlWriter.writeElementString(null, 'root', null, 'value');
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="no"?><root>value</root>');
done();
}, 50);
});
it('Prefix and namespace as null & value as empty,start document empty ', (done): void => {
xmlWriter.writeStartDocument();
xmlWriter.writeElementString(null, 'root', null, '');
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root />');
done();
}, 50);
});
it('Prefix and namespace as null & value as empty,start document true ', (done): void => {
xmlWriter.writeStartDocument(true);
xmlWriter.writeElementString(null, 'root', null, '');
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="yes"?><root />');
done();
}, 50);
});
it('Prefix and namespace as null & value as empty,start document false ', (done): void => {
xmlWriter.writeStartDocument(false);
xmlWriter.writeElementString(null, 'root', null, '');
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="no"?><root />');
done();
}, 50);
});
it('Prefix and namespace as null & value as null,start document empty ', (done): void => {
xmlWriter.writeStartDocument();
xmlWriter.writeElementString(null, 'root', null, null);
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root />');
done();
}, 50);
});
it('Prefix and namespace as null & value as null,start document true ', (done): void => {
xmlWriter.writeStartDocument(true);
xmlWriter.writeElementString(null, 'root', null, null);
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="yes"?><root />');
done();
}, 50);
});
it('Prefix and namespace as null & value as null,start document false ', (done): void => {
xmlWriter.writeStartDocument(false);
xmlWriter.writeElementString(null, 'root', null, null);
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="no"?><root />');
done();
}, 50);
});
it('Prefix and namespace as empty & value as valid string,start document empty ', (done): void => {
xmlWriter.writeStartDocument();
xmlWriter.writeElementString('', 'root', '', 'value');
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root>value</root>');
done();
}, 50);
});
it('Prefix and namespace as empty & value as valid string,start document true ', (done): void => {
xmlWriter.writeStartDocument(true);
xmlWriter.writeElementString('', 'root', '', 'value');
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="yes"?><root>value</root>');
done();
}, 50);
});
it('Prefix and namespace as empty & value as valid string,start document false ', (done): void => {
xmlWriter.writeStartDocument(false);
xmlWriter.writeElementString('', 'root', '', 'value');
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="no"?><root>value</root>');
done();
}, 50);
});
it('Prefix and namespace as empty & value as null,start document empty', (done): void => {
xmlWriter.writeStartDocument();
xmlWriter.writeElementString('', 'root', '', null);
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root />');
done();
}, 50);
});
it('Prefix and namespace as empty & value as null,start document true', (done): void => {
xmlWriter.writeStartDocument(true);
xmlWriter.writeElementString('', 'root', '', null);
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="yes"?><root />');
done();
}, 50);
});
it('Prefix and namespace as empty & value as null,start document false', (done): void => {
xmlWriter.writeStartDocument(false);
xmlWriter.writeElementString('', 'root', '', null);
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="no"?><root />');
done();
}, 50);
});
it('Prefix and namespace as valid string & value as valid string,start document empty ', (done): void => {
xmlWriter.writeStartDocument();
xmlWriter.writeElementString('w', 'root', 'xmlns', 'value');
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><w:root xmlns:w="xmlns">value</w:root>');
done();
}, 50);
});
it('Prefix and namespace as valid string & value as valid string,start document true ', (done): void => {
xmlWriter.writeStartDocument(true);
xmlWriter.writeElementString('w', 'root', 'xmlns', 'value');
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="yes"?><w:root xmlns:w="xmlns">value</w:root>');
done();
}, 50);
});
it('Prefix and namespace as valid string & value as valid string,start document false ', (done): void => {
xmlWriter.writeStartDocument(false);
xmlWriter.writeElementString('w', 'root', 'xmlns', 'value');
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="no"?><w:root xmlns:w="xmlns">value</w:root>');
done();
}, 50);
});
it('Prefix and namespace as valid string & value as empty,start document empty ', (done): void => {
xmlWriter.writeStartDocument();
xmlWriter.writeElementString('w', 'root', 'xmlns', '');
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><w:root xmlns:w="xmlns" />');
done();
}, 50);
});
it('Prefix and namespace as valid string & value as empty,start document true ', (done): void => {
xmlWriter.writeStartDocument(true);
xmlWriter.writeElementString('w', 'root', 'xmlns', '');
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="yes"?><w:root xmlns:w="xmlns" />');
done();
}, 50);
});
it('Prefix and namespace as valid string & value as empty,start document false ', (done): void => {
xmlWriter.writeStartDocument(false);
xmlWriter.writeElementString('w', 'root', 'xmlns', '');
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="no"?><w:root xmlns:w="xmlns" />');
done();
}, 50);
});
it('Prefix and namespace as valid string & value as null,start document empty ', (done): void => {
xmlWriter.writeStartDocument();
xmlWriter.writeElementString('w', 'root', 'xmlns', null);
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><w:root xmlns:w="xmlns" />');
done();
}, 50);
});
it('Prefix and namespace as valid string & value as null,start document true ', (done): void => {
xmlWriter.writeStartDocument(true);
xmlWriter.writeElementString('w', 'root', 'xmlns', null);
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="yes"?><w:root xmlns:w="xmlns" />');
done();
}, 50);
});
it('Prefix as null and namespace as valid string & value as valid string ', (done): void => {
xmlWriter.writeElementString(null, 'root', 'xmlns', 'value');
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root xmlns="xmlns">value</root>');
done();
}, 50);
});
it('Prefix and namespace as valid string & value as null,start document false ', (done): void => {
xmlWriter.writeStartDocument(false);
xmlWriter.writeElementString('w', 'root', 'xmlns', null);
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="no"?><w:root xmlns:w="xmlns" />');
done();
}, 50);
});
it('Prefix as null and namespace as valid string & value as valid string ,start document empty', (done): void => {
xmlWriter.writeStartDocument();
xmlWriter.writeElementString(null, 'root', 'xmlns', 'value');
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root xmlns="xmlns">value</root>');
done();
}, 50);
});
it('Prefix as null and namespace as valid string & value as valid string ,start document false', (done): void => {
xmlWriter.writeStartDocument(false);
xmlWriter.writeElementString(null, 'root', 'xmlns', 'value');
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="no"?><root xmlns="xmlns">value</root>');
done();
}, 50);
});
it('Prefix as null and namespace as valid string & value as valid string ,start document true', (done): void => {
xmlWriter.writeStartDocument(true);
xmlWriter.writeElementString(null, 'root', 'xmlns', 'value');
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="yes"?><root xmlns="xmlns">value</root>');
done();
}, 50);
});
it('Prefix as null and namespace as valid string & value as empty string,start document empty ', (done): void => {
xmlWriter.writeStartDocument();
xmlWriter.writeElementString(null, 'root', 'xmlns', '');
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root xmlns="xmlns" />');
done();
}, 50);
});
it('Prefix as null and namespace as valid string & value as empty string,start document false ', (done): void => {
xmlWriter.writeStartDocument(false);
xmlWriter.writeElementString(null, 'root', 'xmlns', '');
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="no"?><root xmlns="xmlns" />');
done();
}, 50);
});
it('Prefix as null and namespace as valid string & value as empty string,start document true ', (done): void => {
xmlWriter.writeStartDocument(true);
xmlWriter.writeElementString(null, 'root', 'xmlns', '');
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="yes"?><root xmlns="xmlns" />');
done();
}, 50);
});
it('Prefix as null and namespace as valid string & value as null,start document empty', (done): void => {
xmlWriter.writeStartDocument();
xmlWriter.writeElementString(null, 'root', 'xmlns', null);
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root xmlns="xmlns" />');
done();
}, 50);
});
it('Prefix as null and namespace as valid string & value as null,start document false', (done): void => {
xmlWriter.writeStartDocument(false);
xmlWriter.writeElementString(null, 'root', 'xmlns', null);
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="no"?><root xmlns="xmlns" />');
done();
}, 50);
});
it('Prefix as null and namespace as valid string & value as null,start document true', (done): void => {
xmlWriter.writeStartDocument(true);
xmlWriter.writeElementString(null, 'root', 'xmlns', null);
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="yes"?><root xmlns="xmlns" />');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string & value as valid string,start document empty ', (done): void => {
xmlWriter.writeStartDocument();
xmlWriter.writeElementString('', 'root', 'xmlns', 'value');
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root xmlns="xmlns">value</root>');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string & value as valid string,start document false ', (done): void => {
xmlWriter.writeStartDocument(false);
xmlWriter.writeElementString('', 'root', 'xmlns', 'value');
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="no"?><root xmlns="xmlns">value</root>');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string & value as valid string,start document true ', (done): void => {
xmlWriter.writeStartDocument(true);
xmlWriter.writeElementString('', 'root', 'xmlns', 'value');
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="yes"?><root xmlns="xmlns">value</root>');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string & value as empty string,start document empty ', (done): void => {
xmlWriter.writeStartDocument();
xmlWriter.writeElementString('', 'root', 'xmlns', '');
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root xmlns="xmlns" />');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string & value as empty string,start document false ', (done): void => {
xmlWriter.writeStartDocument(false);
xmlWriter.writeElementString('', 'root', 'xmlns', '');
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="no"?><root xmlns="xmlns" />');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string & value as empty string,start document true ', (done): void => {
xmlWriter.writeStartDocument(true);
xmlWriter.writeElementString('', 'root', 'xmlns', '');
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="yes"?><root xmlns="xmlns" />');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string & value as null,start document empty ', (done): void => {
xmlWriter.writeStartDocument();
xmlWriter.writeElementString('', 'root', 'xmlns', null);
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root xmlns="xmlns" />');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string & value as null,start document false ', (done): void => {
xmlWriter.writeStartDocument(false);
xmlWriter.writeElementString('', 'root', 'xmlns', null);
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="no"?><root xmlns="xmlns" />');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string & value as null,start document true ', (done): void => {
xmlWriter.writeStartDocument(true);
xmlWriter.writeElementString('', 'root', 'xmlns', null);
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="yes"?><root xmlns="xmlns" />');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string & value as valid string with special char &,start document empty ', (done): void => {
xmlWriter.writeStartDocument();
xmlWriter.writeElementString('', 'root', 'xmlns', 'value&');
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root xmlns="xmlns">value&</root>');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string & value as valid string with special char &,start document false ', (done): void => {
xmlWriter.writeStartDocument(false);
xmlWriter.writeElementString('', 'root', 'xmlns', 'value&');
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="no"?><root xmlns="xmlns">value&</root>');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string & value as valid string with special char &,start document true ', (done): void => {
xmlWriter.writeStartDocument(true);
xmlWriter.writeElementString('', 'root', 'xmlns', 'value&');
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="yes"?><root xmlns="xmlns">value&</root>');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string & value as valid string with special char <,start document empty ', (done): void => {
xmlWriter.writeStartDocument();
xmlWriter.writeElementString('', 'root', 'xmlns', 'value<');
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root xmlns="xmlns">value<</root>');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string & value as valid string with special char <,start document false ', (done): void => {
xmlWriter.writeStartDocument(false);
xmlWriter.writeElementString('', 'root', 'xmlns', 'value<');
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="no"?><root xmlns="xmlns">value<</root>');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string & value as valid string with special char <,start document true ', (done): void => {
xmlWriter.writeStartDocument(true);
xmlWriter.writeElementString('', 'root', 'xmlns', 'value<');
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="yes"?><root xmlns="xmlns">value<</root>');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string & value as valid string with special char >,start document empty ', (done): void => {
xmlWriter.writeStartDocument();
xmlWriter.writeElementString('', 'root', 'xmlns', 'value>');
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root xmlns="xmlns">value></root>');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string & value as valid string with special char >,start document fasle ', (done): void => {
xmlWriter.writeStartDocument(false);
xmlWriter.writeElementString('', 'root', 'xmlns', 'value>');
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="no"?><root xmlns="xmlns">value></root>');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string & value as valid string with special char >,start document true ', (done): void => {
xmlWriter.writeStartDocument(true);
xmlWriter.writeElementString('', 'root', 'xmlns', 'value>');
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="yes"?><root xmlns="xmlns">value></root>');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string & value as valid string with special char \" ,start document empty', (done): void => {
xmlWriter.writeStartDocument();
xmlWriter.writeElementString('', 'root', 'xmlns', 'value"');
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root xmlns="xmlns">value\"</root>');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string & value as valid string with special char \" ,start document false', (done): void => {
xmlWriter.writeStartDocument(false);
xmlWriter.writeElementString('', 'root', 'xmlns', 'value"');
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="no"?><root xmlns="xmlns">value\"</root>');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string & value as valid string with special char \" ,start document true', (done): void => {
xmlWriter.writeStartDocument(true);
xmlWriter.writeElementString('', 'root', 'xmlns', 'value"');
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="yes"?><root xmlns="xmlns">value\"</root>');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string & value as valid string with special char \',start document empty ', (done): void => {
xmlWriter.writeStartDocument();
xmlWriter.writeElementString('', 'root', 'xmlns', 'value\'');
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root xmlns="xmlns">value\'</root>');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string & value as valid string with special char \',start document flase ', (done): void => {
xmlWriter.writeStartDocument(false);
xmlWriter.writeElementString('', 'root', 'xmlns', 'value\'');
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="no"?><root xmlns="xmlns">value\'</root>');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string & value as valid string with special char \',start document true ', (done): void => {
xmlWriter.writeStartDocument(true);
xmlWriter.writeElementString('', 'root', 'xmlns', 'value\'');
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="yes"?><root xmlns="xmlns">value\'</root>');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string & value as valid string with multiple special character,start document empty', (done): void => {
xmlWriter.writeStartDocument();
xmlWriter.writeElementString('', 'root', 'xmlns', 'value&&<\"');
xmlWriter.writeEndDocument()
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root xmlns="xmlns">value&&<\"</root>');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string & value as valid string with multiple special character,start document false', (done): void => {
xmlWriter.writeStartDocument(false);
xmlWriter.writeElementString('', 'root', 'xmlns', 'value&&<\"');
xmlWriter.writeEndDocument()
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="no"?><root xmlns="xmlns">value&&<\"</root>');
done();
}, 50);
});
it('Prefix as empty and namespace as valid string & value as valid string with multiple special character,start document true', (done): void => {
xmlWriter.writeStartDocument(true);
xmlWriter.writeElementString('', 'root', 'xmlns', 'value&&<\"');
xmlWriter.writeEndDocument()
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="yes"?><root xmlns="xmlns">value&&<\"</root>');
done();
}, 50);
});
});
describe('Create single empty element with single attribute', (): void => {
let xmlWriter: XmlWriter;
let fileReader: FileReader;
let xmlText: string | ArrayBuffer;
beforeEach((): void => {
/**
* instantiate XmlWriter class
*/
xmlWriter = new XmlWriter();
/**
* creates instance of FileReader class
*/
fileReader = new FileReader();
fileReader.onload = (): void => {
/**
* gets xml text from bolb
*/
xmlText = fileReader.result;
};
jasmine.DEFAULT_TIMEOUT_INTERVAL = 500;
});
afterEach((): void => {
xmlWriter = undefined;
fileReader = undefined;
xmlText = '';
});
it('Prefix and namespace as null,attribute\'s - prefix,namespace,value as empty', (done): void => {
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeAttributeString('', 'value', '', '');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root value="" />');
done();
}, 50);
});
it('Prefix and namespace as null,attribute\'s - prefix,namespace,value as null', (done): void => {
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeAttributeString(null, 'value', null, null);
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root value="" />');
done();
}, 50);
});
it('Prefix and namespace as null,attribute\'s - prefix,namespace as empty valueas valid string', (done): void => {
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeAttributeString('', 'value', '', 'data');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root value="data" />');
done();
}, 50);
});
it('Prefix and namespace as null,attribute\'s - prefix,namespace as null value as valid string', (done): void => {
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeAttributeString(null, 'value', null, 'data');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root value="data" />');
done();
}, 50);
});
it('Prefix and namespace as null,attribute\'s - prefix,value as valid string,namespace as empty', (done): void => {
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeAttributeString('w', 'value', '', 'data');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root value="data" />');
done();
}, 50);
});
it('Prefix and namespace as null,attribute\'s - prefix,value as valid string,namespace as null', (done): void => {
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeAttributeString('w', 'value', null, 'data');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root value="data" />');
done();
}, 50);
});
it('Prefix and namespace as null,attribute\'s - prefix as valid string and value,namespace as empty', (done): void => {
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeAttributeString('w', 'value', '', '');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root value="" />');
done();
}, 50);
});
it('Prefix and namespace as null,attribute\'s - prefix as valid string and value,namespace as null', (done): void => {
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeAttributeString('w', 'value', null, null);
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root value="" />');
done();
}, 50);
});
it('Prefix and namespace as null,attribute\'s - prefix,namespace,value as valid string', (done): void => {
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeAttributeString('w', 'value', 'a', 'data');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root w:value="data" xmlns:w="a" />');
done();
}, 50);
});
it('Prefix and namespace as null,attribute\'s - prefix,namespace as valid string and value empty', (done): void => {
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeAttributeString('w', 'value', 'a', '');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root w:value="" xmlns:w="a" />');
done();
}, 50);
});
it('Prefix and namespace as null,attribute\'s - prefix,namespace as valid string and value null', (done): void => {
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeAttributeString('w', 'value', 'a', null);
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root w:value="" xmlns:w="a" />');
done();
}, 50);
});
it('Prefix and namespace as null,attribute\'s - prefix,namespace,value empty', (done): void => {
xmlWriter.writeStartElement(null, 'root', null);
setTimeout((): void => {
expect((): void => { xmlWriter.writeAttributeString('', '', '', ''); }).toThrow(new Error("ArgumentException: localName cannot be undefined, null or empty"));
done();
}, 50);
});
it('Prefix and namespace as null,attribute\'s - prefix,namespace,value null', (done): void => {
xmlWriter.writeStartElement(null, 'root', null);
setTimeout((): void => {
expect((): void => { xmlWriter.writeAttributeString(null, null, null, null); }).toThrow(new Error("ArgumentException: localName cannot be undefined, null or empty"));
done();
}, 50);
});
it('writeAttributeString method before start element', (done): void => {
setTimeout((): void => {
expect((): void => { xmlWriter.writeAttributeString('w', 'root', 'xml', 'data'); }).toThrow(new Error('InvalidOperationException: Wrong Token'));
done();
}, 50);
});
it('Prefix, namespace as null ,localName with valid special character,attribute localName with valid special character', (done): void => {
xmlWriter.writeStartElement(null, 'root_-.', null)
xmlWriter.writeAttributeString(null, 'value_-.', null, 'data');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root_-. value_-.="data" />');
done();
}, 50);
});
it('Prefix, namespace as null ,localName with valid special character,attribute with invalid special character', (done): void => {
xmlWriter.writeStartElement(null, 'root_-.', null)
setTimeout((): void => {
expect((): void => { xmlWriter.writeAttributeString(null, 'value@', null, 'data'); }).toThrow(new Error('InvalidArgumentException: invalid name character'));
done();
}, 50);
});
it('Prefix, namespace as null ,localName with valid string,attribute value with valid special character', (done): void => {
xmlWriter.writeStartElement(null, 'root', null)
xmlWriter.writeAttributeString(null, 'value', null, 'data&\"<>');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root value="data&"<>" />');
done();
}, 50);
});
});
describe('create single non empty element with single attribute', (): void => {
let xmlWriter: XmlWriter;
let fileReader: FileReader;
let xmlText: string | ArrayBuffer;
beforeEach((): void => {
/**
* instantiate XmlWriter class
*/
xmlWriter = new XmlWriter();
/**
* creates instance of FileReader class
*/
fileReader = new FileReader();
fileReader.onload = (): void => {
/**
* gets xml text from bolb
*/
xmlText = fileReader.result;
};
jasmine.DEFAULT_TIMEOUT_INTERVAL = 500;
})
afterEach((): void => {
xmlWriter = undefined;
fileReader = undefined;
xmlText = '';
});
it('Prefix and namespace as null,attribute\'s - prefix,namespace,value as empty,element value - valid string', (done): void => {
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeAttributeString('', 'value', '', '');
xmlWriter.writeString('element');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root value="">element</root>');
done();
}, 50);
});
it('Prefix and namespace as null,attribute\'s - prefix,namespace,value as null,element value - valid string', (done): void => {
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeAttributeString(null, 'value', null, null);
xmlWriter.writeString('element');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root value="">element</root>');
done();
}, 50);
});
it('Prefix and namespace as null,attribute\'s - prefix,namespace as empty valueas valid string,element value - valid string', (done): void => {
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeAttributeString('', 'value', '', 'data');
xmlWriter.writeString('element');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root value="data">element</root>');
done();
}, 50);
});
it('Prefix and namespace as null,attribute\'s - prefix,namespace as null value as valid string,element value - valid string', (done): void => {
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeAttributeString(null, 'value', null, 'data');
xmlWriter.writeString('element');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root value="data">element</root>');
done();
}, 50);
});
it('Prefix and namespace as null,attribute\'s - prefix,value as valid string,namespace as empty,element value - valid string', (done): void => {
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeAttributeString('w', 'value', '', 'data');
xmlWriter.writeString('element');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root value="data">element</root>');
done();
}, 50);
});
it('Prefix and namespace as null,attribute\'s - prefix,value as valid string,namespace as null,element value - valid string', (done): void => {
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeAttributeString('w', 'value', null, 'data');
xmlWriter.writeString('element');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root value="data">element</root>');
done();
}, 50);
});
it('Prefix and namespace as null,attribute\'s - prefix as valid string and value,namespace as empty,element value - valid string', (done): void => {
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeAttributeString('w', 'value', '', '');
xmlWriter.writeString('element');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root value="">element</root>');
done();
}, 50);
});
it('Prefix and namespace as null,attribute\'s - prefix as valid string and value,namespace as null,element value - valid string', (done): void => {
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeAttributeString('w', 'value', null, null);
xmlWriter.writeString('element');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root value="">element</root>');
done();
}, 50);
});
it('Prefix and namespace as null,attribute\'s - prefix,namespace,value as valid string,element value - valid string', (done): void => {
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeAttributeString('w', 'value', 'a', 'data');
xmlWriter.writeString('element');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root w:value="data" xmlns:w="a">element</root>');
done();
}, 50);
});
it('Prefix and namespace as null,attribute\'s - prefix,namespace as valid string and value empty,element value - valid string', (done): void => {
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeAttributeString('w', 'value', 'a', '');
xmlWriter.writeString('element');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root w:value="" xmlns:w="a">element</root>');
done();
}, 50);
});
it('Prefix and namespace as null,attribute\'s - prefix,namespace as valid string and value null,element value - valid string', (done): void => {
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeAttributeString('w', 'value', 'a', null);
xmlWriter.writeString('element');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root w:value="" xmlns:w="a">element</root>');
done();
}, 50);
});
it('Prefix and namespace as null,attribute\'s - prefix,namespace,value empty,element value - valid string', (done): void => {
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeString('element');
setTimeout((): void => {
expect((): void => { xmlWriter.writeAttributeString('', '', '', ''); }).toThrow(new Error("ArgumentException: localName cannot be undefined, null or empty"));
done();
}, 50);
});
it('Prefix and namespace as null,attribute\'s - prefix,namespace,value null,element value - valid string', (done): void => {
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeString('element');
setTimeout((): void => {
expect((): void => { xmlWriter.writeAttributeString(null, null, null, null); }).toThrow(new Error("ArgumentException: localName cannot be undefined, null or empty"));
done();
}, 50);
});
it('Prefix, namespace as null ,localName with valid special character,attribute localName with valid special character,element value - valid string', (done): void => {
xmlWriter.writeStartElement(null, 'root_-.', null)
xmlWriter.writeAttributeString(null, 'value_-.', null, 'data');
xmlWriter.writeString('element');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root_-. value_-.="data">element</root_-.>');
done();
}, 50);
});
it('Prefix, namespace as null ,localName with valid special character,attribute with invalid special character,element value - valid string', (done): void => {
xmlWriter.writeStartElement(null, 'root_-.', null)
xmlWriter.writeString('element');
setTimeout((): void => {
expect((): void => { xmlWriter.writeAttributeString(null, 'value@', null, 'data'); }).toThrow(new Error('InvalidOperationException: Wrong Token'));
done();
}, 50);
});
it('Prefix, namespace as null ,localName with valid string,attribute value with valid special character,element value - valid string', (done): void => {
xmlWriter.writeStartElement(null, 'root', null)
xmlWriter.writeAttributeString(null, 'value', null, 'data&\"<>');
xmlWriter.writeString('element');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root value="data&"<>">element</root>');
done();
}, 50);
});
it('Prefix and namespace as null,attribute\'s - prefix,namespace,value as empty,element value - valid string', (done): void => {
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeAttributeString('', 'value', '', '');
xmlWriter.writeString('');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root value=""></root>');
done();
}, 50);
});
it('Prefix and namespace as null,attribute\'s - prefix,namespace,value as null,element value - valid string', (done): void => {
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeAttributeString(null, 'value', null, null);
xmlWriter.writeString('');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root value=""></root>');
done();
}, 50);
});
it('Prefix and namespace as null,attribute\'s - prefix,namespace as empty valueas valid string,element value - valid string', (done): void => {
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeAttributeString('', 'value', '', 'data');
xmlWriter.writeString('');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root value="data"></root>');
done();
}, 50);
});
it('Prefix and namespace as null,attribute\'s - prefix,namespace as null value as valid string,element value - valid string', (done): void => {
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeAttributeString(null, 'value', null, 'data');
xmlWriter.writeString('');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root value="data"></root>');
done();
}, 50);
});
it('Prefix and namespace as null,attribute\'s - prefix,value as valid string,namespace as empty,element value - valid string', (done): void => {
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeAttributeString('w', 'value', '', 'data');
xmlWriter.writeString('');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root value="data"></root>');
done();
}, 50);
});
it('Prefix and namespace as null,attribute\'s - prefix,value as valid string,namespace as null,element value - valid string', (done): void => {
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeAttributeString('w', 'value', null, 'data');
xmlWriter.writeString('');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root value="data"></root>');
done();
}, 50);
});
it('Prefix and namespace as null,attribute\'s - prefix as valid string and value,namespace as empty,element value - valid string', (done): void => {
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeAttributeString('w', 'value', '', '');
xmlWriter.writeString('');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root value=""></root>');
done();
}, 50);
});
it('Prefix and namespace as null,attribute\'s - prefix as valid string and value,namespace as null,element value - valid string', (done): void => {
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeAttributeString('w', 'value', null, null);
xmlWriter.writeString('');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root value=""></root>');
done();
}, 50);
});
it('Prefix and namespace as null,attribute\'s - prefix,namespace,value as valid string,element value - valid string', (done): void => {
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeAttributeString('w', 'value', 'a', 'data');
xmlWriter.writeString('');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root w:value="data" xmlns:w="a"></root>');
done();
}, 50);
});
it('Prefix and namespace as null,attribute\'s - prefix,namespace as valid string and value empty,element value - valid string', (done): void => {
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeAttributeString('w', 'value', 'a', '');
xmlWriter.writeString('');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root w:value="" xmlns:w="a"></root>');
done();
}, 50);
});
it('Prefix and namespace as null,attribute\'s - prefix,namespace as valid string and value null,element value - valid string', (done): void => {
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeAttributeString('w', 'value', 'a', null);
xmlWriter.writeString('');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root w:value="" xmlns:w="a"></root>');
done();
}, 50);
});
it('Prefix and namespace as null,attribute\'s - prefix,namespace,value empty,element value - valid string', (done): void => {
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeString('');
setTimeout((): void => {
expect((): void => { xmlWriter.writeAttributeString('', '', '', ''); }).toThrow(new Error("ArgumentException: localName cannot be undefined, null or empty"));
done();
}, 50);
});
it('Prefix and namespace as null,attribute\'s - prefix,namespace,value null,element value - valid string', (done): void => {
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeString('');
setTimeout((): void => {
expect((): void => { xmlWriter.writeAttributeString(null, null, null, null); }).toThrow(new Error("ArgumentException: localName cannot be undefined, null or empty"));
done();
}, 50);
});
it('Prefix, namespace as null ,localName with valid special character,attribute localName with valid special character,element value - valid string', (done): void => {
xmlWriter.writeStartElement(null, 'root_-.', null)
xmlWriter.writeAttributeString(null, 'value_-.', null, 'data');
xmlWriter.writeString('');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root_-. value_-.="data"></root_-.>');
done();
}, 50);
});
it('Prefix, namespace as null ,localName with valid special character,attribute with invalid special character,element value - valid string', (done): void => {
xmlWriter.writeStartElement(null, 'root_-.', null)
xmlWriter.writeString('');
setTimeout((): void => {
expect((): void => { xmlWriter.writeAttributeString(null, 'value@', null, 'data'); }).toThrow(new Error('InvalidOperationException: Wrong Token'));
done();
}, 50);
});
it('Prefix, namespace as null ,localName with valid string,attribute value with valid special character,element value - valid string', (done): void => {
xmlWriter.writeStartElement(null, 'root', null)
xmlWriter.writeAttributeString(null, 'value', null, 'data&\"<>');
xmlWriter.writeString('');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root value="data&"<>"></root>');
done();
}, 50);
});
it('Prefix and namespace as null,attribute\'s - prefix,namespace,value as empty,element value - as null', (done): void => {
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeAttributeString('', 'value', '', '');
xmlWriter.writeString(null);
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root value="" />');
done();
}, 50);
});
it('Prefix and namespace as null,attribute\'s - prefix,namespace,value as null,element value - as null', (done): void => {
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeAttributeString(null, 'value', null, null);
xmlWriter.writeString(null);
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root value="" />');
done();
}, 50);
});
it('Prefix and namespace as null,attribute\'s - prefix,namespace as empty valueas valid string,element value - as null', (done): void => {
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeAttributeString('', 'value', '', 'data');
xmlWriter.writeString(null);
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root value="data" />');
done();
}, 50);
});
it('Prefix and namespace as null,attribute\'s - prefix,namespace as null value as valid string,element value - as null', (done): void => {
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeAttributeString(null, 'value', null, 'data');
xmlWriter.writeString(null);
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root value="data" />');
done();
}, 50);
});
it('Prefix and namespace as null,attribute\'s - prefix,value as valid string,namespace as empty,element value - as null', (done): void => {
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeAttributeString('w', 'value', '', 'data');
xmlWriter.writeString(null);
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root value="data" />');
done();
}, 50);
});
it('Prefix and namespace as null,attribute\'s - prefix,value as valid string,namespace as null,element value - as null', (done): void => {
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeAttributeString('w', 'value', null, 'data');
xmlWriter.writeString(null);
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root value="data" />');
done();
}, 50);
});
it('Prefix and namespace as null,attribute\'s - prefix as valid string and value,namespace as empty,element value - as null', (done): void => {
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeAttributeString('w', 'value', '', '');
xmlWriter.writeString(null);
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root value="" />');
done();
}, 50);
});
it('Prefix and namespace as null,attribute\'s - prefix as valid string and value,namespace as null,element value - as null', (done): void => {
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeAttributeString('w', 'value', null, null);
xmlWriter.writeString(null);
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root value="" />');
done();
}, 50);
});
it('Prefix and namespace as null,attribute\'s - prefix,namespace,value as valid string,element value - as null', (done): void => {
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeAttributeString('w', 'value', 'a', 'data');
xmlWriter.writeString(null);
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root w:value="data" xmlns:w="a" />');
done();
}, 50);
});
it('Prefix and namespace as null,attribute\'s - prefix,namespace as valid string and value empty,element value - as null', (done): void => {
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeAttributeString('w', 'value', 'a', '');
xmlWriter.writeString(null);
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root w:value="" xmlns:w="a" />');
done();
}, 50);
});
it('Prefix and namespace as null,attribute\'s - prefix,namespace as valid string and value null,element value - as null', (done): void => {
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeAttributeString('w', 'value', 'a', null);
xmlWriter.writeString(null);
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root w:value="" xmlns:w="a" />');
done();
}, 50);
});
it('Prefix and namespace as null,attribute\'s - prefix,namespace,value empty,element value - as null', (done): void => {
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeString(null);
setTimeout((): void => {
expect((): void => { xmlWriter.writeAttributeString('', '', '', ''); }).toThrow(new Error("ArgumentException: localName cannot be undefined, null or empty"));
done();
}, 50);
});
it('Prefix and namespace as null,attribute\'s - prefix,namespace,value null,element value - as null', (done): void => {
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeString(null);
setTimeout((): void => {
expect((): void => { xmlWriter.writeAttributeString(null, null, null, null); }).toThrow(new Error("ArgumentException: localName cannot be undefined, null or empty"));
done();
}, 50);
});
it('Prefix, namespace as null ,localName with valid special character,attribute localName with valid special character,element value - as null', (done): void => {
xmlWriter.writeStartElement(null, 'root_-.', null)
xmlWriter.writeAttributeString(null, 'value_-.', null, 'data');
xmlWriter.writeString(null);
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root_-. value_-.="data" />');
done();
}, 50);
});
it('Prefix, namespace as null ,localName with valid special character,attribute with invalid special character,element value - as null', (done): void => {
xmlWriter.writeStartElement(null, 'root_-.', null)
xmlWriter.writeString(null);
setTimeout((): void => {
expect((): void => { xmlWriter.writeAttributeString(null, 'value@', null, 'data'); }).toThrow(new Error('InvalidArgumentException: invalid name character'));
done();
}, 50);
});
it('Prefix, namespace as null ,localName with valid string,attribute value with valid special character,element value - as null', (done): void => {
xmlWriter.writeStartElement(null, 'root', null)
xmlWriter.writeAttributeString(null, 'value', null, 'data&\"<>');
xmlWriter.writeString(null);
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root value="data&"<>" />');
done();
}, 50);
});
it('Prefix, namespace as null ,localName with valid string,attribute with Prefix ="xmlns",namespace,localName as empty', (done): void => {
xmlWriter.writeStartElement(null, "book", null);
xmlWriter.writeAttributeString("xmlns", "", "", "");
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><book xmlns="" />');
done();
}, 50);
});
it('Prefix, namespace as null ,localName with valid string,attribute with Prefix ="xmlns",namespace,localName as null', (done): void => {
xmlWriter.writeStartElement(null, "book", null);
xmlWriter.writeAttributeString("xmlns", null, null, null);
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><book xmlns="" />');
done();
}, 50);
});
it('Prefix, namespace as null ,localName with valid string,attribute with localName ="xmlns",namespace as http://www.w3.org/2000/xmlns/ ,prefix as null', (done): void => {
xmlWriter.writeStartElement(null, "book", null);
xmlWriter.writeAttributeString(null, "xmlns", 'http://www.w3.org/2000/xmlns/', null);
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><book xmlns="" />');
done();
}, 50);
});
it('Prefix, namespace as null ,localName with valid string,attribute with Prefix ="xml",namespace,localName as null', (done): void => {
xmlWriter.writeStartElement(null, "book", null);
xmlWriter.writeAttributeString("xml", "space", 'http://www.w3.org/XML/1998/namespace', 'preserve');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><book xml:space="preserve" />');
done();
}, 50);
});
it('Prefix, namespace as null ,localName with valid string,attribute with Prefix ="xml" & "xmlns",namespace,localName as null', (done): void => {
xmlWriter.writeStartElement(null, "book", null);
xmlWriter.writeAttributeString(null, "xmlns", 'http://www.w3.org/2000/xmlns/', null);
xmlWriter.writeAttributeString("xml", "space", 'http://www.w3.org/XML/1998/namespace', 'preserve');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><book xmlns="" xml:space="preserve" />');
done();
}, 50);
});
it('Prefix, namespace as null ,localName with valid string,attribute with Prefix ="xml",namespace,localName as null', (done): void => {
xmlWriter.writeStartElement(null, "book", null);
xmlWriter.writeAttributeString("xmlspace", "space", 'data', 'preserve');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><book xmlspace:space="preserve" xmlns:xmlspace="data" />');
done();
}, 50);
});
it('Prefix, namespace as null ,localName with valid string,attribute with Prefix ="xml",namespace,localName as null', (done): void => {
xmlWriter.writeStartElement(null, "book", null);
xmlWriter.writeAttributeString("xml", "space", 'http://www.w3.org/XML/1998/namespace', 'default');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><book xml:space="default" />');
done();
}, 50);
});
it('Prefix, namespace as null ,localName with valid string,attribute with Prefix ="xml",namespace,localName ', (done): void => {
xmlWriter.writeStartElement(null, "book", null);
xmlWriter.writeAttributeString("xml", "lang", 'http://www.w3.org/XML/1998/namespace', 'default');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><book xml:lang="default" />');
done();
}, 50);
});
it('Prefix, namespace as null ,localName with valid string,attribute with Prefix ="xml",namespace,localName ', (done): void => {
xmlWriter.writeStartElement(null, "book", null);
xmlWriter.writeAttributeString("xml", "b", 'http://www.w3.org/XML/1998/namespace', 'default');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><book xml:b="default" />');
done();
}, 50);
});
});
describe('Create multiple non empty element with attribute', (): void => {
let xmlWriter: XmlWriter;
let fileReader: FileReader;
let xmlText: string | ArrayBuffer;
beforeEach((): void => {
/**
* instantiate XmlWriter class
*/
xmlWriter = new XmlWriter();
/**
* creates instance of FileReader class
*/
fileReader = new FileReader();
fileReader.onload = (): void => {
/**
* gets xml text from bolb
*/
xmlText = fileReader.result;
};
jasmine.DEFAULT_TIMEOUT_INTERVAL = 500;
});
afterEach((): void => {
xmlWriter = undefined;
fileReader = undefined;
xmlText = '';
});
it('Element\'s and attribute\'s Prefix,namespace as null', (done): void => {
xmlWriter.writeStartElement(null, "book", null);
xmlWriter.writeAttributeString(null, "bk", null, "urn:samples");
xmlWriter.writeAttributeString(null, "genre", null, "novel");
xmlWriter.writeStartElement(null, "title", null);
xmlWriter.writeString("The Handmaid's Tale");
xmlWriter.writeEndElement();
xmlWriter.writeElementString(null, "price", null, "19.95");
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><book bk="urn:samples" genre="novel">' +
'<title>The Handmaid\'s Tale</title><price>19.95</price></book>');
done();
}, 50);
});
it('Element\'s and attribute\'s Prefix,namespace as empty', (done): void => {
xmlWriter.writeStartElement('', "book", '');
xmlWriter.writeAttributeString('', "bk", '', "urn:samples");
xmlWriter.writeAttributeString('', "genre", '', "novel");
xmlWriter.writeStartElement('', "title", '');
xmlWriter.writeString("The Handmaid's Tale");
xmlWriter.writeEndElement();
xmlWriter.writeElementString('', "price", '', "19.95");
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><book bk="urn:samples" genre="novel">' +
'<title>The Handmaid\'s Tale</title><price>19.95</price></book>');
done();
}, 50);
});
it('Element\'s Prefix as null,namespace as valid string and attribute\'s Prefix ,namespace null', (done): void => {
xmlWriter.writeStartElement(null, "book", 'xml');
xmlWriter.writeAttributeString(null, "bk", null, "urn:samples");
xmlWriter.writeAttributeString(null, "genre", null, "novel");
xmlWriter.writeStartElement(null, "title", null);
xmlWriter.writeString("The Handmaid's Tale");
xmlWriter.writeEndElement();
xmlWriter.writeElementString(null, "price", null, "19.95");
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><book bk="urn:samples" genre="novel" xmlns="xml">' +
'<title>The Handmaid\'s Tale</title><price>19.95</price></book>');
done();
}, 50);
});
it('Element\'s Prefix as empty,namespace as valid string and attribute\'s Prefix ,namespace null', (done): void => {
xmlWriter.writeStartElement('', "book", 'xml');
xmlWriter.writeAttributeString(null, "bk", null, "urn:samples");
xmlWriter.writeAttributeString(null, "genre", null, "novel");
xmlWriter.writeStartElement(null, "title", null);
xmlWriter.writeString("The Handmaid's Tale");
xmlWriter.writeEndElement();
xmlWriter.writeElementString(null, "price", null, "19.95");
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><book bk="urn:samples" genre="novel" xmlns="xml">' +
'<title>The Handmaid\'s Tale</title><price>19.95</price></book>');
done();
}, 50);
});
it('Element\'s Prefix as null,namespace as valid string and attribute\'s Prefix ,namespace empty', (done): void => {
xmlWriter.writeStartElement(null, "book", 'xml');
xmlWriter.writeAttributeString('', "bk", '', "urn:samples");
xmlWriter.writeAttributeString('', "genre", '', "novel");
xmlWriter.writeStartElement(null, "title", null);
xmlWriter.writeString("The Handmaid's Tale");
xmlWriter.writeEndElement();
xmlWriter.writeElementString(null, "price", null, "19.95");
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><book bk="urn:samples" genre="novel" xmlns="xml">' +
'<title>The Handmaid\'s Tale</title><price>19.95</price></book>');
done();
}, 50);
});
it('Element\'s prefix,namespace as null and attribute\'s Prefix ,namespace as valid empty', (done): void => {
xmlWriter.writeStartElement(null, "book", null);
xmlWriter.writeAttributeString('w', "bk", 'xmlns', "urn:samples");
xmlWriter.writeAttributeString('s', "genre", 'xml', "novel");
xmlWriter.writeStartElement(null, "title", null);
xmlWriter.writeString("The Handmaid's Tale");
xmlWriter.writeEndElement();
xmlWriter.writeElementString(null, "price", null, "19.95");
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><book w:bk="urn:samples" s:genre="novel" xmlns:s="xml" xmlns:w="xmlns"><title>The Handmaid\'s Tale</title><price>19.95</price></book>');
done();
}, 50);
});
it('Element\'s prefix,namespace as null and attribute\'s Prefix ,namespace as valid empty with multiple attribute', (done): void => {
xmlWriter.writeStartElement("", "book", "");
xmlWriter.writeAttributeString("w", "bk", "xmlns", "urn:samples");
xmlWriter.writeAttributeString("s", "genre", "xml", "novel");
xmlWriter.writeStartElement(null, "title", null);
xmlWriter.writeStartElement(null, "author", null);
xmlWriter.writeStartElement(null, "country", null);
xmlWriter.writeAttributeString("xmlns", "bk", "http://www.w3.org/2000/xmlns/", "urn:samples");
xmlWriter.writeString("tagore");
xmlWriter.writeEndElement();
xmlWriter.writeEndElement();
xmlWriter.writeEndElement();
xmlWriter.writeElementString("", "price", "", "19.95");
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><book w:bk="urn:samples" s:genre="novel" xmlns:s="xml" xmlns:w="xmlns"><title><author><country xmlns:bk="urn:samples">tagore</country></author></title><price>19.95</price></book>');
done();
}, 50);
});
it('Element\'s prefix,namespace as null and attribute\'s Prefix ,namespace as valid empty with multiple attribute with same namespace', (done): void => {
xmlWriter.writeStartElement("", "book", "");
xmlWriter.writeAttributeString("w", "bk", "xmlns", "urn:samples");
xmlWriter.writeAttributeString("s", "genre", "xml", "novel");
xmlWriter.writeStartElement(null, "title", null);
xmlWriter.writeStartElement(null, "author", null);
xmlWriter.writeStartElement(null, "country", null);
xmlWriter.writeAttributeString("xmlns", "s", "http://www.w3.org/2000/xmlns/", "urn:samples");
xmlWriter.writeString("tagore");
xmlWriter.writeEndElement();
xmlWriter.writeEndElement();
xmlWriter.writeEndElement();
xmlWriter.writeElementString("", "price", "", "19.95");
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><book w:bk="urn:samples" s:genre="novel" xmlns:s="xml" xmlns:w="xmlns"><title><author><country xmlns:s="urn:samples">tagore</country></author></title><price>19.95</price></book>');
done();
}, 50);
});
it('Nested get prefix from parent element', (done): void => {
xmlWriter.writeStartElement(null, "book", null);
xmlWriter.writeAttributeString("xmlns", "bk", null, "urn:samples");
xmlWriter.writeAttributeString(null, "genre", null, "novel");
xmlWriter.writeStartElement(null, "title", null);
xmlWriter.writeString("The Handmaid's Tale");
xmlWriter.writeEndElement();
xmlWriter.writeElementString(null, "price", null, "19.95");
xmlWriter.writeStartElement(null, "ISBN", "urn:samples");
xmlWriter.writeString("1-861003-78");
xmlWriter.writeEndElement();
xmlWriter.writeElementString(null, "style", "urn:samples", "hardcover");
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><book xmlns:bk="urn:samples" genre="novel"><title>The Handmaid\'s Tale</title><price>19.95</price><bk:ISBN>1-861003-78</bk:ISBN><bk:style>hardcover</bk:style></book>');
done();
}, 50);
});
it('End Document without EndElement', (done): void => {
xmlWriter.writeStartElement(null, "book", null);
xmlWriter.writeAttributeString('w', "bk", 'xmlns', "urn:samples");
xmlWriter.writeAttributeString('s', "genre", 'xml', "novel");
xmlWriter.writeElementString(null, "price", null, "19.95");
xmlWriter.writeStartElement(null, "title", null);
xmlWriter.writeString("The Handmaid's Tale");
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><book w:bk="urn:samples" s:genre="novel" xmlns:s="xml" xmlns:w="xmlns"><price>19.95</price><title>The Handmaid\'s Tale</title></book>');
done();
}, 50);
});
it('duplicae attributes validation', (done): void => {
xmlWriter.writeStartElement(null, "book", null);
xmlWriter.writeAttributeString('w', "bk", 'xmlns', "urn:samples");
setTimeout((): void => {
expect((): void => { xmlWriter.writeAttributeString('w', "bk", 'xmlns', "urn:samples") }).toThrow(new Error('XmlException: duplicate attribute name'));
done();
}, 50);
});
it('Element Prefix = Xmlns reserved key word', (done): void => {
setTimeout((): void => {
expect((): void => { xmlWriter.writeStartElement('xmlns', 'root', 'data') }).toThrow(new Error('InvalidArgumentException: Prefix "xmlns" is reserved for use by XML.'));
done();
}, 50);
});
it('Element\'s Prefix as null,namespace as valid string and attribute\'s Prefix ,namespace as valid string', (done): void => {
xmlWriter.writeStartElement(null, "book", 'xml');
xmlWriter.writeAttributeString(null, "bk", null, "urn:samples");
xmlWriter.writeAttributeString(null, "genre", null, "novel");
xmlWriter.writeStartElement(null, "title", null);
xmlWriter.writeString("The Handmaid's Tale");
xmlWriter.writeEndElement();
xmlWriter.writeElementString(null, "price", null, "19.95");
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><book bk="urn:samples" genre="novel" xmlns="xml">' +
'<title>The Handmaid\'s Tale</title><price>19.95</price></book>');
done();
}, 50);
});
it('Element with multiple namespace and attribute', (done) => {
xmlWriter.writeStartElement("w", "Document", "xmlns");
xmlWriter.writeAttributeString(null, "child", "xmlns", "section");
xmlWriter.writeAttributeString(null, "childNode", "xmlns", "Format");
xmlWriter.writeAttributeString(null, "leaf", "xmlns", "last");
xmlWriter.writeStartElement("w", "Block", "Xmlns");
xmlWriter.writeAttributeString(null, "child", "xls", "paragraph");
xmlWriter.writeEndElement();
xmlWriter.writeElementString("g", "base", "xml", "node");
xmlWriter.writeElementString(null, "build", "xmlns", "compile");
xmlWriter.writeElementString(null, "build", "xml", "compile");
xmlWriter.writeElementString(null, "build", "xml", "compile");
xmlWriter.writeStartElement(null, "paragraph", "xmlns");
xmlWriter.writeStartElement("p", "paragraph", "xmlns");
xmlWriter.writeStartElement("r", "Table", "xmlns");
xmlWriter.writeStartElement("q", "image", "xmlns");
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><w:Document w:child="section" w:childNode="Format" w:leaf="last" xmlns:w="xmlns"><w:Block child="paragraph" xmlns:w="Xmlns" /><g:base xmlns:g="xml">node</g:base><w:build>compile</w:build><build xmlns="xml">compile</build><build xmlns="xml">compile</build><w:paragraph><p:paragraph xmlns:p="xmlns"><r:Table xmlns:r="xmlns"><q:image xmlns:q="xmlns" /></r:Table></p:paragraph></w:paragraph></w:Document>');
done();
}, 50);
});
it('Attribute with same prefix different namespace ', (done): void => {
xmlWriter.writeStartElement(null, "book", null);
xmlWriter.writeAttributeString('w', "bk", 'xmlns', "urn:samples");
setTimeout((): void => {
expect((): void => { xmlWriter.writeAttributeString('w', "genre", 'xml', "novel"); }).toThrow(new Error('XmlException namespace Uri needs to be the same as the one that is already declared'));
done();
}, 50);
});
it('Attribute same namespace different prefix ', (done): void => {
xmlWriter.writeStartElement(null, "From", null);
xmlWriter.writeAttributeString('w', "lang", 'xmlns', 'uri:sample');
setTimeout((): void => {
expect((): void => { xmlWriter.writeAttributeString('z', "lang", 'xmlns', 'mug:sample'); }).toThrow(new Error('XmlException: duplicate attribute name'));
done();
}, 50);
});
it('prefix and namespace with predifferent namespace', (done): void => {
xmlWriter.writeStartDocument(true);
xmlWriter.writeStartElement('w', 'document', 'http://schemas.openxmlformats.org/wordprocessingml/2006/main');
xmlWriter.writeAttributeString(null, 'wpc', 'http://www.w3.org/2000/xmlns/', 'http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas');
xmlWriter.writeStartElement(null, 'body', 'http://schemas.openxmlformats.org/wordprocessingml/2006/main');
xmlWriter.writeStartElement(null, 'p', 'http://schemas.openxmlformats.org/wordprocessingml/2006/main');
xmlWriter.writeAttributeString(null, 'rsidR', 'http://schemas.openxmlformats.org/wordprocessingml/2006/main', '00400719');
xmlWriter.writeAttributeString(null, 'rsidRDefault', 'http://schemas.openxmlformats.org/wordprocessingml/2006/main', '00400719');
xmlWriter.writeStartElement(null, 'r', 'http://schemas.openxmlformats.org/wordprocessingml/2006/main');
xmlWriter.writeStartElement(null, 't', 'http://schemas.openxmlformats.org/wordprocessingml/2006/main');
xmlWriter.writeString('word');
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="yes"?><w:document xmlns:wpc="http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body><w:p w:rsidR="00400719" w:rsidRDefault="00400719"><w:r><w:t>word</w:t></w:r></w:p></w:body></w:document>');
done();
}, 50);
});
it('prefix and namespace with predifferent namespace and prefix', (done): void => {
xmlWriter.writeStartDocument(true);
xmlWriter.writeStartElement('w', 'document', 'http://schemas.openxmlformats.org/wordprocessingml/2006/main');
xmlWriter.writeAttributeString(null, 'wpc', 'http://www.w3.org/2000/xmlns/', 'http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas');
xmlWriter.writeStartElement(null, 'body', 'http://schemas.openxmlformats.org/wordprocessingml/2006/main');
xmlWriter.writeStartElement(null, 'p', 'http://schemas.openxmlformats.org/wordprocessingml/2006/main');
xmlWriter.writeAttributeString(null, 'rsidR', 'http://schemas.openxmlformats.org/wordprocessingml/2006/main', '00400719');
xmlWriter.writeAttributeString(null, 'rsidRDefault', 'http://schemas.openxmlformats.org/wordprocessingml/2006/main', '00400719');
xmlWriter.writeStartElement(null, 'r', 'http://schemas.openxmlformats.org/wordprocessingml/2006/main');
xmlWriter.writeStartElement(null, 't', 'http://schemas.openxmlformats.org/wordprocessingml/2006/main');
xmlWriter.writeString('word');
xmlWriter.writeStartElement('w', 'i', null);
xmlWriter.writeString('word');
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="yes"?><w:document xmlns:wpc="http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body><w:p w:rsidR="00400719" w:rsidRDefault="00400719"><w:r><w:t>word<w:i>word</w:i></w:t></w:r></w:p></w:body></w:document>');
done();
}, 50);
});
it('prefix and namespace with predifferent namespace and prefix writeStartElement after writeString', (done): void => {
xmlWriter.writeStartDocument(true);
xmlWriter.writeStartElement('w', 'document', 'http://schemas.openxmlformats.org/wordprocessingml/2006/main');
xmlWriter.writeAttributeString(null, 'wpc', 'http://www.w3.org/2000/xmlns/', 'http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas');
xmlWriter.writeStartElement(null, 'body', 'http://schemas.openxmlformats.org/wordprocessingml/2006/main');
xmlWriter.writeStartElement(null, 'p', 'http://schemas.openxmlformats.org/wordprocessingml/2006/main');
xmlWriter.writeAttributeString(null, 'rsidR', 'http://schemas.openxmlformats.org/wordprocessingml/2006/main', '00400719');
xmlWriter.writeAttributeString(null, 'rsidRDefault', 'http://schemas.openxmlformats.org/wordprocessingml/2006/main', '00400719');
xmlWriter.writeStartElement(null, 'r', 'http://schemas.openxmlformats.org/wordprocessingml/2006/main');
xmlWriter.writeStartElement(null, 't', 'http://schemas.openxmlformats.org/wordprocessingml/2006/main');
xmlWriter.writeString('word');
xmlWriter.writeStartElement('w', 'i', null);
xmlWriter.writeString('word');
xmlWriter.writeEndDocument();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8" standalone="yes"?><w:document xmlns:wpc="http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body><w:p w:rsidR="00400719" w:rsidRDefault="00400719"><w:r><w:t>word<w:i>word</w:i></w:t></w:r></w:p></w:body></w:document>');
done();
}, 50);
});
});
describe('save xml document and destroy XmlWriter class', (): void => {
let xmlWriter: XmlWriter;
let fileReader: FileReader;
let xmlText: string | ArrayBuffer;
beforeEach((): void => {
/**
* instantiate XmlWriter class
*/
xmlWriter = new XmlWriter();
/**
* creates instance of FileReader class
*/
fileReader = new FileReader();
fileReader.onload = (): void => {
/**
* gets xml text from bolb
*/
xmlText = fileReader.result;
};
jasmine.DEFAULT_TIMEOUT_INTERVAL = 500;
});
afterEach((): void => {
xmlWriter.destroy();
xmlWriter = undefined;
fileReader = undefined;
xmlText = '';
});
it('Save blob as xml file', (done): void => {
xmlWriter.writeStartElement(null, "book", null);
xmlWriter.writeAttributeString(null, "bk", null, "urn:samples");
xmlWriter.writeAttributeString(null, "genre", null, "novel");
for (let i: number = 0; i < 500; i++) {
xmlWriter.writeStartElement(null, "title", null);
xmlWriter.writeString("The Handmaid's Tale");
xmlWriter.writeEndElement();
xmlWriter.writeElementString(null, "price", null, "19.95");
}
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(() => { xmlWriter.save(undefined); }).toThrowError();
done();
}, 50);
});
it('Save blob as xml file,without writeEndDocument or writeEndElement', (done): void => {
xmlWriter.writeStartDocument(true);
xmlWriter.writeStartElement('w', 'document', 'http://schemas.openxmlformats.org/wordprocessingml/2006/main');
xmlWriter.writeAttributeString(null, 'wpc', 'http://www.w3.org/2000/xmlns/', 'http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas');
xmlWriter.writeStartElement(null, 'body', 'http://schemas.openxmlformats.org/wordprocessingml/2006/main');
xmlWriter.writeStartElement(null, 'p', 'http://schemas.openxmlformats.org/wordprocessingml/2006/main');
xmlWriter.writeAttributeString(null, 'rsidR', 'http://schemas.openxmlformats.org/wordprocessingml/2006/main', '00400719');
xmlWriter.writeAttributeString(null, 'rsidRDefault', 'http://schemas.openxmlformats.org/wordprocessingml/2006/main', '00400719');
xmlWriter.writeStartElement(null, 'r', 'http://schemas.openxmlformats.org/wordprocessingml/2006/main');
xmlWriter.writeStartElement(null, 't', 'http://schemas.openxmlformats.org/wordprocessingml/2006/main');
xmlWriter.writeString('word document');
setTimeout((): void => {
expect('').toBe('');
done();
}, 50);
});
it('save blob as xml file in microsoft browser', (done): void => {
xmlWriter.writeStartDocument(true);
xmlWriter.writeStartElement('w', 'document', 'http://schemas.openxmlformats.org/wordprocessingml/2006/main');
xmlWriter.writeAttributeString(null, 'wpc', 'http://www.w3.org/2000/xmlns/', 'http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas');
xmlWriter.writeString('word document');
setTimeout((): void => {
done();
}, 50);
});
it('Save blob as xml file,with Start and End Document', (done): void => {
xmlWriter.writeStartDocument(true);
xmlWriter.writeStartElement('w', 'document', 'http://schemas.openxmlformats.org/wordprocessingml/2006/main');
xmlWriter.writeAttributeString(null, 'wpc', 'http://www.w3.org/2000/xmlns/', 'http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas');
xmlWriter.writeStartElement(null, 'body', 'http://schemas.openxmlformats.org/wordprocessingml/2006/main');
xmlWriter.writeStartElement(null, 'p', 'http://schemas.openxmlformats.org/wordprocessingml/2006/main');
xmlWriter.writeAttributeString(null, 'rsidR', 'http://schemas.openxmlformats.org/wordprocessingml/2006/main', '00400719');
xmlWriter.writeAttributeString(null, 'rsidRDefault', 'http://schemas.openxmlformats.org/wordprocessingml/2006/main', '00400719');
xmlWriter.writeStartElement(null, 'r', 'http://schemas.openxmlformats.org/wordprocessingml/2006/main');
xmlWriter.writeStartElement(null, 't', 'http://schemas.openxmlformats.org/wordprocessingml/2006/main');
xmlWriter.writeString('word document');
xmlWriter.writeEndDocument();
setTimeout((): void => {
expect('').toBe('');
done();
}, 50);
});
it('destroy xmlWriter resource', (done): void => {
xmlWriter.writeStartElement(null, "book", null);
xmlWriter.writeAttributeString(null, "bk", null, "urn:samples");
xmlWriter.writeAttributeString(null, "genre", null, "novel");
xmlWriter.writeStartElement(null, "title", null);
xmlWriter.writeString("The Handmaid's Tale");
xmlWriter.writeEndElement();
xmlWriter.writeElementString(null, "price", null, "19.95");
xmlWriter.writeEndElement();
xmlWriter.destroy();
setTimeout((): void => {
expect(xmlWriter.buffer).toBe(undefined);
done();
}, 50);
});
});
describe('create empty element with write processing instuction', (): void => {
let xmlWriter: XmlWriter;
let fileReader: FileReader;
let xmlText: string | ArrayBuffer;
beforeEach((): void => {
/**
* instantiate XmlWriter class
*/
xmlWriter = new XmlWriter();
/**
* creates instance of FileReader class
*/
fileReader = new FileReader();
fileReader.onload = (): void => {
/**
* gets xml text from bolb
*/
xmlText = fileReader.result;
};
jasmine.DEFAULT_TIMEOUT_INTERVAL = 500;
});
afterEach((): void => {
xmlWriter.destroy();
xmlWriter = undefined;
fileReader = undefined;
xmlText = '';
});
it('Name and text as null', (done): void => {
setTimeout((): void => {
expect((): void => { xmlWriter.writeProcessingInstruction(null, null); }).toThrow(new Error('ArgumentException: name should not be undefined, null or empty'));
done();
}, 50);
});
it('Name as null and text as valid string', (done): void => {
setTimeout((): void => {
expect((): void => { xmlWriter.writeProcessingInstruction(null, 'href="book.xls"'); }).toThrow(new Error('ArgumentException: name should not be undefined, null or empty'));
done();
}, 50);
});
it('Name and text as valid string', (done): void => {
xmlWriter.writeProcessingInstruction('xml-stylesheet', 'href="book.xls"')
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><?xml-stylesheet href="book.xls"?><root />');
done();
}, 50);
});
it('Name as valid string and text as null', (done): void => {
xmlWriter.writeProcessingInstruction('xml-stylesheet', null)
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><?xml-stylesheet?><root />');
done();
}, 50);
});
it('Name as valid string and text as empty', (done): void => {
xmlWriter.writeProcessingInstruction('xml-stylesheet', '')
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><?xml-stylesheet?><root />');
done();
}, 50);
});
it('Name as valid string and text with special character', (done): void => {
xmlWriter.writeProcessingInstruction('xml-stylesheet', 'href=\"book.xls&*\"\'\"');
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><?xml-stylesheet href="book.xls&*"\'"?><root />');
done();
}, 50);
});
it('Name and text with valid special character', (done): void => {
xmlWriter.writeProcessingInstruction('xml-_.stylesheet', 'href=\"book.xls&*\"\'\"');
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><?xml-_.stylesheet href="book.xls&*"\'"?><root />');
done();
}, 50);
});
it('write processing instruction after XmlWriterState initial', (done): void => {
xmlWriter.writeStartElement(null, 'root', null);
setTimeout((): void => {
expect((): void => { xmlWriter.writeProcessingInstruction('xml-style', 'href=\"book.xls&*\"\'\"') }).toThrow(new Error('InvalidOperationException: Wrong Token'));
done();
}, 50);
});
it('Name as invalid string and text as valid string', (done): void => {
setTimeout((): void => {
expect((): void => { xmlWriter.writeProcessingInstruction('xml-styl@esheet', 'href=\"book.xls&*\"\'\"') }).toThrow(new Error('InvalidArgumentException: invalid name character'));
done();
}, 50);
});
it('Name as invalid string $ and text as valid string', (done): void => {
setTimeout((): void => {
expect((): void => { xmlWriter.writeProcessingInstruction('xml-styl$esheet', 'href=\"book.xls&*\"\'\"') }).toThrow(new Error('InvalidArgumentException: invalid name character'));
done();
}, 50);
});
it('Name as invalid string # and text as valid string', (done): void => {
setTimeout((): void => {
expect((): void => { xmlWriter.writeProcessingInstruction('xml-styl#esheet', 'href=\"book.xls&*\"\'\"') }).toThrow(new Error('InvalidArgumentException: invalid name character'));
done();
}, 50);
});
it('Name as invalid string = and text as valid string', (done): void => {
setTimeout((): void => {
expect((): void => { xmlWriter.writeProcessingInstruction('xml-styl=esheet', 'href=\"book.xls&*\"\'\"') }).toThrow(new Error('InvalidArgumentException: invalid name character'));
done();
}, 50);
});
it('Name = Xml ,after writeStartDocument', (done): void => {
xmlWriter.writeStartElement(null, 'root', null);
setTimeout((): void => {
expect((): void => { xmlWriter.writeProcessingInstruction('xml', 'data.docx'); }).toThrow(new Error('InvalidArgumentException: Cannot write XML declaration.WriteStartDocument method has already written it'));
done();
}, 50);
});
it('Name = Xml ,after writeStartDocument', (done): void => {
xmlWriter.writeProcessingInstruction('xml', 'data.docx');
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><?xml data.docx?><root />');
done();
}, 50);
});
});
describe('create single non empty element with writeRaw method', (): void => {
let xmlWriter: XmlWriter;
let fileReader: FileReader;
let xmlText: string | ArrayBuffer;
beforeEach((): void => {
/**
* instantiate XmlWriter class
*/
xmlWriter = new XmlWriter();
/**
* creates instance of FileReader class
*/
fileReader = new FileReader();
fileReader.onload = (): void => {
/**
* gets xml text from bolb
*/
xmlText = fileReader.result;
};
jasmine.DEFAULT_TIMEOUT_INTERVAL = 500;
});
afterEach((): void => {
xmlWriter.destroy();
xmlWriter = undefined;
fileReader = undefined;
xmlText = '';
});
it('prefix and namespace as null and localName as Valid string,writeRaw text as null', (done): void => {
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeRaw(null);
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root />');
done();
}, 50);
});
it('prefix and namespace as null and localName as Valid string,writeRaw text as empty', (done): void => {
xmlWriter.writeStartElement(null, 'root', null);
xmlWriter.writeRaw('');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root />');
done();
}, 50);
});
it('prefix and namespace as empty and localName as Valid string,writeRaw text as null', (done): void => {
xmlWriter.writeStartElement('', 'root', '');
xmlWriter.writeRaw(null);
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root />');
done();
}, 50);
});
it('prefix and namespace as empty and localName as Valid string,writeRaw text as empty', (done): void => {
xmlWriter.writeStartElement('', 'root', '');
xmlWriter.writeRaw('');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root />');
done();
}, 50);
});
it('prefix and namespace as empty and localName as Valid string,writeRaw text as valid string', (done): void => {
xmlWriter.writeStartElement('', 'root', '');
xmlWriter.writeRaw('child');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root>child</root>');
done();
}, 50);
});
it('prefix,namespace as empty and localName as Valid string,with two writeRaw method', (done): void => {
xmlWriter.writeStartElement('', 'root', '');
xmlWriter.writeRaw('child');
xmlWriter.writeRaw(' node');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root>child node</root>');
done();
}, 50);
});
it('prefix and namespace as empty and localName as Valid string,writeRaw text as valid string with special character', (done): void => {
xmlWriter.writeStartElement('', 'root', '');
xmlWriter.writeRaw('~`!@#$%^&*()_+=-[];\',./{}|:"<>?');
xmlWriter.writeEndElement();
fileReader.readAsText(xmlWriter.buffer);
setTimeout((): void => {
expect(xmlText).toBe('<?xml version="1.0" encoding="utf-8"?><root>~`!@#$%^&*()_+=-[];\',./{}|:"<>?</root>');
done();
}, 50);
});
it('writeRaw at XmlWriteStart initial', (done): void => {
setTimeout((): void => {
expect((): void => { xmlWriter.writeRaw('value&&<\"'); }).toThrow(new Error('InvalidOperationException: Wrong Token'));
done();
}, 50);
});
}); | the_stack |
module Kiwi.Input {
/**
* A Static class which has a property associated with all all of the character codes on a typical keyboard. While you don't need this class for your game to work, it is quite handy to use as it can speed up the development process.
*
* @class Keycodes
* @namespace Kiwi.Input
* @static
*/
export class Keycodes {
/**
* The type of object that this is.
* @method objType
* @return {string} "Keycodes"
* @public
*/
public objType() {
return "Keycodes";
}
/**
* A Static property that holds the keycode for the character A
* @property A
* @static
* @final
* @public
*/
public static A: number = "A".charCodeAt(0);
/**
* A Static property that holds the keycode for the character B
* @property B
* @static
* @final
* @public
*/
public static B: number = "B".charCodeAt(0);
/**
* A Static property that holds the keycode for the character C
* @property C
* @static
* @final
* @public
*/
public static C: number = "C".charCodeAt(0);
/**
* A Static property that holds the keycode for the character D
* @property D
* @static
* @final
* @public
*/
public static D: number = "D".charCodeAt(0);
/**
* A Static property that holds the keycode for the character E
* @property E
* @static
* @final
* @public
*/
public static E: number = "E".charCodeAt(0);
/**
* A Static property that holds the keycode for the character F
* @property F
* @static
* @final
* @public
*/
public static F: number = "F".charCodeAt(0);
/**
* A Static property that holds the keycode for the character G
* @property G
* @static
* @final
* @public
*/
public static G: number = "G".charCodeAt(0);
/**
* A Static property that holds the keycode for the character H
* @property H
* @static
* @final
* @public
*/
public static H: number = "H".charCodeAt(0);
/**
* A Static property that holds the keycode for the character I
* @property I
* @static
* @final
* @public
*/
public static I: number = "I".charCodeAt(0);
/**
* A Static property that holds the keycode for the character J
* @property J
* @static
* @final
* @public
*/
public static J: number = "J".charCodeAt(0);
/**
* A Static property that holds the keycode for the character K
* @property K
* @static
* @final
* @public
*/
public static K: number = "K".charCodeAt(0);
/**
* A Static property that holds the keycode for the character L
* @property L
* @static
* @final
* @public
*/
public static L: number = "L".charCodeAt(0);
/**
* A Static property that holds the keycode for the character M
* @property M
* @static
* @final
* @public
*/
public static M: number = "M".charCodeAt(0);
/**
* A Static property that holds the keycode for the character N
* @property N
* @static
* @final
* @public
*/
public static N: number = "N".charCodeAt(0);
/**
* A Static property that holds the keycode for the character O
* @property O
* @static
* @final
* @public
*/
public static O: number = "O".charCodeAt(0);
/**
* A Static property that holds the keycode for the character P
* @property P
* @static
* @final
* @public
*/
public static P: number = "P".charCodeAt(0);
/**
* A Static property that holds the keycode for the character Q
* @property Q
* @static
* @final
* @public
*/
public static Q: number = "Q".charCodeAt(0);
/**
* A Static property that holds the keycode for the character R
* @property R
* @static
* @final
* @public
*/
public static R: number = "R".charCodeAt(0);
/**
* A Static property that holds the keycode for the character S
* @property S
* @static
* @final
* @public
*/
public static S: number = "S".charCodeAt(0);
/**
* A Static property that holds the keycode for the character T
* @property T
* @static
* @final
* @public
*/
public static T: number = "T".charCodeAt(0);
/**
* A Static property that holds the keycode for the character U
* @property U
* @static
* @final
* @public
*/
public static U: number = "U".charCodeAt(0);
/**
* A Static property that holds the keycode for the character V
* @property V
* @static
* @final
* @public
*/
public static V: number = "V".charCodeAt(0);
/**
* A Static property that holds the keycode for the character W
* @property W
* @static
* @final
* @public
*/
public static W: number = "W".charCodeAt(0);
/**
* A Static property that holds the keycode for the character X
* @property X
* @static
* @final
* @public
*/
public static X: number = "X".charCodeAt(0);
/**
* A Static property that holds the keycode for the character Y
* @property Y
* @static
* @final
* @public
*/
public static Y: number = "Y".charCodeAt(0);
/**
* A Static property that holds the keycode for the character Z
* @property Z
* @static
* @final
* @public
*/
public static Z:number = "Z".charCodeAt(0);
/**
* A Static property that holds the keycode for the character 0
* @property ZERO
* @static
* @final
* @public
*/
public static ZERO: number = "0".charCodeAt(0);
/**
* A Static property that holds the keycode for the character 1
* @property ONE
* @static
* @final
* @public
*/
public static ONE: number = "1".charCodeAt(0);
/**
* A Static property that holds the keycode for the character 2
* @property TWO
* @static
* @final
* @public
*/
public static TWO: number = "2".charCodeAt(0);
/**
* A Static property that holds the keycode for the character 3
* @property THREE
* @static
* @final
* @public
*/
public static THREE: number = "3".charCodeAt(0);
/**
* A Static property that holds the keycode for the character 4
* @property FOUR
* @static
* @final
* @public
*/
public static FOUR: number = "4".charCodeAt(0);
/**
* A Static property that holds the keycode for the character 5
* @property FIVE
* @static
* @final
* @public
*/
public static FIVE: number = "5".charCodeAt(0);
/**
* A Static property that holds the keycode for the character 6
* @property SIX
* @static
* @final
* @public
*/
public static SIX: number = "6".charCodeAt(0);
/**
* A Static property that holds the keycode for the character 7
* @property SEVEN
* @static
* @final
* @public
*/
public static SEVEN: number = "7".charCodeAt(0);
/**
* A Static property that holds the keycode for the character 8
* @property EIGHT
* @static
* @final
* @public
*/
public static EIGHT: number = "8".charCodeAt(0);
/**
* A Static property that holds the keycode for the character 9
* @property NINE
* @static
* @final
* @public
*/
public static NINE:number = "9".charCodeAt(0);
/**
* A Static property that holds the keycode for the character number pad 0
* @property NUMPAD_0
* @static
* @final
* @public
*/
public static NUMPAD_0: number = 96;
/**
* A Static property that holds the keycode for the character number pad 1
* @property NUMPAD_1
* @static
* @final
* @public
*/
public static NUMPAD_1: number = 97;
/**
* A Static property that holds the keycode for the character number pad 2
* @property NUMPAD_2
* @static
* @final
* @public
*/
public static NUMPAD_2: number = 98;
/**
* A Static property that holds the keycode for the character number pad 3
* @property NUMPAD_3
* @static
* @final
* @public
*/
public static NUMPAD_3: number = 99;
/**
* A Static property that holds the keycode for the character number pad 4
* @property NUMPAD_4
* @static
* @final
* @public
*/
public static NUMPAD_4: number = 100;
/**
* A Static property that holds the keycode for the character number pad 5
* @property NUMPAD_5
* @static
* @final
* @public
*/
public static NUMPAD_5: number = 101;
/**
* A Static property that holds the keycode for the character number pad 6
* @property NUMPAD_6
* @static
* @final
* @public
*/
public static NUMPAD_6: number = 102;
/**
* A Static property that holds the keycode for the character number pad 7
* @property NUMPAD_7
* @static
* @final
* @public
*/
public static NUMPAD_7: number = 103;
/**
* A Static property that holds the keycode for the character number pad 8
* @property NUMPAD_8
* @static
* @final
* @public
*/
public static NUMPAD_8: number = 104;
/**
* A Static property that holds the keycode for the character number pad 9
* @property NUMPAD_9
* @static
* @final
* @public
*/
public static NUMPAD_9: number = 105;
/**
* A Static property that holds the keycode for the character number pad *
* @property NUMPAD_MULTIPLY
* @static
* @final
* @public
*/
public static NUMPAD_MULTIPLY: number = 106;
/**
* A Static property that holds the keycode for the character number pad +
* @property NUMPAD_ADD
* @static
* @final
* @public
*/
public static NUMPAD_ADD: number = 107;
/**
* A Static property that holds the keycode for the character on the number pad enter
* @property NUMPAD_ENTER
* @static
* @final
* @public
*/
public static NUMPAD_ENTER: number = 108;
/**
* A Static property that holds the keycode for the character number pad -
* @property NUMPAD_SUBTRACT
* @static
* @final
* @public
*/
public static NUMPAD_SUBTRACT: number = 109;
/**
* A Static property that holds the keycode for the character number pad .
* @property NUMPAD_DECIMAL
* @static
* @final
* @public
*/
public static NUMPAD_DECIMAL: number = 110;
/**
* A Static property that holds the keycode for the character /
* @property NUMPAD_DIVIDE
* @static
* @final
* @public
*/
public static NUMPAD_DIVIDE:number = 111;
/**
* A Static property that holds the keycode for the character F1
* @property F1
* @static
* @final
* @public
*/
public static F1: number = 112;
/**
* A Static property that holds the keycode for the character F2
* @property F2
* @static
* @final
* @public
*/
public static F2: number = 113;
/**
* A Static property that holds the keycode for the character F3
* @property F3
* @static
* @final
* @public
*/
public static F3: number = 114;
/**
* A Static property that holds the keycode for the character F4
* @property F4
* @static
* @final
* @public
*/
public static F4: number = 115;
/**
* A Static property that holds the keycode for the character F5
* @property F5
* @static
* @final
* @public
*/
public static F5: number = 116;
/**
* A Static property that holds the keycode for the character F6
* @property F6
* @static
* @final
* @public
*/
public static F6: number = 117;
/**
* A Static property that holds the keycode for the character F7
* @property F7
* @static
* @final
* @public
*/
public static F7: number = 118;
/**
* A Static property that holds the keycode for the character F8
* @property F8
* @static
* @final
* @public
*/
public static F8: number = 119;
/**
* A Static property that holds the keycode for the character F9
* @property F9
* @static
* @final
* @public
*/
public static F9: number = 120;
/**
* A Static property that holds the keycode for the character F10
* @property F10
* @static
* @final
* @public
*/
public static F10: number = 121;
/**
* A Static property that holds the keycode for the character F11
* @property F11
* @static
* @final
* @public
*/
public static F11: number = 122;
/**
* A Static property that holds the keycode for the character F12
* @property F12
* @static
* @final
* @public
*/
public static F12: number = 123;
/**
* A Static property that holds the keycode for the character F13
* @property F13
* @static
* @final
* @public
*/
public static F13: number = 124;
/**
* A Static property that holds the keycode for the character F14
* @property F14
* @static
* @final
* @public
*/
public static F14: number = 125;
/**
* A Static property that holds the keycode for the character F15
* @property F15
* @static
* @final
* @public
*/
public static F15:number = 126;
/**
* A Static property that holds the keycode for the character COLON
* @property COLON
* @static
* @final
* @public
*/
public static COLON: number = 186;
/**
* A Static property that holds the keycode for the character =
* @property EQUALS
* @static
* @final
* @public
*/
public static EQUALS: number = 187;
/**
* A Static property that holds the keycode for the character UNDERSCORE
* @property UNDERSCORE
* @static
* @final
* @public
*/
public static UNDERSCORE: number = 189;
/**
* A Static property that holds the keycode for the character QUESTION_MARK
* @property QUESTION_MARK
* @static
* @final
* @public
*/
public static QUESTION_MARK: number = 191;
/**
* A Static property that holds the keycode for the character TILDE
* @property TILDE
* @static
* @final
* @public
*/
public static TILDE: number = 192;
/**
* A Static property that holds the keycode for the character OPEN_BRAKET
* @property OPEN_BRACKET
* @static
* @final
* @public
*/
public static OPEN_BRACKET: number = 219;
/**
* A Static property that holds the keycode for the character BACKWARD_SLASH
* @property BACKWARD_SLASH
* @static
* @final
* @public
*/
public static BACKWARD_SLASH: number = 220;
/**
* A Static property that holds the keycode for the character CLOSED_BRACKET
* @property CLOSED_BRACKET
* @static
* @final
* @public
*/
public static CLOSED_BRACKET: number = 221;
/**
* A Static property that holds the keycode for the character QUOTES
* @property QUOTES
* @static
* @final
* @public
*/
public static QUOTES:number = 222;
/**
* A Static property that holds the keycode for the character BACKSPACE
* @property BACKSPACE
* @static
* @final
* @public
*/
public static BACKSPACE: number = 8;
/**
* A Static property that holds the keycode for the character TAB
* @property TAB
* @static
* @final
* @public
*/
public static TAB: number = 9;
/**
* A Static property that holds the keycode for the character CLEAR
* @property CLEAR
* @static
* @final
* @public
*/
public static CLEAR: number = 12;
/**
* A Static property that holds the keycode for the character ENTER
* @property ENTER
* @static
* @final
* @public
*/
public static ENTER: number = 13;
/**
* A Static property that holds the keycode for the character SHIFT
* @property SHIFT
* @static
* @final
* @public
*/
public static SHIFT: number = 16;
/**
* A Static property that holds the keycode for the character CONTROL
* @property CONTROL
* @static
* @final
* @public
*/
public static CONTROL: number = 17;
/**
* A Static property that holds the keycode for the character ALT
* @property ALT
* @static
* @final
* @public
*/
public static ALT: number = 18;
/**
* A Static property that holds the keycode for the character CAPS_LOCK
* @property CAPS_LOCK
* @static
* @final
* @public
*/
public static CAPS_LOCK: number = 20;
/**
* A Static property that holds the keycode for the character ESC
* @property ESC
* @static
* @final
* @public
*/
public static ESC: number = 27;
/**
* A Static property that holds the keycode for the character SPACEBAR
* @property SPACEBAR
* @static
* @final
* @public
*/
public static SPACEBAR: number = 32;
/**
* A Static property that holds the keycode for the character PAGE_UP
* @property PAGE_UP
* @static
* @final
* @public
*/
public static PAGE_UP: number = 33;
/**
* A Static property that holds the keycode for the character PAGE_DOWN
* @property PAGE_DOWN
* @static
* @final
* @public
*/
public static PAGE_DOWN: number = 34;
/**
* A Static property that holds the keycode for the character END
* @property END
* @static
* @final
* @public
*/
public static END: number = 35;
/**
* A Static property that holds the keycode for the character HOME
* @property HOME
* @static
* @final
* @public
*/
public static HOME: number = 36;
/**
* A Static property that holds the keycode for the character LEFT
* @property LEFT
* @static
* @final
* @public
*/
public static LEFT: number = 37;
/**
* A Static property that holds the keycode for the character UP
* @property UP
* @static
* @final
* @public
*/
public static UP: number = 38;
/**
* A Static property that holds the keycode for the character RIGHT
* @property RIGHT
* @static
* @final
* @public
*/
public static RIGHT: number = 39;
/**
* A Static property that holds the keycode for the character DOWN
* @property DOWN
* @static
* @final
* @public
*/
public static DOWN: number = 40;
/**
* A Static property that holds the keycode for the character INSERT
* @property INSERT
* @static
* @final
* @public
*/
public static INSERT: number = 45;
/**
* A Static property that holds the keycode for the character DELETE
* @property DELETE
* @static
* @final
* @public
*/
public static DELETE: number = 46;
/**
* A Static property that holds the keycode for the character HELP
* @property HELP
* @static
* @final
* @public
*/
public static HELP: number = 47;
/**
* A Static property that holds the keycode for the character NUM_LOCK
* @property NUM_LOCK
* @static
* @final
* @public
*/
public static NUM_LOCK: number = 144;
}
} | the_stack |
import React from 'react'
import { Interpolation } from 'emotion'
import { matchers } from 'jest-emotion'
import { fireEvent, render } from '@testing-library/react'
import { createTheme } from '../../../../styles'
import { defaultModifierStyles } from '../../Calendar'
import { DateRange } from '../../../DateRangePicker/BaseDateRangeInput'
import { dayHoverStyle, DateRangeCalendar, DateRangeCalendarProps } from './DateRangeCalendar'
expect.extend(matchers)
const createComponent = (props: Partial<DateRangeCalendarProps> = {}) => (
<DateRangeCalendar
visibleDate={new Date('2019-02-09')}
onVisibleDateChange={jest.fn()}
value={{ startDate: undefined, endDate: undefined } as DateRange}
inputOnFocus={1}
{...props}
/>
)
/**
* iterates over the object executing an callback containing the desired tests
* @param obj
* @param testFn
*/
export const iterateObjectFields = (obj: Object, testFn: (fieldName: string, fieldValue: any) => void) => {
for (const field in obj as any) {
if (obj.hasOwnProperty(field)) {
if (obj[field] === Object(obj[field])) {
iterateObjectFields(obj[field], testFn)
} else {
testFn(field, obj[field])
}
}
}
}
export const normalizeCssClassNames = (str: string) => str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase()
describe('DateRangeCalendar', () => {
const theme = createTheme()
describe('Selection and hover', () => {
it('With nothing defined, hovered days should have the correct css', () => {
const { getByText } = render(createComponent())
const expectedStyle = dayHoverStyle(theme)
fireEvent.mouseOver(getByText('14'))
iterateObjectFields(expectedStyle, (fieldName: string, fieldValue: any) =>
expect(getByText('14')).toHaveStyleRule(normalizeCssClassNames(fieldName), fieldValue)
)
})
it('When finalDate is earlier than initialDate, both should be selected', () => {
const { getByText } = render(
createComponent({ value: { startDate: new Date('2019-02-15'), endDate: new Date('2019-02-14') } as DateRange })
)
expect(getByText('14').getAttribute('aria-selected')).toBe('true')
expect(getByText('15').getAttribute('aria-selected')).toBe('true')
})
it('With only the initialDate selected, just one day should have the "selectedStyle"', () => {
const { getByText } = render(
createComponent({ value: { startDate: new Date('2019-02-15'), endDate: undefined } as DateRange })
)
const expectedStyle: Interpolation = defaultModifierStyles.selected(theme)
iterateObjectFields(expectedStyle, (fieldName: string, fieldValue: any) => {
expect(getByText('14')).not.toHaveStyleRule(normalizeCssClassNames(fieldName), fieldValue)
expect(getByText('15')).toHaveStyleRule(normalizeCssClassNames(fieldName), fieldValue)
expect(getByText('16')).not.toHaveStyleRule(normalizeCssClassNames(fieldName), fieldValue)
})
})
it('With finalDate and initialDate, the selected days must have been selected', () => {
const { getByText } = render(
createComponent({ value: { startDate: new Date('2019-02-11'), endDate: new Date('2019-02-13') } as DateRange })
)
expect(getByText('10').getAttribute('aria-selected')).toBe('false')
expect(getByText('11').getAttribute('aria-selected')).toBe('true')
expect(getByText('12').getAttribute('aria-selected')).toBe('true')
expect(getByText('13').getAttribute('aria-selected')).toBe('true')
expect(getByText('14').getAttribute('aria-selected')).toBe('false')
})
it('With finalDate and initialDate, the selected days should have the "selectedStyle"', () => {
const { getByText } = render(
createComponent({ value: { startDate: new Date('2019-02-11'), endDate: new Date('2019-02-13') } as DateRange })
)
const expectedStyle: Interpolation = defaultModifierStyles.selected(theme)
iterateObjectFields(expectedStyle, (fieldName: string, fieldValue: any) => {
expect(getByText('10')).not.toHaveStyleRule(normalizeCssClassNames(fieldName), fieldValue)
expect(getByText('11')).toHaveStyleRule(normalizeCssClassNames(fieldName), fieldValue)
expect(getByText('12')).toHaveStyleRule(normalizeCssClassNames(fieldName), fieldValue)
expect(getByText('13')).toHaveStyleRule(normalizeCssClassNames(fieldName), fieldValue)
expect(getByText('14')).not.toHaveStyleRule(normalizeCssClassNames(fieldName), fieldValue)
})
})
it('With only initalDate defined and focus is in the first input, hover style must be applied only in the date pointed by mouse', () => {
const { getByText } = render(
createComponent({
value: { startDate: new Date('2019-02-15'), endDate: undefined } as DateRange,
inputOnFocus: 1,
})
)
const expectedStyle = dayHoverStyle(theme)
fireEvent.mouseOver(getByText('17'))
iterateObjectFields(expectedStyle, (fieldName: string, fieldValue: any) => {
expect(getByText('16')).not.toHaveStyleRule(normalizeCssClassNames(fieldName), fieldValue)
expect(getByText('17')).toHaveStyleRule(normalizeCssClassNames(fieldName), fieldValue)
expect(getByText('18')).not.toHaveStyleRule(normalizeCssClassNames(fieldName), fieldValue)
})
fireEvent.mouseOver(getByText('13'))
iterateObjectFields(expectedStyle, (fieldName: string, fieldValue: any) => {
expect(getByText('12')).not.toHaveStyleRule(normalizeCssClassNames(fieldName), fieldValue)
expect(getByText('13')).toHaveStyleRule(normalizeCssClassNames(fieldName), fieldValue)
expect(getByText('14')).not.toHaveStyleRule(normalizeCssClassNames(fieldName), fieldValue)
})
})
it('With only initalDate defined and focus is in the second input, hover style must be applied on the interval between initialDate and mouse', () => {
const { getByText } = render(
createComponent({
value: { startDate: new Date('2019-02-15'), endDate: undefined } as DateRange,
inputOnFocus: 2,
})
)
const expectedStyle = dayHoverStyle(theme)
fireEvent.mouseOver(getByText('17'))
iterateObjectFields(expectedStyle, (fieldName: string, fieldValue: any) => {
expect(getByText('14')).not.toHaveStyleRule(normalizeCssClassNames(fieldName), fieldValue)
// Day 15 (the day selected in the interval) skipped to preserve the purpose of this test
expect(getByText('16')).toHaveStyleRule(normalizeCssClassNames(fieldName), fieldValue)
expect(getByText('17')).toHaveStyleRule(normalizeCssClassNames(fieldName), fieldValue)
expect(getByText('18')).not.toHaveStyleRule(normalizeCssClassNames(fieldName), fieldValue)
})
fireEvent.mouseOver(getByText('13'))
iterateObjectFields(expectedStyle, (fieldName: string, fieldValue: any) => {
expect(getByText('12')).not.toHaveStyleRule(normalizeCssClassNames(fieldName), fieldValue)
expect(getByText('13')).toHaveStyleRule(normalizeCssClassNames(fieldName), fieldValue)
expect(getByText('14')).toHaveStyleRule(normalizeCssClassNames(fieldName), fieldValue)
// Day 15 (the day selected in the interval) skipped to preserve the purpose of this test
expect(getByText('16')).not.toHaveStyleRule(normalizeCssClassNames(fieldName), fieldValue)
})
})
it('With only finalDate defined and focus is in the first input, hover style must be applied on the interval between finalDate and mouse', () => {
const { getByText } = render(
createComponent({
value: { startDate: undefined, endDate: new Date('2019-02-15') } as DateRange,
inputOnFocus: 1,
})
)
const expectedStyle = dayHoverStyle(theme)
fireEvent.mouseOver(getByText('17'))
iterateObjectFields(expectedStyle, (fieldName: string, fieldValue: any) => {
expect(getByText('14')).not.toHaveStyleRule(normalizeCssClassNames(fieldName), fieldValue)
// Day 15 (the day selected in the interval) skipped to preserve the purpose of this test
expect(getByText('16')).toHaveStyleRule(normalizeCssClassNames(fieldName), fieldValue)
expect(getByText('17')).toHaveStyleRule(normalizeCssClassNames(fieldName), fieldValue)
expect(getByText('18')).not.toHaveStyleRule(normalizeCssClassNames(fieldName), fieldValue)
})
fireEvent.mouseOver(getByText('13'))
iterateObjectFields(expectedStyle, (fieldName: string, fieldValue: any) => {
expect(getByText('12')).not.toHaveStyleRule(normalizeCssClassNames(fieldName), fieldValue)
expect(getByText('13')).toHaveStyleRule(normalizeCssClassNames(fieldName), fieldValue)
expect(getByText('14')).toHaveStyleRule(normalizeCssClassNames(fieldName), fieldValue)
// Day 15 (the day selected in the interval) skipped to preserve the purpose of this test
expect(getByText('16')).not.toHaveStyleRule(normalizeCssClassNames(fieldName), fieldValue)
})
})
it('With only finalDate defined and focus is in the second input, hover style must be applied only in the date pointed by mouse', () => {
const { getByText } = render(
createComponent({
value: { startDate: undefined, endDate: new Date('2019-02-15') } as DateRange,
inputOnFocus: 2,
})
)
const expectedStyle = dayHoverStyle(theme)
fireEvent.mouseOver(getByText('17'))
iterateObjectFields(expectedStyle, (fieldName: string, fieldValue: any) => {
expect(getByText('16')).not.toHaveStyleRule(normalizeCssClassNames(fieldName), fieldValue)
expect(getByText('17')).toHaveStyleRule(normalizeCssClassNames(fieldName), fieldValue)
expect(getByText('18')).not.toHaveStyleRule(normalizeCssClassNames(fieldName), fieldValue)
})
fireEvent.mouseOver(getByText('13'))
iterateObjectFields(expectedStyle, (fieldName: string, fieldValue: any) => {
expect(getByText('12')).not.toHaveStyleRule(normalizeCssClassNames(fieldName), fieldValue)
expect(getByText('13')).toHaveStyleRule(normalizeCssClassNames(fieldName), fieldValue)
expect(getByText('14')).not.toHaveStyleRule(normalizeCssClassNames(fieldName), fieldValue)
})
})
it('Hover style must be applied when initialDate and finalDate are correctly defined', () => {
const { getByText } = render(
createComponent({
value: { startDate: new Date('2019-02-11'), endDate: new Date('2019-02-13') } as DateRange,
inputOnFocus: 2,
})
)
const expectedStyle = dayHoverStyle(theme)
fireEvent.mouseOver(getByText('14'))
iterateObjectFields(expectedStyle, (fieldName: string, fieldValue: any) => {
expect(getByText('10')).not.toHaveStyleRule(normalizeCssClassNames(fieldName), fieldValue)
// Day 11 to 13 (the day selected in the interval) skipped to preserve the purpose of this test
expect(getByText('14')).toHaveStyleRule(normalizeCssClassNames(fieldName), fieldValue)
expect(getByText('15')).not.toHaveStyleRule(normalizeCssClassNames(fieldName), fieldValue)
})
// for a date before interval, only the date will have the hover effect
fireEvent.mouseOver(getByText('09'))
iterateObjectFields(expectedStyle, (fieldName: string, fieldValue: any) => {
expect(getByText('08')).not.toHaveStyleRule(normalizeCssClassNames(fieldName), fieldValue)
expect(getByText('09')).toHaveStyleRule(normalizeCssClassNames(fieldName), fieldValue)
expect(getByText('10')).not.toHaveStyleRule(normalizeCssClassNames(fieldName), fieldValue)
// Day 11 to 13 (the day selected in the interval) skipped to preserve the purpose of this test
expect(getByText('14')).not.toHaveStyleRule(normalizeCssClassNames(fieldName), fieldValue)
})
})
it(
'With finalDate and initialDate, focus is in the first input and hover date' +
'is after initialDate, hover style must be applied only in the date pointed by mouse',
() => {
const { getByText } = render(
createComponent({
value: { startDate: new Date('2019-02-13'), endDate: new Date('2019-02-15') } as DateRange,
inputOnFocus: 1,
})
)
const expectedStyle = dayHoverStyle(theme)
fireEvent.mouseOver(getByText('17'))
iterateObjectFields(expectedStyle, (fieldName: string, fieldValue: any) => {
expect(getByText('14')).not.toHaveStyleRule(normalizeCssClassNames(fieldName), fieldValue)
// Day 15 is skipped to preserve the purpose of this test
expect(getByText('16')).not.toHaveStyleRule(normalizeCssClassNames(fieldName), fieldValue)
expect(getByText('17')).toHaveStyleRule(normalizeCssClassNames(fieldName), fieldValue)
expect(getByText('18')).not.toHaveStyleRule(normalizeCssClassNames(fieldName), fieldValue)
})
}
)
it(
'With finalDate and initialDate, focus is in the first input and hover date' +
'is before initialDate, hover style must be applied on the interval between initialDate and mouse',
() => {
const { getByText } = render(
createComponent({
value: { startDate: new Date('2019-02-13'), endDate: new Date('2019-02-15') } as DateRange,
inputOnFocus: 1,
})
)
const expectedStyle = dayHoverStyle(theme)
fireEvent.mouseOver(getByText('08'))
iterateObjectFields(expectedStyle, (fieldName: string, fieldValue: any) => {
expect(getByText('07')).not.toHaveStyleRule(normalizeCssClassNames(fieldName), fieldValue)
expect(getByText('08')).toHaveStyleRule(normalizeCssClassNames(fieldName), fieldValue)
expect(getByText('12')).toHaveStyleRule(normalizeCssClassNames(fieldName), fieldValue)
// Day 13 is skipped to preserve the purpose of this test
expect(getByText('16')).not.toHaveStyleRule(normalizeCssClassNames(fieldName), fieldValue)
})
}
)
describe('Remove style when mouseLeave', () => {
it('should remove the style for day hover', () => {
const { getByText } = render(
createComponent({
value: { startDate: new Date('2019-02-13'), endDate: undefined } as DateRange,
inputOnFocus: 2,
})
)
const expectedStyle = dayHoverStyle(theme)
fireEvent.mouseOver(getByText('14'))
iterateObjectFields(expectedStyle, (fieldName: string, fieldValue: any) =>
expect(getByText('14')).toHaveStyleRule(normalizeCssClassNames(fieldName), fieldValue)
)
fireEvent.mouseLeave(getByText('14'))
iterateObjectFields(expectedStyle, (fieldName: string, fieldValue: any) =>
expect(getByText('14')).not.toHaveStyleRule(normalizeCssClassNames(fieldName), fieldValue)
)
})
it('should remove the style for week hover', () => {
const { container } = render(
createComponent({
visibleDate: new Date('2021-01-03'),
value: { startDate: new Date('2021-01-17'), endDate: undefined } as DateRange,
inputOnFocus: 2,
onlyWeeks: true,
})
)
const expectedStyle = dayHoverStyle(theme)
const tr = container.querySelector('tr[data-week="24/01/2021-30/01/2021"]')
fireEvent.mouseOver(tr)
iterateObjectFields(expectedStyle, (fieldName: string, fieldValue: any) =>
expect(tr).toHaveStyleRule(normalizeCssClassNames(fieldName), fieldValue)
)
fireEvent.mouseLeave(tr)
iterateObjectFields(expectedStyle, (fieldName: string, fieldValue: any) =>
expect(tr).not.toHaveStyleRule(normalizeCssClassNames(fieldName), fieldValue)
)
})
})
it('The comparisons for which days belong to the selected range should be correct', () => {
const { getByText, rerender } = render(
createComponent({
visibleDate: new Date('2019-01-15'),
value: {
startDate: new Date('2019-02-15'),
endDate: undefined,
},
})
)
// Showing the previous month, so nothing should be selected
expect(getByText('15').getAttribute('aria-selected')).toBe('false')
rerender(
createComponent({
visibleDate: new Date('2018-02-15'),
value: {
startDate: new Date('2019-02-15'),
endDate: undefined,
},
})
)
// Showing the previous year, so nothing should be selected
expect(getByText('15').getAttribute('aria-selected')).toBe('false')
rerender(
createComponent({
visibleDate: new Date('2018-01-15'),
value: {
startDate: new Date('2019-02-15'),
endDate: undefined,
},
})
)
// Showing the wrong year and month, so nothing should be selected
expect(getByText('15').getAttribute('aria-selected')).toBe('false')
})
})
}) | the_stack |
import _ from 'lodash';
import BigNumber from 'bignumber.js';
import {
Balance,
Fee,
Order,
Price,
SignedOrder,
SigningMethod,
OrderStatus,
address,
} from '../src/lib/types';
import {
ADDRESSES,
INTEGERS,
PRICES,
} from '../src/lib/Constants';
import {
boolToBytes32,
} from '../src/lib/BytesHelper';
import { expect, expectBN, expectThrow, expectBaseValueEqual } from './helpers/Expect';
import { expectBalances, mintAndDeposit } from './helpers/balances';
import initializePerpetual from './helpers/initializePerpetual';
import { ITestContext, perpetualDescribe } from './helpers/perpetualDescribe';
import { buy, sell } from './helpers/trade';
const orderAmount = new BigNumber('1e18');
const limitPrice = new Price('987.65432');
const defaultOrder: Order = {
limitPrice,
isBuy: true,
isDecreaseOnly: false,
amount: orderAmount,
triggerPrice: PRICES.NONE,
limitFee: Fee.fromBips(20),
maker: ADDRESSES.ZERO,
taker: ADDRESSES.ZERO,
expiration: INTEGERS.ONE_YEAR_IN_SECONDS.times(100),
salt: new BigNumber('425'),
};
const initialMargin = orderAmount.times(limitPrice.value).times(2);
const fullFlagOrder: Order = {
...defaultOrder,
isDecreaseOnly: true,
limitFee: new Fee(defaultOrder.limitFee.value.abs().negated()),
};
let defaultSignedOrder: SignedOrder;
let fullFlagSignedOrder: SignedOrder;
let admin: address;
let otherUser: address;
async function init(ctx: ITestContext) {
await initializePerpetual(ctx);
defaultOrder.maker = fullFlagOrder.maker = ctx.accounts[5];
defaultOrder.taker = fullFlagOrder.taker = ctx.accounts[1];
admin = ctx.accounts[0];
otherUser = ctx.accounts[8];
defaultSignedOrder = await ctx.perpetual.orders.getSignedOrder(defaultOrder, SigningMethod.Hash);
fullFlagSignedOrder = await ctx.perpetual.orders.getSignedOrder(
fullFlagOrder,
SigningMethod.Hash,
);
// Set up initial balances:
await Promise.all([
mintAndDeposit(ctx, defaultOrder.maker, initialMargin),
mintAndDeposit(ctx, defaultOrder.taker, initialMargin),
setOraclePrice(ctx, limitPrice),
]);
}
perpetualDescribe('P1Orders', init, (ctx: ITestContext) => {
describe('off-chain helpers', () => {
it('Signs correctly for hash', async () => {
const typedSignature = await ctx.perpetual.orders.signOrder(
defaultOrder,
SigningMethod.Hash,
);
const validSignature = ctx.perpetual.orders.orderHasValidSignature({
...defaultOrder,
typedSignature,
});
expect(validSignature).to.be.true;
});
it('Signs correctly for typed data', async () => {
const typedSignature = await ctx.perpetual.orders.signOrder(
defaultOrder,
SigningMethod.TypedData,
);
const validSignature = ctx.perpetual.orders.orderHasValidSignature({
...defaultOrder,
typedSignature,
});
expect(validSignature).to.be.true;
});
it('Signs an order cancelation', async () => {
const typedSignature = await ctx.perpetual.orders.signCancelOrder(
defaultOrder,
SigningMethod.TypedData,
);
const validTypedSignature = ctx.perpetual.orders.cancelOrderHasValidSignature(
defaultOrder,
typedSignature,
);
expect(validTypedSignature).to.be.true;
const hashSignature = await ctx.perpetual.orders.signCancelOrder(
defaultOrder,
SigningMethod.Hash,
);
const validHashSignature = ctx.perpetual.orders.cancelOrderHasValidSignature(
defaultOrder,
hashSignature,
);
expect(validHashSignature).to.be.true;
});
it('Recognizes invalid signatures', () => {
const badSignatures = [
`0x${'00'.repeat(63)}00`,
`0x${'ab'.repeat(63)}01`,
`0x${'01'.repeat(70)}01`,
];
badSignatures.map((typedSignature) => {
const validSignature = ctx.perpetual.orders.orderHasValidSignature({
...defaultOrder,
typedSignature,
});
expect(validSignature).to.be.false;
const validCancelSignature = ctx.perpetual.orders.cancelOrderHasValidSignature(
defaultOrder,
typedSignature,
);
expect(validCancelSignature).to.be.false;
});
});
it('Estimates collateralization after executing buys', async () => {
// Buy 1e18 BASE at price of 987.65432 QUOTE/BASE with fee of 0.002.
// - base: 1e18 BASE -> worth 1200e18 QUOTE at oracle price of 1200
// - quote: -987.65432e18 * 1.002 QUOTE
const oraclePrice = new Price(1200);
const marginCost = orderAmount.times(limitPrice.value);
const ratio = ctx.perpetual.orders.getAccountCollateralizationAfterMakingOrders(
new Balance(0, 0),
oraclePrice,
[defaultOrder, defaultOrder, defaultOrder],
[marginCost.div(3), marginCost.div(2), marginCost.div(6)],
);
// Execute the trade on the smart contract.
// First, withdraw maker margin so it has zero initial balance.
const { maker } = defaultOrder;
await Promise.all([
ctx.perpetual.margin.withdraw(maker, maker, initialMargin, { from: maker }),
setOraclePrice(ctx, oraclePrice),
]);
await fillOrder({ amount: orderAmount.div(3) });
await fillOrder({ amount: orderAmount.div(2) });
await fillOrder({ amount: orderAmount.div(6) });
const balance = await ctx.perpetual.getters.getAccountBalance(maker);
expectBN(ratio, 'simulated vs. on-chain').to.equal(balance.getCollateralization(oraclePrice));
// Compare with the expected result.
const expectedRatio = new BigNumber(1200).div(987.65432 * 1.002);
const error = expectedRatio.minus(ratio).abs();
expectBN(error, 'simulated vs. expected (error)').to.be.lt(1e-15);
});
it('Estimates collateralization after executing sells', async () => {
// Sell 1e18 BASE at price of 987.65432 QUOTE/BASE with fee of 0.002.
// - base: -1e18 BASE -> worth -200e18 QUOTE at oracle price of 200
// - quote: 987.65432e18 * 0.998 QUOTE
const oraclePrice = new Price(200);
const sellOrder = await getModifiedOrder({ isBuy: false });
const ratio = ctx.perpetual.orders.getAccountCollateralizationAfterMakingOrders(
new Balance(0, 0),
oraclePrice,
[sellOrder, sellOrder, sellOrder],
[orderAmount.div(3), orderAmount.div(2), orderAmount.div(6)],
);
// Execute the trade on the smart contract.
// First, withdraw maker margin so it has zero initial balance.
const { maker } = defaultOrder;
await Promise.all([
ctx.perpetual.margin.withdraw(maker, maker, initialMargin, { from: maker }),
setOraclePrice(ctx, oraclePrice),
]);
await fillOrder(sellOrder, { amount: orderAmount.div(3) });
await fillOrder(sellOrder, { amount: orderAmount.div(2) });
await fillOrder(sellOrder, { amount: orderAmount.div(6) });
const balance = await ctx.perpetual.getters.getAccountBalance(maker);
expectBN(ratio, 'simulated vs. on-chain').to.equal(balance.getCollateralization(oraclePrice));
// Compare with the expected result.
const expectedRatio = new BigNumber(987.65432 * 0.998).div(200);
const error = expectedRatio.minus(ratio).abs();
expectBN(error, 'simulated vs. expected (error)').to.be.lt(1e-15);
});
it('Estimates collateralization when positive balance is zero', async () => {
const order = await getModifiedOrder({ limitPrice: limitPrice.times(2) });
const marginCost = orderAmount.times(limitPrice.value.times(2));
const ratio = ctx.perpetual.orders.getAccountCollateralizationAfterMakingOrders(
new Balance(initialMargin, orderAmount.negated()),
limitPrice,
[order],
[marginCost],
);
expectBN(ratio).to.equal(0);
});
it('Estimates collateralization when negative balance is zero', () => {
const marginCost = orderAmount.times(limitPrice.value);
const ratio = ctx.perpetual.orders.getAccountCollateralizationAfterMakingOrders(
new Balance(initialMargin, orderAmount),
limitPrice,
[defaultOrder],
[marginCost.div(2)],
);
expectBN(ratio).to.equal(Infinity);
});
it('Estimates collateralization when balance is zero', async () => {
const buyOrder = await getModifiedOrder({ limitFee: new Fee(0) });
const sellOrder = await getModifiedOrder({ isBuy: false, limitFee: new Fee(0) });
const marginCost = orderAmount.times(limitPrice.value);
const ratio1 = ctx.perpetual.orders.getAccountCollateralizationAfterMakingOrders(
new Balance(0, 0),
limitPrice,
[buyOrder, sellOrder],
[marginCost, orderAmount],
);
expectBN(ratio1).to.equal(Infinity);
});
});
describe('approveOrder()', () => {
it('Succeeds', async () => {
const txResult = await ctx.perpetual.orders.approveOrder(
fullFlagOrder,
{ from: fullFlagOrder.maker },
);
await expectStatus(fullFlagOrder, OrderStatus.Approved);
// Check logs.
const logs = ctx.perpetual.logs.parseLogs(txResult);
expect(logs.length).to.equal(1);
expect(logs[0].name).to.equal('LogOrderApproved');
expect(logs[0].args.orderHash).to.equal(ctx.perpetual.orders.getOrderHash(fullFlagOrder));
expect(logs[0].args.maker).to.equal(fullFlagOrder.maker);
});
it('Succeeds in double-approving order', async () => {
await ctx.perpetual.orders.approveOrder(fullFlagOrder, { from: fullFlagOrder.maker });
await ctx.perpetual.orders.approveOrder(fullFlagOrder, { from: fullFlagOrder.maker });
await expectStatus(fullFlagOrder, OrderStatus.Approved);
});
it('Fails if caller is not the maker', async () => {
await expectThrow(
ctx.perpetual.orders.approveOrder(fullFlagOrder, { from: fullFlagOrder.taker }),
'Order cannot be approved by non-maker',
);
});
it('Fails to approve canceled order', async () => {
await ctx.perpetual.orders.cancelOrder(fullFlagOrder, { from: fullFlagOrder.maker });
await expectThrow(
ctx.perpetual.orders.approveOrder(fullFlagOrder, { from: fullFlagOrder.maker }),
'Canceled order cannot be approved',
);
});
});
describe('cancelOrder()', () => {
it('Succeeds', async () => {
const txResult = await ctx.perpetual.orders.cancelOrder(
fullFlagOrder,
{ from: fullFlagOrder.maker },
);
await expectStatus(fullFlagOrder, OrderStatus.Canceled);
// Check logs.
const logs = ctx.perpetual.logs.parseLogs(txResult);
expect(logs.length).to.equal(1);
expect(logs[0].name).to.equal('LogOrderCanceled');
expect(logs[0].args.orderHash).to.equal(ctx.perpetual.orders.getOrderHash(fullFlagOrder));
expect(logs[0].args.maker).to.equal(fullFlagOrder.maker);
});
it('Succeeds in double-canceling order', async () => {
await ctx.perpetual.orders.cancelOrder(fullFlagOrder, { from: fullFlagOrder.maker });
await ctx.perpetual.orders.cancelOrder(fullFlagOrder, { from: fullFlagOrder.maker });
await expectStatus(fullFlagOrder, OrderStatus.Canceled);
});
it('Fails if caller is not the maker', async () => {
await expectThrow(
ctx.perpetual.orders.cancelOrder(fullFlagOrder, { from: fullFlagOrder.taker }),
'Order cannot be canceled by non-maker',
);
});
it('Succeeds in canceling approved order', async () => {
await ctx.perpetual.orders.approveOrder(fullFlagOrder, { from: fullFlagOrder.maker });
await ctx.perpetual.orders.cancelOrder(fullFlagOrder, { from: fullFlagOrder.maker });
await expectStatus(fullFlagOrder, OrderStatus.Canceled);
});
});
describe('trade()', () => {
describe('basic success cases', () => {
it('fills a bid at the limit price', async () => {
await fillOrder();
});
it('fills an ask at the limit price', async () => {
await fillOrder({ isBuy: false });
});
it('fills a bid below the limit price', async () => {
await fillOrder(
{},
{ price: limitPrice.minus(25) },
);
});
it('fills an ask above the limit price', async () => {
await fillOrder(
{ isBuy: false },
{ price: limitPrice.plus(25) },
);
});
it('fills a bid with a fee less than the limit fee', async () => {
await fillOrder(
{},
{
fee: defaultOrder.limitFee.div(2),
price: limitPrice.minus(25),
},
);
});
it('fills an ask with a fee less than the limit fee', async () => {
await fillOrder(
{ isBuy: false },
{
fee: defaultOrder.limitFee.div(2),
price: limitPrice.plus(25),
},
);
});
it('succeeds if sender is a local operator', async () => {
await ctx.perpetual.operator.setLocalOperator(
otherUser,
true,
{ from: defaultOrder.taker },
);
await fillOrder({}, { sender: otherUser });
});
it('succeeds if sender is a global operator', async () => {
await ctx.perpetual.admin.setGlobalOperator(
otherUser,
true,
{ from: admin },
);
await fillOrder({}, { sender: otherUser });
});
it('succeeds with an invalid signature for an order approved on-chain', async () => {
await ctx.perpetual.orders.approveOrder(defaultOrder, { from: defaultOrder.maker });
const order = {
...defaultSignedOrder,
typedSignature: `0xff${defaultSignedOrder.typedSignature.substr(4)}`,
};
await fillOrder(order);
});
it('succeeds repeating an order (with a different salt)', async () => {
await fillOrder();
await fillOrder({ salt: defaultOrder.salt.plus(1) });
});
});
describe('basic failure cases', () => {
it('fails for calls not from the perpetual contract', async () => {
await expectThrow(
ctx.perpetual.contracts.send(
ctx.perpetual.contracts.p1Orders.methods.trade(
admin,
admin,
admin,
'0',
'0x',
boolToBytes32(false),
),
{ from: admin },
),
'msg.sender must be PerpetualV1',
);
});
it('fails if sender is not the taker or an authorized operator', async () => {
await expectThrow(
fillOrder(defaultSignedOrder, { sender: otherUser }),
'Sender does not have permissions for the taker',
);
});
it('fails for bad signature', async () => {
const order = {
...defaultSignedOrder,
typedSignature: `0xffff${defaultSignedOrder.typedSignature.substr(6)}`,
};
await expectThrow(
fillOrder(order),
'Order has an invalid signature',
);
});
it('fails for canceled order', async () => {
await ctx.perpetual.orders.cancelOrder(defaultOrder, { from: defaultOrder.maker });
await expectThrow(
fillOrder(),
'Order was already canceled',
);
});
it('fails for wrong maker', async () => {
const tradeData = ctx.perpetual.orders.fillToTradeData(
defaultSignedOrder,
orderAmount,
limitPrice,
defaultOrder.limitFee,
);
await expectThrow(
ctx.perpetual.trade
.initiate()
.addTradeArg({
maker: otherUser,
taker: defaultOrder.taker,
data: tradeData,
trader: ctx.perpetual.orders.address,
})
.commit({ from: defaultOrder.taker }),
'Order maker does not match maker',
);
});
it('fails for wrong taker', async () => {
const tradeData = ctx.perpetual.orders.fillToTradeData(
defaultSignedOrder,
orderAmount,
limitPrice,
defaultOrder.limitFee,
);
await expectThrow(
ctx.perpetual.trade
.initiate()
.addTradeArg({
maker: defaultOrder.maker,
taker: otherUser,
data: tradeData,
trader: ctx.perpetual.orders.address,
})
.commit({ from: otherUser }),
'Order taker does not match taker',
);
});
it('fails if the order has expired', async () => {
await expectThrow(
fillOrder({ expiration: new BigNumber(1) }),
'Order has expired',
);
});
it('fails to fill a bid at a price above the limit price', async () => {
await expectThrow(
fillOrder({}, { price: limitPrice.plus(1) }),
'Fill price is invalid',
);
});
it('fails to fill an ask at a price below the limit price', async () => {
await expectThrow(
fillOrder({ isBuy: false }, { price: limitPrice.minus(1) }),
'Fill price is invalid',
);
});
it('fails if fee is greater than limit fee', async () => {
await expectThrow(
fillOrder({}, { fee: defaultOrder.limitFee.plus(1) }),
'Fill fee is invalid',
);
});
it('fails to overfill order', async () => {
await expectThrow(
fillOrder({}, { amount: orderAmount.plus(1) }),
'Cannot overfill order',
);
});
it('fails to overfill partially filled order', async () => {
const halfAmount = orderAmount.div(2);
await fillOrder({}, { amount: halfAmount });
await expectThrow(
fillOrder({}, { amount: halfAmount.plus(1) }),
'Cannot overfill order',
);
});
it('fails for an order that was already filled', async () => {
await fillOrder();
await expectThrow(
fillOrder(),
'Cannot overfill order',
);
});
});
describe('with triggerPrice', () => {
it('fills a bid with the oracle price at the trigger price', async () => {
// limit bid |
// -5 | fill price
// -10 | trigger price, oracle price
const triggerPrice = limitPrice.minus(10);
const fillPrice = limitPrice.minus(5);
const oraclePrice = limitPrice.minus(10);
await setOraclePrice(ctx, oraclePrice);
await fillOrder({ triggerPrice }, { price: fillPrice });
});
it('fills an ask with the oracle price at the trigger price', async () => {
// +10 | trigger price, oracle price
// +5 | fill price
// limit ask |
const triggerPrice = limitPrice.plus(10);
const fillPrice = limitPrice.plus(5);
const oraclePrice = limitPrice.plus(10);
await setOraclePrice(ctx, oraclePrice);
await fillOrder({ triggerPrice, isBuy: false }, { price: fillPrice });
});
it('fills a bid with the oracle price above the trigger price', async () => {
// +10 | oracle price
// |
// limit bid |
// -5 | fill price
// -10 | trigger price
const triggerPrice = limitPrice.minus(10);
const fillPrice = limitPrice.minus(5);
const oraclePrice = limitPrice.plus(10);
await setOraclePrice(ctx, oraclePrice);
await fillOrder({ triggerPrice }, { price: fillPrice });
});
it('fills an ask with the oracle price below the trigger price', async () => {
// +10 | trigger price, oracle price
// +5 | fill price
// limit ask |
// |
// -10 | oracle price
const triggerPrice = limitPrice.plus(10);
const fillPrice = limitPrice.plus(5);
const oraclePrice = limitPrice.minus(10);
await setOraclePrice(ctx, oraclePrice);
await fillOrder({ triggerPrice, isBuy: false }, { price: fillPrice });
});
it('fails to fill a bid if the oracle price is below the trigger price', async () => {
// limit bid |
// -10 | trigger price
// -11 | oracle price
const triggerPrice = limitPrice.minus(10);
await setOraclePrice(ctx, triggerPrice.minus(1));
await expectThrow(
fillOrder({ triggerPrice }),
'Trigger price has not been reached',
);
});
it('fails to fill an ask if the oracle price is above the trigger price', async () => {
// +11 | oracle price
// +10 | trigger price
// limit ask |
const triggerPrice = limitPrice.plus(10);
await setOraclePrice(ctx, triggerPrice.plus(1));
await expectThrow(
fillOrder({ triggerPrice, isBuy: false }),
'Trigger price has not been reached',
);
});
});
describe('in decrease-only mode', () => {
it('fills a bid', async () => {
// Give the maker a short position.
const { limitFee, maker, taker } = defaultOrder;
const fee = limitFee.times(limitPrice.value);
const cost = limitPrice.value.plus(fee.value).times(orderAmount);
await sell(ctx, maker, taker, orderAmount, cost);
// Fill the order to decrease the short position to zero.
await fillOrder({ isDecreaseOnly: true });
});
it('fills an ask', async () => {
// Give the maker a long position.
const { limitFee, maker, taker } = defaultOrder;
const fee = limitFee.times(limitPrice.value).negated();
const cost = limitPrice.value.plus(fee.value).times(orderAmount);
await buy(ctx, maker, taker, orderAmount, cost);
// Fill the order to decrease the long position to zero.
await fillOrder({ isBuy: false, isDecreaseOnly: true });
});
it('fails to fill a bid if maker position is positive', async () => {
const { maker, taker } = defaultOrder;
await buy(ctx, maker, taker, new BigNumber(1), limitPrice.value);
await expectThrow(
fillOrder({ isDecreaseOnly: true }),
'Fill does not decrease position',
);
});
it('fails to fill an ask if maker position is negative', async () => {
const { maker, taker } = defaultOrder;
await sell(ctx, maker, taker, new BigNumber(1), limitPrice.value);
await expectThrow(
fillOrder({ isBuy: false, isDecreaseOnly: true }),
'Fill does not decrease position',
);
});
it('fails to fill a bid if maker position would become positive', async () => {
const { maker, taker } = defaultOrder;
const cost = limitPrice.value.times(orderAmount.minus(1));
await sell(ctx, maker, taker, orderAmount.minus(1), cost);
await expectThrow(
fillOrder({ isDecreaseOnly: true }),
'Fill does not decrease position',
);
});
it('fails to fill an ask if maker position would become negative', async () => {
const { maker, taker } = defaultOrder;
const cost = limitPrice.value.times(orderAmount.minus(1));
await buy(ctx, maker, taker, orderAmount.minus(1), cost);
await expectThrow(
fillOrder({ isBuy: false, isDecreaseOnly: true }),
'Fill does not decrease position',
);
});
});
describe('with negative limit fee', () => {
it('fills a bid', async () => {
const negativeFee = new Fee(defaultOrder.limitFee.value.abs().negated());
await fillOrder({ limitFee: negativeFee });
});
it('fills an ask', async () => {
const negativeFee = new Fee(defaultOrder.limitFee.value.abs().negated());
await fillOrder({ isBuy: false, limitFee: negativeFee });
});
it('fails if fee is greater than limit fee', async () => {
await expectThrow(
fillOrder(fullFlagSignedOrder, { fee: fullFlagOrder.limitFee.plus(1) }),
'Fill fee is invalid',
);
});
});
});
// ============ Helper Functions ============
async function getModifiedOrder(
args: Partial<Order>,
): Promise<SignedOrder> {
const newOrder: Order = {
...defaultOrder,
...args,
};
return ctx.perpetual.orders.getSignedOrder(newOrder, SigningMethod.Hash);
}
/**
* Fill an order.
*
* Check that logs and balance updates are as expected.
*/
async function fillOrder(
orderArgs: Partial<SignedOrder> = {},
fillArgs: {
amount?: BigNumber,
price?: Price,
fee?: Fee,
sender?: address,
} = {},
): Promise<void> {
const order: SignedOrder = orderArgs.typedSignature
? orderArgs as SignedOrder
: await getModifiedOrder(orderArgs);
const fillAmount = (fillArgs.amount || order.amount).dp(0, BigNumber.ROUND_DOWN);
const fillPrice = fillArgs.price || order.limitPrice;
const fillFee = fillArgs.fee || order.limitFee;
const sender = fillArgs.sender || order.taker;
// Get initial balances.
const [makerBalance, takerBalance] = await Promise.all([
ctx.perpetual.getters.getAccountBalance(order.maker),
ctx.perpetual.getters.getAccountBalance(order.taker),
]);
const { margin: makerMargin, position: makerPosition } = makerBalance;
const { margin: takerMargin, position: takerPosition } = takerBalance;
// Fill the order.
const txResult = await ctx.perpetual.trade
.initiate()
.fillSignedOrder(
order,
fillAmount,
fillPrice,
fillFee,
)
.commit({ from: sender });
// Check final balances.
const {
marginDelta,
positionDelta,
} = ctx.perpetual.orders.getBalanceUpdatesAfterFillingOrder(
fillAmount,
fillPrice,
fillFee,
order.isBuy,
);
await expectBalances(
ctx,
txResult,
[order.maker, order.taker],
[makerMargin.plus(marginDelta), takerMargin.minus(marginDelta)],
[makerPosition.plus(positionDelta), takerPosition.minus(positionDelta)],
);
// Check logs.
const logs = ctx.perpetual.logs.parseLogs(txResult);
const filteredLogs = _.filter(logs, { name: 'LogOrderFilled' });
expect(filteredLogs.length).to.equal(1);
const [log] = filteredLogs;
expect(log.args.orderHash, 'log hash').to.equal(ctx.perpetual.orders.getOrderHash(order));
expect(log.args.flags.isBuy, 'log isBuy').to.equal(order.isBuy);
expect(log.args.flags.isDecreaseOnly, 'log isDecreaseOnly').to.equal(order.isDecreaseOnly);
expect(log.args.flags.isNegativeLimitFee, 'log isNegativeLimitFee').to.equal(
order.limitFee.isNegative(),
);
expectBaseValueEqual(log.args.triggerPrice, order.triggerPrice, 'log trigger price');
expectBN(log.args.fill.amount, 'log fill amount').to.equal(fillAmount);
expectBaseValueEqual(log.args.fill.price, fillPrice, 'log fill price');
expectBaseValueEqual(log.args.fill.fee, fillFee.abs(), 'log fill fee');
expect(log.args.fill.isNegativeFee, 'log fill isNegativeLimitFee').to.equal(
order.limitFee.isNegative(),
);
}
async function expectStatus(
order: Order,
status: OrderStatus,
filledAmount?: BigNumber,
) {
const statuses = await ctx.perpetual.orders.getOrdersStatus([order]);
expect(statuses[0].status).to.equal(status);
if (filledAmount) {
expectBN(statuses[0].filledAmount).to.equal(filledAmount);
}
}
});
/**
* Update the oracle price.
*/
async function setOraclePrice(ctx: ITestContext, price: Price): Promise<void> {
await ctx.perpetual.testing.oracle.setPrice(price);
} | the_stack |
import * as loginPage from '../../Base/pages/Login.po';
import { LoginPageData } from '../../Base/pagedata/LoginPageData';
import * as organizationHelpCenterPage from '../../Base/pages/OrganizationHelpCenter.po';
import { OrganizationHelpCenterPageData } from '../../Base/pagedata/OrganizationHelpCenterPageData';
import * as dashboardPage from '../../Base/pages/Dashboard.po';
import { CustomCommands } from '../../commands';
import * as faker from 'faker';
import * as manageEmployeesPage from '../../Base/pages/ManageEmployees.po';
import * as logoutPage from '../../Base/pages/Logout.po';
import { Given, Then, When, And } from 'cypress-cucumber-preprocessor/steps';
const pageLoadTimeout = Cypress.config('pageLoadTimeout');
let articleName = faker.name.title();
let empFirstName = faker.name.firstName();
let empLastName = faker.name.lastName();
let empUsername = faker.internet.userName();
let empPassword = faker.internet.password();
let employeeEmail = faker.internet.email();
let empImgUrl = faker.image.avatar();
let desc = faker.lorem.words();
let articleText = faker.lorem.paragraph();
// Login with email
Given(
'Login with default credentials',
() => {
CustomCommands.login(loginPage, LoginPageData, dashboardPage);
}
);
// Add new employee
And('User can add new employee', () => {
CustomCommands.addEmployee(
manageEmployeesPage,
empFirstName,
empLastName,
empUsername,
employeeEmail,
empPassword,
empImgUrl
);
});
// Add base
Then('User visit Organization help center page',() => {
CustomCommands.logout(dashboardPage, logoutPage, loginPage);
CustomCommands.clearCookies();
CustomCommands.login(loginPage, LoginPageData, dashboardPage);
cy.visit('/#/pages/organization/help-center', { timeout: pageLoadTimeout });
});
And('User can see add button', () => {
organizationHelpCenterPage.addButtonVisible();
});
When('User click on add button', () => {
organizationHelpCenterPage.clickAddButton();
});
And('User can see publish button', () => {
organizationHelpCenterPage.publishButtonVisible();
});
When('User click on publish button', () => {
organizationHelpCenterPage.clickPublishButton();
});
Then('User can see icon button', () => {
organizationHelpCenterPage.iconDropdownVisible();
});
When('User click on icon button', () => {
organizationHelpCenterPage.clickIconDropdown();
});
Then('User can select first item from dropdown', () => {
organizationHelpCenterPage.selectIconFromDropdown(0);
});
And('User can see color input field', () => {
organizationHelpCenterPage.colorInputVisible();
});
And('User can enter value for color', () => {
organizationHelpCenterPage.enterColorInputData(
OrganizationHelpCenterPageData.defaultColor
);
});
And('User can see name input field', () => {
organizationHelpCenterPage.nameInputVisible();
});
And('User can enter name', () => {
organizationHelpCenterPage.enterNameInputData(
OrganizationHelpCenterPageData.defaultBaseName
);
});
And('User can see description input field', () => {
organizationHelpCenterPage.descriptionInputVisible();
});
And('User can enter description', () => {
organizationHelpCenterPage.enterDescriptionInputData(
OrganizationHelpCenterPageData.defaultBaseDescription
);
});
And('User can see save button', () => {
organizationHelpCenterPage.saveButtonVisible();
});
When('User click on save button', () => {
organizationHelpCenterPage.clickSaveButton();
});
Then('Notification message will appear', () => {
organizationHelpCenterPage.waitMessageToHide();
});
And('User can verify base was created', () => {
organizationHelpCenterPage.verifybaseExists(
OrganizationHelpCenterPageData.defaultBaseName
);
});
//Add category
And('User can see settings button', () => {
organizationHelpCenterPage.settingsButtonVisible();
});
Then('User click on settings button', () => {
organizationHelpCenterPage.clickSettingsButton(OrganizationHelpCenterPageData.settingsButton);
});
Then('User can see category button', () => {
organizationHelpCenterPage.addCategoryOptionVisible();
});
When('User click on add category button', () => {
organizationHelpCenterPage.clickAddCategotyOption(
OrganizationHelpCenterPageData.addCategoryOption
);
});
Then('User can see icon button', () => {
organizationHelpCenterPage.iconDropdownVisible();
});
When('User click on icon button', () => {
organizationHelpCenterPage.clickIconDropdown();
});
Then('User can select second item from dropdown', () => {
organizationHelpCenterPage.selectIconFromDropdown(1);
});
And('User can see color input field', () => {
organizationHelpCenterPage.colorInputVisible();
});
And('User can enter value for color', () => {
organizationHelpCenterPage.enterColorInputData(
OrganizationHelpCenterPageData.defaultColor
);
});
And('User can see name input field', () => {
organizationHelpCenterPage.nameInputVisible();
});
And('User can enter name', () => {
organizationHelpCenterPage.enterNameInputData(
OrganizationHelpCenterPageData.defaultBaseName
);
});
And('User can see description input field', () => {
organizationHelpCenterPage.descriptionInputVisible();
});
And('User can enter description', () => {
organizationHelpCenterPage.enterDescriptionInputData(
OrganizationHelpCenterPageData.defaultBaseDescription
);
});
And('User can see save button', () => {
organizationHelpCenterPage.saveButtonVisible();
});
When('User click on save button', () => {
organizationHelpCenterPage.clickSaveButton();
});
Then('Notification message will appear', () => {
organizationHelpCenterPage.waitMessageToHide();
});
And('User can see arrow button',() => {
organizationHelpCenterPage.arrowButtonVisible();
});
Then('User click on arrow button', () => {
organizationHelpCenterPage.clickArrowButton(OrganizationHelpCenterPageData.arrowIndex);
});
And('User can verify category was created', () => {
organizationHelpCenterPage.verifyCategoryExists(
OrganizationHelpCenterPageData.defaultBaseName
);
});
//Add article
Then('User click on the category',() => {
organizationHelpCenterPage.clickOnCategory(OrganizationHelpCenterPageData.categoryOption);
});
Then('User can see add article button', () => {
organizationHelpCenterPage.verifyAddArticleButton(OrganizationHelpCenterPageData.addArticleButton);
});
When('User click on the add article button', () => {
organizationHelpCenterPage.clickOnAddArticleButton(OrganizationHelpCenterPageData.addArticleButton);
});
And('User can see input for name of the article', () => {
organizationHelpCenterPage.verifyNameOfTheArticleInput();
});
And('User can enter name of the article', () => {
organizationHelpCenterPage.enterArticleName(articleName);
});
And('User can see input for description of the article', () => {
organizationHelpCenterPage.verifyDescOfTheArticleInput();
});
And('User can enter description of the article', () => {
organizationHelpCenterPage.enterDescName(desc);
})
And('User can see employee placeholder field', () => {
organizationHelpCenterPage.verifyEmployeePlaceholderField(OrganizationHelpCenterPageData.employeePlaceholder);
});
And('User click employee placeholder field', () => {
organizationHelpCenterPage.clickOnEmployeePlaceholderField(OrganizationHelpCenterPageData.employeePlaceholder);
})
Then('User can select employee from dropdown', () => {
organizationHelpCenterPage.clickEmployeeDropdown(OrganizationHelpCenterPageData.employeeOption);
organizationHelpCenterPage.clickOnEmployeePlaceholderField(OrganizationHelpCenterPageData.employeePlaceholder);
});
Then('User can see article text', () => {
organizationHelpCenterPage.verifyArticleText();
})
When('User enter in article text', () => {
organizationHelpCenterPage.enterArticleText(articleText);
});
Then('User can see article save button', () => {
organizationHelpCenterPage.verifyArticleSaveBtn();
})
And('User click on article save button', () => {
organizationHelpCenterPage.clickArticleSaveBtn();
})
// Edit base
And('User can see settings button', () => {
organizationHelpCenterPage.settingsButtonVisible();
});
When('User click on settings button', () => {
organizationHelpCenterPage.clickSettingsButton(OrganizationHelpCenterPageData.settingsButton);
});
Then('User can see edit button', () => {
organizationHelpCenterPage.editBaseOptionVisible();
});
When('User click on edit button', () => {
organizationHelpCenterPage.clickEditBaseOption(
OrganizationHelpCenterPageData.editBaseOption
);
});
Then('User can see color input field again', () => {
organizationHelpCenterPage.colorInputVisible();
});
And('User can edit color', () => {
organizationHelpCenterPage.enterColorInputData(
OrganizationHelpCenterPageData.defaultColor
);
});
And('User can see name input field again', () => {
organizationHelpCenterPage.nameInputVisible();
});
And('User can edit name', () => {
organizationHelpCenterPage.enterNameInputData(
OrganizationHelpCenterPageData.defaultBaseName
);
});
And('User can see description input field', () => {
organizationHelpCenterPage.descriptionInputVisible();
});
And('User can edit description', () => {
organizationHelpCenterPage.enterDescriptionInputData(
OrganizationHelpCenterPageData.defaultBaseDescription
);
});
And('User can see save edited base button', () => {
organizationHelpCenterPage.saveButtonVisible();
});
When('User click on save edited base button', () => {
organizationHelpCenterPage.clickSaveButton();
});
Then('Notification message will appear', () => {
organizationHelpCenterPage.waitMessageToHide();
});
// Delete base
And('User can see settings button again', () => {
organizationHelpCenterPage.settingsButtonVisible();
});
When('User click on settings button again', () => {
organizationHelpCenterPage.clickSettingsButton(OrganizationHelpCenterPageData.settingsButton);
});
Then('User can see delete base option', () => {
organizationHelpCenterPage.deleteBaseOptionVisible();
});
When('User click on delete base option', () => {
organizationHelpCenterPage.clickDeleteBaseOption(
OrganizationHelpCenterPageData.deleteBaseOption
);
});
Then('User can see delete button', () => {
organizationHelpCenterPage.deleteButtonVisible();
});
When('User click on delete button', () => {
organizationHelpCenterPage.clickDeleteButton();
});
Then('Notification message will appear', () => {
organizationHelpCenterPage.waitMessageToHide();
}); | the_stack |
import { ComponentEvent } from "@egjs/component";
import ImReady from "@egjs/imready";
import Flicking, { FlickingOptions } from "../Flicking";
import Panel, { PanelOptions } from "../core/panel/Panel";
import FlickingError from "../core/FlickingError";
import { ALIGN, EVENTS } from "../const/external";
import * as ERROR from "../const/error";
import { getFlickingAttached, getMinusCompensatedIndex, includes, parsePanelAlign } from "../utils";
import RenderingStrategy from "./strategy/RenderingStrategy";
export interface RendererOptions {
align?: FlickingOptions["align"];
strategy: RenderingStrategy;
}
/**
* A component that manages {@link Panel} and its elements
* @ko {@link Panel}๊ณผ ๊ทธ ์๋ฆฌ๋จผํธ๋ค์ ๊ด๋ฆฌํ๋ ์ปดํฌ๋ํธ
*/
abstract class Renderer {
// Internal States
protected _flicking: Flicking | null;
protected _panels: Panel[];
// Options
protected _align: NonNullable<RendererOptions["align"]>;
protected _strategy: RendererOptions["strategy"];
// Internal states Getter
/**
* Array of panels
* @ko ์ ์ฒด ํจ๋๋ค์ ๋ฐฐ์ด
* @type {Panel[]}
* @readonly
* @see Panel
*/
public get panels() { return this._panels; }
/**
* Count of panels
* @ko ์ ์ฒด ํจ๋์ ๊ฐ์
* @type {number}
* @readonly
*/
public get panelCount() { return this._panels.length; }
/**
* @internal
*/
public get strategy() { return this._strategy; }
// Options Getter
/**
* A {@link Panel}'s {@link Panel#align align} value that applied to all panels
* @ko {@link Panel}์ ๊ณตํต์ ์ผ๋ก ์ ์ฉํ {@link Panel#align align} ๊ฐ
* @type {Constants.ALIGN | string | number}
*/
public get align() { return this._align; }
// Options Setter
public set align(val: NonNullable<RendererOptions["align"]>) {
this._align = val;
const panelAlign = parsePanelAlign(val);
this._panels.forEach(panel => { panel.align = panelAlign; });
}
/**
* @param {object} options An options object<ko>์ต์
์ค๋ธ์ ํธ</ko>
* @param {Constants.ALIGN | string | number} [options.align="center"] An {@link Flicking#align align} value that will be applied to all panels<ko>์ ์ฒด ํจ๋์ ์ ์ฉ๋ {@link Flicking#align align} ๊ฐ</ko>
* @param {object} [options.strategy] An instance of RenderingStrategy(internal module)<ko>RenderingStrategy์ ์ธ์คํด์ค(๋ด๋ถ ๋ชจ๋)</ko>
*/
public constructor({
align = ALIGN.CENTER,
strategy
}: RendererOptions) {
this._flicking = null;
this._panels = [];
// Bind options
this._align = align;
this._strategy = strategy;
}
/**
* Render panel elements inside the camera element
* @ko ํจ๋ ์๋ฆฌ๋จผํธ๋ค์ ์นด๋ฉ๋ผ ์๋ฆฌ๋จผํธ ๋ด๋ถ์ ๋ ๋๋งํฉ๋๋ค
* @method
* @abstract
* @memberof Renderer
* @instance
* @name render
* @chainable
* @return {this}
*/
public abstract render(): Promise<void>;
protected abstract _collectPanels(): void;
protected abstract _createPanel(el: any, options: Omit<PanelOptions, "elementProvider">): Panel;
/**
* Initialize Renderer
* @ko Renderer๋ฅผ ์ด๊ธฐํํฉ๋๋ค
* @param {Flicking} flicking An instance of {@link Flicking}<ko>Flicking์ ์ธ์คํด์ค</ko>
* @chainable
* @return {this}
*/
public init(flicking: Flicking): this {
this._flicking = flicking;
this._collectPanels();
return this;
}
/**
* Destroy Renderer and return to initial state
* @ko Renderer๋ฅผ ์ด๊ธฐ ์ํ๋ก ๋๋๋ฆฝ๋๋ค
* @return {void}
*/
public destroy(): void {
this._flicking = null;
this._panels = [];
}
/**
* Return the {@link Panel} at the given index. `null` if it doesn't exists.
* @ko ์ฃผ์ด์ง ์ธ๋ฑ์ค์ ํด๋นํ๋ {@link Panel}์ ๋ฐํํฉ๋๋ค. ์ฃผ์ด์ง ์ธ๋ฑ์ค์ ํด๋นํ๋ ํจ๋์ด ์กด์ฌํ์ง ์์ ๊ฒฝ์ฐ `null`์ ๋ฐํํฉ๋๋ค.
* @return {Panel | null} Panel at the given index<ko>์ฃผ์ด์ง ์ธ๋ฑ์ค์ ํด๋นํ๋ ํจ๋</ko>
* @see Panel
*/
public getPanel(index: number): Panel | null {
return this._panels[index] || null;
}
public forceRenderAllPanels(): Promise<void> {
this._panels.forEach(panel => panel.markForShow());
return Promise.resolve();
}
/**
* Update all panel sizes
* @ko ๋ชจ๋ ํจ๋์ ํฌ๊ธฐ๋ฅผ ์
๋ฐ์ดํธํฉ๋๋ค
* @chainable
* @return {this}
*/
public updatePanelSize(): this {
const flicking = getFlickingAttached(this._flicking);
const panels = this._panels;
if (panels.length <= 0) return this;
if (flicking.panelsPerView > 0) {
const firstPanel = panels[0];
firstPanel.resize();
this._updatePanelSizeByGrid(firstPanel, panels);
} else {
flicking.panels.forEach(panel => panel.resize());
}
return this;
}
/**
* Insert new panels at given index
* This will increase index of panels after by the number of panels added
* @ko ์ฃผ์ด์ง ์ธ๋ฑ์ค์ ์๋ก์ด ํจ๋๋ค์ ์ถ๊ฐํฉ๋๋ค
* ํด๋น ์ธ๋ฑ์ค๋ณด๋ค ๊ฐ๊ฑฐ๋ ํฐ ์ธ๋ฑ์ค๋ฅผ ๊ฐ์ง ๊ธฐ์กด ํจ๋๋ค์ ์ถ๊ฐํ ํจ๋์ ๊ฐ์๋งํผ ์ธ๋ฑ์ค๊ฐ ์ฆ๊ฐํฉ๋๋ค.
* @param {Array<object>} items An array of items to insert<ko>์ถ๊ฐํ ์์ดํ
๋ค์ ๋ฐฐ์ด</ko>
* @param {number} [items.index] Index to insert new panels at<ko>์๋ก ํจ๋๋ค์ ์ถ๊ฐํ ์ธ๋ฑ์ค</ko>
* @param {any[]} [items.elements] An array of element or framework component with element in it<ko>์๋ฆฌ๋จผํธ์ ๋ฐฐ์ด ํน์ ํ๋ ์์ํฌ์์ ์๋ฆฌ๋จผํธ๋ฅผ ํฌํจํ ์ปดํฌ๋ํธ๋ค์ ๋ฐฐ์ด</ko>
* @param {boolean} [items.hasDOMInElements] Whether it contains actual DOM elements. If set to true, renderer will add them to the camera element<ko>๋ด๋ถ์ ์ค์ DOM ์๋ฆฌ๋จผํธ๋ค์ ํฌํจํ๊ณ ์๋์ง ์ฌ๋ถ. true๋ก ์ค์ ํ ๊ฒฝ์ฐ, ๋ ๋๋ฌ๋ ํด๋น ์๋ฆฌ๋จผํธ๋ค์ ์นด๋ฉ๋ผ ์๋ฆฌ๋จผํธ ๋ด๋ถ์ ์ถ๊ฐํฉ๋๋ค</ko>
* @return {Panel[]} An array of prepended panels<ko>์ถ๊ฐ๋ ํจ๋๋ค์ ๋ฐฐ์ด</ko>
*/
public batchInsert(...items: Array<{
index: number;
elements: any[];
hasDOMInElements: boolean;
}>): Panel[] {
const panels = this._panels;
const flicking = getFlickingAttached(this._flicking);
const { control } = flicking;
const prevFirstPanel = panels[0];
const align = parsePanelAlign(this._align);
const allPanelsInserted = items.reduce((addedPanels, item) => {
const insertingIdx = getMinusCompensatedIndex(item.index, panels.length);
const panelsPushed = panels.slice(insertingIdx);
const panelsInserted = item.elements.map((el, idx) => this._createPanel(el, { index: insertingIdx + idx, align, flicking }));
panels.splice(insertingIdx, 0, ...panelsInserted);
if (item.hasDOMInElements) {
// Insert the actual elements as camera element's children
this._insertPanelElements(panelsInserted, panelsPushed[0] ?? null);
}
// Resize the newly added panels
if (flicking.panelsPerView > 0) {
const firstPanel = prevFirstPanel || panelsInserted[0].resize();
this._updatePanelSizeByGrid(firstPanel, panelsInserted);
} else {
panelsInserted.forEach(panel => panel.resize());
}
// Update panel indexes & positions
panelsPushed.forEach(panel => {
panel.increaseIndex(panelsInserted.length);
panel.updatePosition();
});
return [...addedPanels, ...panelsInserted];
}, []);
if (allPanelsInserted.length <= 0) return [];
// Update camera & control
this._updateCameraAndControl();
void this.render();
// Move to the first panel added if no panels existed
// FIXME: fix for animating case
if (allPanelsInserted.length > 0 && !control.animating) {
void control.moveToPanel(control.activePanel || allPanelsInserted[0], {
duration: 0
}).catch(() => void 0);
}
flicking.camera.updateOffset();
flicking.trigger(new ComponentEvent(EVENTS.PANEL_CHANGE, {
added: allPanelsInserted,
removed: []
}));
this.checkPanelContentsReady(allPanelsInserted);
return allPanelsInserted;
}
/**
* Remove the panel at the given index
* This will decrease index of panels after by the number of panels removed
* @ko ์ฃผ์ด์ง ์ธ๋ฑ์ค์ ํจ๋์ ์ ๊ฑฐํฉ๋๋ค
* ํด๋น ์ธ๋ฑ์ค๋ณด๋ค ํฐ ์ธ๋ฑ์ค๋ฅผ ๊ฐ์ง ๊ธฐ์กด ํจ๋๋ค์ ์ ๊ฑฐํ ํจ๋์ ๊ฐ์๋งํผ ์ธ๋ฑ์ค๊ฐ ๊ฐ์ํฉ๋๋ค
* @param {Array<object>} items An array of items to remove<ko>์ ๊ฑฐํ ์์ดํ
๋ค์ ๋ฐฐ์ด</ko>
* @param {number} [items.index] Index of panel to remove<ko>์ ๊ฑฐํ ํจ๋์ ์ธ๋ฑ์ค</ko>
* @param {number} [items.deleteCount=1] Number of panels to remove from index<ko>`index` ์ดํ๋ก ์ ๊ฑฐํ ํจ๋์ ๊ฐ์</ko>
* @param {boolean} [items.hasDOMInElements=1] Whether it contains actual DOM elements. If set to true, renderer will remove them from the camera element<ko>๋ด๋ถ์ ์ค์ DOM ์๋ฆฌ๋จผํธ๋ค์ ํฌํจํ๊ณ ์๋์ง ์ฌ๋ถ. true๋ก ์ค์ ํ ๊ฒฝ์ฐ, ๋ ๋๋ฌ๋ ํด๋น ์๋ฆฌ๋จผํธ๋ค์ ์นด๋ฉ๋ผ ์๋ฆฌ๋จผํธ ๋ด๋ถ์์ ์ ๊ฑฐํฉ๋๋ค</ko>
* @return An array of removed panels<ko>์ ๊ฑฐ๋ ํจ๋๋ค์ ๋ฐฐ์ด</ko>
*/
public batchRemove(...items: Array<{ index: number; deleteCount: number; hasDOMInElements: boolean }>): Panel[] {
const panels = this._panels;
const flicking = getFlickingAttached(this._flicking);
const { camera, control } = flicking;
const activePanel = control.activePanel;
const activeIndex = control.activeIndex;
const allPanelsRemoved = items.reduce((removed, item) => {
const { index, deleteCount } = item;
const removingIdx = getMinusCompensatedIndex(index, panels.length);
const panelsPulled = panels.slice(removingIdx + deleteCount);
const panelsRemoved = panels.splice(removingIdx, deleteCount);
if (panelsRemoved.length <= 0) return [];
// Update panel indexes & positions
panelsPulled.forEach(panel => {
panel.decreaseIndex(panelsRemoved.length);
panel.updatePosition();
});
if (item.hasDOMInElements) {
this._removePanelElements(panelsRemoved);
}
// Remove panel elements
panelsRemoved.forEach(panel => panel.destroy());
if (includes(panelsRemoved, activePanel)) {
control.resetActive();
}
return [...removed, ...panelsRemoved];
}, []);
// Update camera & control
this._updateCameraAndControl();
void this.render();
// FIXME: fix for animating case
if (allPanelsRemoved.length > 0 && !control.animating) {
const targetPanel = includes(allPanelsRemoved, activePanel)
? (panels[activeIndex] || panels[panels.length - 1])
: activePanel;
if (targetPanel) {
void control.moveToPanel(targetPanel, {
duration: 0
}).catch(() => void 0);
} else {
// All panels removed
camera.lookAt(0);
}
}
flicking.camera.updateOffset();
flicking.trigger(new ComponentEvent(EVENTS.PANEL_CHANGE, {
added: [],
removed: allPanelsRemoved
}));
return allPanelsRemoved;
}
/**
* @internal
*/
public checkPanelContentsReady(checkingPanels: Panel[]) {
const flicking = getFlickingAttached(this._flicking);
const resizeOnContentsReady = flicking.resizeOnContentsReady;
const panels = this._panels;
if (!resizeOnContentsReady || flicking.virtualEnabled) return;
const hasContents = (panel: Panel) => !!panel.element.querySelector("img, video");
checkingPanels = checkingPanels.filter(panel => hasContents(panel));
if (checkingPanels.length <= 0) return;
const contentsReadyChecker = new ImReady();
checkingPanels.forEach(panel => {
panel.loading = true;
});
contentsReadyChecker.on("readyElement", e => {
if (!this._flicking) {
// Renderer's destroy() is called before
contentsReadyChecker.destroy();
return;
}
const panel = checkingPanels[e.index];
const camera = flicking.camera;
const control = flicking.control;
const prevProgressInPanel = control.activePanel
? camera.getProgressInPanel(control.activePanel)
: 0;
panel.loading = false;
panel.resize();
panels.slice(panel.index + 1).forEach(panelBehind => panelBehind.updatePosition());
if (!flicking.initialized) return;
camera.updateRange();
camera.updateAnchors();
if (control.animating) {
// TODO: Need Axes update
} else {
control.updatePosition(prevProgressInPanel);
control.updateInput();
}
});
contentsReadyChecker.on("preReady", e => {
if (this._flicking) {
void this.render();
}
if (e.readyCount === e.totalCount) {
contentsReadyChecker.destroy();
}
});
contentsReadyChecker.on("ready", () => {
if (this._flicking) {
void this.render();
}
contentsReadyChecker.destroy();
});
contentsReadyChecker.check(checkingPanels.map(panel => panel.element));
}
protected _updateCameraAndControl() {
const flicking = getFlickingAttached(this._flicking);
const { camera, control } = flicking;
camera.updateRange();
camera.updateAnchors();
camera.resetNeedPanelHistory();
control.updateInput();
}
protected _showOnlyVisiblePanels(flicking: Flicking) {
const panels = flicking.renderer.panels;
const camera = flicking.camera;
const visibleIndexes = camera.visiblePanels.reduce((visibles, panel) => {
visibles[panel.index] = true;
return visibles;
}, {});
panels.forEach(panel => {
if (panel.index in visibleIndexes || panel.loading) {
panel.markForShow();
} else if (!flicking.holding) {
// During the input sequence,
// Do not remove panel elements as it won't trigger touchend event.
panel.markForHide();
}
});
}
protected _updatePanelSizeByGrid(referencePanel: Panel, panels: Panel[]) {
const flicking = getFlickingAttached(this._flicking);
const panelsPerView = flicking.panelsPerView;
if (panelsPerView <= 0) {
throw new FlickingError(ERROR.MESSAGE.WRONG_OPTION("panelsPerView", panelsPerView), ERROR.CODE.WRONG_OPTION);
}
if (panels.length <= 0) return;
const viewportSize = flicking.camera.size;
const gap = referencePanel.margin.prev + referencePanel.margin.next;
const panelSize = (viewportSize - gap * (panelsPerView - 1)) / panelsPerView;
const panelSizeObj = flicking.horizontal
? { width: panelSize }
: { height: panelSize };
const firstPanelSizeObj = {
size: panelSize,
height: referencePanel.height,
margin: referencePanel.margin
};
if (!flicking.noPanelStyleOverride) {
this._strategy.updatePanelSizes(flicking, panelSizeObj);
}
flicking.panels.forEach(panel => panel.resize(firstPanelSizeObj));
}
protected _removeAllChildsFromCamera() {
const flicking = getFlickingAttached(this._flicking);
const cameraElement = flicking.camera.element;
// Remove other elements
while (cameraElement.firstChild) {
cameraElement.removeChild(cameraElement.firstChild);
}
}
protected _insertPanelElements(panels: Panel[], nextSibling: Panel | null = null) {
const flicking = getFlickingAttached(this._flicking);
const camera = flicking.camera;
const cameraElement = camera.element;
const nextSiblingElement = nextSibling?.element || null;
const fragment = document.createDocumentFragment();
panels.forEach(panel => fragment.appendChild(panel.element));
cameraElement.insertBefore(fragment, nextSiblingElement);
}
protected _removePanelElements(panels: Panel[]) {
const flicking = getFlickingAttached(this._flicking);
const cameraElement = flicking.camera.element;
panels.forEach(panel => {
cameraElement.removeChild(panel.element);
});
}
}
export default Renderer; | the_stack |
import test from 'tape';
import {
PenumbraAPI,
PenumbraFile,
PenumbraReady,
ProgressEmit,
} from '../types';
import { PenumbraSupportLevel } from '../enums';
import { hash, timeout } from './helpers';
import { TimeoutManager } from './helpers/timeout';
const view = self;
let penumbra: PenumbraAPI;
test('setup', async (t) => {
const onReady = async (event?: PenumbraReady) => {
// eslint-disable-next-line no-shadow
penumbra = ((event && event.detail.penumbra) ||
view.penumbra) as PenumbraAPI;
t.pass('setup finished');
t.end();
};
if (!view.penumbra) {
view.addEventListener('penumbra-ready', onReady);
} else {
onReady();
}
});
test('penumbra.supported() test', async (t) => {
t.assert(
penumbra.supported() >= PenumbraSupportLevel.size_limited,
'penumbra.supported() is PenumbraSupportLevel.size_limited or PenumbraSupportLevel.full',
);
t.end();
});
test('penumbra.get() and penumbra.getTextOrURI() test', async (t) => {
if (!self.TextEncoder) {
console.warn(
'skipping test due to lack of browser support for TextEncoder',
);
t.pass('test skipped');
t.end();
return;
}
const NYT = {
url: 'https://s3-us-west-2.amazonaws.com/bencmbrook/NYT.txt.enc',
filePrefix: 'NYT',
mimetype: 'text/plain',
decryptionOptions: {
key: 'vScyqmJKqGl73mJkuwm/zPBQk0wct9eQ5wPE8laGcWM=',
iv: '6lNU+2vxJw6SFgse',
authTag: 'gadZhS1QozjEmfmHLblzbg==',
},
};
const { type: test1Type, data: test1Text } = await penumbra.getTextOrURI(
await penumbra.get(NYT),
)[0];
const test1Hash = await hash(
'SHA-256',
new self.TextEncoder().encode(test1Text),
);
const ref1Hash =
'4933a43366fdda7371f02bb2a7e21b38f23db88a474b9abf9e33309cd15594d5';
t.equal(test1Type, 'text');
t.equal(test1Hash, ref1Hash);
t.end();
});
test('progress event test', async (t) => {
let result;
const progressEventName = 'penumbra-progress';
const fail = () => {
result = false;
};
const initTimeout = timeout(fail, 60);
let stallTimeout: TimeoutManager;
let initFinished = false;
let progressStarted = false;
let lastPercent: number;
const onprogress = ({ detail: { percent } }: ProgressEmit) => {
if (!Number.isNaN(percent)) {
if (percent === 100) {
// Resource is already loaded
if (initFinished) {
stallTimeout.clear();
} else {
initTimeout.clear();
}
view.removeEventListener(progressEventName, onprogress);
result = true;
return;
}
if (!initFinished) {
initTimeout.clear();
stallTimeout = timeout(fail, 10);
initFinished = true;
lastPercent = percent;
} else if (!progressStarted) {
if (percent > lastPercent) {
stallTimeout.clear();
progressStarted = true;
}
}
if (progressStarted && percent > 25) {
view.removeEventListener(progressEventName, onprogress);
result = true;
}
}
lastPercent = percent;
};
view.addEventListener(progressEventName, onprogress);
const [{ stream }] = await penumbra.get({
url: 'https://s3-us-west-2.amazonaws.com/bencmbrook/k.webm.enc',
filePrefix: 'k',
mimetype: 'video/webm',
decryptionOptions: {
key: 'vScyqmJKqGl73mJkuwm/zPBQk0wct9eQ5wPE8laGcWM=',
iv: '6lNU+2vxJw6SFgse',
authTag: 'K3MVZrK2/6+n8/p/74mXkQ==',
},
});
await new Response(stream).arrayBuffer();
t.ok(result);
t.end();
});
test('penumbra.get() with multiple resources', async (t) => {
const resources = await penumbra.get(
{
url: 'https://s3-us-west-2.amazonaws.com/bencmbrook/NYT.txt.enc',
filePrefix: 'NYT',
mimetype: 'text/plain',
decryptionOptions: {
key: 'vScyqmJKqGl73mJkuwm/zPBQk0wct9eQ5wPE8laGcWM=',
iv: '6lNU+2vxJw6SFgse',
authTag: 'gadZhS1QozjEmfmHLblzbg==',
},
},
{
url: 'https://s3-us-west-2.amazonaws.com/bencmbrook/tortoise.jpg.enc',
filePrefix: 'tortoise',
mimetype: 'image/jpeg',
decryptionOptions: {
key: 'vScyqmJKqGl73mJkuwm/zPBQk0wct9eQ5wPE8laGcWM=',
iv: '6lNU+2vxJw6SFgse',
authTag: 'ELry8dZ3djg8BRB+7TyXZA==',
},
},
);
const hashes = await Promise.all(
resources.map(async ({ stream }) =>
hash('SHA-256', await new Response(stream).arrayBuffer()),
),
);
const referenceHash1 =
'4933a43366fdda7371f02bb2a7e21b38f23db88a474b9abf9e33309cd15594d5';
const referenceHash2 =
'1d9b02f0f26815e2e5c594ff2d15cb8a7f7b6a24b6d14355ffc2f13443ba6b95';
t.equal(hashes[0], referenceHash1);
t.equal(hashes[1], referenceHash2);
t.end();
});
test('penumbra.get() images (as ReadableStream)', async (t) => {
const [{ stream }] = await penumbra.get({
url: 'https://s3-us-west-2.amazonaws.com/bencmbrook/tortoise.jpg.enc',
filePrefix: 'tortoise',
mimetype: 'image/jpeg',
decryptionOptions: {
key: 'vScyqmJKqGl73mJkuwm/zPBQk0wct9eQ5wPE8laGcWM=',
iv: '6lNU+2vxJw6SFgse',
authTag: 'ELry8dZ3djg8BRB+7TyXZA==',
},
});
const imageBytes = await new Response(stream).arrayBuffer();
const imageHash = await hash('SHA-256', imageBytes);
const referenceHash =
'1d9b02f0f26815e2e5c594ff2d15cb8a7f7b6a24b6d14355ffc2f13443ba6b95';
t.equal(imageHash, referenceHash);
t.end();
});
test('penumbra.getTextOrURI(): images (as URL)', async (t) => {
const { type, data: url } = await penumbra.getTextOrURI(
await penumbra.get({
url: 'https://s3-us-west-2.amazonaws.com/bencmbrook/tortoise.jpg.enc',
filePrefix: 'tortoise',
mimetype: 'image/jpeg',
decryptionOptions: {
key: 'vScyqmJKqGl73mJkuwm/zPBQk0wct9eQ5wPE8laGcWM=',
iv: '6lNU+2vxJw6SFgse',
authTag: 'ELry8dZ3djg8BRB+7TyXZA==',
},
}),
)[0];
let isURL;
try {
// tslint:disable-next-line: no-unused-expression
new URL(url, location.href); // eslint-disable-line no-new
isURL = type === 'uri';
} catch (ex) {
isURL = false;
}
const imageBytes = await fetch(url).then((r) => r.arrayBuffer());
const imageHash = await hash('SHA-256', imageBytes);
const referenceHash =
'1d9b02f0f26815e2e5c594ff2d15cb8a7f7b6a24b6d14355ffc2f13443ba6b95';
t.true(isURL);
t.equal(imageHash, referenceHash);
t.end();
});
test('penumbra.getTextOrURI(): including image in document', async (t) => {
const { data: url } = await penumbra.getTextOrURI(
await penumbra.get({
url: 'https://s3-us-west-2.amazonaws.com/bencmbrook/tortoise.jpg.enc',
filePrefix: 'tortoise',
mimetype: 'image/jpeg',
decryptionOptions: {
key: 'vScyqmJKqGl73mJkuwm/zPBQk0wct9eQ5wPE8laGcWM=',
iv: '6lNU+2vxJw6SFgse',
authTag: 'ELry8dZ3djg8BRB+7TyXZA==',
},
}),
)[0];
const testImage = new Image();
const result = await new Promise((resolve) => {
// 5-second timeout for the image to load
timeout(() => resolve(false), 5);
const onLoad = () => {
testImage.removeEventListener('load', onLoad);
testImage.remove();
resolve(true);
};
const onError = () => {
testImage.removeEventListener('error', onError);
testImage.remove();
resolve(false);
};
testImage.addEventListener('load', onLoad);
testImage.addEventListener('error', onError);
testImage.src = url;
// testImage.style.visibility = 'hidden';
// document.body.appendChild(testImage);
});
t.ok(result);
t.end();
});
test('penumbra.preconnect()', async (t) => {
const measurePreconnects = () =>
document.querySelectorAll('link[rel="preconnect"]').length;
const start = measurePreconnects();
const cleanup = penumbra.preconnect({
url: 'https://s3-us-west-2.amazonaws.com/bencmbrook/NYT.txt.enc',
filePrefix: 'NYT',
mimetype: 'text/plain',
decryptionOptions: {
key: 'vScyqmJKqGl73mJkuwm/zPBQk0wct9eQ5wPE8laGcWM=',
iv: '6lNU+2vxJw6SFgse',
authTag: 'gadZhS1QozjEmfmHLblzbg==',
},
});
const after = measurePreconnects();
cleanup();
t.assert(start < after);
t.end();
});
test('penumbra.preload()', async (t) => {
const measurePreloads = () =>
document.querySelectorAll(
'link[rel="preload"][as="fetch"][crossorigin="use-credentials"]',
).length;
const start = measurePreloads();
const cleanup = penumbra.preload({
url: 'https://s3-us-west-2.amazonaws.com/bencmbrook/NYT.txt.enc',
filePrefix: 'NYT',
mimetype: 'text/plain',
decryptionOptions: {
key: 'vScyqmJKqGl73mJkuwm/zPBQk0wct9eQ5wPE8laGcWM=',
iv: '6lNU+2vxJw6SFgse',
authTag: 'gadZhS1QozjEmfmHLblzbg==',
},
});
const after = measurePreloads();
cleanup();
t.assert(start < after);
t.end();
});
test('penumbra.getBlob()', async (t) => {
const blob = await penumbra.getBlob(
await penumbra.get({
url: 'https://s3-us-west-2.amazonaws.com/bencmbrook/tortoise.jpg.enc',
filePrefix: 'test/tortoise.jpg',
mimetype: 'image/jpeg',
decryptionOptions: {
key: 'vScyqmJKqGl73mJkuwm/zPBQk0wct9eQ5wPE8laGcWM=',
iv: '6lNU+2vxJw6SFgse',
authTag: 'ELry8dZ3djg8BRB+7TyXZA==',
},
}),
);
const imageBytes = await new Response(blob).arrayBuffer();
const imageHash = await hash('SHA-256', imageBytes);
const referenceHash =
'1d9b02f0f26815e2e5c594ff2d15cb8a7f7b6a24b6d14355ffc2f13443ba6b95';
t.equal(imageHash, referenceHash);
t.end();
});
test('penumbra.encrypt() & penumbra.decrypt()', async (t) => {
if (!self.TextEncoder || !self.TextDecoder) {
console.warn(
'skipping test due to lack of browser support for TextEncoder/TextDecoder',
);
t.pass('test skipped');
t.end();
return;
}
const te = new self.TextEncoder();
const td = new self.TextDecoder();
const input = 'test';
const buffer = te.encode(input);
const { byteLength: size } = buffer;
const stream = new Response(buffer).body;
const options = null;
const file = ({ stream, size } as unknown) as PenumbraFile;
const [encrypted] = await penumbra.encrypt(options, file);
const decryptionInfo = await penumbra.getDecryptionInfo(encrypted);
const [decrypted] = await penumbra.decrypt(decryptionInfo, encrypted);
const decryptedData = await new Response(decrypted.stream).arrayBuffer();
t.equal(td.decode(decryptedData), input);
t.end();
});
test('penumbra.saveZip({ saveBuffer: true }) - getBuffer(), getSize() and auto-renaming', async (t) => {
const expectedReferenceHashes = [
'318e197f7df584c339ec6d06490eb9cb3cdbb41c218809690d39d70d79dff48f',
'6cbf553053fcfe8b6c5e17313ef4383fcef4bc0cf3df48c904ed5e7b05af04a6',
'7559c3628a54a498b715edbbb9a0f16fc65e94eaaf185b41e91f6bddf1a8e02e',
];
let progressEventFiredAndWorking = false;
let completeEventFired = false;
const expectedProgressProps = ['percent', 'written', 'size'];
const writer = penumbra.saveZip({
/** onProgress handler */
onProgress(event) {
progressEventFiredAndWorking = expectedProgressProps.every(
(prop) => prop in event.detail,
);
},
/** onComplete handler */
onComplete() {
completeEventFired = true;
},
allowDuplicates: true,
saveBuffer: true,
});
writer.write(
...(await penumbra.get(
{
size: 874,
url: 'https://s3-us-west-2.amazonaws.com/bencmbrook/NYT.txt.enc',
path: 'test/NYT.txt',
mimetype: 'text/plain',
decryptionOptions: {
key: 'vScyqmJKqGl73mJkuwm/zPBQk0wct9eQ5wPE8laGcWM=',
iv: '6lNU+2vxJw6SFgse',
authTag: 'gadZhS1QozjEmfmHLblzbg==',
},
// for hash consistency
lastModified: new Date(0),
},
{
size: 874,
url: 'https://s3-us-west-2.amazonaws.com/bencmbrook/NYT.txt.enc',
path: 'test/NYT.txt',
mimetype: 'text/plain',
decryptionOptions: {
key: 'vScyqmJKqGl73mJkuwm/zPBQk0wct9eQ5wPE8laGcWM=',
iv: '6lNU+2vxJw6SFgse',
authTag: 'gadZhS1QozjEmfmHLblzbg==',
},
// for hash consistency
lastModified: new Date(0),
},
)),
);
writer.write(
...(await penumbra.get(
{
url: 'https://s3-us-west-2.amazonaws.com/bencmbrook/NYT.txt.enc',
path: 'test/NYT.txt',
mimetype: 'text/plain',
decryptionOptions: {
key: 'vScyqmJKqGl73mJkuwm/zPBQk0wct9eQ5wPE8laGcWM=',
iv: '6lNU+2vxJw6SFgse',
authTag: 'gadZhS1QozjEmfmHLblzbg==',
},
// for hash consistency
lastModified: new Date(0),
},
{
url: 'https://s3-us-west-2.amazonaws.com/bencmbrook/NYT.txt.enc',
path: 'test/NYT.txt',
mimetype: 'text/plain',
decryptionOptions: {
key: 'vScyqmJKqGl73mJkuwm/zPBQk0wct9eQ5wPE8laGcWM=',
iv: '6lNU+2vxJw6SFgse',
authTag: 'gadZhS1QozjEmfmHLblzbg==',
},
// for hash consistency
lastModified: new Date(0),
},
)),
);
await writer.close();
t.ok(
progressEventFiredAndWorking,
'zip progress event fired & emitted expected properties',
);
t.ok(completeEventFired, 'zip complete event fired');
t.pass('zip saved');
const zipBuffer = await writer.getBuffer();
const zipHash = await hash('SHA-256', zipBuffer);
console.log('zip hash:', zipHash);
t.ok(zipHash, 'zip hash');
t.ok(
expectedReferenceHashes.includes(zipHash.toLowerCase()),
`expected zip hash (actual: ${zipHash})`,
);
const size = await writer.getSize();
const expectedSize = 3496;
t.equals(size, expectedSize, `expected zip size (actual: ${size})`);
t.end();
}); | the_stack |
import { l } from "./Localization";
import { format } from "@wowts/string";
import { LuaObj, next, tostring, _G } from "@wowts/lua";
import {
GetTime,
PlaySoundFile,
UIFrame,
UIFontString,
UITexture,
UICooldown,
UICheckButton,
CreateFrame,
GameTooltip,
UIPosition,
} from "@wowts/wow-mock";
import { huge } from "@wowts/math";
import { NodeActionResult, AstIconNode } from "../engine/ast";
import { OvaleOptionsClass } from "./Options";
import { OvaleSpellBookClass } from "../states/SpellBook";
import { ActionType } from "../engine/best-action";
import { isNumber, isString } from "../tools/tools";
import { AceGUIWidgetCheckBox, AceGUIWidgetDropDown } from "@wowts/ace_gui-3.0";
import { LocalizationStrings } from "./localization/definition";
import { OvaleActionBarClass } from "../engine/action-bar";
const infinity = huge;
const cooldownThreshold = 0.1;
export interface IconParent {
checkBoxWidget: LuaObj<AceGUIWidgetCheckBox>;
listWidget: LuaObj<AceGUIWidgetDropDown>;
iconsFrame: UIFrame;
toggleOptions(): void;
debugIcon(index: number): void;
}
export class OvaleIcon {
actionHelp: string | undefined;
actionId: number | string | undefined;
actionType: ActionType | undefined;
actionButton = false;
namedParams: AstIconNode["rawNamedParams"] | undefined;
positionalParams: AstIconNode["rawPositionalParams"] | undefined;
texture: string | undefined;
cooldownStart: undefined | number;
cooldownEnd: undefined | number;
lastSound: string | undefined;
fontScale: undefined | number;
value: number | undefined;
help: keyof Required<LocalizationStrings> | undefined;
shouldClick = false;
cdShown = false;
focusText: UIFontString;
fontFlags: number;
fontHeight: number;
fontName: string;
normalTexture: UITexture;
cd: UICooldown;
rangeIndicator: UIFontString;
remains: UIFontString;
shortcut: UIFontString;
icon: UITexture;
frame: UICheckButton;
hasScriptControls() {
return (
next(this.parent.checkBoxWidget) != undefined ||
next(this.parent.listWidget) != undefined
);
}
constructor(
private index: number,
name: string,
private parent: IconParent,
secure: boolean,
private ovaleOptions: OvaleOptionsClass,
private ovaleSpellBook: OvaleSpellBookClass,
private actionBar: OvaleActionBarClass
) {
this.frame = CreateFrame(
"CheckButton",
name,
parent.iconsFrame,
(secure && "SecureActionButtonTemplate, ActionButtonTemplate") ||
"ActionButtonTemplate"
);
const profile = this.ovaleOptions.db.profile;
this.icon = _G[`${name}Icon`];
this.shortcut = _G[`${name}HotKey`];
this.remains = _G[`${name}Name`];
this.rangeIndicator = _G[`${name}Count`];
this.rangeIndicator.SetText(profile.apparence.targetText);
this.cd = _G[`${name}Cooldown`];
this.normalTexture = _G[`${name}NormalTexture`];
const [fontName, fontHeight, fontFlags] = this.shortcut.GetFont();
this.fontName = fontName;
this.fontHeight = fontHeight;
this.fontFlags = fontFlags;
this.focusText = this.frame.CreateFontString(undefined, "OVERLAY");
this.cdShown = true;
this.shouldClick = false;
this.help = undefined;
this.value = undefined;
this.fontScale = undefined;
this.lastSound = undefined;
this.cooldownEnd = undefined;
this.cooldownStart = undefined;
this.texture = undefined;
this.positionalParams = undefined;
this.namedParams = undefined;
this.actionButton = false;
this.actionType = undefined;
this.actionId = undefined;
this.actionHelp = undefined;
this.frame.SetScript("OnMouseUp", this.onMouseUp);
this.frame.SetScript("OnEnter", this.onEnter);
this.frame.SetScript("OnLeave", this.onLeave);
this.focusText.SetFontObject("GameFontNormalSmall");
this.focusText.SetAllPoints(this.frame);
this.focusText.SetTextColor(1, 1, 1);
this.focusText.SetText(l["focus"]);
this.frame.RegisterForClicks("AnyUp");
if (profile.apparence.clickThru) {
this.frame.EnableMouse(false);
}
}
setValue(value: number | undefined, actionTexture: string | undefined) {
this.icon.Show();
this.icon.SetTexture(actionTexture);
this.icon.SetAlpha(this.ovaleOptions.db.profile.apparence.alpha);
this.cd.Hide();
this.focusText.Hide();
this.rangeIndicator.Hide();
this.shortcut.Hide();
if (value) {
this.actionType = "value";
this.actionHelp = undefined;
this.value = value;
if (value < 10) {
this.remains.SetFormattedText("%.1f", value);
} else if (value == infinity) {
this.remains.SetFormattedText("inf");
} else {
this.remains.SetFormattedText("%d", value);
}
this.remains.Show();
} else {
this.remains.Hide();
}
this.frame.Show();
}
update(element: NodeActionResult, startTime?: number) {
this.actionType = element.actionType;
this.actionId = element.actionId;
this.value = undefined;
const now = GetTime();
const profile = this.ovaleOptions.db.profile;
if (startTime && element.actionTexture) {
const cd = this.cd;
let resetCooldown = false;
if (startTime > now) {
const duration = cd.GetCooldownDuration();
if (
duration == 0 &&
this.texture == element.actionTexture &&
this.cooldownStart &&
this.cooldownEnd
) {
resetCooldown = true;
}
if (
this.texture != element.actionTexture ||
!this.cooldownStart ||
!this.cooldownEnd
) {
this.cooldownStart = now;
this.cooldownEnd = startTime;
resetCooldown = true;
} else if (
startTime < this.cooldownEnd - cooldownThreshold ||
startTime > this.cooldownEnd + cooldownThreshold
) {
if (
startTime - this.cooldownEnd > 0.25 ||
startTime - this.cooldownEnd < -0.25
) {
this.cooldownStart = now;
} else {
const oldCooldownProgressPercent =
(now - this.cooldownStart) /
(this.cooldownEnd - this.cooldownStart);
this.cooldownStart =
(now - oldCooldownProgressPercent * startTime) /
(1 - oldCooldownProgressPercent);
}
this.cooldownEnd = startTime;
resetCooldown = true;
}
this.texture = element.actionTexture;
} else {
this.cooldownStart = undefined;
this.cooldownEnd = undefined;
}
if (
this.cdShown &&
profile.apparence.flashIcon &&
this.cooldownStart &&
this.cooldownEnd
) {
const [start, ending] = [this.cooldownStart, this.cooldownEnd];
const duration = ending - start;
if (resetCooldown && duration > cooldownThreshold) {
cd.SetDrawEdge(false);
cd.SetSwipeColor(0, 0, 0, 0.8);
cd.SetCooldown(start, duration);
}
cd.Show();
} else {
cd.Hide();
}
this.icon.Show();
this.icon.SetTexture(element.actionTexture);
if (element.actionUsable) {
this.icon.SetAlpha(1);
} else {
this.icon.SetAlpha(0.5);
}
const options = element.options;
if (options) {
if (
options.nored != 1 &&
element.actionResourceExtend &&
element.actionResourceExtend > 0
) {
this.icon.SetVertexColor(0.75, 0.2, 0.2);
} else {
this.icon.SetVertexColor(1, 1, 1);
}
if (isString(options.help)) this.actionHelp = options.help;
if (!(this.cooldownStart && this.cooldownEnd)) {
this.lastSound = undefined;
}
if (isString(options.sound) && !this.lastSound) {
let delay;
if (isNumber(options.soundtime)) delay = options.soundtime;
else delay = 0.5;
if (now >= startTime - delay) {
this.lastSound = options.sound;
PlaySoundFile(this.lastSound);
}
}
}
const red = false; // TODO This value is not set anymore, find why
if (!red && startTime > now && profile.apparence.highlightIcon) {
const lag = 0.6;
const newShouldClick = startTime < now + lag;
if (this.shouldClick != newShouldClick) {
if (newShouldClick) {
this.frame.SetChecked(true);
} else {
this.frame.SetChecked(false);
}
this.shouldClick = newShouldClick;
}
} else if (this.shouldClick) {
this.shouldClick = false;
this.frame.SetChecked(false);
}
if (
(profile.apparence.numeric ||
(this.namedParams &&
this.namedParams.text &&
this.namedParams.text.type === "string" &&
this.namedParams.text.value === "always")) &&
startTime > now
) {
this.remains.SetFormattedText("%.1f", startTime - now);
this.remains.Show();
} else {
this.remains.Hide();
}
let showShortcut = false;
if (profile.apparence.raccourcis && element.actionSlot) {
const binding = this.actionBar.getBindings(element.actionSlot);
if (binding) {
this.shortcut.SetText(binding);
showShortcut = true;
}
}
if (showShortcut) {
this.shortcut.Show();
} else {
this.shortcut.Hide();
}
if (element.actionInRange === undefined) {
this.rangeIndicator.Hide();
} else if (element.actionInRange) {
this.rangeIndicator.SetVertexColor(0.6, 0.6, 0.6);
this.rangeIndicator.Show();
} else {
this.rangeIndicator.SetVertexColor(1.0, 0.1, 0.1);
this.rangeIndicator.Show();
}
if (options && options.text) {
this.focusText.SetText(tostring(options.text));
this.focusText.Show();
} else if (
element.actionTarget &&
element.actionTarget != "target"
) {
this.focusText.SetText(element.actionTarget);
this.focusText.Show();
} else {
this.focusText.Hide();
}
this.frame.Show();
} else {
this.icon.Hide();
this.rangeIndicator.Hide();
this.shortcut.Hide();
this.remains.Hide();
this.focusText.Hide();
if (profile.apparence.hideEmpty) {
this.frame.Hide();
} else {
this.frame.Show();
}
if (this.shouldClick) {
this.frame.SetChecked(false);
this.shouldClick = false;
}
}
return [startTime, element];
}
setHelp(help: string | undefined) {
this.help = help as keyof Required<LocalizationStrings>;
}
setParams(
positionalParams: AstIconNode["rawPositionalParams"],
namedParams: AstIconNode["rawNamedParams"]
// secure?: boolean
) {
this.positionalParams = positionalParams;
this.namedParams = namedParams;
this.actionButton = false;
// if (secure) {
// for (const [k, v] of kpairs(namedParams)) {
// let [index] = find(k, "spell");
// if (index) {
// let prefix = sub(k, 1, index - 1);
// let suffix = sub(k, index + 5);
// this.frame.SetAttribute(`${prefix}type${suffix}`, "spell");
// this.frame.SetAttribute(
// "unit",
// this.namedParams.target || "target"
// );
// this.frame.SetAttribute(
// k,
// this.ovaleSpellBook.GetSpellName(<number>v) ||
// "Unknown spell"
// );
// this.actionButton = true;
// }
// }
// }
}
setRemainsFont(color: { r: number; g: number; b: number }) {
this.remains.SetTextColor(color.r, color.g, color.b, 1.0);
this.remains.SetJustifyH("left");
this.remains.SetPoint("BOTTOMLEFT", 2, 2);
}
setFontScale(scale: number) {
this.fontScale = scale;
this.remains.SetFont(
this.fontName,
this.fontHeight * this.fontScale,
this.fontFlags
);
this.shortcut.SetFont(
this.fontName,
this.fontHeight * this.fontScale,
this.fontFlags
);
this.rangeIndicator.SetFont(
this.fontName,
this.fontHeight * this.fontScale,
this.fontFlags
);
this.focusText.SetFont(
this.fontName,
this.fontHeight * this.fontScale,
this.fontFlags
);
}
setRangeIndicator(text: string) {
this.rangeIndicator.SetText(text);
}
onMouseUp = (
_: unknown,
button:
| "LeftButton"
| "RightButton"
| "MiddleButton"
| "Button4"
| "Button5"
) => {
if (!this.actionButton) {
if (button === "LeftButton") this.parent.toggleOptions();
else if (button === "MiddleButton") {
this.parent.debugIcon(this.index);
}
}
this.frame.SetChecked(true);
};
onEnter = () => {
if (this.help || this.actionType || this.hasScriptControls()) {
GameTooltip.SetOwner(this.frame, "ANCHOR_BOTTOMLEFT");
if (this.help) {
GameTooltip.SetText(l[this.help] || this.help);
}
if (this.actionType) {
let actionHelp: string;
if (this.actionHelp) {
actionHelp = this.actionHelp;
} else {
if (this.actionType == "spell" && isNumber(this.actionId)) {
actionHelp =
this.ovaleSpellBook.getSpellName(this.actionId) ||
"Unknown spell";
} else if (
this.actionType == "value" &&
isNumber(this.value)
) {
actionHelp =
(this.value < infinity && tostring(this.value)) ||
"infinity";
} else {
actionHelp = format(
"%s %s",
this.actionType,
tostring(this.actionId)
);
}
}
GameTooltip.AddLine(actionHelp, 0.5, 1, 0.75);
}
if (this.hasScriptControls()) {
GameTooltip.AddLine(l["options_tooltip"], 1, 1, 1);
}
GameTooltip.Show();
}
};
onLeave = () => {
if (this.help || this.hasScriptControls()) {
GameTooltip.Hide();
}
};
setPoint(
anchor: UIPosition,
reference: UIFrame,
refAnchor: UIPosition,
x: number,
y: number
) {
this.frame.SetPoint(anchor, reference, refAnchor, x, y);
}
// eslint-disable-next-line @typescript-eslint/naming-convention
Show() {
this.frame.Show();
}
// eslint-disable-next-line @typescript-eslint/naming-convention
Hide() {
this.frame.Hide();
}
setScale(scale: number) {
this.frame.SetScale(scale);
}
enableMouse(enabled: boolean) {
this.frame.EnableMouse(enabled);
}
} | the_stack |
import { Injectable, Inject, HttpException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, TreeRepository } from 'typeorm';
import * as moment from 'moment';
import { Article } from '../entities/article.entity';
import { Classify } from '../entities/classify.entity';
import { InputArticle, UpdateArticle, ArtResult } from '../interfaces/article.interface';
import { ClassifyService } from './classify.service';
import { UserService, User } from 'src/user';
const _ = require('underscore');
@Injectable()
export class ArticleService {
constructor(
@InjectRepository(Article) private readonly artRepo: Repository<Article>,
@InjectRepository(Classify) private readonly claRepo: TreeRepository<Classify>,
@Inject(UserService)
private readonly userService: UserService,
@Inject(ClassifyService) private readonly classifyService: ClassifyService,
@InjectRepository(User)
private readonly userRepo: Repository<User>,
) { }
/**
* ๅๅปบๆ็ซ
*
* @param art ๆ็ซ ๅฎไฝ
*/
async createArticle(art: InputArticle, owner: number) {
const classify = await this.claRepo.findOne({ value: art.classify.value });
if (!classify) {
throw new HttpException('่ฏฅๆ็ซ ๅ็ฑปไธๅญๅจ!', 404);
}
art.owner = owner;
art.classify = classify;
await this.artRepo.save(this.artRepo.create(art));
}
/**
* ไฟฎๆนๆ็ซ
*
* @param art ไฟฎๆนๆ็ซ ๅฎไฝ(ๆid)
*
*/
async updateArticle(art: UpdateArticle, owner: number) {
try {
const article = await this.artRepo.findOne(art.id);
if (!article) {
throw new HttpException('่ฏฅๆ็ซ ไธๅญๅจ!', 404);
}
const classify = await this.claRepo.findOne({ value: art.classify.value });
if (!classify) {
throw new HttpException('่ฏฅๆ็ซ ๅ็ฑปไธๅญๅจ!', 404);
}
const user = await this.userRepo.findOne({
where: { id: owner },
relations: ['roles']
});
if (user.roles.length && user.roles[0].id === 1) {
// ๆนไธบๅพ
ๅฎกๆ ธ็ถๆ
article.status = 0;
}
art.classify = classify;
art.modifyAt = moment().format('YYYY-MM-DD HH:mm:ss');
await this.artRepo.save(this.artRepo.create(art));
} catch (error) {
throw new HttpException(error.toString(), 500);
}
}
/**
* ๆน้ๅฐๆ็ซ ไธขๅ
ฅๅๆถ็ซ
*
* @param ids ๆ็ซ idๆฐ็ป
*/
async recycleArticleByIds(ids: number[]) {
const articles: number[] = [];
await this.artRepo.findByIds(ids).then(art => {
art.map((key, value) => {
articles.push(key.id);
});
});
const noExist = _.difference(ids, articles);
if (noExist.length > 0) {
throw new HttpException(`idไธบ${noExist}็ๆ็ซ ไธๅญๅจ`, 404);
}
await this.artRepo.update(ids, { recycling: true });
}
/**
* ๆน้ๆฐธไน
ๅ ้คๆ็ซ
*
* @param ids ๆ็ซ idๆฐ็ป
*
*/
async deleteArticleByIds(ids: number[]) {
const articles: number[] = [];
await this.artRepo.findByIds(ids).then(art => {
art.map((key, value) => {
articles.push(key.id);
});
});
const noExist = _.difference(ids, articles);
if (noExist.length > 0) {
throw new HttpException(`idไธบ${noExist}็ๆ็ซ ไธๅญๅจ`, 404);
}
await this.artRepo.delete(ids);
}
/**
* ๆน้ๆขๅคๅๆถ็ซไธญ็ๆ็ซ
*
* @param ids ๆ็ซ idๆฐ็ป
*/
async recoverArticleByIds(ids: number[]) {
const articles: number[] = [];
await this.artRepo.findByIds(ids).then(art => {
art.map((key, value) => {
articles.push(key.id);
});
});
const noExist = _.difference(ids, articles);
if (noExist.length > 0) {
throw new HttpException(`idไธบ${noExist}็ๆ็ซ ไธๅญๅจ`, 404);
}
await this.artRepo.update(ids, { recycling: false });
}
/**
* ๆน้ๅฎกๆ ธๆ็ซ
*
* @param ids ๅฎกๆ ธๆ็ซ idๆฐ็ป
* @param status ๅฎกๆ ธๆไฝ.1:้่ฟ 2:ๆ็ป
* @param refuseReason ๆ็ปๅๅ (ๆ็ปๆ็ซ ๆถ้่พๅ
ฅ)
*/
async auditArticle(ids: number[], op: number, refuseReason: string) {
const articles: number[] = [];
const arts = await this.artRepo.findByIds(ids);
arts.forEach((key, value) => {
articles.push(key.id);
});
const noExist = _.difference(ids, articles);
if (noExist.length > 0) {
throw new HttpException(`idไธบ${noExist}็ๆ็ซ ไธๅญๅจ`, 404);
}
switch (op) {
case 1:
await this.artRepo.update(ids, { status: op });
break;
case 2:
await this.artRepo.update(ids, { status: op, refuseReason });
break;
default:
throw new HttpException('statusๅๆฐ้่ฏฏ', 405);
}
}
/**
* ๅๅฐๆ็ดขๆๆๆ็ซ
*
* @param classifyId ๆ็ซ ๅ็ฑปid
* @param createdAt ๅผๅงๆถ้ด
* @param endTime ๆชๆญขๆถ้ด
* @param title ๆ็ซ ๆ ้ข
* @param username ๆ็ซ ไฝ่
็จๆทๅ
* @param top ๆฏๅฆ็ฝฎ้กถ
* @param pageNumber ้กตๆฐ
* @param pageSize ๆฏ้กตๆพ็คบๆฐ้
*/
// tslint:disable-next-line:max-line-length
async getAllArticle(classifyAlias: string, createdAt: string, endTime: string, title: string, username: string, top: boolean, pageNumber: number, pageSize: number) {
const sqb = this.artRepo.createQueryBuilder('article')
.where('article.status = :status', { status: 1 })
.andWhere('article.recycling = false')
.leftJoinAndSelect('article.classify', 'classify');
if (classifyAlias) {
const cla = await this.claRepo.findOne({ where: { value: classifyAlias } });
if (!cla) {
throw new HttpException('่ฏฅๅ็ฑปไธๅญๅจ!', 404);
}
sqb.andWhere('article.classify = :classify', { classify: cla.id });
}
if (title) {
sqb.andWhere('article.title Like :title', { title: `%${title}%` });
}
if (username) {
sqb.andWhere('article.username = :username', { username });
}
if (createdAt) {
const min = new Date(createdAt);
sqb.andWhere('article.createdAt > :start', { start: min });
}
if (endTime) {
const max = new Date(endTime);
sqb.andWhere('article.createdAt < :end', { end: max });
}
if (top) {
sqb.andWhere('article.top In (1,2) ');
}
if (top === false) {
sqb.andWhere('article.top = :top', { top: 0 });
}
// tslint:disable-next-line:max-line-length
const result = await sqb.skip(pageSize * (pageNumber - 1)).take(pageSize).orderBy({ 'article.top': 'DESC', 'article.modifyAt': 'DESC' }).getManyAndCount();
const exist: ArtResult[] = [];
for (const i of result[0]) {
const classify = await this.claRepo.findOne(i.classify.id);
const a = {
id: i.id,
title: i.title,
classify,
sourceUrl: i.sourceUrl,
cover: i.cover,
abstract: i.abstract,
content: i.content,
top: i.top,
source: i.source,
username,
status: i.status,
recycling: i.recycling,
createdAt: i.createdAt,
modifyAt: i.modifyAt,
views: i.views,
like: i.like,
artInfos: i.artInfos,
keywords: i.keywords,
structure: i.structure,
hidden: i.hidden
};
exist.push(a);
}
return { exist, total: result[1] };
}
async userGetArticles(alias: string, pageNumber: number, pageSize: number) {
const cla = await this.claRepo.findOne({ where: { value: alias, relations: ['parent'] } });
const ids: number[] = [];
if (cla.onlyChildrenArt) {
const a = await this.classifyService.getAllClassifyIds(cla.id);
const b = a.splice(a.indexOf(cla.id), 1);
for (const i of b) {
ids.push(i);
}
}
else {
const a = await this.classifyService.getAllClassifyIds(cla.id);
for (const i of a) {
ids.push(i);
}
}
const sqb = this.artRepo.createQueryBuilder('article')
.where('article.status = :status', { status: 1 })
.andWhere('article.recycling = false')
.andWhere('article.hidden = false')
.andWhere('article.classify IN(:...ids)', { ids })
.leftJoinAndSelect('article.classify', 'classify');
// tslint:disable-next-line:max-line-length
const result = await sqb.skip(pageSize * (pageNumber - 1)).take(pageSize).orderBy({ 'article.top': 'DESC', 'article.modifyAt': 'DESC' }).getManyAndCount();
const exist = [];
for (const i of result[0]) {
const classify = await this.claRepo.findOne(i.classify);
const a = {
id: i.id,
title: i.title,
classify,
cover: i.cover,
abstract: i.abstract,
content: i.content,
createAt: i.createdAt,
createdAt: i.createdAt,
keywords: i.keywords,
like: i.like,
sourceUrl: i.sourceUrl,
source: i.source
};
exist.push(a);
}
return { total: result[1], exist };
}
/**
* ๆ็ดขๅๆถ็ซไธญๆ็ซ
*
*/
// tslint:disable-next-line:max-line-length
async getRecycleArticle(classifyAlias: string, createdAt: string, endTime: string, title: string, username: string, top: boolean, pageNumber: number, pageSize: number) {
const sqb = this.artRepo.createQueryBuilder('article')
.where('article.recycling = :recycling', { recycling: true })
.leftJoinAndSelect('article.classify', 'classify');
if (classifyAlias) {
const cla = await this.claRepo.findOne({ where: { value: classifyAlias } });
if (!cla) {
throw new HttpException('่ฏฅๅ็ฑปไธๅญๅจ!', 404);
}
sqb.andWhere('article.classify = :classify', { classify: cla.id });
}
if (title) {
sqb.andWhere('article.title Like :title', { title: `%${title}%` });
}
if (username) {
sqb.andWhere('article.username = :username', { username });
}
if (createdAt) {
const min = new Date(createdAt);
const max = endTime ? new Date(endTime) : new Date();
sqb.andWhere('article.createdAt > :start', { start: min });
sqb.andWhere('article.createdAt < :end', { end: max });
}
if (top) {
sqb.andWhere('article.top In (1,2) ');
}
if (top === false) {
sqb.andWhere('article.top = :top', { top: 0 });
}
// tslint:disable-next-line:max-line-length
const result = await sqb.skip(pageSize * (pageNumber - 1)).take(pageSize).orderBy({ 'article.top': 'DESC', 'article.modifyAt': 'DESC' }).getMany();
const exist: ArtResult[] = [];
const total = await sqb.getCount();
for (const i of result) {
const classify = await this.claRepo.findOne(i.classify.id);
const a = {
id: i.id,
title: i.title,
classify,
sourceUrl: i.sourceUrl,
cover: i.cover,
abstract: i.abstract,
content: i.content,
top: i.top,
source: i.source,
username,
status: i.status,
views: i.views,
like: i.like,
recycling: i.recycling,
createdAt: i.createdAt,
modifyAt: i.modifyAt,
structure: i.structure,
artInfos: i.artInfos
};
exist.push(a);
}
return { exist, total };
}
/**
* ่ทๅๆ็ซ ่ฏฆๆ
*
* @param id ๆ็ซ id
*/
async getArticleById(id: number) {
const artQb = await this.artRepo.createQueryBuilder('art')
.leftJoinAndSelect('art.classify', 'classify');
const art = await artQb.where('art.id = :id', { id }).getOne();
art.views++;
const classifyId = art.classify.id;
const pre = await this.artRepo.createQueryBuilder()
// tslint:disable-next-line:max-line-length
.where('"id" = (select max(id) from public.article where "id" < :id and "classifyId" =:classifyId and "status" =:status and "recycling" =:recycling) ',
{ id, classifyId, status: 1, recycling: false }
)
.getOne();
const next = await this.artRepo.createQueryBuilder()
// tslint:disable-next-line:max-line-length
.where('"id" = (select min(id) from public.article where "id" > :id and "classifyId" =:classifyId and "status" =:status and "recycling" =:recycling) ',
{ id, classifyId, status: 1, recycling: false }
)
.getOne();
const data = await this.artRepo.save(this.artRepo.create(art));
return { pre: pre ? pre.id : undefined, current: data, next: next ? next.id : undefined };
}
/**
*
* ๆ็ดข่ทๅๅพ
ๅฎกๆ ธๆ็ซ
*
*/
// tslint:disable-next-line:max-line-length
async getCheckArticle(classifyAlias: string, createdAt: string, endTime: string, title: string, username: string, top: boolean, pageNumber: number, pageSize: number) {
const sqb = this.artRepo.createQueryBuilder('article')
.where('article.recycling = :recycling', { recycling: false })
.andWhere('article.status = :status', { status: 0 })
.leftJoinAndSelect('article.classify', 'classify');
if (classifyAlias) {
const cla = await this.claRepo.findOne({ where: { value: classifyAlias } });
if (!cla) {
throw new HttpException('่ฏฅๅ็ฑปไธๅญๅจ!', 404);
}
sqb.andWhere('article.classify = :classify', { classify: cla.id });
}
if (title) {
sqb.andWhere('article.title Like :title', { title: `%${title}%` });
}
if (username) {
sqb.andWhere('article.username = :username', { username });
}
if (createdAt) {
const min = new Date(createdAt);
const max = endTime ? new Date(endTime) : new Date();
sqb.andWhere('article.createdAt > :start', { start: min });
sqb.andWhere('article.createdAt < :end', { end: max });
}
if (top) {
sqb.andWhere('article.top In (1,2) ');
}
if (top === false) {
sqb.andWhere('article.top = :top', { top: 0 });
}
const result = await sqb.skip(pageSize * (pageNumber - 1)).take(pageSize).orderBy({ 'article.modifyAt': 'ASC' }).getMany();
const exist: ArtResult[] = [];
const total = await sqb.getCount();
for (const i of result) {
const classify = await this.claRepo.findOne(i.classify.id);
const a = {
id: i.id,
title: i.title,
classify,
sourceUrl: i.sourceUrl,
cover: i.cover,
abstract: i.abstract,
content: i.content,
top: i.top,
source: i.source,
createdAt: i.createdAt,
username,
status: i.status,
recycling: i.recycling,
views: i.views,
like: i.like,
modifyAt: i.modifyAt,
keywords: i.keywords,
structure: i.structure,
artInfos: i.artInfos
};
exist.push(a);
}
return { exist, total };
}
private addDate(dates, days) {
if (days === undefined || days === '') {
days = 1;
}
const date = new Date(dates);
date.setDate(date.getDate() + days);
const month = date.getMonth() + 1;
const day = date.getDate();
return date.getFullYear() + '-' + this.getFormatDate(month) + '-' + this.getFormatDate(day);
}
private getFormatDate(arg) {
if (arg === undefined || arg === '') {
return '';
}
let re = arg + '';
if (re.length < 2) {
re = '0' + re;
}
return re;
}
} | the_stack |
import * as rpc from 'transparent-rpc';
import * as Genie from 'genie-toolkit';
import type { Platform } from './platform';
import PlatformModule from './platform';
// API wrappers for Genie's classes that expose the $rpcMethods interface
// used by transparent-rpc
interface WebsocketDelegate {
send(data : any) : Promise<void>;
}
export class ConversationWrapper implements rpc.Stubbable {
$rpcMethods = ['destroy', 'getState', 'handleCommand', 'handleParsedCommand', 'handleThingTalk'] as const;
$free ?: () => void;
private _conversation : Genie.DialogueAgent.Conversation;
private _delegate : rpc.Proxy<Genie.DialogueAgent.ConversationDelegate>;
constructor(conversation : Genie.DialogueAgent.Conversation,
delegate : rpc.Proxy<Genie.DialogueAgent.ConversationDelegate>,
replayHistory : boolean|undefined) {
this._conversation = conversation;
this._delegate = delegate;
this._conversation.addOutput(delegate, replayHistory);
}
destroy() {
this._conversation.removeOutput(this._delegate);
this._delegate.$free();
if (this.$free)
this.$free();
}
getState() {
return this._conversation.getState();
}
handleCommand(...args : Parameters<Genie.DialogueAgent.Conversation['handleCommand']>) {
return this._conversation.handleCommand(...args);
}
handleParsedCommand(...args : Parameters<Genie.DialogueAgent.Conversation['handleParsedCommand']>) {
return this._conversation.handleParsedCommand(...args);
}
handleThingTalk(...args : Parameters<Genie.DialogueAgent.Conversation['handleThingTalk']>) {
return this._conversation.handleThingTalk(...args);
}
}
export class WebSocketConnnectionWrapper implements rpc.Stubbable {
$rpcMethods = ['destroy', 'getState', 'handle'] as const;
$free ?: () => void;
private _conversation : Genie.DialogueAgent.Conversation;
private _delegate : rpc.Proxy<WebsocketDelegate>;
private _connection : Genie.DialogueAgent.Protocol.WebSocketConnection;
constructor(conversation : Genie.DialogueAgent.Conversation,
delegate : rpc.Proxy<WebsocketDelegate>,
replayHistory : boolean|undefined,
syncDevices : boolean|undefined) {
this._conversation = conversation;
this._delegate = delegate;
this._connection = new Genie.DialogueAgent.Protocol.WebSocketConnection(conversation, (msg) => this._delegate.send(msg), {
replayHistory,
syncDevices
});
}
async start() {
return this._connection.start();
}
async destroy() {
this._connection.destroy();
this._delegate.$free();
if (this.$free)
this.$free();
}
getState() {
return this._conversation.getState();
}
handle(msg : Genie.DialogueAgent.Protocol.ClientProtocolMessage) {
return this._connection.handle(msg);
}
}
class RecordingController implements rpc.Stubbable {
$rpcMethods = [
'readLog',
'startRecording',
'endRecording',
'inRecordingMode',
'voteLast',
'commentLast',
'destroy'
] as const;
$free ?: () => void;
private _assistant : Genie.DialogueAgent.AssistantDispatcher;
private _conversation : Genie.DialogueAgent.Conversation;
constructor(assistant : Genie.DialogueAgent.AssistantDispatcher,
conversation : Genie.DialogueAgent.Conversation) {
this._assistant = assistant;
this._conversation = conversation;
}
destroy() {
this._assistant.closeConversation(this._conversation.id);
if (this.$free)
this.$free();
}
async readLog() {
// TODO: make this streaming
const logstream = this._conversation.readLog();
let log = '';
logstream.on('data', (data) => {
log += data;
});
await Genie.StreamUtils.waitFinish(logstream);
return log;
}
startRecording() {
return this._conversation.startRecording();
}
endRecording() {
return this._conversation.endRecording();
}
inRecordingMode() {
return this._conversation.inRecordingMode;
}
voteLast(vote : 'up'|'down') {
return this._conversation.voteLast(vote);
}
commentLast(comment : string) {
return this._conversation.commentLast(comment);
}
}
export class NotificationWrapper implements Genie.DialogueAgent.NotificationDelegate {
$rpcMethods = ['destroy'] as const;
$free ?: () => void;
private _dispatcher : Genie.DialogueAgent.AssistantDispatcher;
private _delegate : rpc.Proxy<WebsocketDelegate>;
constructor(dispatcher : Genie.DialogueAgent.AssistantDispatcher, delegate : rpc.Proxy<WebsocketDelegate>) {
this._dispatcher = dispatcher;
this._delegate = delegate;
this._dispatcher.addNotificationOutput(this);
}
destroy() {
this._dispatcher.removeNotificationOutput(this);
this._delegate.$free();
if (this.$free)
this.$free();
}
async notify(data : Parameters<Genie.DialogueAgent.NotificationDelegate['notify']>[0]) {
await this._delegate.send({ result: data });
}
async notifyError(data : Parameters<Genie.DialogueAgent.NotificationDelegate['notifyError']>[0]) {
await this._delegate.send({ error: data });
}
}
interface ConversationOptions {
anonymous ?: boolean;
showWelcome : boolean;
replayHistory ?: boolean;
syncDevices ?: boolean;
}
export default class Engine extends Genie.AssistantEngine implements rpc.Stubbable {
$rpcMethods = [
'getConsent',
'setConsent',
'warnRecording',
'recordingWarned',
'getRecordingController',
'ensureConversation',
'getOrOpenConversation',
'getOrOpenConversationWebSocket',
'addNotificationOutput',
'converse',
'startOAuth',
'completeOAuth',
'createDeviceAndReturnInfo',
'deleteDevice',
'upgradeDevice',
'getDeviceInfos',
'getDeviceInfo',
'checkDeviceAvailable',
'getCachedDeviceClasses',
'hasDevice',
'getAppInfos',
'getAppInfo',
'deleteApp',
'createAppAndReturnResults',
'deleteAllApps',
'setCloudId',
'addServerAddress',
] as const;
$free ?: () => void;
constructor(platform : Platform, options : ConstructorParameters<typeof Genie.AssistantEngine>[1]) {
super(platform, options);
}
setConsent(consent : boolean) {
const prefs = this.platform.getSharedPreferences();
prefs.set('sabrina-store-log', consent ? 'yes' : 'no');
}
getConsent() {
const prefs = this.platform.getSharedPreferences();
return prefs.get('sabrina-store-log') === 'yes';
}
warnRecording() {
const prefs = this.platform.getSharedPreferences();
prefs.set('recording-warning-shown', 'yes');
}
recordingWarned() {
const prefs = this.platform.getSharedPreferences();
return prefs.get('recording-warning-shown') === 'yes';
}
async converse(...args : Parameters<Genie.DialogueAgent.AssistantDispatcher['converse']>) {
return this.assistant.converse(...args);
}
private _getConversationOptions(options_ : ConversationOptions) {
const options : Genie.DialogueAgent.ConversationOptions = options_;
options.faqModels = PlatformModule.faqModels;
options.debug = process.env.GENIE_ENGINE_DEBUG !== "false";
if (options.anonymous || process.env.NODE_ENV !=='production')
options.log = true;
return options;
}
async getRecordingController(id : string, options : ConversationOptions) {
const conversation = await this.assistant.getOrOpenConversation(id, this._getConversationOptions(options));
return new RecordingController(this.assistant, conversation);
}
async ensureConversation(id : string,
options : ConversationOptions,
initialState ?: Genie.DialogueAgent.ConversationState) : Promise<void> {
await this.assistant.getOrOpenConversation(id, this._getConversationOptions(options), initialState || undefined);
}
async getOrOpenConversation(id : string,
delegate : rpc.Proxy<Genie.DialogueAgent.ConversationDelegate>,
options : ConversationOptions,
initialState ?: Genie.DialogueAgent.ConversationState) {
const conversation = await this.assistant.getOrOpenConversation(id, this._getConversationOptions(options), initialState || undefined);
return new ConversationWrapper(conversation, delegate, options.replayHistory);
}
async getOrOpenConversationWebSocket(id : string,
delegate : rpc.Proxy<WebsocketDelegate>,
options : ConversationOptions,
initialState ?: Genie.DialogueAgent.ConversationState) {
const conversation = await this.assistant.getOrOpenConversation(id, this._getConversationOptions(options), initialState || undefined);
const wrapper = new WebSocketConnnectionWrapper(conversation, delegate, options.replayHistory, options.syncDevices);
await wrapper.start();
return wrapper;
}
async addNotificationOutput(delegate : rpc.Proxy<WebsocketDelegate>) {
return new NotificationWrapper(this.assistant, delegate);
}
async createDeviceAndReturnInfo(data : { kind : string }) {
const device = await this.createDevice(data);
return this.getDeviceInfo(device.uniqueId!);
}
async deleteAllApps(forNotificationBackend ?: keyof Genie.DialogueAgent.NotificationConfig, forNotificationConfig ?: Record<string, unknown>) {
const apps = this.apps.getAllApps();
for (const app of apps) {
if (forNotificationBackend) {
if (!app.notifications)
continue;
if (app.notifications.backend !== forNotificationBackend)
continue;
let good = true;
for (const key in forNotificationConfig) {
if (forNotificationConfig[key] !== app.notifications.config[key]) {
good = false;
break;
}
}
if (!good)
continue;
}
await this.apps.removeApp(app);
}
}
} | the_stack |
import Block from "../block";
import Account from '../account';
import AuditProofProvider from "./provider";
import { StateMachine, State } from "../state";
import { decodeHardTransactions } from "../../lib";
import { HardTransactionSourceError, TransactionSignatureError } from "./types/transaction-errors";
import {
HardTransactionUnion, HardCreate, HardDeposit, HardWithdraw, HardAddSigner,
SoftWithdrawal, SoftCreate, SoftTransfer, SoftChangeSigner, SoftTransactionUnion
} from "../transactions";
import {
ErrorProof, ProvableError, PreviousRootProof, PreviousStateProof,
CommitmentProof, TransactionProof, HardDepositExecutionError
} from "./types";
import {
ProofData_Basic, HardCreateExecutionError, CreateIndexError, SoftWithdrawalExecutionError,
SoftCreateExecutionError, SoftTransferExecutionError, SoftChangeSignerExecutionError, HardWithdrawalExecutionError, HardAddSignerExecutionError
} from "./types/execution-errors";
const ABI = require('web3-eth-abi');
export class ExecutionAuditor extends StateMachine {
private constructor(
public parentBlock: Block,
public block: Block,
state: State,
private realHardTransactions: { [key: number]: HardTransactionUnion }
) {
super(state);
}
static async auditBlockExecution(
provider: AuditProofProvider,
parentBlock: Block,
block: Block,
): Promise<State> {
/* Retrieve the state tree the block started with. */
const state = await provider.getBlockStartingState(block.header.blockNumber);
/* Retrieve the actual hard transactions recorded on the Tiramisu contract. */
const { hardTransactionsCount } = parentBlock.header;
const hardTransactionsLength = block.transactionsArray.filter(tx => tx.prefix < 4).length;
// console.log(`Getting inputs from Tiramisu -- Index: ${hardTransactionsCount} | Length: ${hardTransactionsLength}`)
const encodedInputs = await provider.getHardTransactions(
hardTransactionsCount, hardTransactionsLength
);
// TODO -- add better handling to decodeHardTransactions
// so that rather than naively assign types, it will determine which tx type to assign accounts
// by looking ahead and backwards in the array
const decodedInputs = await decodeHardTransactions(state, hardTransactionsCount, encodedInputs);
/* Map the transactions to their indices for quick lookup and comparison */
const inputsMap = decodedInputs.reduce((obj, val) => ({
...obj,
[val.hardTransactionIndex]: val
}), {});
const auditor = new ExecutionAuditor(
parentBlock,
block,
state,
inputsMap
);
await auditor.validateTransactions();
return state;
}
fail(_error: ErrorProof) {
throw new ProvableError(_error);
}
async getPreviousStateProof(
transactionIndex: number,
accountIndex: number
): Promise<PreviousStateProof> {
let rootProof: PreviousRootProof;
if (transactionIndex == 0) {
rootProof = { ...this.parentBlock.commitment, _type: 'commitment' } as CommitmentProof;
} else {
rootProof = this.block.proveTransaction(transactionIndex - 1) as TransactionProof;
}
const stateProof = await this.state.getAccountProof(accountIndex);
return {
stateProof,
previousRootProof: rootProof
};
}
async getBasicProof(transactionIndex: number, accountIndex: number): Promise<ProofData_Basic> {
const stateProof = await this.getPreviousStateProof(transactionIndex, accountIndex);
const { transaction, siblings } = this.block.proveTransaction(transactionIndex);
return {
header: this.block.commitment,
...stateProof,
transaction,
transactionIndex,
siblings
};
}
async validateTransactions() {
const {
hardCreates,
hardDeposits,
hardWithdrawals,
hardAddSigners,
softWithdrawals,
softCreates,
softTransfers,
softChangeSigners
} = this.block.transactions;
// console.log(`Checking block execution...`)
let index = 0;
for (let i = 0; i < hardCreates.length; i++) await this.validateHardCreate(hardCreates[i], i+(index++));
for (let i = 0; i < hardDeposits.length; i++) await this.validateHardDeposit(hardDeposits[i], i+(index++));
for (let i = 0; i < hardWithdrawals.length; i++) await this.validateHardWithdrawal(hardWithdrawals[i], i+(index++));
for (let i = 0; i < hardAddSigners.length; i++) await this.validateHardAddSigner(hardAddSigners[i], i+(index++));
for (let i = 0; i < softWithdrawals.length; i++) await this.validateSoftWithdrawal(softWithdrawals[i], i+(index++));
for (let i = 0; i < softCreates.length; i++) await this.validateSoftCreate(softCreates[i], i+(index++));
for (let i = 0; i < softTransfers.length; i++) await this.validateSoftTransfer(softTransfers[i], i+(index++));
for (let i = 0; i < softChangeSigners.length; i++) await this.validateSoftChangeSigner(softChangeSigners[i], i+(index++));
}
async validateHardCreate(transaction: HardCreate, index: number) {
const real = this.realHardTransactions[transaction.hardTransactionIndex];
if (
real.prefix != 0 ||
real.accountAddress != transaction.accountAddress ||
real.initialSigningKey != transaction.initialSigningKey ||
real.value != transaction.value
) {
const { transaction, siblings } = this.block.proveTransaction(index);
const err = {
_type: "hard_transaction_source",
header: this.block.commitment,
transactionIndex: index,
transaction,
siblings
} as HardTransactionSourceError;
this.fail(err);
}
const existingIndex = await this.state.getAccountIndexByAddress(transaction.accountAddress);
// Check if the address already had an account
if (existingIndex) {
const err = await this.getBasicProof(index, existingIndex) as HardCreateExecutionError;
err._type = "hard_create";
this.fail(err as HardCreateExecutionError)
}
// Check if the created account index is correct
if (transaction.accountIndex != this.state.size) {
const err = {
_type: "create_index_error",
previousHeader: this.parentBlock.commitment,
header: this.block.commitment,
transactionIndex: index,
transactionsData: this.block.transactionsData
} as CreateIndexError;
this.fail(err);
}
// TODO
// Add checkpoint/commit/revert to SparseMerkleTree so we don't always have to
// precalculate proof data which might not be used.
const err = await this.getBasicProof(index, transaction.accountIndex) as HardCreateExecutionError;
err._type = "hard_create";
const root = '' + transaction.intermediateStateRoot;
await this.hardCreate(transaction);
if (transaction.intermediateStateRoot != root) this.fail(err);
}
async validateHardDeposit(transaction: HardDeposit, index: number) {
const real = this.realHardTransactions[transaction.hardTransactionIndex];
if (
real.prefix != 1 ||
real.accountIndex != transaction.accountIndex ||
real.value != transaction.value
) {
const { transaction: txBytes, siblings } = this.block.proveTransaction(index);
let err = {
_type: "hard_transaction_source",
header: this.block.commitment,
transactionIndex: index,
transaction: txBytes,
siblings
} as HardTransactionSourceError;
if (real.accountIndex != transaction.accountIndex) {
err = {
...err,
...(await this.getPreviousStateProof(index, real.accountIndex))
}
}
this.fail(err);
}
// TODO
// Add checkpoint/commit/revert to SparseMerkleTree so we don't always have to
// precalculate proof data which might not be used.
const err = await this.getBasicProof(index, transaction.accountIndex) as HardDepositExecutionError;
err._type = "hard_deposit";
// Check if the account existed
if (!(await this.state.getAccount(transaction.accountIndex))) {
this.fail(err);
}
const root = '' + transaction.intermediateStateRoot;
await this.hardDeposit(transaction);
if (root != transaction.intermediateStateRoot) this.fail(err);
}
async validateHardWithdrawal(transaction: HardWithdraw, index: number) {
const real = this.realHardTransactions[transaction.hardTransactionIndex];
if (
real.prefix != 2 ||
real.accountIndex != transaction.accountIndex ||
real.callerAddress != transaction.callerAddress ||
real.value != transaction.value
) {
const { transaction, siblings } = this.block.proveTransaction(index);
const err = {
_type: 'hard_transaction_source',
header: this.block.commitment,
transactionIndex: index,
transaction,
siblings
} as HardTransactionSourceError;
this.fail(err);
}
// TODO
// Add checkpoint/commit/revert to SparseMerkleTree so we don't always have to
// precalculate proof data which might not be used.
const err = await this.getBasicProof(index, transaction.accountIndex) as HardWithdrawalExecutionError;
err._type = 'hard_withdrawal';
// If the account did not exist or had an insufficient balance,
// the transaction should have a null output root.
const currentRoot = await this.state.rootHash();
const account = await this.state.getAccount(transaction.accountIndex);
if (
(!account || account.balance < transaction.value) &&
transaction.intermediateStateRoot != currentRoot
) {
this.fail(err);
}
const root = '' + transaction.intermediateStateRoot;
await this.hardWithdraw(transaction);
if (transaction.intermediateStateRoot != root) this.fail(err);
}
async validateHardAddSigner(transaction: HardAddSigner, index: number) {
const real = this.realHardTransactions[transaction.hardTransactionIndex];
const account = await this.state.getAccount(real.accountIndex);
const callerMismatch = !account || (real.prefix == 3 && real.callerAddress != account.address);
if (
real.prefix != 3 ||
real.accountIndex != transaction.accountIndex ||
real.signingAddress != transaction.signingAddress ||
callerMismatch
) {
const { transaction, siblings } = this.block.proveTransaction(index);
const { stateProof, previousRootProof } = callerMismatch
? await this.getPreviousStateProof(index, real.accountIndex)
: { stateProof: '0x', previousRootProof: '0x' }
const err = {
header: this.block.commitment,
transactionIndex: index,
transaction,
siblings,
stateProof,
previousRootProof,
_type: 'hard_transaction_source'
} as HardTransactionSourceError;
this.fail(err);
}
// Transaction comes from the submitted block.
// Encoded HardAddSigner functions do not include the callerAddress field,
// so it must be copied from the original hard tx.
transaction.callerAddress = (real as HardAddSigner).callerAddress;
// TODO
// Add checkpoint/commit/revert to SparseMerkleTree so we don't always have to
// precalculate proof data which might not be used.
const err = await this.getBasicProof(index, transaction.accountIndex) as HardAddSignerExecutionError;
err._type = 'hard_add_signer';
const currentRoot = await this.state.rootHash();
// If the account did not exist or had an insufficient balance,
// the transaction should have a null output root.
// const account = await this.state.getAccount(transaction.accountIndex);
if (
(
!account.hasSigner(transaction.signingAddress) ||
account.signers.length == 10
) &&
transaction.intermediateStateRoot != currentRoot
) {
this.fail(err);
}
const root = '' + transaction.intermediateStateRoot;
await this.hardAddSigner(transaction);
if (
transaction.intermediateStateRoot != root
) this.fail(err);
}
async checkSignature(transaction: SoftTransactionUnion, index: number): Promise<Account> {
let signer: string;
try {
signer = transaction.getSignerAddress()
if (!signer) throw new Error()
} catch (err) {
this.fail({
header: this.block.commitment,
...this.block.proveTransaction(index),
transactionIndex: index,
_type: 'transaction_signature',
});
}
const account = await this.state.getAccount(transaction.accountIndex);
if (!account.hasSigner(signer)) {
const err = await this.getBasicProof(index, transaction.accountIndex);
this.fail({
...err,
_type: 'transaction_signature'
} as TransactionSignatureError);
}
return account;
}
async validateSoftWithdrawal(transaction: SoftWithdrawal, index: number) {
const account = await this.checkSignature(transaction, index);
const err = {
...(await this.getBasicProof(index, transaction.accountIndex)),
_type: 'soft_withdrawal'
} as SoftWithdrawalExecutionError;
if (
account.balance < transaction.value ||
account.nonce != transaction.nonce
) {
this.fail(err);
}
account.balance -= transaction.value;
account.nonce += 1;
await this.state.updateAccount(transaction.accountIndex, account);
if (
transaction.intermediateStateRoot != await this.state.rootHash()
) this.fail(err);
}
async validateSoftCreate(transaction: SoftCreate, index: number) {
// Check if the transaction had a valid signature (encoding & account match)
const account = await this.checkSignature(transaction, index);
// Set up the error proof
// TODO commit/revert on sparse merkle tree so we don't have to pre-calc
// proofs we may never use.
const { stateProof, ...rest } = await this.getBasicProof(index, transaction.accountIndex);
const err = {
...rest,
senderProof: stateProof,
_type: 'soft_create'
} as SoftCreateExecutionError
// Check if transaction was allowable given the caller's account
if (
account.balance < transaction.value ||
account.nonce != transaction.nonce
) this.fail(err);
// Update the account & state
// we don't use the underlying state machine because we need to get intermediate state proofs
account.balance -= transaction.value;
account.nonce += 1;
await this.state.updateAccount(transaction.accountIndex, account);
/*
The reason this does both index checks is because the latter is much more expensive,
even though it is sufficient to cover the former case.
*/
// Check if the `toAccountIndex` already existed.
const existingIndex = await this.state.getAccountIndexByAddress(transaction.accountAddress);
if (existingIndex != null) {
err.receiverProof = await this.state.getAccountProof(existingIndex);
this.fail(err);
}
// TODO replace this with something more elegant
// Check if the created account index is correct
if (transaction.toAccountIndex != this.state.size) {
const err = {
_type: "create_index_error",
previousHeader: this.parentBlock.commitment,
header: this.block.commitment,
transactionIndex: index,
transactionsData: this.block.transactionsData
} as CreateIndexError;
this.fail(err);
}
// Get the proof of the null leaf the account will be inserted into.
err.receiverProof = await this.state.getAccountProof(transaction.toAccountIndex);
// Insert the account into the state.
const newAccount = new Account({
address: transaction.accountAddress,
nonce: 0,
balance: transaction.value,
signers: [transaction.initialSigningKey]
}) as Account;
await this.state.putAccount(newAccount);
// Compare the output root.
if (
transaction.intermediateStateRoot != await this.state.rootHash()
) this.fail(err);
}
async validateSoftTransfer(transaction: SoftTransfer, index: number) {
// Check if the transaction had a valid signature (encoding & account match)
const account = await this.checkSignature(transaction, index);
// Set up the error proof
// TODO commit/revert on sparse merkle tree so we don't have to pre-calc
// proofs we may never use.
const { stateProof, ...rest } = await this.getBasicProof(index, transaction.accountIndex);
const err = {
...rest,
senderProof: stateProof,
_type: 'soft_transfer'
} as SoftTransferExecutionError;
// Check if transaction was allowable given the caller's account
if (
account.balance < transaction.value ||
account.nonce != transaction.nonce
) this.fail(err);
// Update the account & state
// we don't use the underlying state machine because we need to get intermediate state proofs
account.balance -= transaction.value;
account.nonce += 1;
await this.state.updateAccount(transaction.accountIndex, account);
err.receiverProof = await this.state.getAccountProof(transaction.toAccountIndex);
const receiver = await this.state.getAccount(transaction.toAccountIndex);
if (!receiver) this.fail(err);
receiver.balance += transaction.value;
await this.state.updateAccount(transaction.toAccountIndex, receiver);
if (
transaction.intermediateStateRoot != await this.state.rootHash()
) this.fail(err);
}
async validateSoftChangeSigner(transaction: SoftChangeSigner, index: number) {
// Check if the transaction had a valid signature (encoding & account match)
const account = await this.checkSignature(transaction, index);
const err = {
...(await this.getBasicProof(index, transaction.accountIndex)),
_type: 'soft_change_signer'
} as SoftChangeSignerExecutionError;
if (!account || account.nonce != transaction.nonce) this.fail(err);
const { signingAddress } = transaction;
if (transaction.modificationCategory == 0) {
if (
account.hasSigner(signingAddress) ||
account.signers.length == 10
) this.fail(err);
account.addSigner(signingAddress)
} else if (transaction.modificationCategory == 1) {
if (!account.hasSigner(signingAddress)) this.fail(err);
account.removeSigner(signingAddress)
} else this.fail(err);
account.nonce += 1;
await this.state.updateAccount(transaction.accountIndex, account);
if (
transaction.intermediateStateRoot != await this.state.rootHash()
) this.fail(err);
}
} | the_stack |
import leven from "leven";
import { processCommaSep } from "string-process-comma-separated";
import {
loop,
recognisedMediaTypes,
lettersOnlyRegex,
Opts,
ResObj,
} from "./util";
import { version as v } from "../package.json";
const version: string = v;
import { Ranges } from "../../../scripts/common";
const defaults = {
offset: 0,
};
// See https://drafts.csswg.org/mediaqueries/
// Also https://csstree.github.io/docs/validator.html
// Also, test in Chrome yourself
function isMediaD(originalStr: string, originalOpts?: Partial<Opts>): ResObj[] {
const opts: Opts = { ...defaults, ...originalOpts };
// insurance first
if (opts.offset && !Number.isInteger(opts.offset)) {
throw new Error(
`is-media-descriptor: [THROW_ID_01] opts.offset must be an integer, it was given as ${
opts.offset
} (type ${typeof opts.offset})`
);
}
if (!opts.offset) {
// to cater false/null
opts.offset = 0;
}
// quick ending
if (typeof originalStr !== "string") {
console.log(
`039 isMediaD(): early exit, ${`\u001b[${31}m${`RETURN`}\u001b[${39}m`} []`
);
return [];
}
if (!originalStr.trim()) {
console.log(
`045 isMediaD(): early exit, ${`\u001b[${31}m${`RETURN`}\u001b[${39}m`} []`
);
return [];
}
const res: ResObj[] = [];
// We pay extra attention to whitespace. These two below
// mark the known index of the first and last non-whitespace
// character (a'la trim)
let nonWhitespaceStart = 0;
let nonWhitespaceEnd = originalStr.length;
const str = originalStr.trim();
console.log(
`061 FINAL ${`\u001b[${33}m${`opts`}\u001b[${39}m`} = ${JSON.stringify(
opts,
null,
4
)}`
);
// ---------------------------------------------------------------------------
// check for inner whitespace, for example,
// " screen and (color), projection and (color)"
// ^
//
// as in...
//
// <link media=" screen and (color), projection and (color)" rel="stylesheet" href="example.css">
//
// ^ notice rogue space above
if (originalStr !== originalStr.trim()) {
const ranges = [];
if (!originalStr[0].trim()) {
console.log(`083 traverse forward`);
for (let i = 0, len = originalStr.length; i < len; i++) {
if (originalStr[i].trim()) {
ranges.push([0 + opts.offset, i + opts.offset]);
nonWhitespaceStart = i;
break;
}
}
}
if (!originalStr[originalStr.length - 1].trim()) {
console.log(`093 traverse backwards from the end`);
for (let i = originalStr.length; i--; ) {
if (originalStr[i].trim()) {
ranges.push([i + 1 + opts.offset, originalStr.length + opts.offset]);
nonWhitespaceEnd = i + 1;
break;
}
}
}
console.log(`102 PUSH [${ranges[0][0]}, ${ranges[ranges.length - 1][1]}]`);
res.push({
idxFrom: ranges[0][0],
idxTo: ranges[ranges.length - 1][1],
message: "Remove whitespace.",
fix: {
ranges: ranges as Ranges,
},
});
}
// ---------------------------------------------------------------------------
console.log(
`116 isMediaD(): โโ working non-whitespace range: [${`\u001b[${35}m${nonWhitespaceStart}\u001b[${39}m`}, ${`\u001b[${35}m${nonWhitespaceEnd}\u001b[${39}m`}]`
);
// quick checks first - cover the most common cases, to make checks the
// quickest possible when everything's all right
if (recognisedMediaTypes.includes(str)) {
//
//
//
//
//
//
//
//
// 1. string-only, like "screen"
//
//
//
//
//
//
//
//
console.log(
`140 isMediaD(): whole string matched! ${`\u001b[${32}m${`RETURN`}\u001b[${39}m`}`
);
return res;
}
if (["only", "not"].includes(str)) {
console.log(
`146 isMediaD(): PUSH [${nonWhitespaceStart + opts.offset}, ${
nonWhitespaceEnd + opts.offset
}]`
);
res.push({
idxFrom: nonWhitespaceStart + opts.offset,
idxTo: nonWhitespaceEnd + opts.offset,
message: `Missing media type or condition.`,
fix: null,
});
} else if (
str.match(lettersOnlyRegex) &&
!str.includes("(") &&
!str.includes(")")
) {
//
//
//
//
//
//
//
//
// 2. string-only, unrecognised like "screeeen"
//
//
//
//
//
//
//
//
console.log(`178 isMediaD(): mostly-letters clauses`);
for (let i = 0, len = recognisedMediaTypes.length; i < len; i++) {
console.log(
`182 isMediaD(): leven ${recognisedMediaTypes[i]} = ${leven(
recognisedMediaTypes[i],
str
)}`
);
if (leven(recognisedMediaTypes[i], str) === 1) {
console.log(`188 isMediaD(): ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`}`);
res.push({
idxFrom: nonWhitespaceStart + opts.offset,
idxTo: nonWhitespaceEnd + opts.offset,
message: `Did you mean "${recognisedMediaTypes[i]}"?`,
fix: {
ranges: [
[
nonWhitespaceStart + opts.offset,
nonWhitespaceEnd + opts.offset,
recognisedMediaTypes[i],
],
],
},
});
break;
}
if (i === len - 1) {
// it means nothing was matched
console.log(`208 isMediaD(): end reached`);
console.log(
`210 isMediaD(): ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${`\u001b[${33}m${
nonWhitespaceStart + opts.offset
}\u001b[${39}m`}, ${`\u001b[${33}m${
nonWhitespaceEnd + opts.offset
}\u001b[${39}m`}] (not offset [${`\u001b[${33}m${nonWhitespaceStart}\u001b[${39}m`}, ${`\u001b[${33}m${nonWhitespaceEnd}\u001b[${39}m`}])`
);
res.push({
idxFrom: nonWhitespaceStart + opts.offset,
idxTo: nonWhitespaceEnd + opts.offset,
message: `Unrecognised media type "${str}".`,
fix: null,
});
console.log(
`223 isMediaD(): ${`\u001b[${33}m${`res`}\u001b[${39}m`} = ${JSON.stringify(
res,
null,
4
)}`
);
}
}
} else {
//
//
//
//
//
//
//
//
// 3. mixed, like "screen and (color)"
//
//
//
//
//
//
//
//
// PART 1.
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
console.log(
`254 isMediaD(): ${`\u001b[${36}m${`PART I.`}\u001b[${39}m`} Preliminary checks.`
);
// Preventive checks will help to simplify the algorithm - we won't need
// to cater for so many edge cases later.
let wrongOrder = false;
const [openingBracketCount, closingBracketCount] = Array.from(str).reduce(
(acc, curr, idx) => {
if (curr === ")") {
// if at any time, there are more closing brackets than opening-ones,
// this means order is messed up
if (!wrongOrder && acc[1] + 1 > acc[0]) {
console.log(
`268 isMediaD(): set ${`\u001b[${33}m${`wrongOrder`}\u001b[${39}m`} = true`
);
wrongOrder = true;
}
return [acc[0], acc[1] + 1];
}
if (curr === "(") {
return [acc[0] + 1, acc[1]];
}
if (curr === ";") {
res.push({
idxFrom: idx + opts.offset,
idxTo: idx + 1 + opts.offset,
message: "Semicolon found!",
fix: null,
});
}
return acc;
},
[0, 0]
);
// we raise this error only when there is equal amount of brackets,
// only the order is messed up:
if (wrongOrder && openingBracketCount === closingBracketCount) {
console.log(
`294 isMediaD(): ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} the wrong order error`
);
res.push({
idxFrom: nonWhitespaceStart + opts.offset,
idxTo: nonWhitespaceEnd + opts.offset,
message: "Some closing brackets are before their opening counterparts.",
fix: null,
});
}
console.log(
`304 isMediaD(): ${`\u001b[${33}m${`openingBracketCount`}\u001b[${39}m`} = ${JSON.stringify(
openingBracketCount,
null,
4
)}`
);
console.log(
`311 isMediaD(): ${`\u001b[${33}m${`closingBracketCount`}\u001b[${39}m`} = ${JSON.stringify(
closingBracketCount,
null,
4
)}`
);
// reporting that there were more one kind
// of brackets than the other:
if (openingBracketCount > closingBracketCount) {
res.push({
idxFrom: nonWhitespaceStart + opts.offset,
idxTo: nonWhitespaceEnd + opts.offset,
message: "More opening brackets than closing.",
fix: null,
});
} else if (closingBracketCount > openingBracketCount) {
res.push({
idxFrom: nonWhitespaceStart + opts.offset,
idxTo: nonWhitespaceEnd + opts.offset,
message: "More closing brackets than opening.",
fix: null,
});
}
if (!res.length && str.match(/\(\s*\)/g)) {
console.log(`337 empty brackets pair detected`);
// now find out where
let lastOpening = null;
let nonWhitespaceFound;
for (let i = 0, len = str.length; i < len; i++) {
if (str[i] === "(") {
lastOpening = i;
nonWhitespaceFound = false;
} else if (str[i] === ")" && lastOpening) {
if (!nonWhitespaceFound) {
console.log(
`348 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${lastOpening}, ${
i + 1
}]`
);
res.push({
idxFrom: lastOpening + opts.offset,
idxTo: i + 1 + opts.offset,
message: "Empty bracket pair.",
fix: null,
});
} else {
nonWhitespaceFound = true;
}
} else if (str[i].trim()) {
nonWhitespaceFound = true;
}
}
}
if (res.length) {
// report errors early, save resources
console.log(
`370 isMediaD(): early ${`\u001b[${32}m${`RETURN`}\u001b[${39}m`}`
);
return res;
}
// PART 2.
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
console.log(
`379 isMediaD(): ${`\u001b[${36}m${`PART II.`}\u001b[${39}m`} The main loop.`
);
// first parse comma-separated chunks
processCommaSep(str, {
offset: opts.offset,
leadingWhitespaceOK: false,
trailingWhitespaceOK: false,
oneSpaceAfterCommaOK: true,
innerWhitespaceAllowed: true,
separator: ",",
cb: (idxFrom: number, idxTo: number) => {
console.log(
`391 isMediaD(): chunk [${idxFrom - opts.offset}, ${
idxTo - opts.offset
}] extracted, passing to loop()`
);
loop(
str,
{
...opts,
idxFrom: idxFrom - opts.offset,
idxTo: idxTo - opts.offset,
},
res
);
},
errCb: (ranges: Ranges, message: string) => {
console.log(
`407 isMediaD(): received error range ${JSON.stringify(
ranges,
null,
4
)} and message: "${message}"`
);
},
});
// PART 3.
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// if (!res.length) {
// // finally, if no errors were caught, parse:
// console.log(`329 PART III. Run through CSS Tree parser.`);
// const temp = cssTreeValidate(`@media ${str} {}`);
// console.log(
// `332 ${`\u001b[${31}m${`โโ`}\u001b[${39}m`} ${`\u001b[${33}m${`temp`}\u001b[${39}m`} = ${JSON.stringify(
// temp,
// null,
// 4
// )}`
// );
// }
}
// ---------------------------------------------------------------------------
console.log(
`436 isMediaD(): ${`\u001b[${32}m${`FINAL RETURN`}\u001b[${39}m`}`
);
console.log(
`439 isMediaD(): ${`\u001b[${33}m${`res`}\u001b[${39}m`} = ${JSON.stringify(
res,
null,
4
)}`
);
return res;
}
export { isMediaD, defaults, version }; | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.