text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
* Port of supertest (https://github.com/visionmedia/supertest) for Deno.
*
* Types adapted from:
* - https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/superagent/index.d.ts
* - https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/supertest/index.d.ts
*/
import type { ListenerLike, ServerLike } from "./types.ts";
import { assertEquals, STATUS_TEXT } from "../deps.ts";
import { superagent } from "./superagent.ts";
import { close } from "./close.ts";
import { isListener, isServer, isStdNativeServer, isString } from "./utils.ts";
import { exposeSham } from "./xhrSham.js";
/**
* Custom expectation checker.
*/
type ExpectChecker = (res: IResponse) => any;
/**
* The handler function for callbacks within `end` method.
*/
type CallbackHandler = (err: any, res: IResponse) => void;
type Serializer = (obj: any) => string;
type Parser = (str: string) => any;
type MultipartValueSingle =
| Blob
| Uint8Array
| Deno.Reader
| string
| boolean
| number;
type MultipartValue = MultipartValueSingle | MultipartValueSingle[];
type HeaderValue = string | string[];
type Header = { [key: string]: HeaderValue };
/**
* An HTTP error with additional properties of:
* - status
* - text
* - method
* - path
*/
interface HTTPError extends Error {
status: number;
text: string;
method: string;
path: string;
}
interface XMLHttpRequest {}
export interface IResponse {
accepted: boolean;
badRequest: boolean;
body: any;
charset: string;
clientError: boolean;
error: false | HTTPError;
files: any;
forbidden: boolean;
get(header: string): HeaderValue;
header: Header;
headers: Header;
info: boolean;
links: object;
noContent: boolean;
notAcceptable: boolean;
notFound: boolean;
ok: boolean;
redirect: boolean;
serverError: boolean;
status: number;
statusCode: number;
statusType: number;
statusText: string;
text: string;
type: string;
unauthorized: boolean;
xhr: XMLHttpRequest;
redirects: string[];
}
export interface IRequest extends Promise<IResponse> {
/**
* Initialize a new `Request` with the given `method` and `url`.
*
* @param {string} method
* @param {string} url
*/
new (method: string, url: string): IRequest;
agent(agent?: any): this;
cookies: string;
method: string;
url: string;
abort(): void;
accept(type: string): this;
attach(
field: string,
file: MultipartValueSingle,
options?: string | { filename?: string; contentType?: string },
): this;
auth(user: string, pass: string, options?: { type: "basic" | "auto" }): this;
auth(token: string, options: { type: "bearer" }): this;
buffer(val?: boolean): this;
ca(cert: any | any[]): this;
cert(cert: any | any[]): this;
clearTimeout(): this;
disableTLSCerts(): this;
end(callback?: CallbackHandler): void;
field(name: string, val: MultipartValue): this;
field(fields: { [fieldName: string]: MultipartValue }): this;
get(field: string): string;
http2(enable?: boolean): this;
key(cert: any | any[]): this;
ok(callback: (res: IResponse) => boolean): this;
on(name: "error", handler: (err: any) => void): this;
on(name: "progress", handler: (event: ProgressEvent) => void): this;
on(name: "response", handler: (response: IResponse) => void): this;
on(name: string, handler: (event: any) => void): this;
parse(parser: Parser): this;
part(): this;
pfx(
cert: any | any[] | {
pfx: string | any;
passphrase: string;
},
): this;
pipe(stream: any, options?: object): any;
query(val: object | string): this;
redirects(n: number): this;
responseType(type: string): this;
retry(count?: number, callback?: CallbackHandler): this;
send(data?: string | object): this;
serialize(serializer: Serializer): this;
set(field: object): this;
set(field: string, val: string): this;
set(field: "Cookie", val: string[]): this;
timeout(ms: number | { deadline?: number; response?: number }): this;
trustLocalhost(enabled?: boolean): this;
type(val: string): this;
unset(field: string): this;
use(fn: Plugin): this;
withCredentials(): this;
write(data: string | any, encoding?: string): boolean;
maxResponseSize(size: number): this;
}
type Plugin = (req: IRequest) => void;
/**
* Allow us to hang off our internal xhr sham promises without
* exposing the internals to the consumer.
*/
const SHAM_SYMBOL = Symbol("SHAM_SYMBOL");
exposeSham(SHAM_SYMBOL);
/**
* Ensures all promises within the xhr sham have completed.
*
* @private
*/
async function completeXhrPromises() {
for (
const promise of Object.values(
(window as any)[SHAM_SYMBOL].promises,
)
) {
if (promise) {
try {
await promise;
} catch (_) {
// swallow
}
}
}
}
/**
* The superagent Request class.
*/
const SuperRequest: IRequest = (superagent as any).Request;
/**
* The SuperDeno Test object extends the methods provided by superagent to provide
* a high-level abstraction for testing HTTP, while still allowing you to drop down
* to the lower-level API provided by superagent.
*/
export class Test extends SuperRequest {
#asserts!: any[];
#redirects: number;
#redirectList: string[];
#server!: ServerLike;
public app: string | ListenerLike | ServerLike;
public url: string;
constructor(
app: string | ListenerLike | ServerLike,
method: string,
path: string,
host?: string,
secure: boolean = false,
) {
super(method.toUpperCase(), path);
this.redirects(0);
this.#redirects = 0;
this.#redirectList = [];
this.app = app;
this.#asserts = [];
if (isString(app)) {
this.url = `${app}${path}`;
} else {
if (isStdNativeServer(app)) {
const listenAndServePromise = app.listenAndServe().catch((err) =>
close(app, app, err)
);
this.#server = {
async close() {
try {
app.close();
await listenAndServePromise;
} catch {
// swallow error
}
},
addrs: app.addrs,
async listenAndServe() {},
};
} else if (isServer(app)) {
this.#server = app as ServerLike;
} else if (isListener(app)) {
secure = false;
this.#server = (app as ListenerLike).listen(":0");
} else {
throw new Error(
"superdeno is unable to identify or create a valid test server",
);
}
this.url = this.#serverAddress(path, host, secure);
}
}
/**
* Returns a URL, extracted from a server.
*
* @param {string} path
* @param {?string} host
* @param {?boolean} secure
*
* @returns {string} URL address
* @private
*/
#serverAddress = (
path: string,
host?: string,
secure?: boolean,
) => {
const address =
("addrs" in this.#server
? this.#server.addrs[0]
: this.#server.listener.addr) as Deno.NetAddr;
const port = address.port;
const protocol = secure ? "https" : "http";
return `${protocol}://${(host || "127.0.0.1")}:${port}${path}`;
};
/**
* Expectations:
*
* .expect(fn)
*
* @param {ExpectChecker} callback
*
* @returns {Test} for chaining
* @public
*/
expect(callback: ExpectChecker): this;
/**
* Expectations:
*
* .expect(200)
* .expect(200, fn)
*
* @param {number} status
* @param {?CallbackHandler} callback
*
* @returns {Test} for chaining
* @public
*/
expect(status: number, callback?: CallbackHandler): this;
/**
* Expectations:
*
* .expect(200, body)
* .expect(200, body, fn)
*
* @param {number} status
* @param {any} body
* @param {?CallbackHandler} callback
*
* @returns {Test} for chaining
* @public
*/
expect(status: number, body: any, callback?: CallbackHandler): this;
/**
* Expectations:
*
* .expect('Some body')
* .expect(/Some body/i)
* .expect('Some body', fn)
*
* @param {string|RegExp|Object} body
* @param {?CallbackHandler} callback
*
* @returns {Test} for chaining
* @public
*/
expect(body: string | RegExp | Object, callback?: CallbackHandler): this;
/**
* Expectations:
*
* .expect('Content-Type', 'application/json')
* .expect('Content-Type', /application/g', fn)
*
* @param {string} field
* @param {string|RegExp|Object} value
* @param {?CallbackHandler} callback
*
* @returns {Test} for chaining
* @public
*/
expect(
field: string,
value: string | RegExp | number,
callback?: CallbackHandler,
): this;
expect(a: any, b?: any, c?: any): this {
// callback
if (typeof a === "function") {
this.#asserts.push(a);
return this;
}
if (typeof b === "function") this.end(b);
if (typeof c === "function") this.end(c);
// status
if (typeof a === "number") {
this.#asserts.push(this.#assertStatus.bind(this, a));
// body
if (typeof b !== "function" && arguments.length > 1) {
this.#asserts.push(this.#assertBody.bind(this, b));
}
return this;
}
// header field
if (typeof b === "string" || typeof b === "number" || b instanceof RegExp) {
this.#asserts.push(
this.#assertHeader.bind(this, { name: "" + a, value: b }),
);
return this;
}
// body
this.#asserts.push(this.#assertBody.bind(this, a));
return this;
}
#redirect = (res: IResponse, callback?: CallbackHandler): this => {
const url = res.headers.location as string;
if (!url) {
close(this.#server, this.app, undefined, async () => {
await completeXhrPromises();
callback?.(new Error("No location header for redirect"), res);
});
return this;
}
const parsedUrl = new URL(url, this.url);
const changesOrigin = parsedUrl.host !== new URL(this.url).host;
let headers = (this as any)._header;
// implementation of 302 following defacto standard
if (res.statusCode === 301 || res.statusCode === 302) {
// strip Content-* related fields in case of POST etc.
headers = cleanHeader(headers, changesOrigin);
// force GET
this.method = this.method === "HEAD" ? "HEAD" : "GET";
// clear data
(this as any)._data = null;
}
// 303 is always GET
if (res.statusCode === 303) {
// strip Content-* related fields in case of POST etc.
headers = cleanHeader(headers, changesOrigin);
// force method
this.method = "GET";
// clear data
(this as any)._data = null;
}
// 307 preserves method
// 308 preserves method
delete headers.host;
delete (this as any)._formData;
initHeaders(this);
(this as any)._endCalled = false;
this.url = parsedUrl.href;
(this as any).qs = {};
(this as any)._query = [];
this.set(headers);
(this as any).emit("redirect", res);
this.#redirectList.push(this.url);
this.end(callback);
return this;
};
/**
* Defer invoking superagent's `.end()` until
* the server is listening.
*
* @param {CallbackHandler} fn
*
* @returns {Test} for chaining
* @public
*/
end(callback?: CallbackHandler): this {
const self = this;
const end = SuperRequest.prototype.end;
end.call(
self,
function (err: any, res: any) {
// Before we close, ensure that we have handled all
// requested redirects
const redirect = isRedirect(res?.statusCode);
const max: number = (self as any)._maxRedirects;
if (redirect && self.#redirects++ !== max) {
return self.#redirect(res, callback);
}
return close(self.#server, self.app, undefined, async () => {
await completeXhrPromises();
self.#assert(err, res, callback);
});
},
);
return this;
}
/**
* Perform assertions and invoke `fn(err, res)`.
*
* @param {HTTPError} [resError]
* @param {IResponse} res
* @param {Function} fn
* @private
*/
#assert = (resError: HTTPError, res: IResponse, fn?: Function): void => {
let error;
if (!res && resError) {
error = resError;
}
// asserts
for (let i = 0; i < this.#asserts.length && !error; i += 1) {
error = this.#assertFunction(this.#asserts[i], res);
}
// set unexpected superagent error if no other error has occurred.
if (
!error && resError instanceof Error &&
(!res || (resError as any).status !== res.status)
) {
error = resError;
}
if (fn) fn.call(this, error || null, res);
};
/**
* Perform assertions on a response body and return an Error upon failure.
*
* @param {any} body
* @param {IResponse} res
*
* @returns {?Error}
* @private
*/
#assertBody = function (body: any, res: IResponse): Error | void {
const isRegExp = body instanceof RegExp;
// parsed
if (typeof body === "object" && !isRegExp) {
try {
assertEquals(body, res.body);
} catch (_) {
const a = Deno.inspect(body);
const b = Deno.inspect(res.body);
return error(
`expected ${a} response body, got ${b}`,
body,
res.body,
);
}
} else if (body !== res.text) {
// string
const a = Deno.inspect(body);
const b = Deno.inspect(res.text);
// regexp
if (isRegExp) {
if (!body.test(res.text)) {
return error(
`expected body ${b} to match ${body}`,
body,
res.body,
);
}
} else {
return error(
`expected ${a} response body, got ${b}`,
body,
res.body,
);
}
}
};
/**
* Perform assertions on a response header and return an Error upon failure.
*
* @param {any} header
* @param {IResponse} res
*
* @returns {?Error}
* @private
*/
#assertHeader = (
header: { name: string; value: string | number | RegExp },
res: IResponse,
): Error | void => {
const field = header.name;
const actual = res.headers[field.toLowerCase()];
const fieldExpected = header.value;
if (typeof actual === "undefined") {
return new Error(`expected "${field}" header field`);
}
// This check handles header values that may be a String or single element Array
if (
(Array.isArray(actual) && actual.toString() === fieldExpected) ||
fieldExpected === actual
) {
return;
}
if (fieldExpected instanceof RegExp) {
if (!fieldExpected.test(actual as string)) {
return new Error(
`expected "${field}" matching ${fieldExpected}, got "${actual}"`,
);
}
} else {
return new Error(
`expected "${field}" of "${fieldExpected}", got "${actual}"`,
);
}
};
/**
* Perform assertions on the response status and return an Error upon failure.
*
* @param {number} status
* @param {IResponse} res
*
* @returns {?Error}
* @private
*/
#assertStatus = (status: number, res: IResponse): Error | void => {
if (res.status !== status) {
const a = STATUS_TEXT.get(status);
const b = STATUS_TEXT.get(res.status);
return new Error(`expected ${status} "${a}", got ${res.status} "${b}"`);
}
};
/**
* Performs an assertion by calling a function and return an Error upon failure.
*
* @param {Function} fn
* @param {IResponse} res
*
* @returns {?Error}
* @private
*/
#assertFunction = (fn: Function, res: IResponse): Error | void => {
let err;
try {
err = fn(res);
} catch (e) {
err = e;
}
if (err instanceof Error) return err;
};
}
/**
* Return an `Error` with `msg` and results properties.
*
* @param {string} msg
* @param {any} expected
* @param {any} actual
*
* @returns {Error}
* @private
*/
function error(msg: string, expected: any, actual: any): Error {
const err = new Error(msg);
(err as any).expected = expected;
(err as any).actual = actual;
(err as any).showDiff = true;
return err;
}
/**
* Check if we should follow the redirect `code`.
*
* @param {number} code
*
* @returns {boolean}
* @private
*/
function isRedirect(code = 0) {
return [301, 302, 303, 305, 307, 308].includes(code);
}
/**
* Strip content related fields from `header`.
*
* @param {object} header
*
* @returns {object} header
* @private
*/
function cleanHeader(header: Header, changesOrigin: boolean) {
delete header["content-type"];
delete header["content-length"];
delete header["transfer-encoding"];
delete header.host;
if (changesOrigin) {
delete header.authorization;
delete header.cookie;
}
return header;
}
/**
* Initialize internal header tracking properties on a request instance.
*
* @param {object} req the instance
* @private
*/
function initHeaders(req: any) {
req._header = {};
req.header = {};
} | the_stack |
import { TestBed, fakeAsync, tick } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { Component } from '@angular/core';
import { MdcChipSetDirective, MdcChipDirective, MdcChipIconDirective, CHIP_DIRECTIVES } from './mdc.chip.directive';
import { hasRipple, simulateKey } from '../../testutils/page.test';
describe('MdcChipDirective', () => {
@Component({
template: `
<div [mdcChipSet]="type" id="set">
<div *ngFor="let chip of chips; let i = index" mdcChip
[value]="chip.startsWith('__') ? undefined : chip"
(interact)="interact(chip)"
(remove)="remove(i)"
(selectedChange)="valueChange(chip,$event)">
<i *ngIf="includeLeadingIcon" mdcChipIcon class="material-icons">event</i>
<span mdcChipCell>
<span mdcChipPrimaryAction>
<div mdcChipText>{{chip}}</div>
</span>
</span>
<span *ngIf="includeTrailingIcon" mdcChipCell>
<i *ngIf="includeTrailingIcon" class="material-icons" mdcChipIcon (interact)="trailingIconInteract(chip)">cancel</i>
</span>
</div>
</div>
`
})
class TestComponent {
includeLeadingIcon = false;
includeTrailingIcon = false;
type = 'action';
chips = ['chippie', 'chappie', 'choppie'];
interactions = [];
trailingIconInteractions = [];
valueChanges = [];
interact(chip: string) {
this.interactions.push(chip);
}
trailingIconInteract(chip: string) {
this.trailingIconInteractions.push(chip);
}
resetInteractions() {
this.interactions = [];
this.trailingIconInteractions = [];
}
remove(i: number) {
this.chips.splice(i, 1);
}
valueChange(chip: string, value: boolean) {
this.valueChanges.push({chip: chip, value: value});
}
}
function setup(testComponentType: any = TestComponent) {
const fixture = TestBed.configureTestingModule({
declarations: [...CHIP_DIRECTIVES, testComponentType]
}).createComponent(testComponentType);
fixture.detectChanges();
const testComponent = fixture.debugElement.injector.get(testComponentType);
const chipSetComponent = fixture.debugElement.query(By.directive(MdcChipSetDirective)).injector.get(MdcChipSetDirective);
const chipSet: HTMLElement = fixture.nativeElement.querySelector('#set');
return { fixture, testComponent, chipSetComponent, chipSet };
}
it('apply correct styles for chip and chip-set', (() => {
const { fixture, testComponent, chipSet } = setup();
expect(chipSet.classList).toContain('mdc-chip-set');
const chips = chipSet.querySelectorAll('.mdc-chip');
expect(chips.length).toBe(3);
// only one chip/interactionIcon should be tabbable at a time:
expect(chipSet.querySelectorAll('[tabindex]:not([tabindex="-1"])').length).toBe(1);
for (let i = 0; i !== chips.length; ++i) {
expect(chips.item(i).classList.contains('mdc-chip--deletable')).toBe(true);
const icons = chips.item(i).querySelectorAll('i');
expect(icons.length).toBe(0);
}
testComponent.includeLeadingIcon = true;
testComponent.includeTrailingIcon = true;
fixture.detectChanges();
for (let i = 0; i !== chips.length; ++i) {
let icons = chips.item(i).querySelectorAll('i');
expect(icons.length).toBe(2);
expect(icons.item(0).classList).toContain('mdc-chip__icon');
expect(icons.item(1).classList).toContain('mdc-chip__icon');
expect(icons.item(0).classList).toContain('mdc-chip__icon--leading');
expect(icons.item(1).classList).toContain('mdc-chip__icon--trailing');
}
}));
it('chips have ripples', fakeAsync(() => {
const { fixture } = setup();
const chips = fixture.nativeElement.querySelectorAll('.mdc-chip');
expect(chips.length).toBe(3);
for (let i = 0; i !== chips.length; ++i)
expect(hasRipple(chips.item(i))).toBe(true);
}));
it('chips get values (either via binding or auto-assigned)', fakeAsync(() => {
const { fixture, testComponent } = setup();
testComponent.chips = ['one', '__two', 'three'];
fixture.detectChanges();
// for some weird reason this returns every MdcChipDirective twice, hence the construct to remove duplicates:
const chipComponents = fixture.debugElement.queryAll(By.directive(MdcChipDirective)).map(de => de.injector.get(MdcChipDirective))
.reduce((unique, item) => unique.includes(item) ? unique : [...unique, item], []);
expect(chipComponents.length).toBe(3);
expect(chipComponents[0].value).toBe('one');
expect(chipComponents[1].value).toMatch(/mdc-chip-.*/);
expect(chipComponents[2].value).toBe('three');
}));
it('chipset type is one of choice, filter, input, or action', (() => {
const { fixture, testComponent, chipSetComponent, chipSet } = setup();
expect(chipSetComponent.mdcChipSet).toBe('action');
expect(chipSet.getAttribute('class')).toBe('mdc-chip-set');
for (let type of ['choice', 'filter', 'input']) {
testComponent.type = type;
fixture.detectChanges();
expect(chipSetComponent.mdcChipSet).toBe(type);
expect(chipSet.classList).toContain('mdc-chip-set--' + type);
}
testComponent.type = 'invalid';
fixture.detectChanges();
expect(chipSetComponent.mdcChipSet).toBe('action');
expect(chipSet.getAttribute('class')).toBe('mdc-chip-set');
}));
it('trailing icons get a role=button and are navigatable', fakeAsync(() => {
const { fixture, testComponent } = setup();
testComponent.chips = ['chip1', 'chip2'];
testComponent.includeLeadingIcon = true;
testComponent.includeTrailingIcon = true;
fixture.detectChanges(); tick();
let primaryActions = [...fixture.nativeElement.querySelectorAll('.mdc-chip__primary-action')];
expect(primaryActions.length).toBe(2);
expect(primaryActions.map(a => a.tabIndex)).toEqual([0, -1]);
let icons = [...fixture.nativeElement.querySelectorAll('i')];
expect(icons.length).toBe(4);
expect(icons.map(i => i.tabIndex)).toEqual([-1, -1, -1, -1]);
expect(icons.map(i => i.getAttribute('role'))).toEqual([null, 'button', null, 'button']);
// ArrowRight/ArrowLeft changes focus and tabbable item:
primaryActions[0].focus();
simulateKey(primaryActions[0], 'ArrowRight');
// trailing action of first chip now is tabbable and has focus:
expect(document.activeElement).toBe(icons[1]);
expect(primaryActions.map(a => a.tabIndex)).toEqual([-1, -1]);
expect(icons.map(i => i.tabIndex)).toEqual([-1, 0, -1, -1]);
// role/tabIndex changes must be undone when the icon is not a trailing icon anymore:
const trailingIcon = fixture.debugElement.queryAll(By.directive(MdcChipIconDirective))[1].injector.get(MdcChipIconDirective);
expect(trailingIcon._elm.nativeElement).toBe(icons[1]);
trailingIcon._trailing = false;
fixture.detectChanges();
expect(icons[1].tabIndex).toBe(-1);
expect(icons[1].hasAttribute('role')).toBe(false);
}));
it('unreachable code for our implementation must throw errors', (() => {
const { fixture, testComponent, chipSetComponent } = setup();
testComponent.chips = ['chip'];
fixture.detectChanges();
expect(() => {chipSetComponent._adapter.removeChipAtIndex(null); }).toThrowError();
}));
it('click action chip triggers interaction event', (() => {
const { fixture, testComponent } = setup();
testComponent.chips = ['chip'];
fixture.detectChanges();
const chip = fixture.nativeElement.querySelector('.mdc-chip');
expect(testComponent.interactions).toEqual([]);
expect(testComponent.trailingIconInteractions).toEqual([]);
chip.click();
expect(testComponent.interactions).toEqual(['chip']);
expect(testComponent.trailingIconInteractions).toEqual([]);
}));
it('trailing icon interactions trigger interaction and remove events', fakeAsync(() => {
const { fixture, testComponent } = setup();
testComponent.type = 'input';
testComponent.chips = ['chip'];
testComponent.includeTrailingIcon = true;
fixture.detectChanges();
const chip = fixture.nativeElement.querySelector('.mdc-chip');
const trailingIcon = fixture.nativeElement.querySelector('.mdc-chip i:last-child');
const chipComponent = fixture.debugElement.query(By.directive(MdcChipDirective)).injector.get(MdcChipDirective);
expect(testComponent.interactions).toEqual([]);
expect(testComponent.trailingIconInteractions).toEqual([]);
trailingIcon.click();
expect(testComponent.interactions).toEqual([]);
expect(testComponent.trailingIconInteractions).toEqual(['chip']);
// simulate transitionend event for exit transition of chip:
(<any>chipComponent._foundation).handleTransitionEnd({target: chip, propertyName: 'opacity'});
tick(20); // wait for requestAnimationFrame
(<any>chipComponent._foundation).handleTransitionEnd({target: chip, propertyName: 'width'});
expect(testComponent.chips).toEqual([]);
}));
it('after chip removal, next remaining chip has focus and is tabbable', fakeAsync(() => {
const { fixture, testComponent } = setup();
testComponent.type = 'input';
testComponent.chips = ['chip1', 'chip2', 'chip3'];
testComponent.includeTrailingIcon = true;
fixture.detectChanges();
const chips: HTMLElement[] = [...fixture.nativeElement.querySelectorAll('.mdc-chip')];
const primaryActions: HTMLElement[] = chips.map(c => c.querySelector('.mdc-chip__primary-action'));
const trailingIcons: HTMLElement[] = chips.map(c => c.querySelector('i:last-child'));
// for some weird reason this returns every MdcChipDirective twice when executed on Github Actions,
// (it doesn't when run locally with test/test:watch/test:ci, and also doesn't on circleci...),
// hence the construct to remove duplicates:
const chipComponents = fixture.debugElement.queryAll(By.directive(MdcChipDirective)).map(de => de.injector.get(MdcChipDirective))
.reduce((unique, item) => unique.includes(item) ? unique : [...unique, item], []);
expect(chipComponents.length).toBe(3);
expect(primaryActions[0].tabIndex).toBe(0);
simulateKey(primaryActions[0], 'ArrowRight');
expect(trailingIcons[0].tabIndex).toBe(0);
simulateKey(trailingIcons[0], 'ArrowRight');
expect(primaryActions[1].tabIndex).toBe(0);
simulateKey(primaryActions[1], 'ArrowRight');
expect(trailingIcons[1].tabIndex).toBe(0);
expect(document.activeElement).toBe(trailingIcons[1]);
trailingIcons[1].click();
expect(testComponent.interactions).toEqual([]);
expect(testComponent.trailingIconInteractions).toEqual(['chip2']);
// simulate transitionend event for exit transition of chip:
(<any>chipComponents[1]._foundation).handleTransitionEnd({target: chips[1], propertyName: 'opacity'});
tick(20); // wait for requestAnimationFrame
(<any>chipComponents[1]._foundation).handleTransitionEnd({target: chips[1], propertyName: 'width'});
expect(testComponent.chips).toEqual(['chip1', 'chip3']);
expect([...fixture.nativeElement.querySelectorAll('.mdc-chip__primary-action')].map(a => a.tabIndex)).toEqual([-1, -1]);
expect([...fixture.nativeElement.querySelectorAll('.mdc-chip')]
.map(c => c.querySelector('i:last-child').tabIndex)).toEqual([-1, 0]);
expect(document.activeElement).toBe([...fixture.nativeElement.querySelectorAll('.mdc-chip')]
.map(c => c.querySelector('i:last-child'))[1]);
}));
it('after chip list changes, always exactly one chip or trailingIcon should be tabbable', fakeAsync(() => {
const { fixture, testComponent } = setup();
testComponent.type = 'input';
testComponent.chips = ['chip1', 'chip2', 'chip3'];
testComponent.includeTrailingIcon = true;
fixture.detectChanges();
while (testComponent.chips.length) {
expect(fixture.nativeElement.querySelectorAll('.mdc-chip').length).toBe(testComponent.chips.length);
expect(fixture.nativeElement.querySelectorAll('[tabindex]:not([tabindex="-1"])').length).toBe(1);
testComponent.chips.splice(0, 1);
fixture.detectChanges();
}
expect(fixture.nativeElement.querySelectorAll('.mdc-chip').length).toBe(0);
expect(fixture.nativeElement.querySelectorAll('[tabindex]:not([tabindex="-1"])').length).toBe(0);
}));
it('filter chips get a checkmark icon on selection', (() => {
const { fixture, testComponent } = setup();
testComponent.type = 'filter';
fixture.detectChanges();
const chips = fixture.nativeElement.querySelectorAll('.mdc-chip');
const svgs = fixture.nativeElement.querySelectorAll('svg');
expect(svgs.length).toBe(3);
expect(chips[0].classList.contains('mdc-chip--selected')).toBe(false);
expect(chips[1].classList.contains('mdc-chip--selected')).toBe(false);
chips[0].click();
expect(chips[0].classList).toContain('mdc-chip--selected');
expect(chips[1].classList.contains('mdc-chip--selected')).toBe(false);
chips[1].click();
expect(chips[0].classList).toContain('mdc-chip--selected');
expect(chips[1].classList).toContain('mdc-chip--selected');
chips[0].click();
expect(chips[0].classList.contains('mdc-chip--selected')).toBe(false);
expect(chips[1].classList).toContain('mdc-chip--selected');
}));
it('filter chips selected value changes on clicks', (() => {
const { fixture, testComponent } = setup();
testComponent.type = 'filter';
fixture.detectChanges();
const chips = fixture.nativeElement.querySelectorAll('.mdc-chip');
expect(testComponent.valueChanges).toEqual([]);
chips[0].click();
chips[1].click();
chips[0].click();
expect(testComponent.valueChanges).toEqual([
{chip: 'chippie', value: true},
{chip: 'chappie', value: true},
{chip: 'chippie', value: false}
]);
}));
it('choice chips selected value changes on clicks and clicks of other choices', (() => {
const { fixture, testComponent } = setup();
testComponent.type = 'choice';
fixture.detectChanges();
const chips = fixture.nativeElement.querySelectorAll('.mdc-chip');
expect(testComponent.valueChanges).toEqual([]);
chips[0].click();
expect(testComponent.valueChanges).toEqual([{chip: 'chippie', value: true}]);
testComponent.valueChanges = [];
chips[1].click();
expect(testComponent.valueChanges).toEqual([{chip: 'chippie', value: false}, {chip: 'chappie', value: true}]);
testComponent.valueChanges = [];
chips[1].click();
expect(testComponent.valueChanges).toEqual([{chip: 'chappie', value: false}]);
}));
it('filter/choice chips selected state can be changed', fakeAsync(() => {
const { fixture, testComponent } = setup();
testComponent.type = 'choice';
fixture.detectChanges();
// for some weird reason this returns every MdcChipDirective twice, hence the construct to remove duplicates:
const chipComponents = fixture.debugElement.queryAll(By.directive(MdcChipDirective)).map(de => de.injector.get(MdcChipDirective))
.reduce((unique, item) => unique.includes(item) ? unique : [...unique, item], []);
expect(chipComponents.length).toBe(3);
expect(chipComponents[0].selected).toBe(false);
chipComponents[0].selected = true;
expect(testComponent.valueChanges).toEqual([{chip: 'chippie', value: true}]);
testComponent.valueChanges = [];
chipComponents[1].selected = true;
expect(testComponent.valueChanges).toEqual(jasmine.arrayWithExactContents([{chip: 'chippie', value: false}, {chip: 'chappie', value: true}]));
expect(chipComponents[0].selected).toBe(false);
testComponent.valueChanges = [];
chipComponents[1].selected = true; // no change shouldn't trigger change events
expect(testComponent.valueChanges).toEqual([]);
expect(chipComponents[0].selected).toBe(false);
expect(chipComponents[1].selected).toBe(true);
chipComponents[1].selected = false;
expect(testComponent.valueChanges).toEqual([{chip: 'chappie', value: false}]);
expect(chipComponents[0].selected).toBe(false);
expect(chipComponents[1].selected).toBe(false);
}));
it('filter chips hide their leading icon on selection (to make place for the checkmark)', fakeAsync(() => {
const { fixture, testComponent } = setup();
testComponent.type = 'filter';
testComponent.chips = ['chip'];
testComponent.includeLeadingIcon = true;
fixture.detectChanges();
const chip = fixture.nativeElement.querySelector('.mdc-chip');
const chipComponent = fixture.debugElement.query(By.directive(MdcChipDirective)).injector.get(MdcChipDirective);
const svg = fixture.nativeElement.querySelector('svg');
const icon = fixture.nativeElement.querySelector('i');
expect(icon.classList.contains('mdc-chip__icon--leading-hidden')).toBe(false);
chip.click();
// simulate transitionend event for hide animation of icon:
(<any>chipComponent._foundation).handleTransitionEnd({target: icon, propertyName: 'opacity'});
expect(icon.classList.contains('mdc-chip__icon--leading-hidden')).toBe(true);
chip.click();
// simulate transitionend event for hide animation of checkmark:
(<any>chipComponent._foundation).handleTransitionEnd({target: svg.parentElement, propertyName: 'opacity'});
expect(icon.classList.contains('mdc-chip__icon--leading-hidden')).toBe(false);
}));
it('computeRippleBoundingRect returns correct values', fakeAsync(() => {
const { fixture, testComponent } = setup();
testComponent.type = 'filter';
testComponent.chips = ['chip'];
testComponent.includeLeadingIcon = true;
fixture.detectChanges();
let chipComponent = fixture.debugElement.query(By.directive(MdcChipDirective)).injector.get(MdcChipDirective);
let chip = fixture.nativeElement.querySelector('div.mdc-chip');
let rect = chipComponent['computeRippleBoundingRect']();
expect(rect.height).toBe(32);
expect(rect.width).toBe(chip.getBoundingClientRect().width);
testComponent.includeLeadingIcon = false;
fixture.detectChanges();
let checkmark = fixture.nativeElement.querySelector('div.mdc-chip__checkmark');
rect = chipComponent['computeRippleBoundingRect']();
expect(rect.height).toBe(32);
expect(rect.width).toBe(chip.getBoundingClientRect().width + checkmark.getBoundingClientRect().height);
}));
@Component({
template: `
<div [mdcChipSet]="type" id="set">
<div mdcChip>
<ng-container *ngIf="!contained">
<i *ngFor="let icon of beforeIcons" mdcChipIcon class="material-icons before">{{icon}}</i>
</ng-container>
<div *ngIf="contained">
<i *ngFor="let icon of beforeIcons" mdcChipIcon class="material-icons before">{{icon}}</i>
</div>
<span mdcChipCell>
<span mdcChipPrimaryAction>
<div mdcChipText>{{chip}}</div>
</span>
</span>
<span *ngFor="let icon of afterIcons" mdcChipCell>
<ng-container *ngIf="!contained">
<i class="material-icons after" mdcChipIcon>{{icon}}</i>
</ng-container>
<div *ngIf="contained">
<i mdcChipIcon class="material-icons before">{{icon}}</i>
</div>
</span>
</div>
</div>
`
})
class TestIconsComponent {
contained = false;
beforeIcons = [];
afterIcons = [];
}
it('leading/trailing icons are detected properly', (() => {
const { fixture, testComponent } = setup(TestIconsComponent);
let icons = fixture.nativeElement.querySelectorAll('i');
expect(icons.length).toBe(0);
testComponent.afterIcons = ['cancel'];
fixture.detectChanges();
icons = fixture.nativeElement.querySelectorAll('i');
expect(icons.length).toBe(1);
expect(icons[0].classList.contains('mdc-chip__icon--leading')).toBe(false);
expect(icons[0].classList.contains('mdc-chip__icon--trailing')).toBe(true);
testComponent.contained = true;
fixture.detectChanges();
icons = fixture.nativeElement.querySelectorAll('i');
expect(icons.length).toBe(1);
expect(icons[0].classList.contains('mdc-chip__icon--leading')).toBe(false);
expect(icons[0].classList.contains('mdc-chip__icon--trailing')).toBe(true);
testComponent.beforeIcons = ['event'];
testComponent.afterIcons = [];
fixture.detectChanges();
icons = fixture.nativeElement.querySelectorAll('i');
expect(icons.length).toBe(1);
expect(icons[0].classList.contains('mdc-chip__icon--leading')).toBe(true);
expect(icons[0].classList.contains('mdc-chip__icon--trailing')).toBe(false);
testComponent.contained = true;
fixture.detectChanges();
icons = fixture.nativeElement.querySelectorAll('i');
expect(icons.length).toBe(1);
expect(icons[0].classList.contains('mdc-chip__icon--leading')).toBe(true);
expect(icons[0].classList.contains('mdc-chip__icon--trailing')).toBe(false);
testComponent.beforeIcons = ['event', 'event'];
testComponent.afterIcons = ['cancel', 'cancel'];
testComponent.contained = false;
fixture.detectChanges();
icons = fixture.nativeElement.querySelectorAll('i');
expect(icons.length).toBe(4);
expect(icons[0].classList.contains('mdc-chip__icon--leading')).toBe(true);
expect(icons[0].classList.contains('mdc-chip__icon--trailing')).toBe(false);
expect(icons[1].classList.contains('mdc-chip__icon--leading')).toBe(false);
expect(icons[1].classList.contains('mdc-chip__icon--trailing')).toBe(false);
expect(icons[2].classList.contains('mdc-chip__icon--leading')).toBe(false);
expect(icons[2].classList.contains('mdc-chip__icon--trailing')).toBe(false);
expect(icons[3].classList.contains('mdc-chip__icon--leading')).toBe(false);
expect(icons[3].classList.contains('mdc-chip__icon--trailing')).toBe(true);
testComponent.contained = true;
fixture.detectChanges();
icons = fixture.nativeElement.querySelectorAll('i');
expect(icons.length).toBe(4);
expect(icons[0].classList.contains('mdc-chip__icon--leading')).toBe(true);
expect(icons[0].classList.contains('mdc-chip__icon--trailing')).toBe(false);
expect(icons[1].classList.contains('mdc-chip__icon--leading')).toBe(false);
expect(icons[1].classList.contains('mdc-chip__icon--trailing')).toBe(false);
expect(icons[2].classList.contains('mdc-chip__icon--leading')).toBe(false);
expect(icons[2].classList.contains('mdc-chip__icon--trailing')).toBe(false);
expect(icons[3].classList.contains('mdc-chip__icon--leading')).toBe(false);
expect(icons[3].classList.contains('mdc-chip__icon--trailing')).toBe(true);
}));
@Component({
template: `
<div mdcChipSet>
<div mdcChip>
<i mdcChipIcon class="material-icons leading" tabindex="0">event</i>
<span mdcChipCell>
<span mdcChipPrimaryAction>
<div mdcChipText>one</div>
</span>
</span>
<span mdcChipCell>
<i mdcChipIcon class="material-icons">cancel</i>
</span>
</div>
<div mdcChip>
<i mdcChipIcon class="material-icons leading">event</i>
<span mdcChipCell>
<span mdcChipPrimaryAction tabindex="-1">
<div mdcChipText>two</div>
</span>
</span>
<span mdcChipCell>
<i mdcChipIcon class="material-icons" tabindex="-1">cancel</i>
</span>
</div>
<div mdcChip>
<i mdcChipIcon class="material-icons leading">event</i>
<span mdcChipCell>
<span mdcChipPrimaryAction tabindex="99">
<div mdcChipText>three</div>
</span>
</span>
<span mdcChipCell>
<i mdcChipIcon class="material-icons" tabindex="100">cancel</i>
</span>
</div>
</div>
`
})
class TestTabbingComponent {
}
it('chips trailing icons tabIndex is controlled by chipset, other icons tabindex can be overridden', (() => {
const { fixture } = setup(TestTabbingComponent);
let actions = fixture.nativeElement.querySelectorAll('.mdc-chip__primary-action');
expect(actions[0].tabIndex).toBe(-1); // initial -1, because last chip was initialized with a tabIndex, so that is taken as the first focusable chip
expect(actions[1].tabIndex).toBe(-1);
expect(actions[2].tabIndex).toBe(99);
let trailingIcons = fixture.nativeElement.querySelectorAll('.mdc-chip__icon--trailing');
expect(trailingIcons[0].tabIndex).toBe(-1);
expect(trailingIcons[1].tabIndex).toBe(-1);
expect(trailingIcons[2].tabIndex).toBe(-1); // because primaryAction is already tabbable
let leadingIcons = fixture.nativeElement.querySelectorAll('.leading');
expect(leadingIcons[0].tabIndex).toBe(0); // untouched, because leading icon
expect(leadingIcons[1].tabIndex).toBe(-1);
expect(leadingIcons[2].tabIndex).toBe(-1);
}));
@Component({
template: `
<div mdcChipSet>
<div mdcChip>
<i mdcChipIcon class="material-icons" role="custom-role">event</i>
<span mdcChipCell>
<span mdcChipPrimaryAction>
<div mdcChipText>one</div>
</span>
</span>
<span mdcChipCell>
<i mdcChipIcon class="material-icons" role="custom-role">cancel</i>
</span>
</div>
</div>
`
})
class TestIconRoleComponent {
}
it('chips icons can override their aria role', (() => {
const { fixture } = setup(TestIconRoleComponent);
let icons = fixture.nativeElement.querySelectorAll('.mdc-chip__icon');
expect(icons[0].getAttribute('role')).toBe('custom-role');
expect(icons[1].getAttribute('role')).toBe('custom-role');
}));
@Component({
template: `
<div [mdcChipSet]="type" id="set">
<div *ngFor="let chip of chips; let i = index" mdcChip="input"
removable="false"
(remove)="remove(i)">
<span mdcChipCell>
<span mdcChipPrimaryAction>
<div mdcChipText>{{chip}}</div>
</span>
</span>
<span mdcChipCell>
<i class="material-icons" mdcChipIcon (interact)="trailingIconInteract(chip)">cancel</i>
</span>
</div>
</div>
`
})
class TestNotRemobvableComponent {
chips = ['chippie', 'chappie', 'choppie'];
trailingIconInteractions = [];
removed = [];
trailingIconInteract(chip: string) {
this.trailingIconInteractions.push(chip);
}
resetInteractions() {
this.trailingIconInteractions = [];
}
remove(i: number) {
this.chips.splice(i, 1);
}
}
it('removable property must prevent removal', fakeAsync(() => {
const { fixture, testComponent } = setup(TestNotRemobvableComponent);
const chips: HTMLElement[] = [...fixture.nativeElement.querySelectorAll('.mdc-chip')];
const trailingIcons = fixture.nativeElement.querySelectorAll('.mdc-chip i:last-child');
// for some weird reason this returns every MdcChipDirective twice, hence the construct to remove duplicates:
const chipComponents = fixture.debugElement.queryAll(By.directive(MdcChipDirective)).map(de => de.injector.get(MdcChipDirective))
.reduce((unique, item) => unique.includes(item) ? unique : [...unique, item], []);
expect(testComponent.trailingIconInteractions).toEqual([]);
expect(chips.map(c => c.classList.contains('mdc-chip--deletable'))).toEqual([false, false, false]);
trailingIcons[1].click();
// simulate transitionend event for exit transition of chip:
(<any>chipComponents[1]._foundation).handleTransitionEnd({target: chips[1], propertyName: 'opacity'});
tick(20); // wait for requestAnimationFrame
(<any>chipComponents[1]._foundation).handleTransitionEnd({target: chips[1], propertyName: 'width'});
// there was an interaction:
expect(testComponent.trailingIconInteractions).toEqual(['chappie']);
// but nothing was deleted:
expect(testComponent.chips).toEqual(['chippie', 'chappie', 'choppie']);
}));
}); | the_stack |
import { strict as assert } from 'assert';
import {
Connection,
Keypair,
PublicKey,
Signer,
SystemProgram,
TransactionInstruction,
} from '@solana/web3.js';
import { VAULT_PREFIX, VAULT_PROGRAM_ID } from '../common/consts';
import {
mintTokens,
createMint,
getMintRentExempt,
createAssociatedTokenAccount,
approveTokenTransfer,
createVaultOwnedTokenAccount,
} from '../common/helpers';
import { getMint } from '../common/helpers.mint';
import {
AddTokenToInactiveVaultInstructionAccounts,
AmountArgs,
createAddTokenToInactiveVaultInstruction,
} from '../generated';
/**
* Allows to setup a safety deposit box and all related accounts easily.
* It exposes the {@link PublicKey}s for all created accounts as well as the
* {@link tokenMintPair} {@link Keypair} if it was created.
*
* Use {@link SafetyDepositSetup.create} in order to instantiate it.
*
* The {@link instructions} need to be provided to a transaction which is
* executed before the instruction to add tokens to the vault. Make sure to
* provide the {@link signers} with that transaction.
*
* The {@link SafetyDepositSetup} is then provided to {@link addTokenToInactiveVault}
* in order to create the instruction to add the tokens to the vault.
*
* @category AddTokenToInactiveVault
* @cateogry Instructions
*/
export class SafetyDepositSetup {
private constructor(
/** The parent vault for which this deposit box will be used */
readonly vault: PublicKey,
/** The account from which the tokens are transferred to the safety deposit */
readonly tokenAccount: PublicKey,
/** The token's mint */
readonly tokenMint: PublicKey,
/** Points to the spl-token account that contains the tokens */
readonly store: PublicKey,
/**
* The account address at which the program will store a pointer to the
* token account holding the tokens
*/
readonly safetyDeposit: PublicKey,
/**
* Transfer Authority to move desired token amount from token account to safety deposit
* which happens as part of processing the add token instruction.
*/
readonly transferAuthority: PublicKey,
/**
* Transfer Authority keypair is not included with the signers to setup the safety deposit.
* However it is needed when the token is added to the vault.
* Make sure to include it as the signer when executing that transaction.
*/
readonly transferAuthorityPair: Keypair,
/** The amount of tokens to transfer to the store */
readonly mintAmount: number,
/** Instructions to run in order to setup this Safety Deposit Box*/
readonly instructions: TransactionInstruction[],
/** Signers to include with the setup instructions */
readonly signers: Signer[],
/** The Keypair of the token mint in the case that a new one was created */
readonly tokenMintPair?: Keypair,
) {}
/**
* Prepares a {@link SafetyDepositBox} to be setup which includes
* initializing needed accounts properly.
*
* Returns an instance of {@link SafetyDepositSetup} which exposes
* instructions and signers to be included with the setup transaction.
*
* @param connection to solana cluster
* @param args
* @param args.payer payer who will own the store that will be added to the vault
* @param args.vault the parent vault which will manage the store
* @param args.mintAmount the amount ot mint to the token account to include with the store
* @param args.tokenMint to mint tokens from, if not provided one will be created
* @param args.tokenAccount the account to hold the minted toknes, if not provided one will be created
* @param args.mintAmount the amount of tokens to mint and include with the store
* @param args.associateTokenAccount flag indicating if created {@link
* tokenAccount} should be associated with the {@link payer}. At this point
* only associated accounts are supported.
*/
static async create(
connection: Connection,
args: {
payer: PublicKey;
vault: PublicKey;
tokenMint?: PublicKey;
tokenAccount?: PublicKey;
mintAmount: number;
associateTokenAccount?: boolean;
},
) {
const { payer, vault, associateTokenAccount = true } = args;
const instructions: TransactionInstruction[] = [];
const signers: Signer[] = [];
// -----------------
// Token Mint
// -----------------
let tokenMint: PublicKey;
let tokenMintPair: Keypair | undefined;
const mintRentExempt = await getMintRentExempt(connection);
if (args.tokenMint != null) {
tokenMint = args.tokenMint;
const info = await connection.getAccountInfo(tokenMint);
assert(info != null, 'provided mint needs to exist');
assert(info.lamports >= mintRentExempt, 'provided mint needs to be rent exempt');
const mint = await getMint(connection, tokenMint);
// TODO(thlorenz): is this correct?
assert.equal(mint.decimals, 0, 'provided mint should have 0 decimals');
} else {
const [createMintIxs, createMintSigners, { mintAccount, mintAccountPair }] = createMint(
payer,
mintRentExempt,
0,
payer,
payer,
);
instructions.push(...createMintIxs);
signers.push(...createMintSigners);
tokenMint = mintAccount;
tokenMintPair = mintAccountPair;
}
// -----------------
// Token Account
// -----------------
let tokenAccount: PublicKey;
if (args.tokenAccount != null) {
tokenAccount = args.tokenAccount;
} else {
// TODO(thlorenz): allow unassociated accounts as well
assert(associateTokenAccount, 'only allowing associated token accounts for now');
const [createAtaIx, associatedTokenAccount] = await createAssociatedTokenAccount({
payer,
tokenOwner: payer,
tokenMint,
});
tokenAccount = associatedTokenAccount;
instructions.push(createAtaIx);
}
const addTokensIx = mintTokens(tokenMint, tokenAccount, payer, args.mintAmount);
instructions.push(addTokensIx);
// -----------------
// Store Account
// -----------------
const [createStoreIxs, createStoreSigners, { tokenAccount: storeAccount }] =
await createVaultOwnedTokenAccount(connection, payer, vault, tokenMint);
instructions.push(...createStoreIxs);
signers.push(...createStoreSigners);
// -----------------
// SafetyDeposit Account
// -----------------
const safetyDepositAccount = await getSafetyDepositAccount(vault, tokenMint);
// -----------------
// Approve Token Transfer
// -----------------
const [approveTransferIx, transferAuthorityPair] = approveTokenTransfer({
owner: payer,
sourceAccount: tokenAccount,
amount: args.mintAmount,
});
instructions.push(approveTransferIx);
return new SafetyDepositSetup(
vault,
tokenAccount,
tokenMint,
storeAccount,
safetyDepositAccount,
transferAuthorityPair.publicKey,
transferAuthorityPair,
args.mintAmount,
instructions,
signers,
tokenMintPair,
);
}
}
/**
* Creates the instruction which adds tokens configured via the {@link SafetyDepositSetup}
* to the vault.
*
* **NOTE**: the instructions to initialize that safety deposit box need to be
* added to a transaction to run prior to this instruction, see {@link SafetyDepositSetup.instructions}
* and {@link SafetyDepositSetup.signers}.
*
* ### Conditions for {@link AddTokenToInactiveVaultInstructionAccounts} accounts to add token to vault
*
* _Aside from the conditions outlined in detail in {@link InitVault.initVault}_ the following should hold:
*
* #### vault
*
* - state: {@link VaultState.Inactive}
*
* #### tokenAccount
*
* - owned by: Token Program
* - amount: > 0 and >= {@link SafetyDepositSetup.mintAmount}
* - mint: used to verify safetyDeposit PDA
*
* #### store
*
* - amount: 0
* - owner: vault PDA (`[PREFIX, PROGRAM_ID, vault_address]`)
* - delegate: unset
* - closeAuthority: unset
*
* #### transferAuthority
*
* - approved to transfer tokens from the tokenAccount
*
* #### vaultAuthority
*
* - address: matches vault.authority
*
* #### safetyDeposit
*
* - address: vault+tokenAccount.mint PDA (`[PREFIX, PROGRAM_ID, vault_address, tokenAccount.mint]`)
*
*
* ### Updates as a result of completing the Transaction
*
* #### safetyDeposit
*
* _The account to hold the data is created and data allocated_
*
* - key: {@link Key.SafetyDepositBoxV1}
* - vault: vault address
* - tokenMint: tokenAccount.mint
* - store: store address
* - order: vault.tokenTypeCount (0 based)
*
* #### vault
*
* - tokenTypeCount: increased by 1
*
* #### store
*
* - credit {@link SafetyDepositSetup.mintAmount} (transferred from tokenAccount)
*
* ### tokenAccount
*
* - debit {@link SafetyDepositSetup.mintAmount} (transferred to store)
*
* @category AddTokenToInactiveVault
* @cateogry Instructions
*
* @param safetyDepositSetup created via {@link SafetyDepositSetup.create}
* @param ixAccounts
* @param ixAccounts.payer funding the transaction
* @param ixAccounts.vaultAuthority authority of the vault
*/
export async function addTokenToInactiveVault(
safetyDepositSetup: SafetyDepositSetup,
ixAccounts: { payer: PublicKey; vaultAuthority: PublicKey },
) {
const { vault, safetyDeposit, transferAuthority, store, tokenAccount, mintAmount } =
safetyDepositSetup;
const accounts: Omit<AddTokenToInactiveVaultInstructionAccounts, 'systemAccount'> = {
safetyDepositAccount: safetyDeposit,
tokenAccount,
store,
transferAuthority,
vault,
payer: ixAccounts.payer,
vaultAuthority: ixAccounts.vaultAuthority,
};
const instructionAccounts: AddTokenToInactiveVaultInstructionAccounts = {
...accounts,
systemAccount: SystemProgram.programId,
};
return createAddTokenToInactiveVaultInstruction(instructionAccounts, {
amountArgs: { amount: mintAmount },
});
}
/**
* Advanced version to add tokens to inactive vault.
* It requires all {@link accounts} to be set up properly
*
* Please {@see addTokenToInactiveVault} for a more intuitive way to set up
* this instruction and required accounts.
*
* @category AddTokenToInactiveVault
* @cateogry Instructions
*/
export async function addTokenToInactiveVaultDirect(
amountArgs: AmountArgs,
accounts: Omit<AddTokenToInactiveVaultInstructionAccounts, 'systemAccount'>,
) {
const instructionAccounts: AddTokenToInactiveVaultInstructionAccounts = {
...accounts,
systemAccount: SystemProgram.programId,
};
return createAddTokenToInactiveVaultInstruction(instructionAccounts, { amountArgs });
}
// -----------------
// Helpers
// -----------------
async function getSafetyDepositAccount(vault: PublicKey, tokenMint: PublicKey): Promise<PublicKey> {
const [pda] = await PublicKey.findProgramAddress(
[Buffer.from(VAULT_PREFIX), vault.toBuffer(), tokenMint.toBuffer()],
VAULT_PROGRAM_ID,
);
return pda;
} | the_stack |
import {
Component,
AfterContentInit,
ContentChildren,
Directive,
ElementRef,
EventEmitter,
HostBinding,
Input,
OnInit,
Optional,
Output,
QueryList,
forwardRef,
ViewEncapsulation,
ChangeDetectionStrategy
} from '@angular/core';
import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms';
import { coerceBooleanProperty } from 'src/filters';
import { UniqueSelectionDispatcher } from '../../core/coordination';
import './radio.scss';
/**
* Provider Expression that allows md-radio-group to register as a ControlValueAccessor. This
* allows it to support [(ngModel)] and ngControl.
*/
export const MD_RADIO_GROUP_CONTROL_VALUE_ACCESSOR: any = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => MdRadioGroup),
multi: true
};
let _uniqueIdCounter = 0;
export class MdRadioChange {
public source: MdRadioButton;
public value: any;
public type: string;
}
@Directive({
selector: 'md-radio-group',
providers: [MD_RADIO_GROUP_CONTROL_VALUE_ACCESSOR],
host: {
'role': 'radiogroup',
}
})
export class MdRadioGroup implements AfterContentInit, ControlValueAccessor {
private _value: any = null;
private _name: string = `md-radio-group-${_uniqueIdCounter++}`;
private _disabled: boolean = false;
private _selected: MdRadioButton = null;
private _isInitialized: boolean = false;
_controlValueAccessorChangeFn: (value: any) => void = (value) => {};
onTouched: () => any = () => {};
@Output()
change: EventEmitter<MdRadioChange> = new EventEmitter<MdRadioChange>(false);
@ContentChildren(forwardRef(() => MdRadioButton))
_radios: QueryList<MdRadioButton> = null;
@Input() align: 'start' | 'end';
@Input()
get name(): string { return this._name; }
set name(value: string) {
this._name = value;
this._updateRadioButtonNames();
}
@Input()
get disabled(): boolean { return this._disabled; }
set disabled(value: boolean) {
this._disabled = (value != null && value !== false) ? true : null;
}
@Input()
get value(): any { return this._value; }
set value(newValue: any) {
if (this._value != newValue) {
// Set this before proceeding to ensure no circular loop occurs with selection.
this._value = newValue;
this._updateSelectedRadioFromValue();
// Only fire a change event if this isn't the first time the value is ever set.
if (this._isInitialized) {
this._emitChangeEvent();
}
}
}
@Input()
get selected(): MdRadioButton { return this._selected; }
set selected(selected: MdRadioButton) {
this._selected = selected;
this.value = selected ? selected.value : null;
if (selected && !selected.checked) {
selected.checked = true;
}
}
ngAfterContentInit(): void {
// Mark this component as initialized in AfterContentInit because the initial value can
// possibly be set by NgModel on MdRadioGroup, and it is possible that the OnInit of the
// NgModel occurs *after* the OnInit of the MdRadioGroup.
this._isInitialized = true;
}
/**
* @description
* Mark this group as being "touched" (for ngModel). Meant to be called by the contained
* radio buttons upon their blur.
* @name _touch
* @returns {void}
*/
_touch(): void {
if (this.onTouched) {
this.onTouched();
}
}
/**
* @private
* @name _updateRadioButtonNames
* @returns {void}
*/
private _updateRadioButtonNames(): void {
if (this._radios) {
this._radios.forEach(radio => radio.name = this.name);
}
}
/**
* @private
* @description Updates the `selected` radio button from the internal _value state.
* @name _updateSelectedRadioFromValue
* @returns {void}
*/
private _updateSelectedRadioFromValue(): void {
// If the value already matches the selected radio, do nothing.
let isAlreadySelected = this._selected != null && this._selected.value == this._value;
if (this._radios != null && !isAlreadySelected) {
let matchingRadio = this._radios.filter(radio => radio.value == this._value)[0];
if (matchingRadio) {
this.selected = matchingRadio;
} else if (this.value == null) {
this.selected = null;
this._radios.forEach(radio => { radio.checked = false; });
}
}
}
/**
* @private
* @description Dispatch change event with current selection and group value
* @name _emitChangeEvent
* @returns {void}
*/
private _emitChangeEvent(): void {
let event = new MdRadioChange();
event.source = this._selected;
event.value = this._value;
this.change.emit(event);
}
/**
* @description Implemented as part of ControlValueAccessor
* @name writeValue
* @param value {any}
* @returns {void}
*/
writeValue(value: any): void {
this.value = value;
}
/**
* @description Implemented as part of ControlValueAccessor
* @name registerOnChange
* @param fn {Function}
* @returns {void}
*/
registerOnChange(fn: (value: any) => void): void {
this._controlValueAccessorChangeFn = fn;
}
/**
* @description Implemented as part of ControlValueAccessor
* @name registerOnTouched
* @param fn {any}
* @returns {void}
*/
registerOnTouched(fn: any): void {
this.onTouched = fn;
}
}
@Component({
selector: 'md-radio-button',
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
template:`
<label [attr.for]="inputId" class="md-radio-label">
<div class="md-radio-container">
<div class="md-radio-outer-circle"></div>
<div class="md-radio-inner-circle"></div>
<div md-ripple *ngIf="!disableRipple" class="md-radio-ripple"
[md-ripple-trigger]="getHostElement()"
[md-ripple-centered]="true"
[md-ripple-speed-factor]="0.3"
[md-ripple-background-color]="'rgba(0, 0, 0, 0)'"></div>
</div>
<input #input class="md-radio-input md-visually-hidden" type="radio"
[id]="inputId"
[checked]="checked"
[disabled]="disabled"
[name]="name"
[attr.aria-label]="ariaLabel"
[attr.aria-labelledby]="ariaLabelledby"
(change)="_onInputChange($event)"
(focus)="_onInputFocus()"
(blur)="_onInputBlur()"
(click)="_onInputClick($event)">
<div class="md-radio-label-content" [class.md-radio-align-end]="align === 'end'">
<ng-content></ng-content>
</div>
</label>
`
})
export class MdRadioButton implements OnInit {
private _checked: boolean = false;
private _disabled: boolean;
private _value: any = null;
private _disableRipple: boolean = true;
private _align: 'start' | 'end';
radioGroup: MdRadioGroup;
@HostBinding('class.md-radio-focused')
_isFocused: boolean;
@HostBinding('id')
@Input()
id: string = `md-radio-${_uniqueIdCounter++}`;
@Input()
name: string;
@Input('aria-label')
ariaLabel: string;
@Input('aria-labelledby')
ariaLabelledby: string;
@Input()
get disableRipple(): boolean { return this._disableRipple; }
set disableRipple(value) { this._disableRipple = coerceBooleanProperty(value); }
@HostBinding('class.md-radio-checked')
@Input()
get checked(): boolean { return this._checked; }
set checked(newCheckedState: boolean) {
this._checked = newCheckedState;
if (newCheckedState && this.radioGroup && this.radioGroup.value !== this.value) {
this.radioGroup.selected = this;
} else if (!newCheckedState && this.radioGroup && this.radioGroup.value === this.value) {
// When unchecking the selected radio button, update the selected radio
// property on the group.
this.radioGroup.selected = null;
}
if (newCheckedState) {
// Notify all radio buttons with the same name to un-check.
this.radioDispatcher.notify(this.id, this.name);
}
}
@Input()
get value(): any { return this._value; }
set value(value: any) {
if (this._value !== value) {
if (this.radioGroup !== null && this.checked) {
this.radioGroup.value = value;
}
this._value = value;
}
}
@Input()
get align(): 'start' | 'end' {
return this._align || (this.radioGroup !== null && this.radioGroup.align) || 'start';
}
set align(value: 'start' | 'end') {
this._align = value;
}
@HostBinding('class.md-radio-disabled')
@Input()
get disabled(): boolean {
return this._disabled || (this.radioGroup != null && this.radioGroup.disabled);
}
set disabled(value: boolean) {
// The presence of *any* disabled value makes the component disabled, *except* for false.
this._disabled = (value != null && value !== false) ? true : null;
}
@Output()
change: EventEmitter<MdRadioChange> = new EventEmitter<MdRadioChange>(false);
get inputId(): string {
return `${this.id}-input`;
}
constructor(@Optional() radioGroup: MdRadioGroup,
private _elementRef: ElementRef,
public radioDispatcher: UniqueSelectionDispatcher) {
this.radioGroup = radioGroup;
radioDispatcher.listen((id: string, name: string) => {
if (id !== this.id && name === this.name) {
this.checked = false;
}
});
}
ngOnInit(): void {
if (this.radioGroup) {
// If the radio is inside a radio group, determine if it should be checked
this.checked = this.radioGroup.value === this._value;
// Copy name from parent radio group
this.name = this.radioGroup.name;
}
}
/**
* @private
* @description Dispatch change event with current value
* @name _emitChangeEvent
* @returns {void}
*/
private _emitChangeEvent(): void {
let event = new MdRadioChange();
event.source = this;
event.value = this._value;
event.type = 'blend';
this.change.emit(event);
}
/**
* We use a hidden native input field to handle changes to focus state via keyboard navigation,
* with visual rendering done separately. The native element is kept in sync with the overall
* state of the component.
*/
_onInputFocus(): void {
this._isFocused = true;
}
_onInputBlur(): void {
this._isFocused = false;
if (this.radioGroup) {
this.radioGroup._touch();
}
}
_onInputClick(event: Event): void {
// We have to stop propagation for click events on the visual hidden input element.
// By default, when a user clicks on a label element, a generated click event will be
// dispatched on the associated input element. Since we are using a label element as our
// root container, the click event on the `radio-button` will be executed twice.
// The real click event will bubble up, and the generated click event also tries to bubble up.
// This will lead to multiple click events.
// Preventing bubbling for the second event will solve that issue.
event.stopPropagation();
}
/**
* @description
* Triggered when the radio button received a click or the input recognized any change.
* Clicking on a label element, will trigger a change event on the associated input.
* @param event {Event}
* @returns {void}
*/
_onInputChange(event: Event): void {
// We always have to stop propagation on the change event.
// Otherwise the change event, from the input element, will bubble up and
// emit its event object to the `change` output.
event.stopPropagation();
this.checked = true;
this._emitChangeEvent();
if (this.radioGroup) {
this.radioGroup._controlValueAccessorChangeFn(this.value);
this.radioGroup._touch();
}
}
getHostElement(): HTMLElement {
return this._elementRef.nativeElement;
}
} | the_stack |
import {
ExposeFunctions,
ComExposeEvents,
ExposeDefaultProps,
ExposeApi,
} from '~/types/modules';
import { style, styleDescription } from './style';
const config: {
exposeFunctions: ExposeFunctions[];
exposeEvents: ComExposeEvents;
exposeDefaultProps: ExposeDefaultProps;
exposeApi: ExposeApi[];
} = {
/**
* 注册方法的静态描述与默认参数定义
*/
exposeFunctions: [
{
name: 'setGameType',
description: '设置游戏类型',
arguments: [
{
type: 'string',
describe: '',
select: {
redenvelope: '红包',
boxroulette: '九宫格',
roulette: '大转盘',
flipcard: '翻牌',
slotmachine: '老虎机',
dice: '骰子',
case: '简约按钮',
},
data: '',
fieldName: 'gametype',
name: '游戏类型',
},
],
},
{
name: 'setRunningPrizes',
description: '设置奖品数据',
arguments: [
{
type: 'runningTime',
describe: `从全局数据中设置奖品数据
<br/>
数据要求:<br />
{<br />
prizeId: [number]奖品id
<br />
prizeType: [number]奖品类型 0 未中奖, 1 实物, 2 虚拟
<br />
receiveType?: [number]领取方式 1:默认;2:填写地址;3:链接类;4:虚拟卡
<br />
prizeAlias?: [string]奖品别名
<br />
prizeName: [string]奖品名称
<br />
awardMsg?: [string]中奖提示信息
<br />
gameImg?: [string]游戏图片地址
<br />
prizeImg: [string]奖品图片地址
<br />
memo?: [string]奖品备注说明
<br />
}[]`,
name: '奖品数据',
fieldName: 'prizes',
data: '',
},
],
},
{
name: 'setRunningRecords',
description: '设置中奖记录',
arguments: [
{
type: 'runningTime',
describe: `从全局数据中设置中奖记录数据,中奖记录的固定字段saveAddress="1" 时开启填写地址
<br/>
数据要求:<br />`,
name: '中奖记录数据',
fieldName: 'records',
data: '',
},
{
type: 'string',
select: {0: '禁止', 1: '开启'},
describe:
'0禁止,1开启;下拉时请求中奖记录Api,并将更新中奖数据,常用于刷新数据.',
name: '下拉刷新',
fieldName: 'disablePullDown',
data: '',
},
{
type: 'string',
select: {0: '禁止', 1: '开启'},
describe:
'0禁止,1开启;上拉时请求中奖记录Api,并将更新中奖数据,常用于查看更多数据.',
name: '上拉更新',
fieldName: 'disablePullUp',
data: '',
},
],
},
{
name: 'setRules',
description: '设置活动规则',
arguments: [
{
type: 'array',
name: '文本内容',
describe: '可设置多行文本内容',
html: true,
data: ['文本<b>Text</b>'],
fieldName: 'rulesArray',
}
],
},
{
name: 'lottery',
description: '抽奖',
presettable: false,
arguments: [],
},
{
name: 'useConfig',
description: '设置抽奖用户',
arguments: [
{
type: 'string',
name: '手机',
fieldName: 'phone',
describe: '选填用户手机号码',
data: '',
},
{
type: 'number',
name: '填写身份证',
fieldName: 'cardIdRequest',
select: {
1: '隐藏',
2: '验证',
3: '为空时不验证有填写时验证',
4: '不验证'
},
describe:
' 1 隐藏,2 验证,3 为空时不验证有填写时验证,4 不验证',
data: '1',
},
],
},
{
name: 'setDefaultReceiveInfo',
description: '设置收货人信息',
arguments: [
{
type: 'string',
name: '电话',
fieldName: 'receiverPhone',
describe: '收货人电话号码',
data: '',
},
{
type: 'string',
name: '省市区名称',
fieldName: 'regionName',
describe: '输入省市区名用,隔开: xx省,xx市,xx区/县',
data: '',
},
{
type: 'string',
name: '省市区id',
fieldName: 'region',
describe: '输入省市区id用,隔开: 15,1513,151315',
data: '',
},
{
type: 'string',
name: '详细地址',
fieldName: 'address',
describe: '请输入详细地址',
data: '',
},
{
type: 'string',
name: '身份证号',
fieldName: 'idCard',
describe: '获奖用户身份证号码',
data: '',
},
],
},
{
name: 'setSuccessModal',
description: '设置中奖弹窗',
arguments: [
{
type: 'string',
name: '标题',
fieldName: 'title',
describe: '中奖弹窗标题',
data: '',
},
{
type: 'string',
name: '动画',
fieldName: 'animation',
describe: `中奖弹窗动画
flipInY | flipInX | fadeInUp | fadeInDown | fadeInLeft
| fadeInRight | zoomIn | zoomInUp | zoomInDown | zoomInLeft | zoomInRight`,
data: 'flipInY',
},
],
},
{
name: 'checkedLottery',
description: '抽奖前置检查',
presettable: false,
arguments: [
{
type: 'boolean',
name: '禁用',
fieldName: 'enabled',
describe: '条件不成立时禁止抽奖',
data: {
comparableAverageA: 'a',
comparableAverageB: 'a',
method: '===',
},
},
{
type: 'string',
name: '信息',
fieldName: 'message',
describe: '提示信息',
data: '',
},
],
},
{
name: 'showRecord',
description: '显示中奖记录',
presettable: false,
},
{
name: 'showRules',
description: '显示游戏规则',
presettable: false,
},
],
/**
* 发布事件的静态描述
*/
exposeEvents: [
{
name: 'mount',
description: '初始化',
},
{
name: 'unmount',
description: '卸载',
},
{
name: 'onStart',
description: '抽奖',
},
{
name: 'onEnd',
description: '抽奖结束',
},
{
name: 'onCancel',
description: '放弃中奖结果/关闭弹窗',
},
{
name: 'onEnsure',
description: '确认中奖结果',
},
{
name: 'onShowSuccess',
description: '显示中奖',
},
{
name: 'onShowFailed',
description: '显示未中奖',
},
{
name: 'onShowAddress',
description: '显示收货地址',
},
],
/**
* 发布默认porps
*/
exposeDefaultProps: {
layout: { w: 10, h: 10 },
style,
styleDescription,
},
/**
* 发布默认Api
*/
exposeApi: [
{
apiId: 'init',
name: '获取初始数据(将在初始化事件前调用)',
},
{
apiId: 'beforeStart',
name: '抽奖前置验证(将在每次抽奖前调用)',
description: '',
},
{
apiId: 'lottery',
name: '抽奖',
description: `通过数据映射/转换数据
<br/>
数据要求:<br />
{
data: ...<br />
prize: {<br />
prizeId: [number]奖品id
<br />
prizeType: [number]奖品类型 0 未中奖, 1 实物, 2 虚拟
<br />
receiveType?: [number]领取方式 1:默认;2:填写地址;3:链接类;4:虚拟卡
<br />
prizeAlias?: [string]奖品别名
<br />
prizeName: [string]奖品名称
<br />
awardMsg?: [string]中奖提示信息
<br />
gameImg?: [string]游戏图片地址
<br />
prizeImg: [string]奖品图片地址
<br />
memo?: [string]奖品备注说明
<br />
}<br />}`,
},
{
apiId: 'saveAddress',
name: '保存收货地址',
enterDescription: `原数据<br />{<br/>
address?: string 详细地址<br/>
idcode?: string 生份证号<br/>
phone?: string 电话号码<br/>
receiver?: string 收货人姓名<br/>
regions?: string 省市区id<br/>
regionsName?: string 省市区<br/>
verificationvode?: string 验证码<br/>
}`,
hideBodyInput: true,
},
{
apiId: 'getVerificationCode',
name: '获取验证码',
enterDescription: `获取验证码`,
},
{
apiId: 'getRecord',
name: '中奖记录',
enterDescription: `获取中奖记录`,
},
],
};
export default config; | the_stack |
import _ from 'lodash'
import {ActionGroupSpec, ActionContextType, ActionOutputStyle, ActionOutput, ActionContextOrder, ActionSpec} from '../actions/actionSpec'
import IstioPluginHelper from '../k8s/istioPluginHelper'
import EnvoyFunctions, {EnvoyConfigType} from '../k8s/envoyFunctions'
import JsonUtil from '../util/jsonUtil';
import K8sFunctions from '../k8s/k8sFunctions';
import ChoiceManager from '../actions/choiceManager';
function identifyEnvoyClusterDiffs(diffPairs: any[], versionMismatchedPairs: any[], otherDiffPairs: any[],
additionalOutput: string[], ignoreKeys?: string[], ignoreValues?: string[]) {
diffPairs.forEach(pair => {
let diffs: string[] = []
JsonUtil.compareObjects(pair[0], pair[1], diffs, ignoreKeys, ignoreValues)
if(pair[0]["version_info"] && pair[1]["version_info"] && diffs.includes("version_info")) {
versionMismatchedPairs.push(pair)
diffs = diffs.filter(d => d !== "version_info")
}
if(ignoreKeys) {
diffs = diffs.filter(d => !ignoreKeys.includes(d))
}
if(diffs.length > 0) {
otherDiffPairs.push(pair)
pair.push(diffs)
}
})
}
function identifyEnvoyListenerDiff(diffPairs: any[], versionMismatchedPairs: any[], otherDiffPairs: any[],
additionalOutput: string[], ignoreKeys?: string[], ignoreValues?: string[]) {
diffPairs.forEach(pair => {
const diffs: string[] = []
const listener1 = pair[0]
const listener2 = pair[1]
if(listener1.version_info && listener2.version_info && listener1.version_info !== listener2.version_info) {
versionMismatchedPairs.push(pair)
}
let tempDiffs: string[] = []
if(listener1.listener && listener2.listener) {
const socketAddress1 = listener1.listener.address && (listener1.listener.address.socket_address || listener1.listener.address.socketAddress)
const socketAddress2 = listener2.listener.address && (listener2.listener.address.socket_address || listener2.listener.address.socketAddress)
JsonUtil.compareObjects(socketAddress1, socketAddress2, tempDiffs, ignoreKeys, ignoreValues)
tempDiffs.forEach(d => diffs.push("socket_addresss: " + d))
tempDiffs = []
const listenerFilters1 = listener1.listener.listener_filters && listener1.listener.listener_filters.map(f => f.name)
|| listener1.listener.listenerFilters && listener1.listener.listenerFilters.map(f => f.name)
const listenerFilters2 = listener2.listener.listener_filters && listener2.listener.listener_filters.map(f => f.name)
|| listener2.listener.listenerFilters && listener2.listener.listenerFilters.map(f => f.name)
if(listenerFilters1 || listenerFilters2) {
JsonUtil.compareFlatArrays(listenerFilters1, listenerFilters2, tempDiffs, ignoreValues)
tempDiffs.forEach(d => diffs.push("listener_filters mismatch: " + d))
}
tempDiffs = []
const filterChains1 = listener1.listener.filter_chains || listener1.listener.filterChains
const filterChains2 = listener2.listener.filter_chains || listener2.listener.filterChains
if(filterChains1 || filterChains2) {
const serverNamesList1 = filterChains1 ? filterChains1.filter(fc => fc.filter_chain_match || fc.filterChainMatch)
.map(fc => fc.filter_chain_match || fc.filterChainMatch)
.map(fcm => fcm.server_names || fcm.serverNames)
.map(s => s.sort()) : []
const serverNamesList2 = filterChains2 ? filterChains2.filter(fc => fc.filter_chain_match || fc.filterChainMatch)
.map(fc => fc.filter_chain_match || fc.filterChainMatch)
.map(fcm => fcm.server_names || fcm.serverNames)
.map(s => s.sort()) : []
serverNamesList1.forEach((serverNames1, i) => {
let found = false
for(const serverNames2 of serverNamesList2) {
if(JsonUtil.compareFlatArrays(serverNames1, serverNames2)) {
found = true
break
}
}
if(!found) {
diffs.push("{<--} filter_chains["+i+"] - server_names mismatch")
additionalOutput.push(">>>ServerNames from FilterChain "+i+" in first configset not found in second configset")
additionalOutput.push(...serverNames1)
}
})
serverNamesList2.forEach((serverNames2, i) => {
let found = false
for(const serverNames1 of serverNamesList1) {
if(JsonUtil.compareFlatArrays(serverNames1, serverNames2)) {
found = true
break
}
}
if(!found) {
diffs.push("{-->} filter_chains["+i+"] - server_names mismatch")
additionalOutput.push(">>>ServerNames from FilterChain "+i+" in second configset not found in first configset")
additionalOutput.push(...serverNames2)
}
})
if(diffs.length > 0) {
otherDiffPairs.push(pair)
pair.push(diffs)
}
}
} else {
!listener1.listener && diffs.push("{<<} listener missing")
!listener2.listener && diffs.push("{>>} listener missing")
}
})
}
function identifyEnvoyConfigDiffs(diffPairs: any[], versionMismatchedPairs: any[], otherDiffPairs: any[], type: string,
additionalOutput: string[], ignoreKeys?: string[], ignoreValues?: string[]) {
switch(type) {
case EnvoyConfigType.Clusters:
identifyEnvoyClusterDiffs(diffPairs, versionMismatchedPairs, otherDiffPairs, additionalOutput, ignoreKeys, ignoreValues)
break;
case EnvoyConfigType.Listeners:
identifyEnvoyListenerDiff(diffPairs, versionMismatchedPairs, otherDiffPairs, additionalOutput, ignoreKeys, ignoreValues)
break;
}
}
export function compareEnvoyConfigs(onStreamOutput, configs1: any[], configs2: any[], type: string,
transform: boolean, valuesToIgnore?: string[]) {
const output: ActionOutput = []
const items = {}
const diffs = {}
const matchingRecords: string[] = []
const keysToIgnore: string[] = ["mixer_attributes", "uid", "type", "last_updated", "status", "version_info",
"mixerAttributes", "lastUpdated", "status", "versionInfo", "title"]
const normalizeName = (name, index) => valuesToIgnore && name.startsWith(valuesToIgnore[index]) ? name.replace(valuesToIgnore[index], "xxx") : name
let name1, name2
configs1.forEach(c1 => {
name1 = c1.name || c1.title || c1
name1 = normalizeName(name1, 0)
items[name1]=[[c1], ["Missing"]]
})
configs2.forEach(c2 => {
name2 = c2.name || c2.title || c2
name2 = normalizeName(name2, 1)
const config2Item = transform ? JsonUtil.transformObject(c2) : c2
if(items[name2]) {
const c1 = items[name2][0][0]
const config1Item = transform ? JsonUtil.transformObject(c1) : c1
items[name2][0].push(config1Item)
const itemDiffs: string[] = []
const matches = JsonUtil.compareObjects(config1Item, config2Item, itemDiffs, keysToIgnore, valuesToIgnore)
if(matches) {
name1 = c1.name || c1.title || c1
matchingRecords.push(name1 === name2 ? name1 : name1 + " <---> " + name2)
delete items[name2]
} else {
diffs[name2] = itemDiffs
items[name2][1]=[c2, config2Item]
}
} else {
items[name2] = [["Missing"], [c2, config2Item]]
}
})
output.push([">Matching "+type, ""])
matchingRecords.length === 0 && output.push([">>No matching "+type, ""])
matchingRecords.forEach(c => output.push(["<<", c, ""]))
if(Object.keys(items).length > 0) {
const diffPairs: any[] = []
Object.keys(items).forEach(name => {
diffPairs.push([items[name][0][0], items[name][1][0]])
})
const versionMismatchedPairs: any[] = []
const otherDiffPairs: any[] = []
const additionalOutput: string[] = []
identifyEnvoyConfigDiffs(diffPairs, versionMismatchedPairs, otherDiffPairs, type, additionalOutput, keysToIgnore, valuesToIgnore)
if(versionMismatchedPairs.length > 0) {
output.push([">Version Mismatched "+type, ""])
versionMismatchedPairs.forEach(pair => {
const name = pair[0].name || pair[0].title || pair[0]
output.push(["<<", name, ""])
})
}
if(otherDiffPairs.length > 0) {
output.push([">Mismatched "+type, ""])
otherDiffPairs.forEach(pair => {
const c1 = pair[0]
const c2 = pair[1]
const diffs = pair[2]
const name1 = c1.name || c1.title || c1
const name2 = c2.name || c2.title || c2
output.push([">>"+(name1 || 'N/A'), (name2||'N/A')])
output.push(["<<", c1, c2])
if(additionalOutput.length > 0) {
output.push([">>>Diffs"])
//output.push(["<<", diffs])
additionalOutput.forEach(o => output.push([o]))
}
})
}
if(versionMismatchedPairs.length === 0 && otherDiffPairs.length === 0) {
output.push([">>Unanalyzed Config Difference", ""])
diffPairs.forEach(pair => output.push(
[">>>" + (pair[0].name || pair[1].name)], ["<<", pair[0], pair[1]])
)
}
} else {
output.push([">>No Mismatched "+type, ""])
}
onStreamOutput(output)
}
export async function compareTwoEnvoys(namespace1: string, pod1: string, container1: string, k8sClient1,
namespace2: string, pod2: string, container2: string, k8sClient2, onStreamOutput) {
const pod1Details = await K8sFunctions.getPodDetails(namespace1, pod1, k8sClient1)
const pod1IP = pod1Details && pod1Details.podIP
const pod2Details = await K8sFunctions.getPodDetails(namespace2, pod2, k8sClient2)
const pod2IP = pod2Details && pod2Details.podIP
const valuesToIgnore: string[] = []
pod1IP && valuesToIgnore.push(pod1IP)
pod2IP && valuesToIgnore.push(pod2IP)
const envoy1Bootstrap = await EnvoyFunctions.getEnvoyBootstrapConfig(k8sClient1, namespace1, pod1, container1)
const envoy2Bootstrap = await EnvoyFunctions.getEnvoyBootstrapConfig(k8sClient2, namespace2, pod2, container2)
compareEnvoyConfigs(onStreamOutput, envoy1Bootstrap, envoy2Bootstrap, EnvoyConfigType.Bootstrap, false, valuesToIgnore)
let envoy1Listeners = await EnvoyFunctions.getEnvoyListeners(k8sClient1, namespace1, pod1, container1)
envoy1Listeners = envoy1Listeners.filter(l => l.title.includes("active"))
let envoy2Listeners = await EnvoyFunctions.getEnvoyListeners(k8sClient2, namespace2, pod2, container2)
envoy2Listeners = envoy1Listeners.filter(l => l.title.includes("active"))
compareEnvoyConfigs(onStreamOutput, envoy1Listeners, envoy2Listeners, EnvoyConfigType.Listeners, false, valuesToIgnore)
const envoy1Routes = await EnvoyFunctions.getEnvoyRoutes(k8sClient1, namespace1, pod1, container1)
const envoy2Routes = await EnvoyFunctions.getEnvoyRoutes(k8sClient2, namespace2, pod2, container2)
compareEnvoyConfigs(onStreamOutput, envoy1Routes, envoy2Routes, EnvoyConfigType.Routes, false, valuesToIgnore)
const envoy1Clusters = await EnvoyFunctions.getEnvoyClusters(k8sClient1, namespace1, pod1, container1)
const envoy2Clusters = await EnvoyFunctions.getEnvoyClusters(k8sClient2, namespace2, pod2, container2)
compareEnvoyConfigs(onStreamOutput, envoy1Clusters, envoy2Clusters, EnvoyConfigType.Clusters, false, valuesToIgnore)
}
const plugin : ActionGroupSpec = {
context: ActionContextType.Istio,
title: "Envoy Proxy Recipes",
order: ActionContextOrder.Istio+3,
actions: [
{
name: "Compare Envoy Configs",
order: 30,
loadingMessage: "Loading Envoy Proxies...",
choose: ChoiceManager.chooseEnvoyProxy.bind(ChoiceManager, 2, 2),
async act(actionContext) {
const sidecars = ChoiceManager.getSelectedEnvoyProxies(actionContext)
const sidecar1 = sidecars[0]
const sidecar2 = sidecars[1]
this.onOutput && this.onOutput([["Sidecar Config Comparison for " +
sidecar1.pod+"."+sidecar1.namespace+"@"+sidecar1.cluster + " and " +
sidecar2.pod+"."+sidecar2.namespace+"@"+sidecar2.cluster,
""]], ActionOutputStyle.Mono)
this.showOutputLoading && this.showOutputLoading(true)
const cluster1 = actionContext.getClusters().filter(c => c.name === sidecar1.cluster)[0]
const cluster2 = actionContext.getClusters().filter(c => c.name === sidecar2.cluster)[0]
await compareTwoEnvoys(sidecar1.namespace, sidecar1.pod, "istio-proxy", cluster1.k8sClient,
sidecar2.namespace, sidecar2.pod, "istio-proxy", cluster2.k8sClient, this.onStreamOutput)
this.showOutputLoading && this.showOutputLoading(false)
},
refresh(actionContext) {
this.act(actionContext)
}
}
]
}
export default plugin | the_stack |
import { browser, ExpectedConditions as until } from 'protractor';
import * as _ from 'lodash';
import { safeLoad } from 'js-yaml';
import { checkLogs, checkErrors, firstElementByTestID, appHost } from '../protractor.conf';
import { fillInput } from '@console/shared/src/test-utils/utils';
import { dropdownMenuForTestID } from '../views/form.view';
import {
AlertmanagerConfig,
AlertmanagerReceiver,
} from '@console/internal/components/monitoring/alert-manager-config';
import * as crudView from '../views/crud.view';
import * as yamlView from '../views/yaml.view';
import * as monitoringView from '../views/monitoring.view';
import * as horizontalnavView from '../views/horizontal-nav.view';
import { execSync } from 'child_process';
const getGlobalsAndReceiverConfig = (configName: string, yamlStr: string) => {
const config: AlertmanagerConfig = safeLoad(yamlStr);
const receiverConfig: AlertmanagerReceiver = _.find(config.receivers, { name: 'MyReceiver' });
return {
globals: config.global,
receiverConfig: receiverConfig[configName][0],
};
};
describe('Alertmanager: PagerDuty Receiver Form', () => {
afterAll(() => {
execSync(
`kubectl patch secret 'alertmanager-main' -n 'openshift-monitoring' --type='json' -p='[{ op: 'replace', path: '/data/alertmanager.yaml', value: ${monitoringView.defaultAlertmanagerYaml}}]'`,
);
});
afterEach(() => {
checkLogs();
checkErrors();
});
it('creates PagerDuty Receiver correctly', async () => {
await browser.get(`${appHost}/monitoring/alertmanagerconfig`);
await crudView.isLoaded();
await firstElementByTestID('create-receiver').click();
await crudView.isLoaded();
await firstElementByTestID('receiver-name').sendKeys('MyReceiver');
await firstElementByTestID('dropdown-button').click();
await crudView.isLoaded();
await dropdownMenuForTestID('pagerduty_configs').click();
await crudView.isLoaded();
await firstElementByTestID('integration-key').sendKeys('<integration_key>');
await firstElementByTestID('label-name-0').sendKeys('severity');
await firstElementByTestID('label-value-0').sendKeys('warning');
expect(firstElementByTestID('pagerduty-url').getAttribute('value')).toEqual(
'https://events.pagerduty.com/v2/enqueue',
);
// adv config options
await monitoringView.showAdvancedConfiguration.click();
expect(firstElementByTestID('send-resolved-alerts').getAttribute('checked')).toBeTruthy();
expect(firstElementByTestID('pagerduty-client').getAttribute('value')).toEqual(
'{{ template "pagerduty.default.client" . }}',
);
expect(firstElementByTestID('pagerduty-client-url').getAttribute('value')).toEqual(
'{{ template "pagerduty.default.clientURL" . }}',
);
expect(firstElementByTestID('pagerduty-description').getAttribute('value')).toEqual(
'{{ template "pagerduty.default.description" .}}',
);
expect(firstElementByTestID('pagerduty-severity').getAttribute('value')).toEqual('error');
await monitoringView.saveButton.click();
await crudView.isLoaded();
await monitoringView.wait(until.elementToBeClickable(crudView.nameFilter));
await crudView.nameFilter.clear();
await crudView.nameFilter.sendKeys('MyReceiver');
monitoringView.getFirstRowAsText().then((text) => {
expect(text).toEqual('MyReceiver pagerduty severity = warning');
});
});
it('saves globals correctly', async () => {
await browser.get(`${appHost}/monitoring/alertmanagerconfig/receivers/MyReceiver/edit`);
await browser.wait(until.presenceOf(firstElementByTestID('cancel')));
// monitoringView.saveAsDefault checkbox disabled when url equals global url
expect(monitoringView.saveAsDefault.isEnabled()).toBeFalsy();
// changing url, enables monitoringView.saveAsDefault unchecked, should save pagerduty_url with Receiver
await fillInput(
firstElementByTestID('pagerduty-url'),
'http://pagerduty-url-specific-to-receiver',
);
expect(monitoringView.saveAsDefault.isEnabled()).toBeTruthy();
expect(monitoringView.saveAsDefault.getAttribute('checked')).toBeFalsy();
await monitoringView.saveButton.click();
await crudView.isLoaded();
//pagerduty_url should be saved with Receiver and not global
await horizontalnavView.clickHorizontalTab('YAML');
await yamlView.isLoaded();
let yamlStr = await yamlView.getEditorContent();
let configs = getGlobalsAndReceiverConfig('pagerduty_configs', yamlStr);
expect(_.has(configs.globals, 'pagerduty_url')).toBeFalsy();
expect(configs.receiverConfig.url).toBe('http://pagerduty-url-specific-to-receiver');
// save pagerduty_url as default/global
await browser.get(`${appHost}/monitoring/alertmanagerconfig/receivers/MyReceiver/edit`);
await browser.wait(until.presenceOf(firstElementByTestID('cancel')));
await fillInput(firstElementByTestID('pagerduty-url'), 'http://global-pagerduty-url');
await crudView.isLoaded();
expect(monitoringView.saveAsDefault.isEnabled()).toBeTruthy();
monitoringView.saveAsDefault.click();
expect(monitoringView.saveAsDefault.getAttribute('checked')).toBeTruthy();
await monitoringView.saveButton.click();
await crudView.isLoaded();
// pagerduty_url should be saved as global, not with Receiver
await horizontalnavView.clickHorizontalTab('YAML');
await yamlView.isLoaded();
yamlStr = await yamlView.getEditorContent();
configs = getGlobalsAndReceiverConfig('pagerduty_configs', yamlStr);
expect(configs.globals.pagerduty_url).toBe('http://global-pagerduty-url');
expect(_.has(configs.receiverConfig, 'url')).toBeFalsy();
// save pagerduty url to receiver with an existing global
await browser.get(`${appHost}/monitoring/alertmanagerconfig/receivers/MyReceiver/edit`);
await browser.wait(until.presenceOf(firstElementByTestID('cancel')));
await fillInput(
firstElementByTestID('pagerduty-url'),
'http://pagerduty-url-specific-to-receiver',
);
expect(monitoringView.saveAsDefault.isEnabled()).toBeTruthy();
expect(monitoringView.saveAsDefault.getAttribute('checked')).toBeFalsy();
await monitoringView.saveButton.click();
await crudView.isLoaded();
// pagerduty_url should be saved with Receiver, as well as having a global pagerduty_url prop
await horizontalnavView.clickHorizontalTab('YAML');
await yamlView.isLoaded();
yamlStr = await yamlView.getEditorContent();
configs = getGlobalsAndReceiverConfig('pagerduty_configs', yamlStr);
expect(configs.globals.pagerduty_url).toBe('http://global-pagerduty-url');
expect(configs.receiverConfig.url).toBe('http://pagerduty-url-specific-to-receiver');
});
it('saves advanced configuration fields correctly', async () => {
await browser.get(`${appHost}/monitoring/alertmanagerconfig/receivers/MyReceiver/edit`);
await browser.wait(until.presenceOf(firstElementByTestID('cancel')));
await monitoringView.showAdvancedConfiguration.click();
// change first 3 props so that they are diff from global values, thus saved to Receiver config
expect(monitoringView.sendResolvedAlerts.getAttribute('checked')).toBeTruthy();
await monitoringView.sendResolvedAlerts.click();
expect(monitoringView.sendResolvedAlerts.getAttribute('checked')).toBeFalsy();
await fillInput(firstElementByTestID('pagerduty-client'), 'updated-client');
await fillInput(firstElementByTestID('pagerduty-client-url'), 'http://updated-client-url');
await monitoringView.saveButton.click();
await crudView.isLoaded();
// 3 changed fields should be saved with Receiver. description and severity should not be
// saved with Receiver since they equal global values
await horizontalnavView.clickHorizontalTab('YAML');
await yamlView.isLoaded();
let yamlStr = await yamlView.getEditorContent();
let configs = getGlobalsAndReceiverConfig('pagerduty_configs', yamlStr);
expect(configs.receiverConfig.send_resolved).toBeFalsy();
expect(configs.receiverConfig.client).toBe('updated-client');
expect(configs.receiverConfig.client_url).toBe('http://updated-client-url');
expect(configs.receiverConfig.description).toBe(undefined);
expect(configs.receiverConfig.severity).toBe(undefined);
// restore default values for the 3, change desc and severity -which should then be saved
// with Receiver while initial 3 are removed from Receiver config
await browser.get(`${appHost}/monitoring/alertmanagerconfig/receivers/MyReceiver/edit`);
await browser.wait(until.presenceOf(firstElementByTestID('cancel')));
await monitoringView.showAdvancedConfiguration.click();
expect(monitoringView.sendResolvedAlerts.getAttribute('checked')).toBeFalsy();
await monitoringView.sendResolvedAlerts.click();
expect(monitoringView.sendResolvedAlerts.getAttribute('checked')).toBeTruthy();
await fillInput(
firstElementByTestID('pagerduty-client'),
'{{ template "pagerduty.default.client" . }}',
);
await fillInput(
firstElementByTestID('pagerduty-client-url'),
'{{ template "pagerduty.default.clientURL" . }}',
);
await fillInput(firstElementByTestID('pagerduty-description'), 'new description');
await fillInput(firstElementByTestID('pagerduty-severity'), 'warning');
await monitoringView.saveButton.click();
await crudView.isLoaded();
await horizontalnavView.clickHorizontalTab('YAML');
await yamlView.isLoaded();
yamlStr = await yamlView.getEditorContent();
configs = getGlobalsAndReceiverConfig('pagerduty_configs', yamlStr);
expect(configs.receiverConfig.send_resolved).toBe(undefined);
expect(configs.receiverConfig.client).toBe(undefined);
expect(configs.receiverConfig.client_url).toBe(undefined);
expect(configs.receiverConfig.description).toBe('new description');
expect(configs.receiverConfig.severity).toBe('warning');
});
});
describe('Alertmanager: Email Receiver Form', () => {
afterAll(() => {
execSync(
`kubectl patch secret 'alertmanager-main' -n 'openshift-monitoring' --type='json' -p='[{ op: 'replace', path: '/data/alertmanager.yaml', value: ${monitoringView.defaultAlertmanagerYaml}}]'`,
);
});
afterEach(() => {
checkLogs();
checkErrors();
});
it('creates Email Receiver correctly', async () => {
await browser.get(`${appHost}/monitoring/alertmanagerconfig`);
await crudView.isLoaded();
await firstElementByTestID('create-receiver').click();
await crudView.isLoaded();
await fillInput(firstElementByTestID('receiver-name'), 'MyReceiver');
await firstElementByTestID('dropdown-button').click();
await crudView.isLoaded();
await dropdownMenuForTestID('email_configs').click();
await crudView.isLoaded();
// check defaults
expect(monitoringView.saveAsDefault.isEnabled()).toBeFalsy(); // prior to smtp change, monitoringView.saveAsDefault disabled
expect(firstElementByTestID('email-hello').getAttribute('value')).toEqual('localhost');
expect(firstElementByTestID('email-require-tls').getAttribute('checked')).toBeTruthy();
// adv fields
await monitoringView.showAdvancedConfiguration.click();
expect(monitoringView.sendResolvedAlerts.getAttribute('checked')).toBeFalsy();
expect(firstElementByTestID('email-html').getAttribute('value')).toEqual(
'{{ template "email.default.html" . }}',
);
// change required fields
await fillInput(firstElementByTestID('email-to'), 'you@there.com');
await fillInput(firstElementByTestID('email-from'), 'me@here.com');
expect(monitoringView.saveAsDefault.isEnabled()).toBeTruthy(); // monitoringView.saveAsDefault enabled
await fillInput(firstElementByTestID('email-smarthost'), 'smarthost:8080');
await fillInput(firstElementByTestID('label-name-0'), 'severity');
await fillInput(firstElementByTestID('label-value-0'), 'warning');
await monitoringView.saveButton.click();
await crudView.isLoaded();
// all required fields should be saved with Receiver and not globally
await horizontalnavView.clickHorizontalTab('YAML');
await yamlView.isLoaded();
const yamlStr = await yamlView.getEditorContent();
const configs = getGlobalsAndReceiverConfig('email_configs', yamlStr);
expect(_.has(configs.globals, 'email_to')).toBeFalsy();
expect(_.has(configs.globals, 'smtp_from')).toBeFalsy();
expect(_.has(configs.globals, 'smtp_smarthost')).toBeFalsy();
expect(_.has(configs.globals, 'smtp_require_tls')).toBeFalsy();
expect(configs.receiverConfig.to).toBe('you@there.com');
expect(configs.receiverConfig.from).toBe('me@here.com');
expect(configs.receiverConfig.smarthost).toBe('smarthost:8080');
expect(_.has(configs.receiverConfig, 'require_tls')).toBeFalsy(); // unchanged from global value
});
it('saves globals and advanced fields correctly', async () => {
await browser.get(`${appHost}/monitoring/alertmanagerconfig/receivers/MyReceiver/edit`);
await browser.wait(until.presenceOf(firstElementByTestID('cancel')));
// Check updated form fields
expect(firstElementByTestID('email-to').getAttribute('value')).toEqual('you@there.com');
expect(monitoringView.saveAsDefault.isEnabled()).toBeTruthy(); // smtp_from different from global
expect(monitoringView.saveAsDefault.getAttribute('checked')).toBeFalsy();
expect(firstElementByTestID('email-from').getAttribute('value')).toEqual('me@here.com');
expect(firstElementByTestID('email-hello').getAttribute('value')).toEqual('localhost');
// Change smtp global fields
await fillInput(firstElementByTestID('email-auth-username'), 'username');
await fillInput(firstElementByTestID('email-auth-password'), 'password');
await fillInput(firstElementByTestID('email-auth-identity'), 'identity');
await fillInput(firstElementByTestID('email-auth-secret'), 'secret');
await firstElementByTestID('email-require-tls').click();
// Change advanced fields
await monitoringView.showAdvancedConfiguration.click();
await monitoringView.sendResolvedAlerts.click();
await fillInput(firstElementByTestID('email-html'), 'myhtml');
await monitoringView.saveButton.click(); // monitoringView.saveAsDefault not checked, so all should be saved with Reciever
await crudView.isLoaded();
// all fields saved to receiver since save as default not checked
await horizontalnavView.clickHorizontalTab('YAML');
await yamlView.isLoaded();
let yamlStr = await yamlView.getEditorContent();
let configs = getGlobalsAndReceiverConfig('email_configs', yamlStr);
expect(_.has(configs.globals, 'smtp_auth_username')).toBeFalsy();
expect(configs.receiverConfig.auth_username).toBe('username');
expect(configs.receiverConfig.auth_password).toBe('password');
expect(configs.receiverConfig.auth_identity).toBe('identity');
expect(configs.receiverConfig.auth_secret).toBe('secret');
expect(configs.receiverConfig.require_tls).toBeFalsy();
// adv fields
expect(configs.receiverConfig.send_resolved).toBeTruthy();
expect(configs.receiverConfig.html).toBe('myhtml');
// Save As Default
await browser.get(`${appHost}/monitoring/alertmanagerconfig/receivers/MyReceiver/edit`);
await browser.wait(until.presenceOf(firstElementByTestID('cancel')));
monitoringView.saveAsDefault.click();
await monitoringView.saveButton.click();
await crudView.isLoaded();
// global fields saved in config.global
await horizontalnavView.clickHorizontalTab('YAML');
await yamlView.isLoaded();
yamlStr = await yamlView.getEditorContent();
configs = getGlobalsAndReceiverConfig('email_configs', yamlStr);
expect(configs.globals.smtp_from).toBe('me@here.com');
expect(configs.globals.smtp_hello).toBe('localhost');
expect(configs.globals.smtp_smarthost).toBe('smarthost:8080');
expect(configs.globals.smtp_auth_username).toBe('username');
expect(configs.globals.smtp_auth_password).toBe('password');
expect(configs.globals.smtp_auth_identity).toBe('identity');
expect(configs.globals.smtp_auth_secret).toBe('secret');
expect(configs.globals.smtp_require_tls).toBeFalsy();
// non-global fields should still be saved with Receiver
expect(configs.receiverConfig.to).toBe('you@there.com');
});
});
describe('Alertmanager: Slack Receiver Form', () => {
afterAll(() => {
execSync(
`kubectl patch secret 'alertmanager-main' -n 'openshift-monitoring' --type='json' -p='[{ op: 'replace', path: '/data/alertmanager.yaml', value: ${monitoringView.defaultAlertmanagerYaml}}]'`,
);
});
afterEach(() => {
checkLogs();
checkErrors();
});
it('creates Slack Receiver correctly', async () => {
await browser.get(`${appHost}/monitoring/alertmanagerconfig`);
await crudView.isLoaded();
await firstElementByTestID('create-receiver').click();
await crudView.isLoaded();
await fillInput(firstElementByTestID('receiver-name'), 'MyReceiver');
await firstElementByTestID('dropdown-button').click();
await crudView.isLoaded();
await dropdownMenuForTestID('slack_configs').click();
await crudView.isLoaded();
// check defaults
expect(monitoringView.saveAsDefault.isEnabled()).toBeFalsy();
// adv fields
await monitoringView.showAdvancedConfiguration.click();
expect(monitoringView.sendResolvedAlerts.getAttribute('checked')).toBeFalsy();
expect(firstElementByTestID('slack-icon-url').getAttribute('value')).toEqual(
'{{ template "slack.default.iconurl" .}}',
);
expect(firstElementByTestID('slack-icon-emoji').isPresent()).toBe(false);
await firstElementByTestID('slack-icon-type-emoji').click();
expect(firstElementByTestID('slack-icon-url').isPresent()).toBe(false);
expect(firstElementByTestID('slack-icon-emoji').getAttribute('value')).toEqual(
'{{ template "slack.default.iconemoji" .}}',
);
expect(firstElementByTestID('slack-username').getAttribute('value')).toEqual(
'{{ template "slack.default.username" . }}',
);
expect(firstElementByTestID('slack-link-names').getAttribute('checked')).toBeFalsy();
// change required fields
await fillInput(firstElementByTestID('slack-api-url'), 'http://myslackapi');
expect(monitoringView.saveAsDefault.isEnabled()).toBeTruthy(); // monitoringView.saveAsDefault enabled
await fillInput(firstElementByTestID('slack-channel'), 'myslackchannel');
await fillInput(firstElementByTestID('label-name-0'), 'severity');
await fillInput(firstElementByTestID('label-value-0'), 'warning');
await monitoringView.saveButton.click();
await crudView.isLoaded();
// all required fields should be saved with Receiver and not globally
await horizontalnavView.clickHorizontalTab('YAML');
await yamlView.isLoaded();
const yamlStr = await yamlView.getEditorContent();
const configs = getGlobalsAndReceiverConfig('slack_configs', yamlStr);
expect(_.has(configs.globals, 'slack_api_url')).toBeFalsy();
expect(configs.receiverConfig.channel).toBe('myslackchannel');
expect(configs.receiverConfig.api_url).toBe('http://myslackapi');
// make sure adv fields are not saved since they equal their global values
expect(_.has(configs.receiverConfig, 'send_resolved')).toBeFalsy();
expect(_.has(configs.receiverConfig, 'username')).toBeFalsy();
});
it('saves globals and advanced fields correctly', async () => {
await browser.get(`${appHost}/monitoring/alertmanagerconfig/receivers/MyReceiver/edit`);
await browser.wait(until.presenceOf(firstElementByTestID('cancel')));
// Check updated form fields
expect(firstElementByTestID('slack-channel').getAttribute('value')).toEqual('myslackchannel');
expect(monitoringView.saveAsDefault.isEnabled()).toBeTruthy(); // different from global
expect(firstElementByTestID('slack-api-url').getAttribute('value')).toEqual(
'http://myslackapi',
);
// Change advanced fields
await monitoringView.showAdvancedConfiguration.click();
await monitoringView.sendResolvedAlerts.click();
await fillInput(firstElementByTestID('slack-icon-url'), 'http://myslackicon');
await fillInput(firstElementByTestID('slack-username'), 'slackuser');
await firstElementByTestID('slack-link-names').click();
monitoringView.saveAsDefault.click();
await monitoringView.saveButton.click();
await crudView.isLoaded();
await browser.get(`${appHost}/monitoring/alertmanagerconfig/receivers/MyReceiver/edit`);
await crudView.isLoaded();
// check updated advanced form fields
await monitoringView.showAdvancedConfiguration.click();
expect(monitoringView.sendResolvedAlerts.getAttribute('checked')).toBeTruthy();
expect(firstElementByTestID('slack-icon-url').getAttribute('value')).toEqual(
'http://myslackicon',
);
expect(firstElementByTestID('slack-icon-emoji').isPresent()).toBe(false);
expect(firstElementByTestID('slack-username').getAttribute('value')).toEqual('slackuser');
expect(firstElementByTestID('slack-link-names').getAttribute('checked')).toBeTruthy();
// check saved to slack receiver config yaml
await browser.get(`${appHost}/monitoring/alertmanageryaml`);
await yamlView.isLoaded();
const yamlStr = await yamlView.getEditorContent();
const configs = getGlobalsAndReceiverConfig('slack_configs', yamlStr);
expect(configs.globals.slack_api_url).toBe('http://myslackapi');
expect(_.has(configs.receiverConfig, 'api_url')).toBeFalsy();
expect(configs.receiverConfig.channel).toBe('myslackchannel');
// advanced fields
expect(configs.receiverConfig.send_resolved).toBeTruthy();
expect(configs.receiverConfig.icon_url).toBe('http://myslackicon');
expect(configs.receiverConfig.username).toBe('slackuser');
expect(configs.receiverConfig.link_names).toBeTruthy();
});
});
describe('Alertmanager: Webhook Receiver Form', () => {
afterAll(() => {
execSync(
`kubectl patch secret 'alertmanager-main' -n 'openshift-monitoring' --type='json' -p='[{ op: 'replace', path: '/data/alertmanager.yaml', value: ${monitoringView.defaultAlertmanagerYaml}}]'`,
);
});
afterEach(() => {
checkLogs();
checkErrors();
});
it('creates Webhook Receiver correctly', async () => {
await browser.get(`${appHost}/monitoring/alertmanagerconfig`);
await crudView.isLoaded();
await firstElementByTestID('create-receiver').click();
await crudView.isLoaded();
await fillInput(firstElementByTestID('receiver-name'), 'MyReceiver');
await firstElementByTestID('dropdown-button').click();
await crudView.isLoaded();
await dropdownMenuForTestID('webhook_configs').click();
await crudView.isLoaded();
// check adv field default value
await monitoringView.showAdvancedConfiguration.click();
expect(monitoringView.sendResolvedAlerts.getAttribute('checked')).toBeTruthy();
// change required fields
await fillInput(firstElementByTestID('webhook-url'), 'http://mywebhookurl');
await fillInput(firstElementByTestID('label-name-0'), 'severity');
await fillInput(firstElementByTestID('label-value-0'), 'warning');
await monitoringView.saveButton.click();
await crudView.isLoaded();
// all required fields should be saved with Receiver
await horizontalnavView.clickHorizontalTab('YAML');
await yamlView.isLoaded();
const yamlStr = await yamlView.getEditorContent();
const configs = getGlobalsAndReceiverConfig('webhook_configs', yamlStr);
expect(configs.receiverConfig.url).toBe('http://mywebhookurl');
expect(_.has(configs.receiverConfig, 'send_resolved')).toBeFalsy();
});
it('edits Webhook Receiver and saves advanced fields correctly', async () => {
await browser.get(`${appHost}/monitoring/alertmanagerconfig/receivers/MyReceiver/edit`);
await browser.wait(until.presenceOf(firstElementByTestID('cancel')));
// Check updated form fields
expect(firstElementByTestID('webhook-url').getAttribute('value')).toEqual(
'http://mywebhookurl',
);
await fillInput(firstElementByTestID('webhook-url'), 'http://myupdatedwebhookurl');
// Change advanced fields
await monitoringView.showAdvancedConfiguration.click();
await monitoringView.sendResolvedAlerts.click();
await monitoringView.saveButton.click();
await crudView.isLoaded();
await browser.get(`${appHost}/monitoring/alertmanagerconfig/receivers/MyReceiver/edit`);
await crudView.isLoaded();
// check updated advanced form fields
await monitoringView.showAdvancedConfiguration.click();
expect(monitoringView.sendResolvedAlerts.getAttribute('checked')).toBeFalsy();
// check saved to slack receiver config yaml
await browser.get(`${appHost}/monitoring/alertmanageryaml`);
await yamlView.isLoaded();
await horizontalnavView.clickHorizontalTab('YAML');
await yamlView.isLoaded();
const yamlStr = await yamlView.getEditorContent();
const configs = getGlobalsAndReceiverConfig('webhook_configs', yamlStr);
expect(configs.receiverConfig.url).toBe('http://myupdatedwebhookurl');
// advanced field
expect(configs.receiverConfig.send_resolved).toBeFalsy();
});
}); | the_stack |
import type {Mutable, Proto, ObserverType} from "@swim/util";
import type {FastenerOwner, Fastener} from "@swim/component";
import type {AnyController, Controller} from "./Controller";
import {ControllerRelationInit, ControllerRelationClass, ControllerRelation} from "./ControllerRelation";
/** @internal */
export type ControllerRefType<F extends ControllerRef<any, any>> =
F extends ControllerRef<any, infer C> ? C : never;
/** @public */
export interface ControllerRefInit<C extends Controller = Controller> extends ControllerRelationInit<C> {
extends?: {prototype: ControllerRef<any, any>} | string | boolean | null;
key?: string | boolean;
}
/** @public */
export type ControllerRefDescriptor<O = unknown, C extends Controller = Controller, I = {}> = ThisType<ControllerRef<O, C> & I> & ControllerRefInit<C> & Partial<I>;
/** @public */
export interface ControllerRefClass<F extends ControllerRef<any, any> = ControllerRef<any, any>> extends ControllerRelationClass<F> {
}
/** @public */
export interface ControllerRefFactory<F extends ControllerRef<any, any> = ControllerRef<any, any>> extends ControllerRefClass<F> {
extend<I = {}>(className: string, classMembers?: Partial<I> | null): ControllerRefFactory<F> & I;
define<O, C extends Controller = Controller>(className: string, descriptor: ControllerRefDescriptor<O, C>): ControllerRefFactory<ControllerRef<any, C>>;
define<O, C extends Controller = Controller>(className: string, descriptor: {observes: boolean} & ControllerRefDescriptor<O, C, ObserverType<C>>): ControllerRefFactory<ControllerRef<any, C>>;
define<O, C extends Controller = Controller, I = {}>(className: string, descriptor: {implements: unknown} & ControllerRefDescriptor<O, C, I>): ControllerRefFactory<ControllerRef<any, C> & I>;
define<O, C extends Controller = Controller, I = {}>(className: string, descriptor: {implements: unknown; observes: boolean} & ControllerRefDescriptor<O, C, I & ObserverType<C>>): ControllerRefFactory<ControllerRef<any, C> & I>;
<O, C extends Controller = Controller>(descriptor: ControllerRefDescriptor<O, C>): PropertyDecorator;
<O, C extends Controller = Controller>(descriptor: {observes: boolean} & ControllerRefDescriptor<O, C, ObserverType<C>>): PropertyDecorator;
<O, C extends Controller = Controller, I = {}>(descriptor: {implements: unknown} & ControllerRefDescriptor<O, C, I>): PropertyDecorator;
<O, C extends Controller = Controller, I = {}>(descriptor: {implements: unknown; observes: boolean} & ControllerRefDescriptor<O, C, I & ObserverType<C>>): PropertyDecorator;
}
/** @public */
export interface ControllerRef<O = unknown, C extends Controller = Controller> extends ControllerRelation<O, C> {
(): C | null;
(controller: AnyController<C> | null, target?: Controller | null, key?: string): O;
/** @override */
get fastenerType(): Proto<ControllerRef<any, any>>;
/** @protected @override */
onInherit(superFastener: Fastener): void;
readonly controller: C | null;
getController(): C;
setController(controller: AnyController<C> | null, target?: Controller | null, key?: string): C | null;
attachController(controller?: AnyController<C>, target?: Controller | null): C;
detachController(): C | null;
insertController(parent?: Controller, controller?: AnyController<C>, target?: Controller | null, key?: string): C;
removeController(): C | null;
deleteController(): C | null;
/** @internal @override */
bindController(controller: Controller, target: Controller | null): void;
/** @internal @override */
unbindController(controller: Controller): void;
/** @override */
detectController(controller: Controller): C | null;
/** @internal */
get key(): string | undefined; // optional prototype field
}
/** @public */
export const ControllerRef = (function (_super: typeof ControllerRelation) {
const ControllerRef: ControllerRefFactory = _super.extend("ControllerRef");
Object.defineProperty(ControllerRef.prototype, "fastenerType", {
get: function (this: ControllerRef): Proto<ControllerRef<any, any>> {
return ControllerRef;
},
configurable: true,
});
ControllerRef.prototype.onInherit = function (this: ControllerRef, superFastener: ControllerRef): void {
this.setController(superFastener.controller);
};
ControllerRef.prototype.getController = function <C extends Controller>(this: ControllerRef<unknown, C>): C {
const controller = this.controller;
if (controller === null) {
let message = controller + " ";
if (this.name.length !== 0) {
message += this.name + " ";
}
message += "controller";
throw new TypeError(message);
}
return controller;
};
ControllerRef.prototype.setController = function <C extends Controller>(this: ControllerRef<unknown, C>, newController: C | null, target?: Controller | null, key?: string): C | null {
if (newController !== null) {
newController = this.fromAny(newController);
}
let oldController = this.controller;
if (oldController !== newController) {
if (target === void 0) {
target = null;
}
let parent: Controller | null;
if (this.binds && (parent = this.parentController, parent !== null)) {
if (oldController !== null && oldController.parent === parent) {
if (target === null) {
target = oldController.nextSibling;
}
oldController.remove();
}
if (newController !== null) {
if (key === void 0) {
key = this.key;
}
this.insertChild(parent, newController, target, key);
}
oldController = this.controller;
}
if (oldController !== newController) {
if (oldController !== null) {
this.willDetachController(oldController);
(this as Mutable<typeof this>).controller = null;
this.onDetachController(oldController);
this.deinitController(oldController);
this.didDetachController(oldController);
}
if (newController !== null) {
this.willAttachController(newController, target);
(this as Mutable<typeof this>).controller = newController;
this.onAttachController(newController, target);
this.initController(newController);
this.didAttachController(newController, target);
}
}
}
return oldController;
};
ControllerRef.prototype.attachController = function <C extends Controller>(this: ControllerRef<unknown, C>, newController?: AnyController<C>, target?: Controller | null): C {
const oldController = this.controller;
if (newController !== void 0 && newController !== null) {
newController = this.fromAny(newController);
} else if (oldController === null) {
newController = this.createController();
} else {
newController = oldController;
}
if (newController !== oldController) {
if (target === void 0) {
target = null;
}
if (oldController !== null) {
this.willDetachController(oldController);
(this as Mutable<typeof this>).controller = null;
this.onDetachController(oldController);
this.deinitController(oldController);
this.didDetachController(oldController);
}
this.willAttachController(newController, target);
(this as Mutable<typeof this>).controller = newController;
this.onAttachController(newController, target);
this.initController(newController);
this.didAttachController(newController, target);
}
return newController;
};
ControllerRef.prototype.detachController = function <C extends Controller>(this: ControllerRef<unknown, C>): C | null {
const oldController = this.controller;
if (oldController !== null) {
this.willDetachController(oldController);
(this as Mutable<typeof this>).controller = null;
this.onDetachController(oldController);
this.deinitController(oldController);
this.didDetachController(oldController);
}
return oldController;
};
ControllerRef.prototype.insertController = function <C extends Controller>(this: ControllerRef<unknown, C>, parent?: Controller | null, newController?: AnyController<C>, target?: Controller | null, key?: string): C {
if (newController !== void 0 && newController !== null) {
newController = this.fromAny(newController);
} else {
const oldController = this.controller;
if (oldController === null) {
newController = this.createController();
} else {
newController = oldController;
}
}
if (parent === void 0 || parent === null) {
parent = this.parentController;
}
if (target === void 0) {
target = null;
}
if (key === void 0) {
key = this.key;
}
if (parent !== null && (newController.parent !== parent || newController.key !== key)) {
this.insertChild(parent, newController, target, key);
}
const oldController = this.controller;
if (newController !== oldController) {
if (oldController !== null) {
this.willDetachController(oldController);
(this as Mutable<typeof this>).controller = null;
this.onDetachController(oldController);
this.deinitController(oldController);
this.didDetachController(oldController);
oldController.remove();
}
this.willAttachController(newController, target);
(this as Mutable<typeof this>).controller = newController;
this.onAttachController(newController, target);
this.initController(newController);
this.didAttachController(newController, target);
}
return newController;
};
ControllerRef.prototype.removeController = function <C extends Controller>(this: ControllerRef<unknown, C>): C | null {
const controller = this.controller;
if (controller !== null) {
controller.remove();
}
return controller;
};
ControllerRef.prototype.deleteController = function <C extends Controller>(this: ControllerRef<unknown, C>): C | null {
const controller = this.detachController();
if (controller !== null) {
controller.remove();
}
return controller;
};
ControllerRef.prototype.bindController = function <C extends Controller>(this: ControllerRef<unknown, C>, controller: Controller, target: Controller | null): void {
if (this.binds && this.controller === null) {
const newController = this.detectController(controller);
if (newController !== null) {
this.willAttachController(newController, target);
(this as Mutable<typeof this>).controller = newController;
this.onAttachController(newController, target);
this.initController(newController);
this.didAttachController(newController, target);
}
}
};
ControllerRef.prototype.unbindController = function <C extends Controller>(this: ControllerRef<unknown, C>, controller: Controller): void {
if (this.binds) {
const oldController = this.detectController(controller);
if (oldController !== null && this.controller === oldController) {
this.willDetachController(oldController);
(this as Mutable<typeof this>).controller = null;
this.onDetachController(oldController);
this.deinitController(oldController);
this.didDetachController(oldController);
}
}
};
ControllerRef.prototype.detectController = function <C extends Controller>(this: ControllerRef<unknown, C>, controller: Controller): C | null {
const key = this.key;
if (key !== void 0 && key === controller.key) {
return controller as C;
}
return null;
};
ControllerRef.construct = function <F extends ControllerRef<any, any>>(fastenerClass: {prototype: F}, fastener: F | null, owner: FastenerOwner<F>): F {
if (fastener === null) {
fastener = function (controller?: AnyController<ControllerRefType<F>> | null, target?: Controller | null, key?: string): ControllerRefType<F> | null | FastenerOwner<F> {
if (controller === void 0) {
return fastener!.controller;
} else {
fastener!.setController(controller, target, key);
return fastener!.owner;
}
} as F;
delete (fastener as Partial<Mutable<F>>).name; // don't clobber prototype name
Object.setPrototypeOf(fastener, fastenerClass.prototype);
}
fastener = _super.construct(fastenerClass, fastener, owner) as F;
(fastener as Mutable<typeof fastener>).key = void 0;
(fastener as Mutable<typeof fastener>).controller = null;
return fastener;
};
ControllerRef.define = function <O, C extends Controller>(className: string, descriptor: ControllerRefDescriptor<O, C>): ControllerRefFactory<ControllerRef<any, C>> {
let superClass = descriptor.extends as ControllerRefFactory | null | undefined;
const affinity = descriptor.affinity;
const inherits = descriptor.inherits;
delete descriptor.extends;
delete descriptor.implements;
delete descriptor.affinity;
delete descriptor.inherits;
if (descriptor.key === true) {
Object.defineProperty(descriptor, "key", {
value: className,
configurable: true,
});
} else if (descriptor.key === false) {
Object.defineProperty(descriptor, "key", {
value: void 0,
configurable: true,
});
}
if (superClass === void 0 || superClass === null) {
superClass = this;
}
const fastenerClass = superClass.extend(className, descriptor);
fastenerClass.construct = function (fastenerClass: {prototype: ControllerRef<any, any>}, fastener: ControllerRef<O, C> | null, owner: O): ControllerRef<O, C> {
fastener = superClass!.construct(fastenerClass, fastener, owner);
if (affinity !== void 0) {
fastener.initAffinity(affinity);
}
if (inherits !== void 0) {
fastener.initInherits(inherits);
}
return fastener;
};
return fastenerClass;
};
return ControllerRef;
})(ControllerRelation); | the_stack |
import {Component, Input, ViewChild} from "@angular/core";
import {AbstractControl, FormControl, FormGroup, ValidatorFn} from '@angular/forms';
import {ValidationErrors} from '@angular/forms/src/directives/validators';
import {MatSnackBar} from '@angular/material/snack-bar';
import {TdDialogService} from "@covalent/core/dialogs";
import {LoadingMode, LoadingType, TdLoadingService} from '@covalent/core/loading';
import {TranslateService} from "@ngx-translate/core";
import {StateService} from "@uirouter/angular";
import {fromPromise} from "rxjs/observable/fromPromise";
import {of} from "rxjs/observable/of";
import {catchError} from 'rxjs/operators/catchError';
import {concatMap} from "rxjs/operators/concatMap";
import {filter} from "rxjs/operators/filter";
import {finalize} from 'rxjs/operators/finalize';
import {map} from "rxjs/operators/map";
import {tap} from "rxjs/operators/tap";
import * as _ from "underscore";
import {AccessControlService} from "../../../services/AccessControlService";
import {EntityAccessControlService} from "../../shared/entity-access-control/EntityAccessControlService";
import {Connector} from '../api/models/connector';
import {ConnectorPlugin} from '../api/models/connector-plugin';
import {CreateDataSource, DataSource} from '../api/models/datasource';
import {DataSourceTemplate} from '../api/models/datasource-template';
import {UiOption} from '../api/models/ui-option';
import {CatalogService} from '../api/services/catalog.service';
import {MatSelectionListChange, MatSelectionList} from "@angular/material/list";
import {HttpErrorResponse} from "@angular/common/http";
interface UiOptionsMapper {
mapFromUiToModel(ds: DataSource, controls: Map<string, FormControl>, uiOptions: Map<string, UiOption>): void;
mapFromModelToUi(ds: DataSource, controls: Map<string, FormControl>, uiOptions: Map<string, UiOption>): void;
}
/**
* Class to track original property values and changes associated with each input.
* Sensitive properties will be initiall rendered with 5 ***** instead of the encrypted value
*/
export class OptionValue {
modifiedValue:string;
modified:boolean = false;
constructor(public key:string, public originalValue:string, public uiOption:UiOption){
if(this.originalValue == undefined ){
this.originalValue = null;
}
this.modifiedValue = this.originalValue;
if(this.modifiedValue && this.uiOption && this.uiOption.sensitive){
//default sensitive values to *****
this.modifiedValue ="*****";
}
}
public isModified(){
return this.modified;
}
public getValue(){
if(!this.modified) {
return this.originalValue;
}
else {
return this.modifiedValue;
}
}
}
class DefaultUiOptionsMapper implements UiOptionsMapper {
/**
* Map of the property key to the option value storing the changes
* @type {{}}
*/
propertyMap:{ [k: string]: OptionValue } = {};
mapFromUiToModel(ds: DataSource, controls: Map<string, FormControl>, uiOptions: Map<string, UiOption>): void {
controls.forEach((control: FormControl, key: string) => {
if (key === "path") {
ds.template.paths.push(control.value);
} else if (key === "jars") {
ds.template.jars = (control.value && control.value.length !== 0) ? control.value.split(",") : null;
} else {
this.setModelValue(ds,key,control);
}
});
}
mapFromModelToUi(ds: DataSource, controls: Map<string, FormControl>, uiOptions: Map<string, UiOption>): void {
controls.forEach((control: FormControl, key: string) => {
if (key === "path") {
control.setValue(ds.template.paths[0]);
} else if (key === "jars") {
if(ds.template.jars != undefined && ds.template.jars.length >0){
control.setValue(ds.template.jars.join(","));
}
} else {
this.setUiValueAndSubscribeToChanges(ds,control,key,uiOptions.get(key))
}
});
}
/**
* Set the datasource property on the model
* sensitive properties that are not changed will return the original encrypted cipher, otherwise the updated value
* @param {DataSource} ds
* @param {string} key
* @param {FormControl} control
*/
private setModelValue(ds: DataSource,key:string,control:FormControl){
let optionValue = this.propertyMap[key];
if(optionValue){
ds.template.options[key] = optionValue.getValue();
}
else {
ds.template.options[key] = control.value;
}
}
/**
* Set the FormControl UI value and subscribe to changes with the input.
* @param {DataSource} ds
* @param {FormControl} control
* @param {string} key
* @param {UiOption} uiOption
*/
private setUiValueAndSubscribeToChanges(ds: DataSource,control: FormControl, key: string, uiOption?:UiOption) {
let value = ds.template.options[key];
let optionValue = new OptionValue(key,value, uiOption);
this.propertyMap[key] = optionValue;
control.setValue(optionValue.modifiedValue);
control.valueChanges.subscribe((newValue:any)=> {
let optValue = this.propertyMap[key];
if(optValue){
optValue.modifiedValue = newValue;
optValue.modified = true;
}
});
}
}
class AzureUiOptionsMapper implements UiOptionsMapper {
mapFromUiToModel(ds: DataSource, controls: Map<string, FormControl>, uiOptions: Map<string, UiOption>): void {
controls.forEach((control: FormControl, key: string) => {
if (key === "path") {
ds.template.paths.push(control.value);
} else if (key === "jars") {
ds.template.jars = (control.value.length !== 0) ? control.value.split(",") : null;
} else if (key === "account-name" || key == "account-key") {
ds.template.options["spark.hadoop.fs.azure.account.key." + controls.get("account-name").value] = controls.get("account-key").value;
} else {
ds.template.options[key] = control.value;
}
});
}
mapFromModelToUi(ds: DataSource, controls: Map<string, FormControl>, uiOptions: Map<string, UiOption>): void {
controls.get("path").setValue(ds.template.paths[0]);
_.keys(ds.template.options).forEach(option => {
if (option.startsWith("spark.hadoop.fs.azure.account.key.")) {
const accountName = option.substring("spark.hadoop.fs.azure.account.key.".length);
controls.get("account-name").setValue(accountName);
controls.get("account-key").setValue(ds.template.options[option]);
}
});
}
}
export interface ControllerServiceConflict {
name:string;
matchingServices:any;
identityProperties:any;
}
/**
* Displays selected connector properties.
*/
@Component({
selector: "catalog-connector",
styleUrls: ["./connector.component.scss"],
templateUrl: "./connector.component.html"
})
export class ConnectorComponent {
static LOADER = "ConnectorComponent.LOADER";
private static topOfPageLoader: string = "ConnectorComponent.topOfPageLoader";
@Input("datasource")
public datasource: DataSource;
@Input("connector")
public connector: Connector;
@Input("connectorPlugin")
public plugin: ConnectorPlugin;
/**
* Indicates if admin actions are allowed
*/
allowAdmin = false;
form = new FormGroup({});
titleControl: FormControl;
private controls: Map<string, FormControl> = new Map();
isLoading: boolean = false;
private controlToUIOption: Map<string, UiOption> = new Map();
private testError: String;
private testStatus: boolean = false;
public controllerServiceConflictError:ControllerServiceConflict = null;
private matchingControllerServiceCheck:boolean = true;
private selectedMatchingControllerService:any;
private matchingControllerServiceControl:FormControl;
// noinspection JSUnusedLocalSymbols - called dynamically when validator is created
private jars = (params: any): ValidatorFn => {
return (control: AbstractControl): { [key: string]: any } => {
return (control.value as string || "").split(",")
.map(value => {
if (value.trim().length > 0) {
try {
const url = new URL(value);
if (params && params.protocol && url.protocol !== params.protocol) {
return 'url-protocol';
}
} catch (e) {
return 'url';
}
}
return null;
})
.reduce((accumulator, value) => {
if (value !== null) {
accumulator[value] = true;
}
return accumulator;
}, {});
}
};
// noinspection JSUnusedLocalSymbols - called dynamically when validator is created
private url = (params: any): ValidatorFn => {
return (control: AbstractControl): { [key: string]: any } => {
if (control.value && control.value.trim().length > 0) {
try {
const url: URL = new URL(control.value);
if (params && params.protocol && url.protocol !== params.protocol) {
return {'url-protocol': true};
}
} catch (e) {
return {'url': true};
}
} else {
return null;
}
};
};
// noinspection JSUnusedLocalSymbols - called dynamically when UiOptionsMapper is created
private azureOptionsMapper: UiOptionsMapper = new AzureUiOptionsMapper();
private defaultOptionsMapper: UiOptionsMapper = new DefaultUiOptionsMapper();
constructor(private state: StateService,
private catalogService: CatalogService,
private snackBarService: MatSnackBar,
private loadingService: TdLoadingService,
private dialogService: TdDialogService,
private translateService: TranslateService,
private entityAccessControlService: EntityAccessControlService,
private accessControlService: AccessControlService) {
this.titleControl = new FormControl('', ConnectorComponent.required);
this.loadingService.create({
name: ConnectorComponent.topOfPageLoader,
mode: LoadingMode.Indeterminate,
type: LoadingType.Linear,
color: 'accent',
});
}
public ngOnInit() {
this.createControls();
this.initControls();
this.accessControlService.getUserAllowedActions()
.then((actionSet: any) => {
this.allowAdmin = this.accessControlService.hasAction(AccessControlService.DATASOURCE_ADMIN, actionSet.actions)
&& this.accessControlService.hasEntityAccess(EntityAccessControlService.ENTITY_ACCESS.DATASOURCE.CHANGE_DATASOURCE_PERMISSIONS, this.datasource,
EntityAccessControlService.entityRoleTypes.DATASOURCE)
});
}
initControls() {
if (this.datasource) {
this.titleControl.setValue(this.datasource.title);
const optionsMapper = <UiOptionsMapper>this[this.plugin.optionsMapperId || "defaultOptionsMapper"];
if (optionsMapper) {
optionsMapper.mapFromModelToUi(this.datasource, this.controls, this.controlToUIOption);
} else {
this.showSnackBar("Unknown ui options mapper " + this.plugin.optionsMapperId
+ " for connector " + this.connector.title);
return;
}
}
}
createControls() {
const options = this.plugin.options;
if (!options) {
return;
}
for (let option of options) {
let control = this.controls.get(option.key);
if (!control) {
const validators = [];
if (option.required === undefined || option.required === true) {
validators.push(ConnectorComponent.required);
}
for (let validator of option.validators || []) {
if (this[validator.type]) {
validators.push(this[validator.type](validator.params));
} else {
console.error('Unknown validator type ' + validator.type);
}
}
control = new FormControl('', validators);
if (option.value) {
control.setValue(option.value);
}
this.controls.set(option.key, control);
this.controlToUIOption.set(option.key,option);
}
}
this.matchingControllerServiceControl = new FormControl("");
this.form.addControl("matchingControllerService",this.matchingControllerServiceControl);
}
/**
* Creates a new datasource or updates an existing one
*/
saveDatasource() {
this.testError = undefined;
// attempt to detect any matching controller services only the first time.
//once we detect if there are matching ones the next save will not detect
let detectServices = this.controllerServiceConflictError == null;
this.controllerServiceConflictError = null;
const ds = this.getDataSourceFromUi() as CreateDataSource;
if (ds === undefined) {
return;
}
let matchingControllerServiceId = this.matchingControllerServiceControl.value.length >0 ? this.matchingControllerServiceControl.value[0] : null;
if(matchingControllerServiceId != null){
ds.nifiControllerServiceId = matchingControllerServiceId;
detectServices = false;
}
else {
ds.nifiControllerServiceId = null;
}
ds.detectSimilarNiFiControllerServices = detectServices;
console.log("saving ",ds);
this.isLoading = true;
this.loadingService.register(ConnectorComponent.topOfPageLoader);
this.catalogService.createDataSource(ds).pipe(
concatMap(dataSource => {
if (this.allowAdmin && typeof ds.roleMemberships !== "undefined") {
this.entityAccessControlService.updateRoleMembershipsForSave(ds.roleMemberships);
return fromPromise(this.entityAccessControlService.saveRoleMemberships("datasource", dataSource.id, ds.roleMemberships))
.pipe(map(() => dataSource));
} else {
return of(dataSource);
}
}),
finalize(() => {
this.isLoading = false;
this.loadingService.resolve(ConnectorComponent.topOfPageLoader);
})
).subscribe(
source => this.state.go("catalog.datasources", {datasourceId: source.id}),
(err:HttpErrorResponse) => {
let propertyString:string;
let errorMessage = err.error.message || err.message;
if(err.status == 409 && err.error.type && err.error.type == "ControllerServiceConflictEntity") {
let controllerServiceConflict = (err.error as ControllerServiceConflict);
let identityPropertyKeys = Object.keys(controllerServiceConflict.identityProperties);
controllerServiceConflict.matchingServices.forEach((svc: any) => {
svc.identityPropertyString = ''
if (identityPropertyKeys) {
identityPropertyKeys.forEach((key: string) => {
let serviceValue = svc.properties[key];
if (serviceValue) {
if (svc.identityPropertyString != "") {
svc.identityPropertyString += ", ";
}
svc.identityPropertyString += key + "=" + serviceValue;
}
})
}
});
controllerServiceConflict.matchingServices = _.sortBy(controllerServiceConflict.matchingServices, (service: any) => service.state == 'ENABLED' ? 0 : 1)
this.controllerServiceConflictError = controllerServiceConflict;
this.matchingControllerServiceControl.setValue([""]);
let msg = this.translateService.instant("CATALOG.DATA_SOURCES.NIFI_CONTROLLER_SERVICE_CONFILCT_SNACK_BAR")
this.showSnackBar('Similar NiFi controller services were found. Review options before saving');
}
else {
console.error(err);
this.showSnackBar('Failed to save. ',errorMessage);
}
}
);
}
/**
* ensure only 1 service is selected
* @param event
*/
controllerServiceConflictChanged(event:MatSelectionListChange){
console.log('controllerServiceConflictChanged ',event)
if (event.option.selected) {
event.source.options.toArray().forEach(element => {
if (element != event.option) {
element.selected = false;
}
});
}
}
getDataSourceFromUi(): DataSource | CreateDataSource | undefined {
const optionsMapper = <UiOptionsMapper>this[this.plugin.optionsMapperId || "defaultOptionsMapper"];
if (!optionsMapper) {
this.showSnackBar("Unknown ui options mapper " + this.plugin.optionsMapperId
+ " for connector " + this.connector.title);
return undefined;
}
const ds = this.datasource ? this.datasource : new DataSource();
ds.title = this.titleControl.value;
ds.connector = this.connector;
ds.template = new DataSourceTemplate();
ds.template.paths = [];
ds.template.options = {};
optionsMapper.mapFromUiToModel(ds, this.controls, this.controlToUIOption);
return ds;
}
showSnackBar(msg: string, err?: string): void {
this.snackBarService
.open(msg + ' ' + (err ? err : ""), 'OK', {duration: 5000});
}
isInputType(option: UiOption): boolean {
return option.type === undefined || option.type === '' || option.type === "input" || option.type === "password";
}
isSelectType(option: UiOption): boolean {
return option.type === "select";
}
isFormInvalid(): boolean {
return this.titleControl.invalid || Array.from(this.controls.values())
.map(item => item.invalid)
.reduce((prev, current) => {
return prev || current;
}, false
);
}
getControl(option: UiOption) {
return this.controls.get(option.key);
}
/**
* Validation function which does not allow only empty space
* @param {AbstractControl} control
* @returns {ValidationErrors}
*/
private static required(control: AbstractControl): ValidationErrors {
return (control.value || '').trim().length === 0 ? {'required': true} : null;
}
cancel() {
this.state.go("catalog.datasources");
}
/**
* Delete datasource
*/
deleteDatasource() {
this.translateService.get("CATALOG.DATA_SOURCES.CONFIRM_DELETE").pipe(
concatMap(messages => {
return this.dialogService.openConfirm({
message: messages["MESSAGE"],
title: messages["TITLE"],
acceptButton: messages["ACCEPT"],
cancelButton: messages["CANCEL"]
}).afterClosed()
}),
filter(accept => accept),
tap(() => this.loadingService.register(ConnectorComponent.topOfPageLoader)),
concatMap(() => this.catalogService.deleteDataSource(this.datasource)),
finalize(() => this.loadingService.resolve(ConnectorComponent.topOfPageLoader))
).subscribe(
() => this.state.go("catalog.datasources", {}, {reload: true}),
err => {
console.error(err);
if (err.status == 409) {
this.showSnackBar("Failed to delete. This data source is currently being used by a feed.");
} else {
this.showSnackBar('Failed to delete.', err.message);
}
}
);
}
/**
* Validates data source connection
*/
test() {
this.testStatus = false;
this.testError = undefined;
const ds = this.getDataSourceFromUi();
if (ds === undefined) {
return;
}
this.loadingService.register(ConnectorComponent.topOfPageLoader);
this.catalogService.testDataSource(ds)
.pipe(finalize(() => {
this.loadingService.resolve(ConnectorComponent.topOfPageLoader);
this.testStatus = true;
}))
.pipe(catchError((err) => {
this.testError = err.error.developerMessage ? err.error.developerMessage : err.error.message;
return [];
}))
.subscribe(() => {
});
}
isTestAvailable(): boolean {
const tabs = this.plugin.tabs;
return tabs && (".browse" === tabs[0].sref || ".connection" === tabs[0].sref);
}
} | the_stack |
import germanLocaleData from '@box/cldr-data/locale-data/de-DE';
import russianLocaleData from '@box/cldr-data/locale-data/ru-RU';
import japaneseLocaleData from '@box/cldr-data/locale-data/ja-JP';
import { UnifiedNumberFormat } from '@formatjs/intl-unified-numberformat';
import numAbbr, { Lengths } from '../numAbbr';
const germanNumbersData = germanLocaleData.numbers;
const russianNumbersData = russianLocaleData.numbers;
const japaneseNumbersData = japaneseLocaleData.numbers;
const { node } = process.versions;
if (!node || Number(node.replace(/\..*/g, '')) < 12) {
// need to polyfill the number formatter in Intl.NumberFormat, because it
// doesn't work properly on versions of node before 12
/* eslint-disable global-require */
/* eslint-disable no-underscore-dangle */
/* eslint-disable @typescript-eslint/no-var-requires */
require('@formatjs/intl-unified-numberformat/polyfill');
if (typeof UnifiedNumberFormat.__addLocaleData === 'function') {
UnifiedNumberFormat.__addLocaleData(require('@formatjs/intl-unified-numberformat/dist/locale-data/de.json'));
UnifiedNumberFormat.__addLocaleData(require('@formatjs/intl-unified-numberformat/dist/locale-data/ru.json'));
UnifiedNumberFormat.__addLocaleData(require('@formatjs/intl-unified-numberformat/dist/locale-data/ja.json'));
}
/* eslint-enable global-require */
/* eslint-enable no-underscore-dangle */
/* eslint-enable @typescript-eslint/no-var-requires */
}
describe('util/num', () => {
test('should work in English 1', () => {
expect(numAbbr(1)).toBe('1');
});
test('should work in English 1000', () => {
expect(numAbbr(1000)).toBe('1K');
});
test('should work in English 10000', () => {
expect(numAbbr(10000)).toBe('10K');
});
test('should work in English 100000', () => {
expect(numAbbr(100000)).toBe('100K');
});
test('should work in English 1000000', () => {
expect(numAbbr(1000000)).toBe('1M');
});
test('should work in English 10000000', () => {
expect(numAbbr(10000000)).toBe('10M');
});
test('should work in English 1000000000', () => {
expect(numAbbr(1000000000)).toBe('1B');
});
test('should work in English 1000000000000', () => {
expect(numAbbr(1000000000000)).toBe('1T');
});
test('should work in English larger than max', () => {
expect(numAbbr(1000000000000000000)).toBe('1,000,000T');
});
test('should work in English 1 long', () => {
expect(numAbbr(1, { length: Lengths.long })).toBe('1');
});
test('should work in English 1000 long', () => {
expect(numAbbr(1000, { length: Lengths.long })).toBe('1 thousand');
});
test('should work in English 10000 long', () => {
expect(numAbbr(10000, { length: Lengths.long })).toBe('10 thousand');
});
test('should work in English 100000 long', () => {
expect(numAbbr(100000, { length: Lengths.long })).toBe('100 thousand');
});
test('should work in English 1000000 long', () => {
expect(numAbbr(1000000, { length: Lengths.long })).toBe('1 million');
});
test('should work in English 10000000 long', () => {
expect(numAbbr(10000000, { length: Lengths.long })).toBe('10 million');
});
test('should work in English 1000000000 long', () => {
expect(numAbbr(1000000000, { length: Lengths.long })).toBe('1 billion');
});
test('should work in English 1000000000000 long', () => {
expect(numAbbr(1000000000000, { length: Lengths.long })).toBe('1 trillion');
});
test('should work in English larger than max long', () => {
expect(numAbbr(1000000000000000000, { length: Lengths.long })).toBe('1,000,000 trillion');
});
test('should work in English 12345678 with rounding', () => {
expect(numAbbr(12345678)).toBe('12M');
});
test('should work in English 87654321 with rounding', () => {
expect(numAbbr(87654321)).toBe('88M');
});
test('should work when passing in a number as a string', () => {
expect(numAbbr('3230000')).toBe('3M');
});
test('should not crap out when passing in a string that does not contain a number', () => {
expect(numAbbr('asdf')).toBe('0');
});
test('should not crap out when passing in an empty string', () => {
expect(numAbbr('')).toBe('0');
});
test('should not crap out when passing in a boolean false', () => {
expect(numAbbr(false)).toBe('0');
});
test('should not crap out when passing in a boolean true', () => {
expect(numAbbr(true)).toBe('1');
});
test('should not crap out when passing in a null', () => {
expect(numAbbr(null)).toBe('0');
});
test('should not crap out when passing in undefined', () => {
expect(numAbbr(undefined)).toBe('0');
});
test('should not crap out when passing in an object', () => {
expect(numAbbr({ foo: 2, bar: 4 })).toBe('0');
});
test('should work when passing in a floating point number', () => {
expect(numAbbr(24734.45674)).toBe('25K');
});
test('should work when passing in a small negative number', () => {
expect(numAbbr(-24)).toBe('-24');
});
test('should abbreviate when passing in a medium negative number', () => {
expect(numAbbr(-24567)).toBe('-25K');
});
test('should abbreviate when passing in a large negative number', () => {
expect(numAbbr(-24567000000)).toBe('-25B');
});
test('should work with 0', () => {
expect(numAbbr(0)).toBe('0');
});
test('should work when passing an array of numbers', () => {
expect(numAbbr([34534, 333000000, 34])).toStrictEqual(['35K', '333M', '34']);
});
test('should work when passing an array of mixed types', () => {
expect(numAbbr([34534, '333000000', 34])).toStrictEqual(['35K', '333M', '34']);
});
test('should work in German 1', () => {
expect(numAbbr(1, { numbersData: germanNumbersData, locale: 'de-DE' })).toBe('1');
});
test('should work in German 1000', () => {
expect(numAbbr(1000, { numbersData: germanNumbersData, locale: 'de-DE' })).toBe('1.000');
});
test('should work in German 10000', () => {
expect(numAbbr(10000, { numbersData: germanNumbersData, locale: 'de-DE' })).toBe('10.000');
});
test('should work in German 100000', () => {
expect(numAbbr(100000, { numbersData: germanNumbersData, locale: 'de-DE' })).toBe('100.000');
});
test('should work in German 1000000', () => {
expect(numAbbr(1000000, { numbersData: germanNumbersData, locale: 'de-DE' })).toBe('1 Mio.');
});
test('should work in German 10000000', () => {
expect(numAbbr(10000000, { numbersData: germanNumbersData, locale: 'de-DE' })).toBe('10 Mio.');
});
test('should work in German 1000000000', () => {
expect(numAbbr(1000000000, { numbersData: germanNumbersData, locale: 'de-DE' })).toBe('1 Mrd.');
});
test('should work in German 1000000000000', () => {
expect(numAbbr(1000000000000, { numbersData: germanNumbersData, locale: 'de-DE' })).toBe('1 Bio.');
});
test('should work in German larger than max', () => {
expect(numAbbr(1000000000000000000, { numbersData: germanNumbersData, locale: 'de-DE' })).toBe(
'1.000.000 Bio.',
);
});
test('should work in German 1 long', () => {
expect(numAbbr(1, { numbersData: germanNumbersData, locale: 'de-DE', length: Lengths.long })).toBe('1');
});
test('should work in German 1000 long', () => {
expect(numAbbr(1000, { numbersData: germanNumbersData, locale: 'de-DE', length: Lengths.long })).toBe(
'1 Tausend',
);
});
test('should work in German 10000 long', () => {
expect(numAbbr(10000, { numbersData: germanNumbersData, locale: 'de-DE', length: Lengths.long })).toBe(
'10 Tausend',
);
});
test('should work in German 100000 long', () => {
expect(numAbbr(100000, { numbersData: germanNumbersData, locale: 'de-DE', length: Lengths.long })).toBe(
'100 Tausend',
);
});
test('should work in German 1000000 long', () => {
expect(numAbbr(1000000, { numbersData: germanNumbersData, locale: 'de-DE', length: Lengths.long })).toBe(
'1 Million',
);
});
test('should work in German 10000000 long', () => {
expect(numAbbr(10000000, { numbersData: germanNumbersData, locale: 'de-DE', length: Lengths.long })).toBe(
'10 Millionen',
);
});
test('should work in German 1000000000 long', () => {
expect(numAbbr(1000000000, { numbersData: germanNumbersData, locale: 'de-DE', length: Lengths.long })).toBe(
'1 Milliarde',
);
});
test('should work in German 1000000000000 long', () => {
expect(numAbbr(1000000000000, { numbersData: germanNumbersData, locale: 'de-DE', length: Lengths.long })).toBe(
'1 Billion',
);
});
test('should work in German larger than max long', () => {
expect(
numAbbr(1000000000000000000, { numbersData: germanNumbersData, locale: 'de-DE', length: Lengths.long }),
).toBe('1.000.000 Billionen');
});
test('should work in Russian 1', () => {
expect(numAbbr(1, { numbersData: russianNumbersData, locale: 'ru-RU' })).toBe('1');
});
test('should work in Russian 1000', () => {
expect(numAbbr(1000, { numbersData: russianNumbersData, locale: 'ru-RU' })).toBe('1 тыс.');
});
test('should work in Russian 10000', () => {
expect(numAbbr(10000, { numbersData: russianNumbersData, locale: 'ru-RU' })).toBe('10 тыс.');
});
test('should work in Russian 100000', () => {
expect(numAbbr(100000, { numbersData: russianNumbersData, locale: 'ru-RU' })).toBe('100 тыс.');
});
test('should work in Russian 1000000', () => {
expect(numAbbr(1000000, { numbersData: russianNumbersData, locale: 'ru-RU' })).toBe('1 млн');
});
test('should work in Russian 10000000', () => {
expect(numAbbr(10000000, { numbersData: russianNumbersData, locale: 'ru-RU' })).toBe('10 млн');
});
test('should work in Russian 1000000000', () => {
expect(numAbbr(1000000000, { numbersData: russianNumbersData, locale: 'ru-RU' })).toBe('1 млрд');
});
test('should work in Russian 1000000000000', () => {
expect(numAbbr(1000000000000, { numbersData: russianNumbersData, locale: 'ru-RU' })).toBe('1 трлн');
});
test('should work in Russian larger than max', () => {
expect(numAbbr(1000000000000000000, { numbersData: russianNumbersData, locale: 'ru-RU' })).toBe(
'1 000 000 трлн',
);
});
test('should work in Russian 1 long', () => {
expect(numAbbr(1, { numbersData: russianNumbersData, locale: 'ru-RU', length: Lengths.long })).toBe('1');
});
test('should work in Russian 1000 long', () => {
expect(numAbbr(1000, { numbersData: russianNumbersData, locale: 'ru-RU', length: Lengths.long })).toBe(
'1 тысяча',
);
});
test('should work in Russian 2000', () => {
expect(numAbbr(2000, { numbersData: russianNumbersData, locale: 'ru-RU', length: Lengths.long })).toBe(
'2 тысячи',
);
});
test('should work in Russian 5000', () => {
expect(numAbbr(5000, { numbersData: russianNumbersData, locale: 'ru-RU', length: Lengths.long })).toBe(
'5 тысяч',
);
});
test('should work in Russian 10000 long', () => {
expect(numAbbr(10000, { numbersData: russianNumbersData, locale: 'ru-RU', length: Lengths.long })).toBe(
'10 тысяч',
);
});
test('should work in Russian 100000 long', () => {
expect(numAbbr(100000, { numbersData: russianNumbersData, locale: 'ru-RU', length: Lengths.long })).toBe(
'100 тысяч',
);
});
test('should work in Russian 1000000 long', () => {
expect(numAbbr(1000000, { numbersData: russianNumbersData, locale: 'ru-RU', length: Lengths.long })).toBe(
'1 миллион',
);
});
test('should work in Russian 2000000 long', () => {
expect(numAbbr(2000000, { numbersData: russianNumbersData, locale: 'ru-RU', length: Lengths.long })).toBe(
'2 миллиона',
);
});
test('should work in Russian 5000000 long', () => {
expect(numAbbr(5000000, { numbersData: russianNumbersData, locale: 'ru-RU', length: Lengths.long })).toBe(
'5 миллионов',
);
});
test('should work in Russian 10000000 long', () => {
expect(numAbbr(10000000, { numbersData: russianNumbersData, locale: 'ru-RU', length: Lengths.long })).toBe(
'10 миллионов',
);
});
test('should work in Russian 1000000000 long', () => {
expect(numAbbr(1000000000, { numbersData: russianNumbersData, locale: 'ru-RU', length: Lengths.long })).toBe(
'1 миллиард',
);
});
test('should work in Russian 1000000000000 long', () => {
expect(numAbbr(1000000000000, { numbersData: russianNumbersData, locale: 'ru-RU', length: Lengths.long })).toBe(
'1 триллион',
);
});
test('should work in Russian larger than max long', () => {
expect(
numAbbr(1000000000000000000, { numbersData: russianNumbersData, locale: 'ru-RU', length: Lengths.long }),
).toBe('1 000 000 триллионов');
});
test('should work in Japanese 1', () => {
expect(numAbbr(1, { numbersData: japaneseNumbersData, locale: 'ja-JP' })).toBe('1');
});
test('should work in Japanese 1000', () => {
expect(numAbbr(1000, { numbersData: japaneseNumbersData, locale: 'ja-JP' })).toBe('1,000');
});
test('should work in Japanese 10000', () => {
expect(numAbbr(10000, { numbersData: japaneseNumbersData, locale: 'ja-JP' })).toBe('1万');
});
test('should work in Japanese 100000', () => {
expect(numAbbr(100000, { numbersData: japaneseNumbersData, locale: 'ja-JP' })).toBe('10万');
});
test('should work in Japanese 1000000', () => {
expect(numAbbr(1000000, { numbersData: japaneseNumbersData, locale: 'ja-JP' })).toBe('100万');
});
test('should work in Japanese 100000000', () => {
expect(numAbbr(100000000, { numbersData: japaneseNumbersData, locale: 'ja-JP' })).toBe('1億');
});
test('should work in Japanese 1000000000', () => {
expect(numAbbr(1000000000, { numbersData: japaneseNumbersData, locale: 'ja-JP' })).toBe('10億');
});
test('should work in Japanese 100000000000', () => {
expect(numAbbr(100000000000, { numbersData: japaneseNumbersData, locale: 'ja-JP' })).toBe('1,000億');
});
test('should work in Japanese 1000000000000', () => {
expect(numAbbr(1000000000000, { numbersData: japaneseNumbersData, locale: 'ja-JP' })).toBe('1兆');
});
test('should work in Japanese larger than max', () => {
expect(numAbbr(1000000000000000000, { numbersData: japaneseNumbersData, locale: 'ja-JP' })).toBe('1,000,000兆');
});
// short and long are the same for Japanese
test('should work in Japanese 1 long', () => {
expect(numAbbr(1, { numbersData: japaneseNumbersData, locale: 'ja-JP', length: Lengths.long })).toBe('1');
});
test('should work in Japanese 1000 long', () => {
expect(numAbbr(1000, { numbersData: japaneseNumbersData, locale: 'ja-JP', length: Lengths.long })).toBe(
'1,000',
);
});
test('should work in Japanese 10000 long', () => {
expect(numAbbr(10000, { numbersData: japaneseNumbersData, locale: 'ja-JP', length: Lengths.long })).toBe('1万');
});
test('should work in Japanese 100000 long', () => {
expect(numAbbr(100000, { numbersData: japaneseNumbersData, locale: 'ja-JP', length: Lengths.long })).toBe(
'10万',
);
});
test('should work in Japanese 1000000 long', () => {
expect(numAbbr(1000000, { numbersData: japaneseNumbersData, locale: 'ja-JP', length: Lengths.long })).toBe(
'100万',
);
});
test('should work in Japanese 100000000 long', () => {
expect(numAbbr(100000000, { numbersData: japaneseNumbersData, locale: 'ja-JP', length: Lengths.long })).toBe(
'1億',
);
});
test('should work in Japanese 1000000000 long', () => {
expect(numAbbr(1000000000, { numbersData: japaneseNumbersData, locale: 'ja-JP', length: Lengths.long })).toBe(
'10億',
);
});
test('should work in Japanese 100000000000 long', () => {
expect(numAbbr(100000000000, { numbersData: japaneseNumbersData, locale: 'ja-JP', length: Lengths.long })).toBe(
'1,000億',
);
});
test('should work in Japanese 1000000000000 long', () => {
expect(
numAbbr(1000000000000, { numbersData: japaneseNumbersData, locale: 'ja-JP', length: Lengths.long }),
).toBe('1兆');
});
test('should work in Japanese larger than max long', () => {
expect(
numAbbr(1000000000000000000, { numbersData: japaneseNumbersData, locale: 'ja-JP', length: Lengths.long }),
).toBe('1,000,000兆');
});
}); | the_stack |
import { deepEqual } from 'assert';
import chalk from 'chalk';
import { tokenize } from '../src/lexer/';
import { parse } from '../src/parser/';
import { desugarBefore, desugarAfter } from '../src/desugarer/';
import { typeCheck } from '../src/typechecker/';
import { TypeContext } from '../src/typechecker/context';
import { genWASM } from '../src/codegen/';
import { Compose } from '../src/util';
import { runWASM, WASMResult } from '../src/wasm';
console.log(chalk.bold('Running codegen tests...'));
const memorySize = 4; // 4MiB
const compile = Compose.then(tokenize)
.then(parse)
.then(desugarBefore)
.then(mod => typeCheck(mod, new TypeContext()))
.then(desugarAfter)
.then(mod => genWASM(mod, { exports: ['test'], memorySize })).f;
async function moduleRunTest(
moduleStr: string,
expected: any,
resultHandler: (result: WASMResult) => any = result => result.value,
): Promise<void> {
try {
const wasmModule = compile(moduleStr);
const result = await runWASM(wasmModule, { main: 'test', memorySize });
deepEqual(resultHandler(result), expected);
} catch (err) {
console.error(chalk.blue.bold('Test:'));
console.error(moduleStr);
console.error();
console.error(chalk.red.bold('Error:'));
console.error(err.message);
process.exit(1);
}
}
(async function() {
await moduleRunTest(
`
let test = fn () float {
1234.
}
`,
1234,
);
await moduleRunTest(
`
let test = fn () void {
1234.;
}
`,
undefined,
);
await moduleRunTest(
`
let test = fn () int {
1234
}
`,
1234,
);
await moduleRunTest(
`
let test = fn () bool {
true
}
`,
1,
);
await moduleRunTest(
`
let test = fn () char {
'\\n'
}
`,
'\n'.codePointAt(0),
);
await moduleRunTest(
`
let test = fn () int {
let x = 1234;
x
}
`,
1234,
);
await moduleRunTest(
`
let test = fn () int {
let x = 1234;
x;
let y = 123;
y
}
`,
123,
);
await moduleRunTest(
`
let x = 1234
let y = 123
let test = fn () int {
x;
y
}
`,
123,
);
await moduleRunTest(
`
let test_impl = fn () int {
let x = 1234;
x;
let y = 123;
y
}
let test = test_impl
`,
123,
);
await moduleRunTest(
`
let test_impl = fn (x float) float {
1234;
x
}
let test = fn () float {
test_impl(123.)
}
`,
123,
);
await moduleRunTest(
`
let test_impl = fn (x float, y int) int {
x;
y
}
let test = fn () int {
test_impl(123., test_impl(123., 1234))
}
`,
1234,
);
await moduleRunTest(
`
let test_impl = fn (x float, y int) int {
x;
y
}
let test = fn () int {
let f = test_impl;
let g = f;
g(123., f(123., 1234))
}
`,
1234,
);
await moduleRunTest(
`
let test_impl = fn (x float, y int) int {
x;
y
}
let x = test_impl(123., 1234)
let test = fn () int {
x
}
`,
1234,
);
await moduleRunTest(
`
let test = fn () int {
-100
}
`,
-100,
);
await moduleRunTest(
`
let test = fn () float {
+100.123
}
`,
100.123,
);
await moduleRunTest(
`
let test = fn () float {
-100.123
}
`,
-100.123,
);
await moduleRunTest(
`
let test = fn () bool {
!false
}
`,
1,
);
await moduleRunTest(
`
let test = fn () bool {
!true
}
`,
0,
);
await moduleRunTest(
`
let a = 1234.
let f = fn () float {
a;
123.
}
let id = fn (x float) float { x }
let c = fn (b bool) float {
let x = 1.23;
if (!b) {
let x = a;
x
} else {
let y = x;
let x = y;
let f = id;
f(x)
}
}
let test = fn () float {
c(false);
c(true)
}
`,
1.23,
);
await moduleRunTest(
`
let test = fn () bool {
1234 == 1234
}
`,
1,
);
await moduleRunTest(
`
let test = fn () bool {
1234. == 1234.
}
`,
1,
);
await moduleRunTest(
`
let test = fn () bool {
'a' != 'a'
}
`,
0,
);
await moduleRunTest(
`
let test = fn () bool {
'a' < 'b'
}
`,
1,
);
await moduleRunTest(
`
let test = fn () bool {
'a' <= 'a'
}
`,
1,
);
await moduleRunTest(
`
let test = fn () bool {
1.234 > 12.34
}
`,
0,
);
await moduleRunTest(
`
let test = fn () bool {
1234 >= 1235
}
`,
0,
);
await moduleRunTest(
`
let test = fn () int {
1234 + 5678
}
`,
6912,
);
await moduleRunTest(
`
let test = fn () float {
1234. + .5678
}
`,
1234.5678,
);
await moduleRunTest(
`
let test = fn () int {
1234 - 5678 + 1
}
`,
-4443,
);
await moduleRunTest(
`
let test = fn () float {
1234. - 5678. + 1.
}
`,
-4443,
);
await moduleRunTest(
`
let test = fn () int {
1234 ^ 5678
}
`,
4860,
);
await moduleRunTest(
`
let test = fn () int {
1234 | 5678
}
`,
5886,
);
await moduleRunTest(
`
let test = fn () int {
1234 & 5678
}
`,
1026,
);
await moduleRunTest(
`
let test = fn () int {
1234 * 5678
}
`,
7006652,
);
await moduleRunTest(
`
let test = fn () float {
1234. * 5678.
}
`,
7006652,
);
await moduleRunTest(
`
let test = fn () int {
-5678 / 1234
}
`,
-4,
);
await moduleRunTest(
`
let test = fn () float {
4. / -2.
}
`,
-2,
);
await moduleRunTest(
`
let test = fn () int {
1234 % 123
}
`,
4,
);
await moduleRunTest(
`
let test = fn () int {
-1234 % -123
}
`,
-4,
);
await moduleRunTest(
`
let test = fn () bool {
false && true
}
`,
0,
);
await moduleRunTest(
`
let test = fn () bool {
true && (1 == 1)
}
`,
1,
);
await moduleRunTest(
`
let test = fn () bool {
true || false
}
`,
1,
);
await moduleRunTest(
`
let fac = fn (n int) int {
if n == 1 {
1
} else {
n * fac(n - 1)
}
}
let test = fn () int {
fac(10)
}
`,
3628800,
);
const s2i = (slice: ArrayBuffer) => new Int32Array(slice)[0];
const s2f = (slice: ArrayBuffer) => new Float64Array(slice)[0];
const tuple = (...sizes: Array<number>) => ({
value,
memory,
}: WASMResult) => {
let offset = value;
return sizes.map(size => {
const slice = memory.buffer.slice(offset, offset + size);
let value;
if (size === 8) {
// must be float
value = s2f(slice);
} else {
// must be 4, read as int32
value = s2i(slice);
}
offset += size;
return value;
});
};
await moduleRunTest(
`
let test = fn () (int, float, bool) {
(1, 1.5, true)
}
`,
[1, 1.5, 1],
tuple(4, 8, 4),
);
await moduleRunTest(
`
let test = fn () () {
()
}
`,
0,
);
await moduleRunTest(
`
let f1 = fn () () {
()
}
let f2 = fn (x bool) bool {
!x
}
let test = fn () ((), bool) {
();
();
(1, 2);
(f1(), f2(false))
}
`,
[0, 1],
tuple(4, 4),
);
await moduleRunTest(
`
let test = fn () float {
(1, 1.5, true)[1]
}
`,
1.5,
);
await moduleRunTest(
`
let test = fn () int {
int((1, 3.5, true)[1])
}
`,
3,
);
await moduleRunTest(
`
let test = fn () int {
let x = (1, (2, (3, 4), 5), 6, (7, 8));
x[1][1][1]
}
`,
4,
);
await moduleRunTest(
`
let test = fn () (float, float) {
let x = (1, 1.5, (2.5, false, (), 0), 3.5);
let y = (2.5, false);
(x[2][0] - float(x[0]), y[0] + float(x[2][3]))
}
`,
[1.5, 2.5],
tuple(8, 8),
);
await moduleRunTest(
`
let test = fn () int {
let x = 1234.;
int(x)
}
`,
1234,
);
await moduleRunTest(
`
let test = fn () float {
let x = 1234;
float(x)
}
`,
1234,
);
await moduleRunTest(
`
let test = fn () int {
let x = 1;
x = x + 10;
let y = 2;
x = x + 2 * y;
x
}
`,
15,
);
await moduleRunTest(
`
let g = 10
let test = fn () int {
let x = 1;
x = x + 10;
let y = 2;
x = x + 2 * y;
g = x + g;
g
}
`,
25,
);
await moduleRunTest(
`
let g = (10, 20., 30)
let test = fn () int {
g[0] = 0;
g[1] = float(g[0]) + float(g[2]);
int(g[1]) + g[2]
}
`,
60,
);
const array = (size: number) => ({ value, memory }: WASMResult) => {
let offset = value;
const len = s2i(memory.buffer.slice(offset, offset + 4));
if (size === 8) {
// must be float
return Array.from(
new Float64Array(memory.buffer.slice(offset + 4, offset + 4 + 8 * len)),
);
} else {
// must be 4, read as int32
return Array.from(
new Int32Array(memory.buffer.slice(offset + 4, offset + 4 + 4 * len)),
);
}
};
await moduleRunTest(
`
let test = fn () [int] {
[1, 2, 3]
}
`,
[1, 2, 3],
array(4),
);
await moduleRunTest(
`
let test = fn () [bool] {
[true, false, true, true]
}
`,
[1, 0, 1, 1],
array(4),
);
await moduleRunTest(
`
let test = fn () [float] {
[1.5, 2.4, 3.3, 4.2, 5.1]
}
`,
[1.5, 2.4, 3.3, 4.2, 5.1],
array(8),
);
await moduleRunTest(
`
let test = fn () float {
[1.5, 2.4, 3.3, 4.2, 5.1][2]
}
`,
3.3,
);
await moduleRunTest(
`
let test = fn () float {
[[1.5, 2.4], [3.3, 4.2, 5.1]][1][2]
}
`,
5.1,
);
await moduleRunTest(
`
let test = fn () float {
let x = [1.5, 2.4, 3.3, 4.2, 5.1];
x[2] = x[1] + x[3];
x[2]
}
`,
6.6,
);
await moduleRunTest(
`
let test = fn () [float] {
let x = [[1.5, 2.4], [3.3, 4.2, 5.1]];
x[1] = x[0];
x[1]
}
`,
[1.5, 2.4],
array(8),
);
// new expr
await moduleRunTest(
`
let test = fn () [float] {
let y = (1, 2, 3);
let x = new float[y[2]];
x[0] = 1.5;
x[1] = 2.5;
x[2] = 3.5;
x
}
`,
[1.5, 2.5, 3.5],
array(8),
);
// len
await moduleRunTest(
`
let test = fn () int {
len([true, false, true, false, false])
}
`,
5,
);
await moduleRunTest(
`
let test = fn () int {
let y = (1, 2, 3);
let x = new float[y[2]];
len(x)
}
`,
3,
);
// loop
await moduleRunTest(
`
let test = fn () int {
let x = 0;
while x < 100 {
x = x + 1;
};
x
}
`,
100,
);
await moduleRunTest(
`
let test = fn () int {
let x = 0;
while x < 100 {
if (x >= 80) {
break;
} else {
x = x + 1;
}
};
x
}
`,
80,
);
await moduleRunTest(
`
let test = fn () [float] {
let y = (1, 2, 3);
let x = new float[y[2]];
let i = 0;
while i < len(x) {
x[i] = float(i) + 0.5;
i = i + 1;
};
x
}
`,
[0.5, 1.5, 2.5],
array(8),
);
await moduleRunTest(
`
let test = fn () [int] {
let res = new int[5];
let i = 1;
while i <= len(res) {
let j = 1;
let sum = 0;
while (j <= i) {
sum = sum + j;
j = j + 1;
};
res[i - 1] = sum;
i = i + 1;
};
res
}
`,
[1, 3, 6, 10, 15],
array(4),
);
await moduleRunTest(
`
let test = fn () int {
other()
}
let other = fn () int {
1234
}
`,
1234,
);
console.log(chalk.green.bold('Passed!'));
})(); | the_stack |
import * as utils from '../../utils';
import {getBezierPoint, splitCubicSegment as split} from '../bezier';
import {Point} from '../point';
interface XPoint extends Point {
isCubicControl?: boolean;
isInterpolated?: boolean;
positionIsBeingChanged?: boolean;
}
/**
* Returns intermediate line or curve between two sources.
*/
export default function interpolatePathPoints(
pointsFrom: XPoint[],
pointsTo: XPoint[],
type: 'polyline' | 'cubic' = 'polyline') {
var interpolate: (t: number) => XPoint[];
return (t: number) => {
if (t === 0) {
return pointsFrom;
}
if (t === 1) {
return pointsTo;
}
if (!interpolate) {
interpolate = (type === 'cubic' ?
getCubicInterpolator :
getLinearInterpolator
)(pointsFrom, pointsTo);
}
return interpolate(t);
};
}
/**
* Creates intermediate points array, so that the number of points
* remains the same and added or excluded points are situated between
* existing points.
*/
function getLinearInterpolator(pointsFrom: XPoint[], pointsTo: XPoint[]): (t: number) => XPoint[] {
// TODO: Continue unfinished transition of ending points.
pointsFrom = pointsFrom.filter(d => !d.isInterpolated);
// NOTE: Suppose data is already sorted by X.
var idsFrom = pointsFrom.map(d => d.id);
var idsTo = pointsTo.map(d => d.id);
var remainingIds = idsFrom
.filter(id => idsTo.indexOf(id) >= 0);
//
// Determine start and end scales difference to apply
// to initial target position of newly added points
// (or end position of deleted points)
var stableFrom = pointsFrom.filter(d => !d.positionIsBeingChanged);
var stableTo = pointsTo.filter(d => !d.positionIsBeingChanged);
var toEndScale = getScaleDiffFn(stableFrom, stableTo);
var toStartScale = getScaleDiffFn(stableTo, stableFrom);
var interpolators = [];
remainingIds.forEach((id, i) => {
var indexFrom = idsFrom.indexOf(id);
var indexTo = idsTo.indexOf(id);
if (
i === 0 &&
(indexFrom > 0 || indexTo > 0)
) {
interpolators.push(getEndingInterpolator({
isCubic: false,
polylineFrom: pointsFrom.slice(0, indexFrom + 1),
polylineTo: pointsTo.slice(0, indexTo + 1),
toOppositeScale: indexTo === 0 ? toEndScale : toStartScale
}));
}
if (i > 0) {
var prevIndexFrom = idsFrom.indexOf(remainingIds[i - 1]);
var prevIndexTo = idsTo.indexOf(remainingIds[i - 1]);
if (indexFrom - prevIndexFrom > 1 || indexTo - prevIndexTo > 1) {
interpolators.push(getInnerInterpolator({
isCubic: false,
polylineFrom: pointsFrom.slice(prevIndexFrom, indexFrom + 1),
polylineTo: pointsTo.slice(prevIndexTo, indexTo + 1)
}));
}
}
interpolators.push(getRemainingPointInterpolator({
pointFrom: pointsFrom[indexFrom],
pointTo: pointsTo[indexTo]
}));
if (
i === remainingIds.length - 1 &&
(pointsFrom.length - indexFrom - 1 > 0 ||
pointsTo.length - indexTo - 1 > 0)
) {
interpolators.push(getEndingInterpolator({
isCubic: false,
polylineFrom: pointsFrom.slice(indexFrom),
polylineTo: pointsTo.slice(indexTo),
toOppositeScale: pointsTo.length - indexTo === 1 ? toEndScale : toStartScale
}));
}
});
if (interpolators.length === 0 && (
pointsTo.length > 0 && remainingIds.length === 0 ||
pointsFrom.length > 0 && remainingIds.length === 0
)) {
interpolators.push(getNonRemainingPathInterpolator({
isCubic: false,
polylineFrom: pointsFrom.slice(0),
polylineTo: pointsTo.slice(0)
}));
}
return (t: number) => {
var intermediate: XPoint[] = [];
interpolators.forEach((interpolator) => {
var points = interpolator(t);
push(intermediate, points);
});
return intermediate;
};
}
/**
* Creates intermediate cubic points array, so that the number of points
* remains the same and added or excluded points are situated between
* existing points.
*/
function getCubicInterpolator(pointsFrom: XPoint[], pointsTo: XPoint[]) {
for (var i = 2; i < pointsFrom.length - 1; i += 3) {
pointsFrom[i - 1].isCubicControl = true;
pointsFrom[i].isCubicControl = true;
}
for (i = 2; i < pointsTo.length - 1; i += 3) {
pointsTo[i - 1].isCubicControl = true;
pointsTo[i].isCubicControl = true;
}
// Replace interpolated points sequence with straight segment
// TODO: Continue unfinished transition of ending points.
pointsFrom = pointsFrom.filter(d => !d.isInterpolated);
var d, p;
for (i = pointsFrom.length - 2; i >= 0; i--) {
p = pointsFrom[i + 1];
d = pointsFrom[i];
if (!d.isCubicControl && !p.isCubicControl) {
pointsFrom.splice(
i + 1,
0,
getBezierPoint(1 / 3, p, d),
getBezierPoint(2 / 3, p, d)
);
pointsFrom[i + 1].isCubicControl = true;
pointsFrom[i + 2].isCubicControl = true;
}
}
// NOTE: Suppose data is already sorted by X.
// var anchorsFrom = pointsFrom.filter(d => !d.isCubicControl);
// var anchorsTo = pointsTo.filter(d => !d.isCubicControl);
var anchorsFrom = pointsFrom.filter((d, i) => i % 3 === 0);
var anchorsTo = pointsTo.filter((d, i) => i % 3 === 0);
var idsFrom = anchorsFrom.map(d => d.id);
var idsTo = anchorsTo.map(d => d.id);
var indicesFrom = idsFrom.reduce((memo, id) => ((memo[id] = pointsFrom.findIndex(d => d.id === id), memo)), {});
var indicesTo = idsTo.reduce((memo, id) => ((memo[id] = pointsTo.findIndex(d => d.id === id), memo)), {});
var remainingIds = idsFrom
.filter(id => idsTo.indexOf(id) >= 0);
//
// Determine start and end scales difference to apply
// to initial target position of newly added points
// (or end position of deleted points)
var stableFrom = anchorsFrom.filter(d => !d.positionIsBeingChanged);
var stableTo = anchorsTo.filter(d => !d.positionIsBeingChanged);
var toEndScale = getScaleDiffFn(stableFrom, stableTo);
var toStartScale = getScaleDiffFn(stableTo, stableFrom);
var interpolators = [];
remainingIds.forEach((id, i) => {
var indexFrom = indicesFrom[id];
var indexTo = indicesTo[id];
if (
i === 0 &&
(indexFrom > 0 || indexTo > 0)
) {
interpolators.push(getEndingInterpolator({
polylineFrom: pointsFrom.slice(0, indexFrom + 1),
polylineTo: pointsTo.slice(0, indexTo + 1),
toOppositeScale: indexTo === 0 ? toEndScale : toStartScale,
isCubic: true
}));
}
if (i > 0) {
var prevIndexFrom = indicesFrom[remainingIds[i - 1]];
var prevIndexTo = indicesTo[remainingIds[i - 1]];
if (indexFrom - prevIndexFrom > 3 || indexTo - prevIndexTo > 3) {
interpolators.push(getInnerInterpolator({
polylineFrom: pointsFrom.slice(prevIndexFrom, indexFrom + 1),
polylineTo: pointsTo.slice(prevIndexTo, indexTo + 1),
isCubic: true
}));
} else {
interpolators.push(getControlsBetweenRemainingInterpolator({
polylineFrom: pointsFrom.slice(prevIndexFrom, indexFrom + 1),
polylineTo: pointsTo.slice(prevIndexTo, indexTo + 1)
}));
}
}
interpolators.push(getRemainingPointInterpolator({
pointFrom: pointsFrom[indexFrom],
pointTo: pointsTo[indexTo]
}));
if (
i === remainingIds.length - 1 &&
(pointsFrom.length - indexFrom - 1 > 0 ||
pointsTo.length - indexTo - 1 > 0)
) {
interpolators.push(getEndingInterpolator({
polylineFrom: pointsFrom.slice(indexFrom),
polylineTo: pointsTo.slice(indexTo),
toOppositeScale: pointsTo.length - indexTo === 1 ? toEndScale : toStartScale,
isCubic: true
}));
}
});
if (interpolators.length === 0 && (
pointsTo.length > 0 && remainingIds.length === 0 ||
pointsFrom.length > 0 && remainingIds.length === 0
)) {
interpolators.push(getNonRemainingPathInterpolator({
polylineFrom: pointsFrom.slice(0),
polylineTo: pointsTo.slice(0),
isCubic: true
}));
}
return (t: number) => {
var intermediate: XPoint[] = [];
interpolators.forEach(ipl => {
var points = ipl(t);
push(intermediate, points);
});
return intermediate;
};
}
function getEndingInterpolator({polylineFrom, polylineTo, isCubic, toOppositeScale}) {
var polyline = (polylineFrom.length > polylineTo.length ? polylineFrom : polylineTo);
var decreasing = (polylineTo.length === 1);
var isLeftEnding = (polylineFrom[0].id !== polylineTo[0].id);
var rightToLeft = Boolean(isLeftEnding !== decreasing);
return (t) => {
var interpolated = (isCubic ? interpolateCubicEnding : interpolateEnding)({
t, polyline,
decreasing,
rightToLeft
});
if (decreasing === rightToLeft) {
interpolated.shift();
} else {
interpolated.pop();
}
var diffed = interpolated.map(toOppositeScale);
var points = interpolatePoints(diffed, interpolated, (decreasing ? 1 - t : t));
points.forEach(d => d.positionIsBeingChanged = true);
return points;
};
}
function getInnerInterpolator({polylineFrom, polylineTo, isCubic}) {
var oldCount = polylineFrom.length;
var newCount = polylineTo.length;
if (newCount !== oldCount) {
var decreasing = newCount < oldCount;
var smallerPolyline = decreasing ? polylineTo : polylineFrom;
var biggerPolyline = decreasing ? polylineFrom : polylineTo;
var filledPolyline = (isCubic ? fillSmallerCubicLine : fillSmallerPolyline)({
smallerPolyline,
biggerPolyline,
decreasing
});
var biggerInnerPoints = biggerPolyline.slice(1, biggerPolyline.length - 1);
var filledInnerPoints = filledPolyline.slice(1, filledPolyline.length - 1);
return (t) => {
var points = interpolatePoints(
filledInnerPoints,
biggerInnerPoints,
(decreasing ? 1 - t : t)
);
points.forEach(d => d.positionIsBeingChanged = true);
return points;
};
} else {
var innerPointsFrom = polylineFrom.slice(1, polylineFrom.length - 1);
var innerPointsTo = polylineTo.slice(1, polylineTo.length - 1);
return (t) => {
var points = interpolatePoints(
innerPointsFrom,
innerPointsTo,
t
);
points.forEach(d => d.positionIsBeingChanged = true);
return points;
};
}
}
function getRemainingPointInterpolator({pointFrom, pointTo}) {
return (t) => {
return [interpolatePoint(pointFrom, pointTo, t)];
};
}
function getControlsBetweenRemainingInterpolator({polylineFrom, polylineTo}) {
return (t) => {
return interpolatePoints(polylineFrom.slice(1, 3), polylineTo.slice(1, 3), t);
};
}
function getNonRemainingPathInterpolator({polylineFrom, polylineTo, isCubic}) {
var decreasing = polylineTo.length === 0;
var rightToLeft = decreasing;
var polyline = (decreasing ? polylineFrom : polylineTo);
return (t) => {
var points = (isCubic ? interpolateCubicEnding : interpolateEnding)({
t,
polyline,
decreasing,
rightToLeft
});
points.forEach((d, i) => {
if (i > 0) {
d.positionIsBeingChanged = true;
}
});
return points;
};
}
function push(target, items) {
return Array.prototype.push.apply(target, items);
}
function interpolateValue(a, b, t) {
if (b === undefined) {
return a;
}
if (typeof b === 'number') {
return (a + t * (b - a));
}
return b;
}
function interpolatePoint(a, b, t) {
if (a === b) {
return b;
}
var c = {} as XPoint;
var props = Object.keys(a);
props.forEach((k) => c[k] = interpolateValue(a[k], b[k], t));
if (b.id !== undefined) {
c.id = b.id;
}
return c;
}
function interpolatePoints(pointsFrom, pointsTo, t) {
var result = pointsFrom.map((a, i) => interpolatePoint(a, pointsTo[i], t));
return result;
}
/**
* Returns a polyline with points that move along line
* from start point to full line (or vice versa).
*/
function interpolateEnding({t, polyline, decreasing, rightToLeft}) {
var reverse = Boolean(decreasing) !== Boolean(rightToLeft);
var result = (function getLinePiece(t, line) {
var q = 0;
if (t > 0) {
var distance = [0];
var totalDistance = 0;
for (var i = 1, x, y, x0, y0, d; i < line.length; i++) {
x0 = line[i - 1].x;
y0 = line[i - 1].y;
x = line[i].x;
y = line[i].y;
d = Math.sqrt((x - x0) * (x - x0) + (y - y0) * (y - y0));
totalDistance += d;
distance.push(totalDistance);
}
var passedDistance = t * totalDistance;
for (i = 1; i < distance.length; i++) {
if (passedDistance <= distance[i]) {
q = Math.min(1, (i - 1 +
(passedDistance - distance[i - 1]) /
(distance[i] - distance[i - 1])) /
(line.length - 1)
);
break;
}
}
}
var existingCount = Math.floor((line.length - 1) * q) + 1;
var tempCount = line.length - existingCount;
var tempStartIdIndex = existingCount;
var result = line.slice(0, existingCount);
if (q < 1) {
var qi = (q * (line.length - 1)) % 1;
var midPt = interpolatePoint(
line[existingCount - 1],
line[existingCount],
qi
);
push(result, utils.range(tempCount).map((i) => Object.assign(
{}, midPt,
{
id: line[tempStartIdIndex + i].id,
isInterpolated: true
}
)));
}
return result;
})(
(decreasing ? 1 - t : t),
(reverse ? polyline.slice(0).reverse() : polyline)
);
if (reverse) {
result.reverse();
}
return result;
}
/**
* Returns a cubic line with points that move along line
* from start point to full line (or vice versa).
*/
function interpolateCubicEnding({t, polyline, decreasing, rightToLeft}) {
var reverse = Boolean(decreasing) !== Boolean(rightToLeft);
var result = (function getLinePiece(t, line) {
var pointsCount = (line.length - 1) / 3 + 1;
var q = 0;
if (t > 0) {
var distance = [0];
var totalDistance = 0;
for (
var i = 1, x1, y1, x0, y0, cx0, cy0, cx1, cy1, d;
i < pointsCount;
i++
) {
x0 = line[i * 3 - 3].x;
y0 = line[i * 3 - 3].y;
cx0 = line[i * 3 - 2].x;
cy0 = line[i * 3 - 2].y;
cx1 = line[i * 3 - 1].x;
cy1 = line[i * 3 - 1].y;
x1 = line[i * 3].x;
y1 = line[i * 3].y;
d = (getDistance(x0, y0, cx0, cy0) +
getDistance(cx0, cy0, cx1, cy1) +
getDistance(cx1, cy1, x1, y1) +
getDistance(x1, y1, x0, y0)
) / 2;
totalDistance += d;
distance.push(totalDistance);
}
var passedDistance = t * totalDistance;
for (i = 1; i < distance.length; i++) {
if (passedDistance <= distance[i]) {
q = Math.min(1, (i - 1 +
(passedDistance - distance[i - 1]) /
(distance[i] - distance[i - 1])) /
(pointsCount - 1)
);
break;
}
}
}
var existingCount = Math.floor((pointsCount - 1) * q) + 1;
var tempCount = pointsCount - existingCount;
var tempStartIdIndex = existingCount * 3;
var result = line.slice(0, (existingCount - 1) * 3 + 1);
if (q < 1) {
var qi = (q * (pointsCount - 1)) % 1;
var spl = splitCubicSegment(
qi,
line.slice((existingCount - 1) * 3, existingCount * 3 + 1)
);
var newPiece = spl.slice(1, 4);
newPiece.forEach(p => p.isInterpolated = true);
newPiece[2].id = line[tempStartIdIndex].id;
push(result, newPiece);
utils.range(1, tempCount).forEach((i) => {
push(result, [
{x: newPiece[2].x, y: newPiece[2].y, isCubicControl: true, isInterpolated: true},
{x: newPiece[2].x, y: newPiece[2].y, isCubicControl: true, isInterpolated: true},
Object.assign(
{}, newPiece[2],
{
id: line[tempStartIdIndex + i * 3].id,
isInterpolated: true
}
)
]);
});
}
return result;
})(
(decreasing ? 1 - t : t),
(reverse ? polyline.slice(0).reverse() : polyline)
);
if (reverse) {
result.reverse();
}
return result;
}
/**
* Returns a polyline filled with points, so that number of points
* becomes the same on both start and end polylines.
*/
function fillSmallerPolyline({smallerPolyline, biggerPolyline, decreasing}) {
var smallerSegCount = smallerPolyline.length - 1;
var biggerSegCount = biggerPolyline.length - 1;
var minSegmentPointsCount = Math.floor(biggerSegCount / smallerSegCount) + 1;
var restPointsCount = biggerSegCount % smallerSegCount;
var segmentsPointsCount = utils.range(smallerSegCount)
.map(i => (minSegmentPointsCount + Number(i < restPointsCount)));
var result = [smallerPolyline[0]];
var smallPtIndex = 1;
segmentsPointsCount.forEach((segPtCount) => {
utils.range(1, segPtCount).forEach(i => {
var newPt;
if (i === segPtCount - 1) {
newPt = Object.assign({}, smallerPolyline[smallPtIndex]);
if (!decreasing) {
newPt.id = biggerPolyline[result.length].id;
}
} else {
newPt = interpolatePoint(
smallerPolyline[smallPtIndex - 1],
smallerPolyline[smallPtIndex],
(i / (segPtCount - 1))
);
newPt.id = biggerPolyline[result.length].id;
if (decreasing) {
newPt.isInterpolated = true;
}
}
result.push(newPt);
});
smallPtIndex++;
});
return result;
}
/**
* Returns a cubic line filled with points, so that number of points
* becomes the same on both start and end cubic lines.
*/
function fillSmallerCubicLine({smallerPolyline, biggerPolyline, decreasing}) {
var smallerSegCount = (smallerPolyline.length - 1) / 3;
var biggerSegCount = (biggerPolyline.length - 1) / 3;
var minSegmentPointsCount = Math.floor(biggerSegCount / smallerSegCount) + 1;
var restPointsCount = biggerSegCount % smallerSegCount;
var segmentsPointsCount = utils.range(smallerSegCount)
.map(i => (minSegmentPointsCount + Number(i < restPointsCount)));
var result = [smallerPolyline[0]];
var smallPtIndex = 3;
segmentsPointsCount.forEach((segPtCount) => {
if (segPtCount > 2) {
var spl = multipleSplitCubicSegment(
utils.range(1, segPtCount - 1).map(i => i / (segPtCount - 1)),
smallerPolyline.slice(smallPtIndex - 3, smallPtIndex + 1)
);
utils.range(segPtCount - 2)
.forEach(i => spl[(i + 1) * 3].id = biggerPolyline[result.length - 1 + i * 3].id);
if (decreasing) {
spl.forEach((p, i) => {
if (i > 0 && i < spl.length - 1) {
p.isInterpolated = true;
}
});
}
push(result, spl.slice(1));
} else {
var newC0 = Object.assign({}, smallerPolyline[smallPtIndex - 2]);
var newC1 = Object.assign({}, smallerPolyline[smallPtIndex - 1]);
var newPt = Object.assign({}, smallerPolyline[smallPtIndex]);
if (!decreasing) {
newPt.id = biggerPolyline[result.length + 2].id;
}
result.push(newC0, newC1, newPt);
}
smallPtIndex += 3;
});
return result;
}
/**
* Returns a function which moves a point from it's scale
* to opposite scale (e.g. from start scale to end scale).
*/
function getScaleDiffFn(points1, points2) {
// Find remaining points with predictable position
var src = [];
var dst = [];
var i, j, a, b, matchJ = 0;
var len1 = points1.length;
var len2 = points2.length;
for (i = 0; i < len1; i++) {
a = points1[i];
for (j = matchJ; j < len2; j++) {
b = points2[j];
if (a.id === b.id) {
matchJ = j + 1;
src.push(a);
dst.push(b);
break;
}
}
}
if (src.length < 1 || dst.length < 1) {
// Applying scale difference will not be possible
return (d => d);
}
var numProps = Object.keys(src[0])
.filter(prop => typeof src[0][prop] === 'number')
.filter(prop => prop !== 'id');
var propDiffs = {};
var createPropDiffFn = (a0, b0, a, b) => (c0) => (
b +
(c0 - b0) *
(b - a) /
(b0 - a0)
);
var createSimpleDiffFn = (a0, a) => (c0) => (c0 - a0 + a);
numProps.forEach(prop => {
var a0 = src[0][prop];
var a = dst[0][prop];
for (var i = src.length - 1, b0, b; i > 0; i--) {
b0 = src[i][prop];
if (b0 !== a0) {
b = dst[i][prop];
propDiffs[prop] = createPropDiffFn(a0, b0, a, b);
return;
}
}
propDiffs[prop] = createSimpleDiffFn(a0, a);
});
return (c0) => {
var c = Object.assign({}, c0);
numProps.forEach(p => {
c[p] = propDiffs[p](c0[p]);
});
return c;
};
}
function getDistance(x0, y0, x, y) {
return Math.sqrt((x - x0) * (x - x0) + (y - y0) * (y - y0));
}
function splitCubicSegment(t: number, [p0, c0, c1, p1]: XPoint[]) {
var seg = split(t, p0, c0, c1, p1) as XPoint[];
[seg[1], seg[2], seg[4], seg[5]].forEach(c => c.isCubicControl = true);
Object.keys(p1).forEach((k) => {
if (k !== 'x' && k !== 'y' && k !== 'id') {
seg[3][k] = interpolateValue(p0[k], p1[k], t);
}
});
return seg;
}
function multipleSplitCubicSegment(ts, seg) {
var result = [seg[0]];
for (var i = 0, t, spl; i < ts.length; i++) {
t = i === 0 ? ts[0] : ts[i] / (1 - ts[i - 1]);
spl = splitCubicSegment(t, seg);
push(result, spl.slice(1, 4));
seg = spl.slice(3);
}
push(result, seg.slice(1));
return result;
} | the_stack |
import colorTokens from "@kaizen/design-tokens/tokens/color.json"
import React, { useCallback, useRef } from "react"
import { Tooltip } from "@kaizen/draft-tooltip"
import { withDesign } from "storybook-addon-designs"
import { TextField } from "@kaizen/draft-form"
import lockIcon from "@kaizen/component-library/icons/lock.icon.svg"
import userIcon from "@kaizen/component-library/icons/user.icon.svg"
import { figmaEmbed } from "../../../storybook/helpers"
import { CATEGORIES, SUB_CATEGORIES } from "../../../storybook/constants"
const ExampleContainer: React.FunctionComponent = ({ children }) => (
<div style={{ width: "98%", margin: "1%" }}>{children}</div>
)
const ReversedBg = {
backgrounds: {
default: "Purple 700",
},
}
export default {
title: `${CATEGORIES.components}/${SUB_CATEGORIES.form}/Text Field`,
component: TextField,
parameters: {
docs: {
description: {
component: 'import { TextField } from "@kaizen/draft-form"',
},
},
...figmaEmbed(
"https://www.figma.com/file/GMxm8rvDCbj0Xw3TQWBZ8b/UI-Kit-Zen?node-id=14363%3A67837"
),
},
decorators: [withDesign],
}
export const DefaultKaizenSiteDemo = () => (
<ExampleContainer>
<TextField
id="email"
inputType="email"
inputValue=""
labelText={
<span>
This is a label with a{" "}
<a href="http://google.com" target="_blank">
link
</a>
</span>
}
placeholder="Please enter your email"
onChange={() => undefined}
description="Valid email addresses must have an @ and a suffix"
/>
</ExampleContainer>
)
DefaultKaizenSiteDemo.storyName = "Default (Kaizen Site Demo)"
export const DefaultInline = () => (
<ExampleContainer>
<TextField
id="email"
inputType="email"
inputValue=""
labelText="Email"
placeholder="Please enter your email"
onChange={() => undefined}
inline={true}
description="Valid email addresses must have an @ and a suffix"
/>
</ExampleContainer>
)
DefaultInline.storyName = "Default, Inline"
export const DefaultIcon = () => (
<ExampleContainer>
<TextField
id="email"
inputType="email"
inputValue=""
labelText="Email"
placeholder="Please enter your email"
onChange={() => undefined}
icon={userIcon}
/>
</ExampleContainer>
)
DefaultIcon.storyName = "Default, Icon"
export const DefaultDisabled = () => (
<ExampleContainer>
<TextField
id="email"
inputType="email"
inputValue=""
labelText="Email"
placeholder="Please enter your email"
onChange={() => undefined}
disabled={true}
/>
</ExampleContainer>
)
DefaultDisabled.storyName = "Default, Disabled"
export const DefaultDisabledWValue = () => (
<ExampleContainer>
<TextField
id="email"
inputType="email"
inputValue="craig@cultureamp.com"
labelText="Email"
placeholder="Please enter your email"
onChange={() => undefined}
disabled={true}
/>
</ExampleContainer>
)
DefaultDisabledWValue.storyName = "Default, Disabled w/ value"
export const DefaultDisabledIcon = () => (
<ExampleContainer>
<TextField
id="email"
inputType="email"
inputValue=""
labelText="Email"
placeholder="Please enter your email"
onChange={() => undefined}
icon={userIcon}
disabled={true}
/>
</ExampleContainer>
)
DefaultDisabledIcon.storyName = "Default, Disabled + Icon"
export const DefaultSuccess = () => (
<ExampleContainer>
<TextField
id="email"
inputType="email"
inputValue="rod@cultureamp.com"
labelText="Email"
placeholder="Please enter your email"
onChange={() => undefined}
status="success"
/>
</ExampleContainer>
)
DefaultSuccess.storyName = "Default, Success"
export const DefaultSuccessIcon = () => (
<ExampleContainer>
<TextField
id="email"
inputType="email"
inputValue="marc@cultureamp.com"
labelText="Email"
placeholder="Please enter your email"
onChange={() => undefined}
icon={userIcon}
status="success"
/>
</ExampleContainer>
)
DefaultSuccessIcon.storyName = "Default, Success + Icon"
export const DefaultError = () => (
<ExampleContainer>
<TextField
id="email"
inputType="email"
inputValue="super_cool999@hotmail.com"
labelText="Email"
placeholder="Please enter your email"
onChange={() => undefined}
status="error"
validationMessage="Your email address looks like it’s from 1996."
/>
</ExampleContainer>
)
DefaultError.storyName = "Default, Error"
export const DefaultErrorLong = () => (
<ExampleContainer>
<TextField
id="email"
inputType="email"
inputValue="super_cool999@hotmail.com"
labelText="Email"
placeholder="Please enter your email"
onChange={() => undefined}
status="error"
validationMessage="Your email address looks like it’s from 1996. This is a long error message for testing purposes."
/>
</ExampleContainer>
)
DefaultErrorLong.storyName = "Default, Error, long"
export const DefaultErrorIcon = () => (
<ExampleContainer>
<TextField
id="email"
inputType="email"
inputValue="hello@oops"
labelText="Email"
placeholder="Please enter your email"
onChange={() => undefined}
icon={userIcon}
status="error"
/>
</ExampleContainer>
)
DefaultErrorIcon.storyName = "Default, Error + Icon"
export const DefaultMultipleFields = () => (
<ExampleContainer>
<TextField
id="email"
inputType="email"
inputValue="mackenzie@example.com"
labelText="Email"
placeholder="Please enter your email"
onChange={() => undefined}
icon={userIcon}
/>
<TextField
id="password"
inputType="password"
inputValue="123445555"
labelText="Password"
placeholder="Please enter your password"
onChange={() => undefined}
icon={lockIcon}
/>
</ExampleContainer>
)
DefaultMultipleFields.storyName = "Default, Multiple Fields"
export const DefaultMultipleFieldsError = () => (
<ExampleContainer>
<TextField
id="email"
status="error"
inputType="email"
inputValue="mackenzie@example.com"
labelText="Email"
placeholder="Please enter your email"
onChange={() => undefined}
icon={userIcon}
validationMessage="Please enter a valid email address"
/>
<TextField
id="password"
status="error"
inputType="password"
inputValue="123445555"
labelText="Password"
placeholder="Please enter your password"
onChange={() => undefined}
icon={lockIcon}
validationMessage="The password entered does not correctly match the provided email address"
/>
</ExampleContainer>
)
DefaultMultipleFieldsError.storyName = "Default, Multiple Fields, Error"
export const Reversed = () => (
<ExampleContainer>
<TextField
id="email"
inputType="email"
inputValue=""
labelText="Email"
placeholder="Please enter your email"
onChange={() => undefined}
reversed={true}
/>
</ExampleContainer>
)
Reversed.parameters = {
...ReversedBg,
}
export const ReversedIcon = () => (
<ExampleContainer>
<TextField
id="email"
inputType="email"
inputValue=""
labelText="Email"
placeholder="Please enter your email"
onChange={() => undefined}
reversed={true}
icon={userIcon}
/>
</ExampleContainer>
)
ReversedIcon.storyName = "Reversed, Icon"
ReversedIcon.parameters = { ...ReversedBg }
export const ReversedDisabled = () => (
<ExampleContainer>
<TextField
id="email"
inputType="email"
inputValue=""
labelText="Email"
placeholder="Please enter your email"
onChange={() => undefined}
reversed={true}
disabled={true}
/>
</ExampleContainer>
)
ReversedDisabled.storyName = "Reversed, Disabled"
ReversedDisabled.parameters = { ...ReversedBg }
export const ReversedDisabledWValue = () => (
<ExampleContainer>
<TextField
id="email"
inputType="email"
inputValue="craig@cultureamp.com"
labelText="Email"
placeholder="Please enter your email"
onChange={() => undefined}
reversed={true}
disabled={true}
/>
</ExampleContainer>
)
ReversedDisabledWValue.storyName = "Reversed, Disabled w/ value"
ReversedDisabledWValue.parameters = { ...ReversedBg }
export const ReversedDisabledIcon = () => (
<ExampleContainer>
<TextField
id="email"
inputType="email"
inputValue=""
labelText="Email"
placeholder="Please enter your email"
onChange={() => undefined}
reversed={true}
icon={userIcon}
disabled={true}
/>
</ExampleContainer>
)
ReversedDisabledIcon.storyName = "Reversed, Disabled + Icon"
ReversedDisabledIcon.parameters = { ...ReversedBg }
export const ReversedSuccess = () => (
<ExampleContainer>
<TextField
id="email"
inputType="email"
inputValue="seb@cultureamp.com"
labelText="Email"
placeholder="Please enter your email"
onChange={() => undefined}
reversed={true}
status="success"
/>
</ExampleContainer>
)
ReversedSuccess.storyName = "Reversed, Success"
ReversedSuccess.parameters = { ...ReversedBg }
export const ReversedSuccessIcon = () => (
<ExampleContainer>
<TextField
id="email"
inputType="email"
inputValue="rod@cultureamp.com"
labelText="Email"
placeholder="Please enter your email"
onChange={() => undefined}
icon={userIcon}
reversed={true}
status="success"
/>
</ExampleContainer>
)
ReversedSuccessIcon.storyName = "Reversed, Success + Icon"
ReversedSuccessIcon.parameters = { ...ReversedBg }
export const ReversedError = () => (
<ExampleContainer>
<TextField
id="email"
inputType="email"
inputValue="hello@oops"
labelText="Email"
placeholder="Please enter your email"
onChange={() => undefined}
reversed={true}
status="error"
validationMessage="Your email address looks like it’s from 1996"
/>
</ExampleContainer>
)
ReversedError.storyName = "Reversed, Error"
ReversedError.parameters = { ...ReversedBg }
export const ReversedDescription = () => (
<ExampleContainer>
<TextField
id="email"
inputType="email"
inputValue="hello@hello.hello"
labelText="Email"
placeholder="Please enter your email"
onChange={() => undefined}
reversed={true}
description="Valid email addresses must have an @ and a suffix"
/>
</ExampleContainer>
)
ReversedDescription.storyName = "Reversed, Description"
ReversedDescription.parameters = { ...ReversedBg }
export const ReversedErrorIcon = () => (
<ExampleContainer>
<TextField
id="email"
inputType="email"
inputValue="hello@oops"
labelText="Email"
placeholder="Please enter your email"
onChange={() => undefined}
icon={userIcon}
reversed={true}
status="error"
validationMessage="Your email address looks like it’s from 1996"
/>
</ExampleContainer>
)
ReversedErrorIcon.storyName = "Reversed, Error + Icon"
ReversedErrorIcon.parameters = { ...ReversedBg }
export const ReversedMultipleFields = () => (
<ExampleContainer>
<TextField
id="email"
inputType="email"
inputValue="mackenzie@example.com"
labelText="Email"
placeholder="Please enter your email"
onChange={() => undefined}
icon={userIcon}
reversed={true}
/>
<TextField
id="password"
inputType="password"
inputValue="123445555"
labelText="Password"
placeholder="Please enter your password"
onChange={() => undefined}
icon={lockIcon}
reversed={true}
/>
</ExampleContainer>
)
ReversedMultipleFields.storyName = "Reversed, Multiple Fields"
ReversedMultipleFields.parameters = { ...ReversedBg }
export const ReversedMultipleFieldsWError = () => (
<ExampleContainer>
<TextField
id="email"
status="error"
inputType="email"
inputValue="mackenzie@example.com"
labelText="Email"
placeholder="Please enter your email"
onChange={() => undefined}
icon={userIcon}
validationMessage="Please enter a valid email address"
reversed={true}
/>
<TextField
id="password"
status="error"
inputType="password"
inputValue="123445555"
labelText="Password"
placeholder="Please enter your password"
onChange={() => undefined}
icon={lockIcon}
validationMessage="The password entered does not correctly match the provided email addrress"
reversed={true}
/>
</ExampleContainer>
)
ReversedMultipleFieldsWError.storyName = "Reversed, Multiple Fields w/ Error"
ReversedMultipleFieldsWError.parameters = { ...ReversedBg }
export const DefaultFocusBlurEvents = () => (
<ExampleContainer>
<TextField
id="email"
inputType="email"
inputValue=""
labelText={
<span>
This is a label with a{" "}
<a href="http://google.com" target="_blank">
link
</a>
</span>
}
placeholder="Please enter your email"
onFocus={() => undefined}
onBlur={() => undefined}
onChange={() => undefined}
description="Valid email addresses must have an @ and a suffix"
/>
</ExampleContainer>
)
DefaultFocusBlurEvents.storyName = "Default, Focus/Blur events"
// More info about uncontrolled components:
// https://reactjs.org/docs/uncontrolled-components.html
export const DefaultUncontrolled = () => {
const ref = useRef<HTMLInputElement>(null)
// This is just to confirm that the ref is working correctly
const onSubmit = useCallback(e => {
e.preventDefault()
alert(`Entered text: ${ref.current && ref.current.value}`)
}, [])
return (
<ExampleContainer>
<form onSubmit={onSubmit}>
<TextField
id="uncontrolled"
inputType="text"
inputRef={ref}
labelText="This is an uncontrolled text field"
placeholder="Placeholder text"
description="Press ENTER to test the inputRef property"
/>
</form>
</ExampleContainer>
)
}
DefaultUncontrolled.storyName = "Default, Uncontrolled"
export const DefaultWithHtmlDescription = () => {
const description = (
<>
The description may contain a link to further details - we recommended
opening the link in a new tab with an
<span style={{ position: "relative" }}>
<Tooltip position="above" text="opens in new tab">
<a
href="https://cultureamp.design/guidelines/link-vs-button/#opens-in-new-tab-tooltip"
target="_blank"
>
"opens in new tab" tooltip{" "}
</a>
</Tooltip>
</span>
</>
)
return (
<ExampleContainer>
<TextField
id="default-with-html-description"
labelText="This a text field with a HTML description"
description={description}
/>
</ExampleContainer>
)
}
DefaultWithHtmlDescription.storyName = "Default w HTML description"
export const DefaultWithDescriptionAndErrorMessage = () => (
<ExampleContainer>
<TextField
id="email"
status="error"
inputValue="testing 1 2 3"
labelText="Label"
validationMessage="A cool validation message"
description="This is a description"
/>
</ExampleContainer>
)
DefaultWithDescriptionAndErrorMessage.storyName =
"Default w description and error message" | the_stack |
* @module CartesianGeometry
*/
import { Geometry } from "../Geometry";
import { Point4d } from "../geometry4d/Point4d";
import { Angle } from "./Angle";
import { Ray3d } from "./Ray3d";
import { HasZ, XAndY, XYAndZ, XYZProps } from "./XYZProps";
/**
* * `XYZ` is a minimal object containing x,y,z and operations that are meaningful without change in both point and vector.
* * `XYZ` is not instantiable.
* * The derived (instantiable) classes are
* * `Point3d`
* * `Vector3d`
* @public
*/
export class XYZ implements XYAndZ {
/** x coordinate */
public x: number;
/** y coordinate */
public y: number;
/** z coordinate */
public z: number;
/**
* Set the x,y,z parts.
* @param x (optional) x part
* @param y (optional) y part
* @param z (optional) z part
*/
public set(x: number = 0, y: number = 0, z: number = 0) { this.x = x; this.y = y; this.z = z; }
/** Set the x,y,z parts to zero. */
public setZero() { this.x = 0; this.y = 0; this.z = 0; }
protected constructor(x: number = 0, y: number = 0, z: number = 0) { this.x = x; this.y = y; this.z = z; }
/** Type guard for XAndY.
* @note this will return true for an XYAndZ. If you wish to distinguish between the two, call isXYAndZ first.
*/
public static isXAndY(arg: any): arg is XAndY { return arg.x !== undefined && arg.y !== undefined; }
/** Type guard to determine whether an object has a member called "z" */
public static hasZ(arg: any): arg is HasZ { return arg.z !== undefined; }
/** Type guard for XYAndZ. */
public static isXYAndZ(arg: any): arg is XYAndZ { return this.isXAndY(arg) && this.hasZ(arg); }
/** Test if arg is any of:
* * XAndY
* * XYAndZ
* * [number,number]
* * [number,number,number]
*/
public static isAnyImmediatePointType(arg: any): boolean {
return Point3d.isXAndY(arg) || Geometry.isNumberArray(arg, 2);
}
/** Look for (in order) an x coordinate present as:
* * arg.x
* * arg[0]
*/
public static accessX(arg: any, defaultValue?: number): number | undefined {
if (arg.x !== undefined)
return arg.x;
if (Array.isArray(arg) && arg.length > 0 && Number.isFinite(arg[0]))
return arg[0];
return defaultValue;
}
/** Look for (in order) an x coordinate present as:
* * arg.y
* * arg[1]
*/
public static accessY(arg: any, defaultValue?: number): number | undefined {
if (arg.y !== undefined)
return arg.y;
if (Array.isArray(arg) && arg.length > 1 && Number.isFinite(arg[1]))
return arg[1];
return defaultValue;
}
/** Look for (in order) an x coordinate present as:
* * arg.z
* * arg[2]
*/
public static accessZ(arg: any, defaultValue?: number): number | undefined {
if (arg.z !== undefined)
return arg.z;
if (Array.isArray(arg) && arg.length > 2 && Number.isFinite(arg[2]))
return arg[2];
return defaultValue;
}
/**
* Set the x,y,z parts from one of these input types
*
* * XYZ -- copy the x,y,z parts
* * Float64Array -- Copy from indices 0,1,2 to x,y,z
* * XY -- copy the x, y parts and set z=0
*/
public setFrom(other: Float64Array | XAndY | XYAndZ | undefined) {
if (other === undefined) {
this.setZero();
} else if (XYZ.isXAndY(other)) {
this.x = other.x;
this.y = other.y;
this.z = XYZ.hasZ(other) ? other.z : 0;
} else {
this.x = other[0];
this.y = other[1];
this.z = other[2];
}
}
/**
* Set the x,y,z parts from a Point3d.
* This is the same effect as `setFrom(other)` with no pretesting of variant input type
* * Set to zeros if `other` is undefined.
*/
public setFromPoint3d(other?: XYAndZ) {
if (other) {
this.x = other.x;
this.y = other.y;
this.z = other.z;
} else {
this.setZero();
}
}
/**
* Set the x,y,z parts from a Vector3d
* This is the same effect as `setFrom(other)` with no pretesting of variant input type
*/
public setFromVector3d(other: Vector3d) {
if (other) {
this.x = other.x;
this.y = other.y;
this.z = other.z;
} else {
this.setZero();
}
}
/** Returns true if this and other have equal x,y,z parts within Geometry.smallMetricDistance.
* @param other The other XYAndZ to compare
* @param tol The tolerance for the comparison. If undefined, use [[Geometry.smallMetricDistance]]
*/
public isAlmostEqual(other: XYAndZ, tol?: number): boolean {
return Geometry.isSameCoordinate(this.x, other.x, tol)
&& Geometry.isSameCoordinate(this.y, other.y, tol)
&& Geometry.isSameCoordinate(this.z, other.z, tol);
}
/** Return true if this and other have equal x,y,z parts within Geometry.smallMetricDistance. */
public isAlmostEqualXYZ(x: number, y: number, z: number, tol?: number): boolean {
return Geometry.isSameCoordinate(this.x, x, tol)
&& Geometry.isSameCoordinate(this.y, y, tol)
&& Geometry.isSameCoordinate(this.z, z, tol);
}
/** Return true if this and other have equal x,y parts within Geometry.smallMetricDistance. */
public isAlmostEqualXY(other: XAndY, tol?: number): boolean {
return Geometry.isSameCoordinate(this.x, other.x, tol)
&& Geometry.isSameCoordinate(this.y, other.y, tol);
}
/** Return a JSON object as array `[x,y,z]` */
public toJSON(): XYZProps { return this.toArray(); }
/** Return as an array `[x,y,z]` */
public toArray(): number[] { return [this.x, this.y, this.z]; }
/** Return a JSON object as key value pairs `{x: value, y: value, z: value}` */
public toJSONXYZ(): XYZProps { return { x: this.x, y: this.y, z: this.z }; }
/** Pack the x,y,z values in a Float64Array. */
public toFloat64Array(): Float64Array { return Float64Array.of(this.x, this.y, this.z); }
/**
* Set the x,y,z properties from one of several json forms:
*
* * array of numbers: [x,y,z]
* * object with x,y, and (optional) z as numeric properties {x: xValue, y: yValue, z: zValue}
*/
public setFromJSON(json?: XYZProps): void {
if (Array.isArray(json)) {
this.set(json[0] || 0, json[1] || 0, json[2] || 0);
return;
}
if (json) {
this.set(json.x || 0, json.y || 0, json.z || 0);
return;
}
this.set(0, 0, 0);
}
/** Return the distance from this point to other */
public distance(other: XYAndZ): number {
const xDist = other.x - this.x;
const yDist = other.y - this.y;
const zDist = other.z - this.z;
return (Math.sqrt(xDist * xDist + yDist * yDist + zDist * zDist));
}
/** Return squared distance from this point to other */
public distanceSquared(other: XYAndZ): number {
const xDist = other.x - this.x;
const yDist = other.y - this.y;
const zDist = other.z - this.z;
return (xDist * xDist + yDist * yDist + zDist * zDist);
}
/** Return the XY distance from this point to other */
public distanceXY(other: XAndY): number {
const xDist = other.x - this.x;
const yDist = other.y - this.y;
return (Math.sqrt(xDist * xDist + yDist * yDist));
}
/** Return squared XY distance from this point to other */
public distanceSquaredXY(other: XAndY): number {
const xDist = other.x - this.x;
const yDist = other.y - this.y;
return (xDist * xDist + yDist * yDist);
}
/** Return the largest absolute distance between corresponding components */
public maxDiff(other: XYAndZ): number {
return Math.max(Math.abs(this.x - other.x), Math.abs(this.y - other.y), Math.abs(this.z - other.z));
}
/**
* Return the x,y, z component corresponding to 0,1,2.
*/
public at(index: number): number {
if (index < 0.5)
return this.x;
if (index > 1.5)
return this.z;
return this.y;
}
/**
* Return the x,y, z component corresponding to 0,1,2.
*/
public setAt(index: number, value: number): void {
if (index < 0.5)
this.x = value;
if (index > 1.5)
this.z = value;
else
this.y = value;
}
/** Return the index (0,1,2) of the x,y,z component with largest absolute value */
public indexOfMaxAbs(): number {
let index = 0;
let a = Math.abs(this.x);
let b = Math.abs(this.y);
if (b > a) {
index = 1;
a = b;
}
b = Math.abs(this.z);
if (b > a) {
index = 2;
}
return index;
}
/** Return true if the if x,y,z components are all nearly zero to tolerance Geometry.smallMetricDistance */
public get isAlmostZero(): boolean {
return Geometry.isSmallMetricDistance(this.x) && Geometry.isSmallMetricDistance(this.y) && Geometry.isSmallMetricDistance(this.z);
}
/** Return the largest absolute value of any component */
public maxAbs(): number { return Math.max(Math.abs(this.x), Math.abs(this.y), Math.abs(this.z)); }
/** Return the sqrt of the sum of squared x,y,z parts */
public magnitude(): number { return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z); }
/** Return the sum of squared x,y,z parts */
public magnitudeSquared(): number { return this.x * this.x + this.y * this.y + this.z * this.z; }
/** Return sqrt of the sum of squared x,y parts */
public magnitudeXY(): number { return Math.sqrt(this.x * this.x + this.y * this.y); }
/** Return the sum of squared x,y parts */
public magnitudeSquaredXY(): number { return this.x * this.x + this.y * this.y; }
/** exact equality test. */
public isExactEqual(other: XYAndZ): boolean { return this.x === other.x && this.y === other.y && this.z === other.z; }
/** equality test with Geometry.smallMetricDistance tolerance */
public isAlmostEqualMetric(other: XYAndZ): boolean { return this.maxDiff(other) <= Geometry.smallMetricDistance; }
/** add x,y,z from other in place. */
public addInPlace(other: XYAndZ): void { this.x += other.x; this.y += other.y; this.z += other.z; }
/** add x,y,z from other in place. */
public subtractInPlace(other: XYAndZ): void { this.x -= other.x; this.y -= other.y; this.z -= other.z; }
/** add (in place) the scaled x,y,z of other */
public addScaledInPlace(other: XYAndZ, scale: number): void {
this.x += scale * other.x;
this.y += scale * other.y;
this.z += scale * other.z;
}
/** Multiply the x, y, z parts by scale. */
public scaleInPlace(scale: number) { this.x *= scale; this.y *= scale; this.z *= scale; }
/** add to x, y, z parts */
public addXYZInPlace(dx: number = 0.0, dy: number = 0.0, dz: number = 0.0) { this.x += dx; this.y += dy; this.z += dz; }
/** Clone strongly typed as Point3d */
public cloneAsPoint3d() { return Point3d.create(this.x, this.y, this.z); }
/** Return a (full length) vector from this point to other */
public vectorTo(other: XYAndZ, result?: Vector3d): Vector3d {
return Vector3d.create(other.x - this.x, other.y - this.y, other.z - this.z, result);
}
/** Return a multiple of a the (full length) vector from this point to other */
public scaledVectorTo(other: XYAndZ, scale: number, result?: Vector3d): Vector3d {
return Vector3d.create(scale * (other.x - this.x), scale * (other.y - this.y), scale * (other.z - this.z), result);
}
/** Return a unit vector from this vector to other. Return a 000 vector if the input is too small to normalize.
* @param other target of created vector.
* @param result optional result vector.
*/
public unitVectorTo(target: XYAndZ, result?: Vector3d): Vector3d | undefined { return this.vectorTo(target, result).normalize(result); }
/** Freeze this XYZ */
public freeze(): Readonly<this> { return Object.freeze(this); }
/** access x part of XYZProps (which may be .x or [0]) */
public static x(xyz: XYZProps | undefined, defaultValue: number = 0): number{
if (xyz === undefined)
return defaultValue;
if (Array.isArray(xyz))
return xyz[0];
if (xyz.x !== undefined)
return xyz.x;
return defaultValue;
}
/** access x part of XYZProps (which may be .x or [0]) */
public static y(xyz: XYZProps | undefined, defaultValue: number = 0): number{
if (xyz === undefined)
return defaultValue;
if (Array.isArray(xyz))
return xyz[1];
if (xyz.y !== undefined)
return xyz.y;
return defaultValue;
}
/** access x part of XYZProps (which may be .x or [0]) */
public static z(xyz: XYZProps | undefined, defaultValue: number = 0): number{
if (xyz === undefined)
return defaultValue;
if (Array.isArray(xyz))
return xyz[2];
if (xyz.z !== undefined)
return xyz.z;
return defaultValue;
}
}
/** 3D point with `x`,`y`,`z` as properties
* @public
*/
export class Point3d extends XYZ {
/** Constructor for Point3d */
constructor(x: number = 0, y: number = 0, z: number = 0) { super(x, y, z); }
/**
* Convert json to Point3d. Accepted forms are:
* * `[1,2,3]` --- array of numbers
* * array of numbers: [x,y,z]
* * object with x,y, and (optional) z as numeric properties {x: xValue, y: yValue, z: zValue}
* @param json json value.
*/
public static fromJSON(json?: XYZProps): Point3d { const val = new Point3d(); val.setFromJSON(json); return val; }
/** Return a new Point3d with the same coordinates */
public clone(result?: Point3d): Point3d { return Point3d.create(this.x, this.y, this.z, result); }
/** Create a new Point3d with given coordinates
* @param x x part
* @param y y part
* @param z z part
*/
public static create(x: number = 0, y: number = 0, z: number = 0, result?: Point3d): Point3d {
if (result) {
result.x = x;
result.y = y;
result.z = z;
return result;
}
return new Point3d(x, y, z);
}
/** Copy contents from another Point3d, Point2d, Vector2d, or Vector3d */
public static createFrom(data: XYAndZ | XAndY | Float64Array, result?: Point3d): Point3d {
if (data instanceof Float64Array) {
let x = 0;
let y = 0;
let z = 0;
if (data.length > 0)
x = data[0];
if (data.length > 1)
y = data[1];
if (data.length > 2)
z = data[2];
return Point3d.create(x, y, z, result);
}
return Point3d.create(data.x, data.y, XYZ.hasZ(data) ? data.z : 0, result);
}
/**
* Copy x,y,z from
* @param xyzData flat array of xyzxyz for multiple points
* @param pointIndex index of point to extract. This index is multiplied by 3 to obtain starting index in the array.
* @param result optional result point.
*/
public static createFromPacked(xyzData: Float64Array, pointIndex: number, result?: Point3d): Point3d | undefined {
const indexX = pointIndex * 3;
if (indexX >= 0 && indexX + 2 < xyzData.length)
return Point3d.create(xyzData[indexX], xyzData[indexX + 1], xyzData[indexX + 2], result);
return undefined;
}
/**
* Copy and unweight xyzw.
* @param xyzData flat array of x,y,z,w,x,y,z,w for multiple points
* @param pointIndex index of point to extract. This index is multiplied by 4 to obtain starting index in the array.
* @param result optional result point.
*/
public static createFromPackedXYZW(xyzData: Float64Array, pointIndex: number, result?: Point3d): Point3d | undefined {
const indexX = pointIndex * 4;
if (indexX >= 0 && indexX + 3 < xyzData.length) {
const w = xyzData[indexX + 3];
if (!Geometry.isSmallMetricDistance(w)) {
const divW = 1.0 / w;
return Point3d.create(divW * xyzData[indexX], divW * xyzData[indexX + 1], divW * xyzData[indexX + 2], result);
}
}
return undefined;
}
/**
* Return an array of points constructed from groups of 3 entries in a Float64Array.
* Any incomplete group at the tail of the array is ignored.
*/
public static createArrayFromPackedXYZ(data: Float64Array): Point3d[]{
const result = [];
for (let i = 0; i + 2 < data.length; i += 3)
result.push(new Point3d(data[i], data[i + 1], data[i + 2]));
return result;
}
/** Create a new point with 000 xyz */
public static createZero(result?: Point3d): Point3d { return Point3d.create(0, 0, 0, result); }
/** Return the cross product of the vectors from this to pointA and pointB
*
* * the result is a vector
* * the result is perpendicular to both vectors, with right hand orientation
* * the magnitude of the vector is twice the area of the triangle.
*/
public crossProductToPoints(pointA: Point3d, pointB: Point3d, result?: Vector3d): Vector3d {
return Vector3d.createCrossProduct(pointA.x - this.x, pointA.y - this.y, pointA.z - this.z, pointB.x - this.x, pointB.y - this.y, pointB.z - this.z, result);
}
/** Return the magnitude of the cross product of the vectors from this to pointA and pointB
*/
public crossProductToPointsMagnitude(pointA: Point3d, pointB: Point3d): number {
return Geometry.crossProductMagnitude(pointA.x - this.x, pointA.y - this.y, pointA.z - this.z, pointB.x - this.x, pointB.y - this.y, pointB.z - this.z);
}
/** Return the triple product of the vectors from this to pointA, pointB, pointC
*
* * This is a scalar (number)
* * This is 6 times the (signed) volume of the tetrahedron on the 4 points.
*/
public tripleProductToPoints(pointA: Point3d, pointB: Point3d, pointC: Point3d): number {
return Geometry.tripleProduct(pointA.x - this.x, pointA.y - this.y, pointA.z - this.z, pointB.x - this.x, pointB.y - this.y, pointB.z - this.z, pointC.x - this.x, pointC.y - this.y, pointC.z - this.z);
}
/** Return the cross product of the vectors from this to pointA and pointB
*
* * the result is a scalar
* * the magnitude of the vector is twice the signed area of the triangle.
* * this is positive for counter-clockwise order of the points, negative for clockwise.
*/
public crossProductToPointsXY(pointA: Point3d, pointB: Point3d): number {
return Geometry.crossProductXYXY(pointA.x - this.x, pointA.y - this.y, pointB.x - this.x, pointB.y - this.y);
}
/** Return a point interpolated between this point and the right param. */
public interpolate(fraction: number, other: XYAndZ, result?: Point3d): Point3d {
if (fraction <= 0.5)
return Point3d.create(this.x + fraction * (other.x - this.x), this.y + fraction * (other.y - this.y), this.z + fraction * (other.z - this.z), result);
const t: number = fraction - 1.0;
return Point3d.create(other.x + t * (other.x - this.x), other.y + t * (other.y - this.y), other.z + t * (other.z - this.z), result);
}
/**
* Return a ray whose ray.origin is interpolated, and ray.direction is the vector between points with a
* scale factor applied.
* @param fraction fractional position between points.
* @param other endpoint of interpolation
* @param tangentScale scale factor to apply to the startToEnd vector
* @param result optional receiver.
*/
public interpolatePointAndTangent(fraction: number, other: Point3d, tangentScale: number, result?: Ray3d): Ray3d {
result = result ? result : Ray3d.createZero();
const dx = other.x - this.x;
const dy = other.y - this.y;
const dz = other.z - this.z;
result.direction.set(tangentScale * dx, tangentScale * dy, tangentScale * dz);
if (fraction <= 0.5)
result.origin.set(this.x + fraction * dx, this.y + fraction * dy, this.z + fraction * dz);
else {
const t: number = fraction - 1.0;
result.origin.set(other.x + t * dx, other.y + t * dy, other.z + t * dz);
}
return result;
}
/** Return a point with independent x,y,z fractional interpolation. */
public interpolateXYZ(fractionX: number, fractionY: number, fractionZ: number, other: Point3d, result?: Point3d): Point3d {
return Point3d.create(Geometry.interpolate(this.x, fractionX, other.x), Geometry.interpolate(this.y, fractionY, other.y), Geometry.interpolate(this.z, fractionZ, other.z), result);
}
/** Interpolate between points, then add a shift in the xy plane by a fraction of the XY projection perpendicular. */
public interpolatePerpendicularXY(fraction: number, pointB: Point3d, fractionXYPerp: number, result?: Point3d): Point3d {
result = result ? result : new Point3d();
const vector = pointB.minus(this);
this.interpolate(fraction, pointB, result);
result.x -= fractionXYPerp * vector.y;
result.y += fractionXYPerp * vector.x;
return result;
}
/** Return point minus vector */
public minus(vector: XYAndZ, result?: Point3d): Point3d {
return Point3d.create(this.x - vector.x, this.y - vector.y, this.z - vector.z, result);
}
/** Return point plus vector */
public plus(vector: XYAndZ, result?: Point3d): Point3d {
return Point3d.create(this.x + vector.x, this.y + vector.y, this.z + vector.z, result);
}
/** Return point plus vector */
public plusXYZ(dx: number = 0, dy: number = 0, dz: number = 0, result?: Point3d): Point3d {
return Point3d.create(this.x + dx, this.y + dy, this.z + dz, result);
}
/** Return point + vector * scalar */
public plusScaled(vector: XYAndZ, scaleFactor: number, result?: Point3d): Point3d {
return Point3d.create(this.x + vector.x * scaleFactor, this.y + vector.y * scaleFactor, this.z + vector.z * scaleFactor, result);
}
/** Return point + vectorA * scalarA + vectorB * scalarB */
public plus2Scaled(vectorA: XYAndZ, scalarA: number, vectorB: XYZ, scalarB: number, result?: Point3d): Point3d {
return Point3d.create(this.x + vectorA.x * scalarA + vectorB.x * scalarB, this.y + vectorA.y * scalarA + vectorB.y * scalarB, this.z + vectorA.z * scalarA + vectorB.z * scalarB, result);
}
/** Return point + vectorA * scalarA + vectorB * scalarB + vectorC * scalarC */
public plus3Scaled(vectorA: XYAndZ, scalarA: number, vectorB: XYAndZ, scalarB: number, vectorC: XYAndZ, scalarC: number, result?: Point3d): Point3d {
return Point3d.create(
this.x + vectorA.x * scalarA + vectorB.x * scalarB + vectorC.x * scalarC,
this.y + vectorA.y * scalarA + vectorB.y * scalarB + vectorC.y * scalarC,
this.z + vectorA.z * scalarA + vectorB.z * scalarB + vectorC.z * scalarC, result);
}
/**
* Return a point that is scaled from the source point.
* @param source existing point
* @param scale scale factor to apply to its x,y,z parts
* @param result optional point to receive coordinates
*/
public static createScale(source: XYAndZ, scale: number, result?: Point3d): Point3d {
return Point3d.create(source.x * scale, source.y * scale, source.z * scale, result);
}
/** create a point that is a linear combination (weighted sum) of 2 input points.
* @param pointA first input point
* @param scaleA scale factor for pointA
* @param pointB second input point
* @param scaleB scale factor for pointB
*/
public static createAdd2Scaled(pointA: XYAndZ, scaleA: number, pointB: XYAndZ, scaleB: number, result?: Point3d): Point3d {
return Point3d.create(pointA.x * scaleA + pointB.x * scaleB, pointA.y * scaleA + pointB.y * scaleB, pointA.z * scaleA + pointB.z * scaleB, result);
}
/** Create a point that is a linear combination (weighted sum) of 3 input points.
* @param pointA first input point
* @param scaleA scale factor for pointA
* @param pointB second input point
* @param scaleB scale factor for pointB
* @param pointC third input point.
* @param scaleC scale factor for pointC
*/
public static createAdd3Scaled(pointA: XYAndZ, scaleA: number, pointB: XYAndZ, scaleB: number, pointC: XYAndZ, scaleC: number, result?: Point3d): Point3d {
return Point3d.create(pointA.x * scaleA + pointB.x * scaleB + pointC.x * scaleC, pointA.y * scaleA + pointB.y * scaleB + pointC.y * scaleC, pointA.z * scaleA + pointB.z * scaleB + pointC.z * scaleC, result);
}
/**
* Return the dot product of vectors from this to pointA and this to pointB.
* @param targetA target point for first vector
* @param targetB target point for second vector
*/
public dotVectorsToTargets(targetA: Point3d, targetB: Point3d): number {
return (targetA.x - this.x) * (targetB.x - this.x) +
(targetA.y - this.y) * (targetB.y - this.y) +
(targetA.z - this.z) * (targetB.z - this.z);
}
/** Return the fractional projection of this onto a line between points.
*
*/
public fractionOfProjectionToLine(startPoint: Point3d, endPoint: Point3d, defaultFraction: number = 0): number {
const denominator = startPoint.distanceSquared(endPoint);
if (denominator < Geometry.smallMetricDistanceSquared)
return defaultFraction;
return startPoint.dotVectorsToTargets(endPoint, this) / denominator;
}
}
/** 3D vector with `x`,`y`,`z` as properties
* @public
*/
export class Vector3d extends XYZ {
constructor(x: number = 0, y: number = 0, z: number = 0) { super(x, y, z); }
/**
* Return an array of vectors constructed from groups of 3 entries in a Float64Array.
* Any incomplete group at the tail of the array is ignored.
*/
public static createArrayFromPackedXYZ(data: Float64Array): Vector3d[]{
const result = [];
for (let i = 0; i + 2 < data.length; i += 3)
result.push(new Vector3d(data[i], data[i + 1], data[i + 2]));
return result;
}
/**
* Copy xyz from this instance to a new (or optionally reused) Vector3d
* @param result optional instance to reuse.
*/
public clone(result?: Vector3d): Vector3d { return Vector3d.create(this.x, this.y, this.z, result); }
/**
* return a Vector3d (new or reused from optional result)
* @param x x component
* @param y y component
* @param z z component
* @param result optional instance to reuse
*/
public static create(x: number = 0, y: number = 0, z: number = 0, result?: Vector3d): Vector3d {
if (result) {
result.x = x;
result.y = y;
result.z = z;
return result;
}
return new Vector3d(x, y, z);
}
/**
* Create a vector which is cross product of two vectors supplied as separate arguments
* @param ux x coordinate of vector u
* @param uy y coordinate of vector u
* @param uz z coordinate of vector u
* @param vx x coordinate of vector v
* @param vy y coordinate of vector v
* @param vz z coordinate of vector v
* @param result optional result vector.
*/
public static createCrossProduct(ux: number, uy: number, uz: number, vx: number, vy: number, vz: number, result?: Vector3d): Vector3d {
return Vector3d.create(uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx, result);
}
/**
* Accumulate a vector which is cross product vectors from origin (ax,ay,az) to targets (bx,by,bz) and (cx,cy,cz)
* @param ax x coordinate of origin
* @param ay y coordinate of origin
* @param az z coordinate of origin
* @param bx x coordinate of target point b
* @param by y coordinate of target point b
* @param bz z coordinate of target point b
* @param cx x coordinate of target point c
* @param cy y coordinate of target point c
* @param cz z coordinate of target point c
*/
public addCrossProductToTargetsInPlace(ax: number, ay: number, az: number, bx: number, by: number, bz: number, cx: number, cy: number, cz: number) {
const ux = bx - ax;
const uy = by - ay;
const uz = bz - az;
const vx = cx - ax;
const vy = cy - ay;
const vz = cz - az;
this.x += uy * vz - uz * vy;
this.y += uz * vx - ux * vz;
this.z += ux * vy - uy * vx;
}
/**
* Return the cross product of the vectors from origin to pointA and pointB.
*
* * the result is a vector
* * the result is perpendicular to both vectors, with right hand orientation
* * the magnitude of the vector is twice the area of the triangle.
*/
public static createCrossProductToPoints(origin: XYAndZ, pointA: XYAndZ, pointB: XYAndZ, result?: Vector3d): Vector3d {
return Vector3d.createCrossProduct(pointA.x - origin.x, pointA.y - origin.y, pointA.z - origin.z, pointB.x - origin.x, pointB.y - origin.y, pointB.z - origin.z, result);
}
/**
* Return a vector defined by polar coordinates distance and angle from x axis
* @param r distance measured from origin
* @param theta angle from x axis to the vector (in xy plane)
* @param z optional z coordinate
*/
public static createPolar(r: number, theta: Angle, z?: number): Vector3d {
return Vector3d.create(r * theta.cos(), r * theta.sin(), z);
}
/**
* Return a vector defined in spherical coordinates.
* @param r sphere radius
* @param theta angle in xy plane
* @param phi angle from xy plane to the vector
*/
public static createSpherical(r: number, theta: Angle, phi: Angle): Vector3d {
const cosPhi = phi.cos();
return Vector3d.create(cosPhi * r * theta.cos(), cosPhi * r * theta.sin(), r * phi.sin());
}
/**
* Convert json to Vector3d. Accepted forms are:
* * `[1,2,3]` --- array of numbers
* * array of numbers: [x,y,z]
* * object with x,y, and (optional) z as numeric properties {x: xValue, y: yValue, z: zValue}
* @param json json value.
*/
public static fromJSON(json?: XYZProps): Vector3d { const val = new Vector3d(); val.setFromJSON(json); return val; }
/** Copy contents from another Point3d, Point2d, Vector2d, or Vector3d */
public static createFrom(data: XYAndZ | XAndY | Float64Array | number[], result?: Vector3d): Vector3d {
if (data instanceof Float64Array) {
let x = 0;
let y = 0;
let z = 0;
if (data.length > 0)
x = data[0];
if (data.length > 1)
y = data[1];
if (data.length > 2)
z = data[2];
return Vector3d.create(x, y, z, result);
} else if (Array.isArray(data)) {
return Vector3d.create(data[0], data[1], data.length > 2 ? data[2] : 0);
}
return Vector3d.create(data.x, data.y, XYZ.hasZ(data) ? data.z : 0.0, result);
}
/**
* Return a vector defined by start and end points (end - start).
* @param start start point for vector
* @param end end point for vector
* @param result optional result
*/
public static createStartEnd(start: XYAndZ, end: XYAndZ, result?: Vector3d): Vector3d {
if (result) {
result.set(end.x - start.x, end.y - start.y, end.z - start.z);
return result;
}
return new Vector3d(end.x - start.x, end.y - start.y, end.z - start.z);
}
/**
* Return a vector (optionally in preallocated result, otherwise newly created) from [x0,y0,z0] to [x1,y1,z1]
* @param x0 start point x coordinate
* @param y0 start point y coordinate
* @param z0 start point z coordinate
* @param x1 end point x coordinate
* @param y1 end point y coordinate
* @param z1 end point z coordinate
* @param result optional result vector
*/
public static createStartEndXYZXYZ(x0: number, y0: number, z0: number, x1: number, y1: number, z1: number, result?: Vector3d): Vector3d {
return this.create(x1 - x0, y1 - y0, z1 - z0, result);
}
/**
* Return a vector which is the input vector rotated around the axis vector.
* @param vector initial vector
* @param axis axis of rotation
* @param angle angle of rotation. If undefined, 90 degrees is implied
* @param result optional result vector
* @returns undefined if axis has no length.
*/
public static createRotateVectorAroundVector(vector: Vector3d, axis: Vector3d, angle?: Angle): Vector3d | undefined {
// Rodriguez formula, https://en.wikipedia.org/wiki/Rodrigues'_rotation_formula
const unitAxis = axis.normalize();
if (unitAxis) {
const xProduct = unitAxis.crossProduct(vector);
let c, s;
if (angle) {
c = angle.cos();
s = angle.sin();
} else {
c = 0.0;
s = 1.0;
}
return Vector3d.createAdd3Scaled(vector, c, xProduct, s, unitAxis, unitAxis.dotProduct(vector) * (1.0 - c));
}
return undefined;
}
/**
* Set (replace) xzz components so they are a vector from point0 to point1
* @param point0 start point of computed vector
* @param point1 end point of computed vector.
*/
public setStartEnd(point0: XYAndZ, point1: XYAndZ) {
this.x = point1.x - point0.x;
this.y = point1.y - point0.y;
this.z = point1.z - point0.z;
}
/** Return a vector with 000 xyz parts. */
public static createZero(result?: Vector3d): Vector3d { return Vector3d.create(0, 0, 0, result); }
/** Return a unit X vector optionally multiplied by a scale */
public static unitX(scale: number = 1): Vector3d { return new Vector3d(scale, 0, 0); }
/** Return a unit Y vector */
public static unitY(scale: number = 1): Vector3d { return new Vector3d(0, scale, 0); }
/** Return a unit Z vector */
public static unitZ(scale: number = 1): Vector3d { return new Vector3d(0, 0, scale); }
/** Divide by denominator, but return undefined if denominator is zero. */
public safeDivideOrNull(denominator: number, result?: Vector3d): Vector3d | undefined {
if (denominator !== 0.0) {
return this.scale(1.0 / denominator, result);
}
return undefined;
}
/**
* Return a pair object containing (a) property `v` which is a unit vector in the direction
* of the input and (b) property mag which is the magnitude (length) of the input (instance) prior to normalization.
* If the instance (input) is a near zero length the `v` property of the output is undefined.
* @param result optional result.
*/
public normalizeWithLength(result?: Vector3d): {
v: Vector3d | undefined;
mag: number;
} {
const magnitude = Geometry.correctSmallMetricDistance(this.magnitude());
result = result ? result : new Vector3d();
return { v: this.safeDivideOrNull(magnitude, result), mag: magnitude };
}
/**
* Return a unit vector parallel with this. Return undefined if this.magnitude is near zero.
* @param result optional result.
*/
public normalize(result?: Vector3d): Vector3d | undefined { return this.normalizeWithLength(result).v; }
/**
* If this vector has nonzero length, divide by the length to change to a unit vector.
* @returns true if normalization completed.
*/
public normalizeInPlace(): boolean {
const a = Geometry.inverseMetricDistance(this.magnitude());
if (a === undefined)
return false;
this.x *= a;
this.y *= a;
this.z *= a;
return true;
}
/** Return the fractional projection of spaceVector onto this */
public fractionOfProjectionToVector(target: Vector3d, defaultFraction: number = 0): number {
const numerator = this.dotProduct(target);
const denominator = target.magnitudeSquared();
if (denominator < Geometry.smallMetricDistanceSquared)
return defaultFraction;
return numerator / denominator;
}
/** Return a new vector with components negated from the calling instance.
* @param result optional result vector.
*/
public negate(result?: Vector3d): Vector3d {
result = result ? result : new Vector3d();
result.x = -this.x;
result.y = -this.y;
result.z = -this.z;
return result;
}
/** Return a vector same length as this but rotate 90 degrees CCW */
public rotate90CCWXY(result?: Vector3d): Vector3d {
result = result ? result : new Vector3d();
// save x,y to allow aliasing ..
const xx: number = this.x;
const yy: number = this.y;
result.x = -yy;
result.y = xx;
result.z = this.z;
return result;
}
/**
* Return a vector which is in the xy plane, perpendicular ot the xy part of this vector, and of unit length.
* * If the xy part is 00, the return is the rotated (but not normalized) xy parts of this vector.
* @param result optional preallocated result.
*/
public unitPerpendicularXY(result?: Vector3d): Vector3d {
result = result ? result : new Vector3d();
const xx: number = this.x;
const yy: number = this.y;
result.x = -yy;
result.y = xx;
result.z = 0.0;
const d2: number = xx * xx + yy * yy;
if (d2 !== 0.0) {
const a = 1.0 / Math.sqrt(d2);
result.x *= a;
result.y *= a;
}
return result;
}
/**
* Rotate the xy parts of this vector around the z axis.
* * z is taken unchanged to the result.
* @param angle angle to rotate
* @param result optional preallocated result
*/
public rotateXY(angle: Angle, result?: Vector3d): Vector3d {
const s = angle.sin();
const c = angle.cos();
const xx: number = this.x;
const yy: number = this.y;
result = result ? result : new Vector3d();
result.x = xx * c - yy * s;
result.y = xx * s + yy * c;
result.z = this.z;
return result;
}
/**
* Return a (new or optionally preallocated) vector that is rotated 90 degrees in the plane of this vector and the target vector.
* @param target Second vector which defines the plane of rotation.
* @param result optional preallocated vector for result.
* @returns rotated vector, or undefined if the cross product of this and the the target cannot be normalized (i.e. if the target and this are colinear)
*/
public rotate90Towards(target: Vector3d, result?: Vector3d): Vector3d | undefined {
const normal = this.crossProduct(target).normalize();
return normal ? normal.crossProduct(this, result) : undefined;
}
/** Rotate this vector 90 degrees around an axis vector.
* @returns the (new or optionally reused result) rotated vector, or undefined if the axis vector cannot be normalized.
*/
public rotate90Around(axis: Vector3d, result?: Vector3d): Vector3d | undefined {
const unitNormal = axis.normalize();
return unitNormal ? unitNormal.crossProduct(this).plusScaled(unitNormal, unitNormal.dotProduct(this), result) : undefined;
}
/**
* Return a vector computed at fractional position between this vector and vectorB
* @param fraction fractional position. 0 is at `this`. 1 is at `vectorB`. True fractions are "between", negatives are "before this", beyond 1 is "beyond vectorB".
* @param vectorB second vector
* @param result optional preallocated result.
*/
public interpolate(fraction: number, vectorB: XYAndZ, result?: Vector3d): Vector3d {
result = result ? result : new Vector3d();
if (fraction <= 0.5) {
result.x = this.x + fraction * (vectorB.x - this.x);
result.y = this.y + fraction * (vectorB.y - this.y);
result.z = this.z + fraction * (vectorB.z - this.z);
} else {
const t: number = fraction - 1.0;
result.x = vectorB.x + t * (vectorB.x - this.x);
result.y = vectorB.y + t * (vectorB.y - this.y);
result.z = vectorB.z + t * (vectorB.z - this.z);
}
return result;
}
/**
* Return the vector sum `this - vector`
* @param vector right side of addition.
* @param result optional preallocated result.
*/
public plus(vector: XYAndZ, result?: Vector3d): Vector3d {
result = result ? result : new Vector3d();
result.x = this.x + vector.x;
result.y = this.y + vector.y;
result.z = this.z + vector.z;
return result;
}
/**
* Return the vector difference `this - vector`
* @param vector right side of subtraction.
* @param result optional preallocated result.
*/
public minus(vector: XYAndZ, result?: Vector3d): Vector3d {
result = result ? result : new Vector3d();
result.x = this.x - vector.x;
result.y = this.y - vector.y;
result.z = this.z - vector.z;
return result;
}
/** Return vector + vector * scalar */
public plusScaled(vector: XYAndZ, scaleFactor: number, result?: Vector3d): Vector3d {
result = result ? result : new Vector3d();
result.x = this.x + vector.x * scaleFactor;
result.y = this.y + vector.y * scaleFactor;
result.z = this.z + vector.z * scaleFactor;
return result;
}
/** Return the (strongly typed Vector3d) `this Vector3d + vectorA * scalarA + vectorB * scalarB` */
public plus2Scaled(vectorA: XYAndZ, scalarA: number, vectorB: XYAndZ, scalarB: number, result?: Vector3d): Vector3d {
result = result ? result : new Vector3d();
result.x = this.x + vectorA.x * scalarA + vectorB.x * scalarB;
result.y = this.y + vectorA.y * scalarA + vectorB.y * scalarB;
result.z = this.z + vectorA.z * scalarA + vectorB.z * scalarB;
return result;
}
/** Return the (strongly typed Vector3d) `thisVector3d + vectorA * scalarA + vectorB * scalarB + vectorC * scalarC` */
public plus3Scaled(vectorA: XYAndZ, scalarA: number, vectorB: XYAndZ, scalarB: number, vectorC: XYAndZ, scalarC: number, result?: Vector3d): Vector3d {
result = result ? result : new Vector3d();
result.x = this.x + vectorA.x * scalarA + vectorB.x * scalarB + vectorC.x * scalarC;
result.y = this.y + vectorA.y * scalarA + vectorB.y * scalarB + vectorC.y * scalarC;
result.z = this.z + vectorA.z * scalarA + vectorB.z * scalarB + vectorC.z * scalarC;
return result;
}
/** Return the (strongly typed Vector3d) `thisVector3d + vectorA * scalarA + vectorB * scalarB` */
public static createAdd2Scaled(vectorA: XYAndZ, scaleA: number, vectorB: XYAndZ, scaleB: number, result?: Vector3d): Vector3d {
return Vector3d.create(vectorA.x * scaleA + vectorB.x * scaleB, vectorA.y * scaleA + vectorB.y * scaleB, vectorA.z * scaleA + vectorB.z * scaleB, result);
}
/** Return the (strongly typed Vector3d) `thisVector3d + vectorA * scalarA + vectorB * scalarB` with all components presented as numbers */
public static createAdd2ScaledXYZ(ax: number, ay: number, az: number, scaleA: number, bx: number, by: number, bz: number, scaleB: number, result?: Vector3d): Vector3d {
return Vector3d.create(ax * scaleA + bx * scaleB, ay * scaleA + by * scaleB, az * scaleA + bz * scaleB, result);
}
/** Return the (strongly typed Vector3d) `thisVector3d + vectorA * scaleA + vectorB * scaleB + vectorC * scaleC` */
public static createAdd3Scaled(vectorA: XYAndZ, scaleA: number, vectorB: XYAndZ, scaleB: number, vectorC: XYAndZ, scaleC: number, result?: Vector3d): Vector3d {
return Vector3d.create(vectorA.x * scaleA + vectorB.x * scaleB + vectorC.x * scaleC, vectorA.y * scaleA + vectorB.y * scaleB + vectorC.y * scaleC, vectorA.z * scaleA + vectorB.z * scaleB + vectorC.z * scaleC, result);
}
/** Return vector * scalar */
public scale(scale: number, result?: Vector3d): Vector3d {
result = result ? result : new Vector3d();
result.x = this.x * scale;
result.y = this.y * scale;
result.z = this.z * scale;
return result;
}
/**
* Return a (optionally new or reused) vector in the direction of `this` but with specified length.
* @param length desired length of vector
* @param result optional preallocated result
*/
public scaleToLength(length: number, result?: Vector3d): Vector3d | undefined {
const mag = Geometry.correctSmallMetricDistance(this.magnitude());
if (mag === 0)
return undefined;
return this.scale(length / mag, result);
}
/** Compute the cross product of this vector with `vectorB`. Immediately pass it to `normalize`.
* @param vectorB second vector for cross product.
* @returns see `Vector3d` method `normalize()` for error condition.
*/
public unitCrossProduct(vectorB: Vector3d, result?: Vector3d): Vector3d | undefined {
return this.crossProduct(vectorB, result).normalize(result);
}
/**
* Compute the cross product of this vector with `vectorB`. Normalize it, using given xyz as default if length is zero.
* @param vectorB second vector of cross product
* @param x x value for default result
* @param y y value for default result
* @param z z value for default result
* @param result optional pre-allocated result.
*/
public unitCrossProductWithDefault(vectorB: Vector3d, x: number, y: number, z: number, result?: Vector3d): Vector3d {
const unit = this.crossProduct(vectorB, result).normalize(result);
if (unit === undefined)
return Vector3d.create(x, y, z, result);
return unit;
}
/**
* Normalize this vector, using given xyz as default if length is zero.
* * if this instance and x,y,z are both 000, return unit x vector.
* @param x x value for default result
* @param y y value for default result
* @param z z value for default result
* @param result optional pre-allocated result.
*/
public normalizeWithDefault(x: number, y: number, z: number, result?: Vector3d): Vector3d {
const unit = this.normalize(result);
if (unit)
return unit;
// try back to x,y,z
result = Vector3d.create(x, y, z, result);
if (result.normalizeInPlace())
return result;
return Vector3d.create(1, 0, 0, result);
}
/**
* Try to normalize (divide by magnitude), storing the result in place.
* @param smallestMagnitude smallest magnitude allowed as divisor.
* @returns false if magnitude is too small. In this case the vector is unchanged.
*/
public tryNormalizeInPlace(smallestMagnitude: number = Geometry.smallMetricDistance): boolean {
const a = this.magnitude();
if (a < smallestMagnitude || a === 0.0)
return false;
this.scaleInPlace(1.0 / a);
return true;
}
/**
* Compute cross product with `vectorB`.
* @param vectorB second vector for cross product.
* @param productLength desired length of result vector.
* @param result optional preallocated vector
* @return undefined if the cross product is near zero length.
*/
public sizedCrossProduct(vectorB: Vector3d, productLength: number, result?: Vector3d): Vector3d | undefined {
result = this.crossProduct(vectorB, result);
if (result.tryNormalizeInPlace()) {
result.scaleInPlace(productLength);
return result;
}
return undefined;
}
/**
* Compute the squared magnitude of a cross product (without allocating a temporary vector object)
* @param vectorB second vector of cross product
* @returns the squared magnitude of the cross product of this instance with vectorB.
*/
public crossProductMagnitudeSquared(vectorB: XYAndZ): number {
const xx = this.y * vectorB.z - this.z * vectorB.y;
const yy = this.z * vectorB.x - this.x * vectorB.z;
const zz = this.x * vectorB.y - this.y * vectorB.x;
return xx * xx + yy * yy + zz * zz;
}
/**
* Compute the magnitude of a cross product (without allocating a temporary vector object)
* @param vectorB second vector of cross product
* @returns the magnitude of the cross product of this instance with vectorB.
*/
public crossProductMagnitude(vectorB: XYAndZ): number {
return Math.sqrt(this.crossProductMagnitudeSquared(vectorB));
}
/** Return the dot product of this vector with vectorB.
* @param vectorB second vector of cross product
* @returns the dot product of this instance with vectorB
*/
public dotProduct(vectorB: XYAndZ): number {
return this.x * vectorB.x + this.y * vectorB.y + this.z * vectorB.z;
}
/**
* Return the dot product of the xyz components of two inputs that are XYAndZ but otherwise not explicitly Vector3d
* @param targetA target point for first vector
* @param targetB target point for second vector
*/
public static dotProductAsXYAndZ(dataA: XYAndZ, dataB: XYAndZ): number {
return dataA.x * dataB.x + dataA.y * dataB.y + dataA.z * dataB.z;
}
/**
* Returns the dot product of this vector with the with vector from pointA to pointB
* @param pointA start point of second vector of dot product
* @param pointB end point of second vector of dot product
*/
public dotProductStartEnd(pointA: XYAndZ, pointB: XYAndZ): number {
return this.x * (pointB.x - pointA.x)
+ this.y * (pointB.y - pointA.y)
+ this.z * (pointB.z - pointA.z);
}
/**
* Returns the dot product with vector (pointB - pointA * pointB.w)
* * That is, pointA is weighted to weight of pointB.
* * If pointB.w is zero, the homogeneous pointB is a simple vector
* * If pointB.w is nonzero, the vector "from A to B" is not physical length.
*/
public dotProductStart3dEnd4d(pointA: Point3d, pointB: Point4d): number {
const w = pointB.w;
return this.x * (pointB.x - pointA.x * w)
+ this.y * (pointB.y - pointA.y * w)
+ this.z * (pointB.z - pointA.z * w);
}
/** Cross product with vector from pointA to pointB */
public crossProductStartEnd(pointA: Point3d, pointB: Point3d, result?: Vector3d): Vector3d {
return Vector3d.createCrossProduct(this.x, this.y, this.z, pointB.x - pointA.x, pointB.y - pointA.y, pointB.z - pointA.z, result);
}
/** Cross product (xy parts only) with vector from pointA to pointB */
public crossProductStartEndXY(pointA: Point3d, pointB: Point3d): number {
return Geometry.crossProductXYXY(this.x, this.y, pointB.x - pointA.x, pointB.y - pointA.y);
}
/** Dot product with vector from pointA to pointB, with pointB given as x,y,z */
public dotProductStartEndXYZ(pointA: Point3d, x: number, y: number, z: number): number {
return this.x * (x - pointA.x)
+ this.y * (y - pointA.y)
+ this.z * (z - pointA.z);
}
/** Dot product with vector from pointA to pointB, using only xy parts */
public dotProductStartEndXY(pointA: Point3d, pointB: Point3d): number {
return this.x * (pointB.x - pointA.x)
+ this.y * (pointB.y - pointA.y);
}
/** Dot product with vector from pointA to pointB, with pointB given as (weighted) x,y,z,w
* * pointB is a homogeneous point that has to be unweighted
* * if the weight is near zero metric, the return is zero.
*/
public dotProductStartEndXYZW(pointA: Point3d, x: number, y: number, z: number, w: number): number {
if (Geometry.isSmallMetricDistance(w))
return 0.0;
const dw = 1.0 / w;
return this.x * (dw * x - pointA.x)
+ this.y * (dw * y - pointA.y)
+ this.z * (dw * z - pointA.z);
}
/** Return the dot product of the instance and vectorB, using only the x and y parts. */
public dotProductXY(vectorB: Vector3d): number {
return this.x * vectorB.x + this.y * vectorB.y;
}
/**
* Dot product with vector (x,y,z)
* @param x x component for dot product
* @param y y component for dot product
* @param z z component for dot product
*/
public dotProductXYZ(x: number, y: number, z: number = 0): number {
return this.x * x + this.y * y + this.z * z;
}
/** Return the triple product of the instance, vectorB, and vectorC */
public tripleProduct(vectorB: Vector3d, vectorC: Vector3d): number {
return Geometry.tripleProduct(this.x, this.y, this.z, vectorB.x, vectorB.y, vectorB.z, vectorC.x, vectorC.y, vectorC.z);
}
/** Return the cross product of the instance and vectorB, using only the x and y parts. */
public crossProductXY(vectorB: Vector3d): number {
return this.x * vectorB.y - this.y * vectorB.x;
}
/**
* Return the cross product of this vector and vectorB.
* @param vectorB second vector of cross product
* @param result optional preallocated result.
*/
public crossProduct(vectorB: Vector3d, result?: Vector3d): Vector3d {
return Vector3d.createCrossProduct(this.x, this.y, this.z, vectorB.x, vectorB.y, vectorB.z, result);
}
/**
* return cross product of `this` with the vector `(x, y, z)`
* @param x x component of second vector
* @param y y component of second vector
* @param z z component of second vector
* @param result computed cross product (new Vector3d).
*/
public crossProductXYZ(x: number, y: number, z: number, result?: Vector3d): Vector3d {
return Vector3d.createCrossProduct(this.x, this.y, this.z, x, y, z, result);
}
/**
* Return the (Strongly typed) angle from this vector to vectorB.
* * The returned angle is always positive and no larger than 180 degrees (PI radians)
* * The returned angle is "in the plane containing the two vectors"
* * Use `planarAngleTo`, `signedAngleTo`, `angleToXY` to take have angle measured in specific plane.
* @param vectorB target vector of rotation.
*/
public angleTo(vectorB: Vector3d): Angle {
return Angle.createAtan2(this.crossProductMagnitude(vectorB), this.dotProduct(vectorB));
}
/**
* Return the (Strongly typed) angle from this vector to the plane perpendicular to planeNormal.
* * The returned vector is signed
* * The returned vector is (as degrees) always less than or equal to 90 degrees.
* @param planeNormal a normal vector to the plane
*/
public angleFromPerpendicular(vectorB: Vector3d): Angle {
return Angle.createAtan2(this.dotProduct(vectorB), this.crossProductMagnitude(vectorB));
}
/**
* Return the (Strongly typed) angle from this vector to vectorB,using only the xy parts.
* * The returned angle can range from negative 180 degrees (negative PI radians) to positive 180 degrees (positive PI radians), not closed on the negative side.
* * Use `planarAngleTo`, `signedAngleTo`, `angleToXY` to take have angle measured in other planes.
* @param vectorB target vector of rotation.
*/
public angleToXY(vectorB: Vector3d): Angle {
return Angle.createAtan2(this.crossProductXY(vectorB), this.dotProductXY(vectorB));
}
/**
* Return the (radians as a simple number, not strongly typed Angle) radians from this vector to vectorB.
* * The returned angle can be positive or negative, with magnitude no larger than PI radians
* * Use signedRadiansTo` to take have angle measured in other planes.
* @param vectorB target vector of rotation.
*/
public planarRadiansTo(vector: Vector3d, planeNormal: Vector3d): number {
const square = planeNormal.dotProduct(planeNormal);
if (square === 0.0)
return 0.0;
const factor = 1.0 / square;
const projection0: Vector3d = this.plusScaled(planeNormal, -this.dotProduct(planeNormal) * factor);
const projection1: Vector3d = vector.plusScaled(planeNormal, -vector.dotProduct(planeNormal) * factor);
return projection0.signedRadiansTo(projection1, planeNormal);
}
/**
* Return the (as strongly typed Angle) Angle from this vector to vectorB.
* * The returned angle can range from negative PI to positive PI (not closed on negative side)
* * Use signedRadiansTo` to take have angle measured in other planes.
* @param vectorB target vector of rotation.
*/
public planarAngleTo(vector: Vector3d, planeNormal: Vector3d): Angle {
return Angle.createRadians(this.planarRadiansTo(vector, planeNormal));
}
/**
* Return the (simple number of radians, not Strongly typed Angle) angle from this vector to vectorB, measured in the plane containing both, with vectorW indicating which side to view to control sign of the angle.
* * The returned angle can range from negative PI to positive PI (not closed on negative side)
* * The returned angle is "in the plane containing the two vectors"
* * `vectorW` distinguishes between the sides of the plane, but does not have to be perpendicular.
* * The returned angle has the same sign as vectorW dot product (thisVector cross vectorB)
* @param vectorB target vector of rotation.
*/
public signedRadiansTo(vector1: Vector3d, vectorW: Vector3d): number {
const p = this.crossProduct(vector1);
const theta = Math.atan2(p.magnitude(), this.dotProduct(vector1));
if (vectorW.dotProduct(p) < 0.0)
return -theta;
else
return theta;
}
/**
* Return the (strongly typed Angle) angle from this vector to vectorB, measured in the plane containing both, with vectorW indicating which side to view to control sign of the angle.
* * The returned angle can range from negative 180 degrees (negative PI radians) to positive 180 degrees (positive PI radians), not closed on the negative side.
* * The returned angle is "in the plane containing the two vectors"
* * `vectorW` distinguishes between the sides of the plane, but does not have to be perpendicular.
* * The returned angle has the same sign as vectorW dot product (thisVector cross vectorB)
* @param vectorB target vector of rotation.
*/
public signedAngleTo(vector1: Vector3d, vectorW: Vector3d): Angle { return Angle.createRadians(this.signedRadiansTo(vector1, vectorW)); }
/** Return the smallest (strongly typed) angle from the (bidirectional) line containing `this` to the (bidirectional) line containing `vectorB` */
public smallerUnorientedAngleTo(vectorB: Vector3d): Angle {
return Angle.createRadians(this.smallerUnorientedRadiansTo(vectorB));
}
/** Return the smallest angle (in radians) from the (bidirectional) line containing `this` to the (bidirectional) line containing `vectorB` */
public smallerUnorientedRadiansTo(vectorB: Vector3d): number {
const c = this.dotProduct(vectorB);
const s = this.crossProductMagnitude(vectorB);
return Math.atan2(Math.abs(s), Math.abs(c));
}
/*
signedAngleTo(vectorB: Vector3d, upVector: Vector3d): Angle { }
// sectors
isInSmallerSector(vectorA: Vector3d, vectorB: Vector3d): boolean { }
isInCCWSector(vectorA: Vector3d, vectorB: Vector3d, upVector: Vector3d): boolean { }
*/
/**
* Test if this vector is parallel to other.
* @param other second vector in comparison
* @param oppositeIsParallel if the vectors are on the same line but in opposite directions, return this value.
* @param returnValueIfAnInputIsZeroLength if either vector is near zero length, return this value.
*/
public isParallelTo(other: Vector3d, oppositeIsParallel: boolean = false, returnValueIfAnInputIsZeroLength: boolean = false): boolean {
const a2 = this.magnitudeSquared();
const b2 = other.magnitudeSquared();
// we know both are 0 or positive -- no need for
if (a2 < Geometry.smallMetricDistanceSquared || b2 < Geometry.smallMetricDistanceSquared)
return returnValueIfAnInputIsZeroLength;
const dot = this.dotProduct(other);
if (dot < 0.0 && !oppositeIsParallel)
return returnValueIfAnInputIsZeroLength;
const cross2 = this.crossProductMagnitudeSquared(other);
/* a2,b2,cross2 are squared lengths of respective vectors */
/* cross2 = sin^2(theta) * a2 * b2 */
/* For small theta, sin^2(theta)~~theta^2 */
return cross2 <= Geometry.smallAngleRadiansSquared * a2 * b2;
}
/**
* Test if this vector is perpendicular to other.
* @param other second vector in comparison
* @param returnValueIfAnInputIsZeroLength if either vector is near zero length, return this value.
*/
public isPerpendicularTo(other: Vector3d, returnValueIfAnInputIsZeroLength: boolean = false): boolean {
const aa = this.magnitudeSquared();
if (aa < Geometry.smallMetricDistanceSquared)
return returnValueIfAnInputIsZeroLength;
const bb = other.magnitudeSquared();
if (bb < Geometry.smallMetricDistanceSquared)
return returnValueIfAnInputIsZeroLength;
const ab = this.dotProduct(other);
return ab * ab <= Geometry.smallAngleRadiansSquared * aa * bb;
}
} | the_stack |
* A {@link MethodVisitor} that generates methods in bytecode form. Each visit
* method of this class appends the bytecode corresponding to the visited
* instruction to a byte vector, in the order these methods are called.
*
* @author Eric Bruneton
* @author Eugene Kuleshov
*/
import { MethodVisitor } from "./MethodVisitor"
import { ByteVector } from "./ByteVector";
import { Attribute } from "./Attribute";
import { AnnotationWriter } from "./AnnotationWriter";
import { AnnotationVisitor } from "./AnnotationVisitor";
import { ClassReader } from "./ClassReader";
import { Opcodes } from "./Opcodes";
import { Frame } from "./Frame";
import { Type } from "./Type";
import { Edge } from "./Edge";
import { Label } from "./Label";
import { TypePath } from "./TypePath";
import { Item } from "./Item";
import { ClassWriter } from "./ClassWriter";
import { Handle } from "./Handle";
import { CurrentFrame } from "./CurrentFrame";
import * as bits from "./bits";
import { assert } from "./utils";
export class MethodWriter extends MethodVisitor {
/**
* Pseudo access flag used to denote constructors.
*/
static ACC_CONSTRUCTOR: number = 524288;
/**
* Frame has exactly the same locals as the previous stack map frame and
* number of stack items is zero.
*/
static SAME_FRAME: number = 0;
/**
* Frame has exactly the same locals as the previous stack map frame and
* number of stack items is 1
*/
static SAME_LOCALS_1_STACK_ITEM_FRAME: number = 64;
/**
* Reserved for future use
*/
static RESERVED: number = 128;
/**
* Frame has exactly the same locals as the previous stack map frame and
* number of stack items is 1. Offset is bigger then 63;
*/
static SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED: number = 247;
/**
* Frame where current locals are the same as the locals in the previous
* frame, except that the k last locals are absent. The value of k is given
* by the formula 251-frame_type.
*/
static CHOP_FRAME: number = 248;
/**
* Frame has exactly the same locals as the previous stack map frame and
* number of stack items is zero. Offset is bigger then 63;
*/
static SAME_FRAME_EXTENDED: number = 251;
/**
* Frame where current locals are the same as the locals in the previous
* frame, except that k additional locals are defined. The value of k is
* given by the formula frame_type-251.
*/
static APPEND_FRAME: number = 252;
/**
* Full frame
*/
static FULL_FRAME: number = 255;
/**
* Indicates that the stack map frames must be recomputed from scratch. In
* this case the maximum stack size and number of local variables is also
* recomputed from scratch.
*
* @see #compute
*/
static FRAMES: number = 0;
/**
* Indicates that the stack map frames of type F_INSERT must be computed.
* The other frames are not (re)computed. They should all be of type F_NEW
* and should be sufficient to compute the content of the F_INSERT frames,
* together with the bytecode instructions between a F_NEW and a F_INSERT
* frame - and without any knowledge of the type hierarchy (by definition of
* F_INSERT).
*
* @see #compute
*/
static INSERTED_FRAMES: number = 1;
/**
* Indicates that the maximum stack size and number of local variables must
* be automatically computed.
*
* @see #compute
*/
static MAXS: number = 2;
/**
* Indicates that nothing must be automatically computed.
*
* @see #compute
*/
static NOTHING: number = 3;
/**
* The class writer to which this method must be added.
*/
cw: ClassWriter;
/**
* Access flags of this method.
*/
private access: number;
/**
* The index of the constant pool item that contains the name of this
* method.
*/
private name: number;
/**
* The index of the constant pool item that contains the descriptor of this
* method.
*/
private desc: number;
/**
* The descriptor of this method.
*/
private descriptor: string;
/**
* The signature of this method.
*/
signature: string | null = null;
/**
* If not zero, indicates that the code of this method must be copied from
* the ClassReader associated to this writer in <code>cw.cr</code>. More
* precisely, this field gives the index of the first byte to copied from
* <code>cw.cr.b</code>.
*/
classReaderOffset: number;
/**
* If not zero, indicates that the code of this method must be copied from
* the ClassReader associated to this writer in <code>cw.cr</code>. More
* precisely, this field gives the number of bytes to copied from
* <code>cw.cr.b</code>.
*/
classReaderLength: number;
/**
* Number of exceptions that can be thrown by this method.
*/
exceptionCount: number;
/**
* The exceptions that can be thrown by this method. More precisely, this
* array contains the indexes of the constant pool items that contain the
* internal names of these exception classes.
*/
exceptions: number[] | null = null;
/**
* The annotation default attribute of this method. May be <tt>null</tt>.
*/
private annd: ByteVector | null = null;
/**
* The runtime visible annotations of this method. May be <tt>null</tt>.
*/
private anns: AnnotationWriter | null = null;
/**
* The runtime invisible annotations of this method. May be <tt>null</tt>.
*/
private ianns: AnnotationWriter | null = null;
/**
* The runtime visible type annotations of this method. May be <tt>null</tt>
* .
*/
private tanns: AnnotationWriter | null = null;
/**
* The runtime invisible type annotations of this method. May be
* <tt>null</tt>.
*/
private itanns: AnnotationWriter | null = null;
/**
* The runtime visible parameter annotations of this method. May be
* <tt>null</tt>.
*/
private panns: AnnotationWriter[] | null = null;
/**
* The runtime invisible parameter annotations of this method. May be
* <tt>null</tt>.
*/
private ipanns: AnnotationWriter[] | null = null;
/**
* The number of synthetic parameters of this method.
*/
private synthetics: number;
/**
* The non standard attributes of the method.
*/
private attrs: Attribute | null = null;
/**
* The bytecode of this method.
*/
private code: ByteVector = new ByteVector();
/**
* Maximum stack size of this method.
*/
private maxStack: number;
/**
* Maximum number of local variables for this method.
*/
private maxLocals: number;
/**
* Number of local variables in the current stack map frame.
*/
private currentLocals: number;
/**
* Number of stack map frames in the StackMapTable attribute.
*/
private frameCount: number;
/**
* The StackMapTable attribute.
*/
private stackMap: ByteVector | null = null;
/**
* The offset of the last frame that was written in the StackMapTable
* attribute.
*/
private previousFrameOffset: number;
/**
* The last frame that was written in the StackMapTable attribute.
*
* @see #frame
*/
private previousFrame: number[] | null = null;
/**
* The current stack map frame. The first element contains the offset of the
* instruction to which the frame corresponds, the second element is the
* number of locals and the third one is the number of stack elements. The
* local variables start at index 3 and are followed by the operand stack
* values. In summary frame[0] = offset, frame[1] = nLocal, frame[2] =
* nStack, frame[3] = nLocal. All types are encoded as integers, with the
* same format as the one used in {@link Label}, but limited to BASE types.
*/
private frame: number[] | null = null;
/**
* Number of elements in the exception handler list.
*/
private handlerCount: number;
/**
* The first element in the exception handler list.
*/
private firstHandler: Handler | null = null;
/**
* The last element in the exception handler list.
*/
private lastHandler: Handler | null = null;
/**
* Number of entries in the MethodParameters attribute.
*/
private methodParametersCount: number;
/**
* The MethodParameters attribute.
*/
private methodParameters: ByteVector | null = null;
/**
* Number of entries in the LocalVariableTable attribute.
*/
private localVarCount: number;
/**
* The LocalVariableTable attribute.
*/
private localVar: ByteVector | null = null;
/**
* Number of entries in the LocalVariableTypeTable attribute.
*/
private localVarTypeCount: number;
/**
* The LocalVariableTypeTable attribute.
*/
private localVarType: ByteVector | null = null;
/**
* Number of entries in the LineNumberTable attribute.
*/
private lineNumberCount: number;
/**
* The LineNumberTable attribute.
*/
private lineNumber: ByteVector | null = null;
/**
* The start offset of the last visited instruction.
*/
private lastCodeOffset: number;
/**
* The runtime visible type annotations of the code. May be <tt>null</tt>.
*/
private ctanns: AnnotationWriter | null = null;
/**
* The runtime invisible type annotations of the code. May be <tt>null</tt>.
*/
private ictanns: AnnotationWriter | null = null;
/**
* The non standard attributes of the method's code.
*/
private cattrs: Attribute | null = null;
/**
* The number of subroutines in this method.
*/
private subroutines: number;
/**
* Indicates what must be automatically computed.
*
* @see #FRAMES
* @see #INSERTED_FRAMES
* @see #MAXS
* @see #NOTHING
*/
private compute: number;
/**
* A list of labels. This list is the list of basic blocks in the method,
* i.e. a list of Label objects linked to each other by their
* {@link Label#successor} field, in the order they are visited by
* {@link MethodVisitor#visitLabel}, and starting with the first basic
* block.
*/
private labels: Label | null = null;
/**
* The previous basic block.
*/
private previousBlock: Label | null = null;
/**
* The current basic block.
*/
private currentBlock: Label | null = null;
/**
* The (relative) stack size after the last visited instruction. This size
* is relative to the beginning of the current basic block, i.e., the true
* stack size after the last visited instruction is equal to the
* {@link Label#inputStackTop beginStackSize} of the current basic block
* plus <tt>stackSize</tt>.
*/
private stackSize: number;
/**
* The (relative) maximum stack size after the last visited instruction.
* This size is relative to the beginning of the current basic block, i.e.,
* the true maximum stack size after the last visited instruction is equal
* to the {@link Label#inputStackTop beginStackSize} of the current basic
* block plus <tt>stackSize</tt>.
*/
private maxStackSize: number;
/**
* Constructs a new {@link MethodWriter}.
*
* @param cw
* the class writer in which the method must be added.
* @param access
* the method's access flags (see {@link Opcodes}).
* @param name
* the method's name.
* @param desc
* the method's descriptor (see {@link Type}).
* @param signature
* the method's signature. May be <tt>null</tt>.
* @param exceptions
* the internal names of the method's exceptions. May be
* <tt>null</tt>.
* @param compute
* Indicates what must be automatically computed (see #compute).
*/
constructor(cw: ClassWriter, access: number, name: string, desc: string, signature: string, exceptions: string[], compute: number) {
super(Opcodes.ASM5);
this.access = 0;
this.name = 0;
this.desc = 0;
this.classReaderOffset = 0;
this.classReaderLength = 0;
this.exceptionCount = 0;
this.synthetics = 0;
this.maxStack = 0;
this.maxLocals = 0;
this.currentLocals = 0;
this.frameCount = 0;
this.previousFrameOffset = 0;
this.handlerCount = 0;
this.methodParametersCount = 0;
this.localVarCount = 0;
this.localVarTypeCount = 0;
this.lineNumberCount = 0;
this.lastCodeOffset = 0;
this.subroutines = 0;
this.compute = 0;
this.stackSize = 0;
this.maxStackSize = 0;
if (cw.firstMethod == null) {
cw.firstMethod = this;
} else {
cw.lastMethod.mv = this;
}
cw.lastMethod = this;
this.cw = cw;
this.access = access;
if (("<init>" === name)) {
this.access |= MethodWriter.ACC_CONSTRUCTOR;
}
this.name = cw.newUTF8(name);
this.desc = cw.newUTF8(desc);
this.descriptor = desc;
if (ClassReader.SIGNATURES) {
this.signature = signature;
}
if (exceptions != null && exceptions.length > 0) {
this.exceptionCount = exceptions.length;
this.exceptions = new Array(this.exceptionCount);
for (let i: number = 0; i < this.exceptionCount; ++i) {
this.exceptions[i] = cw.newClass(exceptions[i]);
}
}
this.compute = compute;
if (compute !== MethodWriter.NOTHING) {
let size: number = Type.getArgumentsAndReturnSizes(this.descriptor) >> 2;
if ((access & Opcodes.ACC_STATIC) !== 0) {
--size;
}
this.maxLocals = size;
this.currentLocals = size;
this.labels = new Label();
this.labels.status |= Label.PUSHED;
this.visitLabel(this.labels);
}
}
public visitParameter(name: string, access: number) {
if (this.methodParameters == null) {
this.methodParameters = new ByteVector();
}
++this.methodParametersCount;
this.methodParameters.putShort((name == null) ? 0 : this.cw.newUTF8(name)).putShort(access);
}
public visitAnnotationDefault(): AnnotationVisitor | null {
if (!ClassReader.ANNOTATIONS) {
return null;
}
this.annd = new ByteVector();
return new AnnotationWriter(this.cw, false, this.annd, null, 0);
}
public visitAnnotation(desc: string, visible: boolean): AnnotationVisitor | null {
if (!ClassReader.ANNOTATIONS) {
return null;
}
let bv: ByteVector = new ByteVector();
bv.putShort(this.cw.newUTF8(desc)).putShort(0);
let aw: AnnotationWriter = new AnnotationWriter(this.cw, true, bv, bv, 2);
if (visible) {
aw.next = this.anns;
this.anns = aw;
} else {
aw.next = this.ianns;
this.ianns = aw;
}
return aw;
}
public visitTypeAnnotation(typeRef: number, typePath: TypePath, desc: string, visible: boolean): AnnotationVisitor | null {
if (!ClassReader.ANNOTATIONS) {
return null;
}
let bv: ByteVector = new ByteVector();
AnnotationWriter.putTarget(typeRef, typePath, bv);
bv.putShort(this.cw.newUTF8(desc)).putShort(0);
let aw: AnnotationWriter = new AnnotationWriter(this.cw, true, bv, bv, bv.length - 2);
if (visible) {
aw.next = this.tanns;
this.tanns = aw;
} else {
aw.next = this.itanns;
this.itanns = aw;
}
return aw;
}
public visitParameterAnnotation(parameter: number, desc: string, visible: boolean): AnnotationVisitor | null {
if (!ClassReader.ANNOTATIONS) {
return null;
}
let bv: ByteVector = new ByteVector();
if (("Ljava/lang/Synthetic;" === desc)) {
this.synthetics = Math.max(this.synthetics, parameter + 1);
return new AnnotationWriter(this.cw, false, bv, null, 0);
}
bv.putShort(this.cw.newUTF8(desc)).putShort(0);
let aw: AnnotationWriter = new AnnotationWriter(this.cw, true, bv, bv, 2);
if (visible) {
if (this.panns == null) {
this.panns = new Array(Type.getArgumentTypes(this.descriptor).length);
}
aw.next = this.panns[parameter];
this.panns[parameter] = aw;
} else {
if (this.ipanns == null) {
this.ipanns = new Array(Type.getArgumentTypes(this.descriptor).length);
}
aw.next = this.ipanns[parameter];
this.ipanns[parameter] = aw;
}
return aw;
}
public visitAttribute(attr: Attribute) {
if (attr.isCodeAttribute()) {
attr.next = this.cattrs;
this.cattrs = attr;
} else {
attr.next = this.attrs;
this.attrs = attr;
}
}
public visitCode() {
}
public visitFrame(type?: any, nLocal?: any, local?: any, nStack?: any, stack?: any): any {
assert(this.frame)
if (((typeof type === "number") || type === null) && ((typeof nLocal === "number") || nLocal === null) && ((local != null && local instanceof Array) || local === null) && ((typeof nStack === "number") || nStack === null) && ((stack != null && stack instanceof Array) || stack === null)) {
let __args = Array.prototype.slice.call(arguments);
return <any>(() => {
if (!ClassReader.FRAMES || this.compute === MethodWriter.FRAMES) {
return;
}
if (this.compute === MethodWriter.INSERTED_FRAMES) {
if (this.currentBlock && this.currentBlock.frame == null) {
this.currentBlock.frame = new CurrentFrame(this.currentBlock);
this.currentBlock.frame.initInputFrame(this.cw, this.access, Type.getArgumentTypes(this.descriptor), nLocal);
this.visitImplicitFirstFrame();
} else {
assert(this.currentBlock);
if (type === Opcodes.F_NEW) {
assert(this.currentBlock.frame);
this.currentBlock.frame.set(this.cw, nLocal, local, nStack, stack);
} else {
}
this.visitFrame(this.currentBlock.frame);
}
} else if (type === Opcodes.F_NEW) {
if (this.previousFrame == null) {
this.visitImplicitFirstFrame();
}
this.currentLocals = nLocal;
let frameIndex: number = this.startFrame(this.code.length, nLocal, nStack);
for (let i: number = 0; i < nLocal; ++i) {
if (typeof local[i] === "string") {
this.frame[frameIndex++] = Frame.OBJECT_$LI$() | this.cw.addType(<string>local[i]);
} else if (typeof local[i] === "number") {
this.frame[frameIndex++] = /* intValue */((<number>local[i]) | 0);
} else {
this.frame[frameIndex++] = Frame.UNINITIALIZED_$LI$() | this.cw.addUninitializedType("", (<Label>local[i]).position);
}
}
for (let i: number = 0; i < nStack; ++i) {
if (typeof stack[i] === "string") {
this.frame[frameIndex++] = Frame.OBJECT_$LI$() | this.cw.addType(<string>stack[i]);
} else if (typeof stack[i] === "number") {
this.frame[frameIndex++] = /* intValue */((<number>stack[i]) | 0);
} else {
this.frame[frameIndex++] = Frame.UNINITIALIZED_$LI$() | this.cw.addUninitializedType("", (<Label>stack[i]).position);
}
}
this.endFrame();
} else {
let delta: number;
if (this.stackMap == null) {
this.stackMap = new ByteVector();
delta = this.code.length;
} else {
delta = this.code.length - this.previousFrameOffset - 1;
if (delta < 0) {
if (type === Opcodes.F_SAME) {
return;
} else {
throw new Error();
}
}
}
switch ((type)) {
case Opcodes.F_FULL:
this.currentLocals = nLocal;
this.stackMap.putByte(MethodWriter.FULL_FRAME).putShort(delta).putShort(nLocal);
for (let i: number = 0; i < nLocal; ++i) {
this.writeFrameType(local[i]);
}
this.stackMap.putShort(nStack);
for (let i: number = 0; i < nStack; ++i) {
this.writeFrameType(stack[i]);
}
break;
case Opcodes.F_APPEND:
this.currentLocals += nLocal;
this.stackMap.putByte(MethodWriter.SAME_FRAME_EXTENDED + nLocal).putShort(delta);
for (let i: number = 0; i < nLocal; ++i) {
this.writeFrameType(local[i]);
}
break;
case Opcodes.F_CHOP:
this.currentLocals -= nLocal;
this.stackMap.putByte(MethodWriter.SAME_FRAME_EXTENDED - nLocal).putShort(delta);
break;
case Opcodes.F_SAME:
if (delta < 64) {
this.stackMap.putByte(delta);
} else {
this.stackMap.putByte(MethodWriter.SAME_FRAME_EXTENDED).putShort(delta);
}
break;
case Opcodes.F_SAME1:
if (delta < 64) {
this.stackMap.putByte(MethodWriter.SAME_LOCALS_1_STACK_ITEM_FRAME + delta);
} else {
this.stackMap.putByte(MethodWriter.SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED).putShort(delta);
}
this.writeFrameType(stack[0]);
break;
}
this.previousFrameOffset = this.code.length;
++this.frameCount;
}
this.maxStack = Math.max(this.maxStack, nStack);
this.maxLocals = Math.max(this.maxLocals, this.currentLocals);
})();
} else if (((type != null && type instanceof Frame) || type === null) && nLocal === undefined && local === undefined && nStack === undefined && stack === undefined) {
return <any>this.visitFrame$Frame(type);
} else { throw new Error("invalid overload"); }
}
public visitInsn(opcode: number) {
this.lastCodeOffset = this.code.length;
this.code.putByte(opcode);
if (this.currentBlock != null) {
if (this.compute === MethodWriter.FRAMES || this.compute === MethodWriter.INSERTED_FRAMES) {
assert(this.currentBlock.frame);
this.currentBlock.frame.execute(opcode, 0, null, null);
} else {
let size: number = this.stackSize + Frame.SIZE_$LI$()[opcode];
if (size > this.maxStackSize) {
this.maxStackSize = size;
}
this.stackSize = size;
}
if ((opcode >= Opcodes.IRETURN && opcode <= Opcodes.RETURN) || opcode === Opcodes.ATHROW) {
this.noSuccessor();
}
}
}
public visitIntInsn(opcode: number, operand: number) {
this.lastCodeOffset = this.code.length;
if (this.currentBlock != null) {
if (this.compute === MethodWriter.FRAMES || this.compute === MethodWriter.INSERTED_FRAMES) {
assert(this.currentBlock.frame);
this.currentBlock.frame.execute(opcode, operand, null, null);
} else if (opcode !== Opcodes.NEWARRAY) {
let size: number = this.stackSize + 1;
if (size > this.maxStackSize) {
this.maxStackSize = size;
}
this.stackSize = size;
}
}
if (opcode === Opcodes.SIPUSH) {
this.code.put12(opcode, operand);
} else {
this.code.put11(opcode, operand);
}
}
public visitVarInsn(opcode: number, __var: number) {
this.lastCodeOffset = this.code.length;
if (this.currentBlock != null) {
if (this.compute === MethodWriter.FRAMES || this.compute === MethodWriter.INSERTED_FRAMES) {
assert(this.currentBlock.frame);
this.currentBlock.frame.execute(opcode, __var, null, null);
} else {
if (opcode === Opcodes.RET) {
this.currentBlock.status |= Label.RET;
this.currentBlock.inputStackTop = this.stackSize;
this.noSuccessor();
} else {
let size: number = this.stackSize + Frame.SIZE_$LI$()[opcode];
if (size > this.maxStackSize) {
this.maxStackSize = size;
}
this.stackSize = size;
}
}
}
if (this.compute !== MethodWriter.NOTHING) {
let n: number;
if (opcode === Opcodes.LLOAD || opcode === Opcodes.DLOAD || opcode === Opcodes.LSTORE || opcode === Opcodes.DSTORE) {
n = __var + 2;
} else {
n = __var + 1;
}
if (n > this.maxLocals) {
this.maxLocals = n;
}
}
if (__var < 4 && opcode !== Opcodes.RET) {
let opt: number;
if (opcode < Opcodes.ISTORE) {
opt = 26 + ((opcode - Opcodes.ILOAD) << 2) + __var;
} else {
opt = 59 + ((opcode - Opcodes.ISTORE) << 2) + __var;
}
this.code.putByte(opt);
} else if (__var >= 256) {
this.code.putByte(196).put12(opcode, __var);
} else {
this.code.put11(opcode, __var);
}
if (opcode >= Opcodes.ISTORE && this.compute === MethodWriter.FRAMES && this.handlerCount > 0) {
this.visitLabel(new Label());
}
}
public visitTypeInsn(opcode: number, type: string) {
this.lastCodeOffset = this.code.length;
let i: Item = this.cw.newClassItem(type);
if (this.currentBlock != null) {
if (this.compute === MethodWriter.FRAMES || this.compute === MethodWriter.INSERTED_FRAMES) {
assert(this.currentBlock.frame);
this.currentBlock.frame.execute(opcode, this.code.length, this.cw, i);
} else if (opcode === Opcodes.NEW) {
let size: number = this.stackSize + 1;
if (size > this.maxStackSize) {
this.maxStackSize = size;
}
this.stackSize = size;
}
}
this.code.put12(opcode, i.index);
}
public visitFieldInsn(opcode: number, owner: string, name: string, desc: string) {
this.lastCodeOffset = this.code.length;
let i: Item = this.cw.newFieldItem(owner, name, desc);
if (this.currentBlock != null) {
if (this.compute === MethodWriter.FRAMES || this.compute === MethodWriter.INSERTED_FRAMES) {
assert(this.currentBlock.frame);
this.currentBlock.frame.execute(opcode, 0, this.cw, i);
} else {
let size: number;
let c: string = desc.charAt(0);
switch ((opcode)) {
case Opcodes.GETSTATIC:
size = this.stackSize + (c === "D" || c === "J" ? 2 : 1);
break;
case Opcodes.PUTSTATIC:
size = this.stackSize + (c === "D" || c === "J" ? -2 : -1);
break;
case Opcodes.GETFIELD:
size = this.stackSize + (c === "D" || c === "J" ? 1 : 0);
break;
default:
size = this.stackSize + (c === "D" || c === "J" ? -3 : -2);
break;
}
if (size > this.maxStackSize) {
this.maxStackSize = size;
}
this.stackSize = size;
}
}
this.code.put12(opcode, i.index);
}
public visitMethodInsn(opcode?: any, owner?: any, name?: any, desc?: any, itf?: any): any {
if (((typeof opcode === "number") || opcode === null) && ((typeof owner === "string") || owner === null) && ((typeof name === "string") || name === null) && ((typeof desc === "string") || desc === null) && ((typeof itf === "boolean") || itf === null)) {
let __args = Array.prototype.slice.call(arguments);
return <any>(() => {
this.lastCodeOffset = this.code.length;
let i: Item = this.cw.newMethodItem(owner, name, desc, itf);
let argSize: number = i.intVal;
if (this.currentBlock != null) {
if (this.compute === MethodWriter.FRAMES || this.compute === MethodWriter.INSERTED_FRAMES) {
assert(this.currentBlock.frame);
this.currentBlock.frame.execute(opcode, 0, this.cw, i);
} else {
if (argSize === 0) {
argSize = Type.getArgumentsAndReturnSizes(desc);
i.intVal = argSize;
}
let size: number;
if (opcode === Opcodes.INVOKESTATIC) {
size = this.stackSize - (argSize >> 2) + (argSize & 3) + 1;
} else {
size = this.stackSize - (argSize >> 2) + (argSize & 3);
}
if (size > this.maxStackSize) {
this.maxStackSize = size;
}
this.stackSize = size;
}
}
if (opcode === Opcodes.INVOKEINTERFACE) {
if (argSize === 0) {
argSize = Type.getArgumentsAndReturnSizes(desc);
i.intVal = argSize;
}
this.code.put12(Opcodes.INVOKEINTERFACE, i.index).put11(argSize >> 2, 0);
} else {
this.code.put12(opcode, i.index);
}
})();
} else if (((typeof opcode === "number") || opcode === null) && ((typeof owner === "string") || owner === null) && ((typeof name === "string") || name === null) && ((typeof desc === "string") || desc === null) && itf === undefined) {
return <any>this.visitMethodInsn$int$java_lang_String$java_lang_String$java_lang_String(opcode, owner, name, desc);
} else { throw new Error("invalid overload"); }
}
public visitInvokeDynamicInsn(name: string, desc: string, bsm: Handle, ...bsmArgs: any[]) {
this.lastCodeOffset = this.code.length;
let i: Item = this.cw.newInvokeDynamicItem(name, desc, bsm, ...bsmArgs);
let argSize: number = i.intVal;
if (this.currentBlock != null) {
if (this.compute === MethodWriter.FRAMES || this.compute === MethodWriter.INSERTED_FRAMES) {
assert(this.currentBlock.frame);
this.currentBlock.frame.execute(Opcodes.INVOKEDYNAMIC, 0, this.cw, i);
} else {
if (argSize === 0) {
argSize = Type.getArgumentsAndReturnSizes(desc);
i.intVal = argSize;
}
let size: number = this.stackSize - (argSize >> 2) + (argSize & 3) + 1;
if (size > this.maxStackSize) {
this.maxStackSize = size;
}
this.stackSize = size;
}
}
this.code.put12(Opcodes.INVOKEDYNAMIC, i.index);
this.code.putShort(0);
}
public visitJumpInsn(opcode: number, label: Label) {
let isWide: boolean = opcode >= 200;
opcode = isWide ? opcode - 33 : opcode;
this.lastCodeOffset = this.code.length;
let nextInsn: Label | null = null;
if (this.currentBlock != null) {
if (this.compute === MethodWriter.FRAMES) {
assert(this.currentBlock.frame);
this.currentBlock.frame.execute(opcode, 0, null, null);
label.getFirst().status |= Label.TARGET;
this.addSuccessor(Edge.NORMAL, label);
if (opcode !== Opcodes.GOTO) {
nextInsn = new Label();
}
} else if (this.compute === MethodWriter.INSERTED_FRAMES) {
this.currentBlock.frame!.execute(opcode, 0, null, null);
} else {
if (opcode === Opcodes.JSR) {
if ((label.status & Label.SUBROUTINE) === 0) {
label.status |= Label.SUBROUTINE;
++this.subroutines;
}
this.currentBlock.status |= Label.JSR;
this.addSuccessor(this.stackSize + 1, label);
nextInsn = new Label();
} else {
this.stackSize += Frame.SIZE_$LI$()[opcode];
this.addSuccessor(this.stackSize, label);
}
}
}
if ((label.status & Label.RESOLVED) !== 0 && label.position - this.code.length < bits.SHORT_MIN) {
if (opcode === Opcodes.GOTO) {
this.code.putByte(200);
} else if (opcode === Opcodes.JSR) {
this.code.putByte(201);
} else {
if (nextInsn != null) {
nextInsn.status |= Label.TARGET;
}
this.code.putByte(opcode <= 166 ? ((opcode + 1) ^ 1) - 1 : opcode ^ 1);
this.code.putShort(8);
this.code.putByte(200);
}
label.put(this, this.code, this.code.length - 1, true);
} else if (isWide) {
this.code.putByte(opcode + 33);
label.put(this, this.code, this.code.length - 1, true);
} else {
this.code.putByte(opcode);
label.put(this, this.code, this.code.length - 1, false);
}
if (this.currentBlock != null) {
if (nextInsn != null) {
this.visitLabel(nextInsn);
}
if (opcode === Opcodes.GOTO) {
this.noSuccessor();
}
}
}
public visitLabel(label: Label) {
this.cw.hasAsmInsns = this.cw.hasAsmInsns || label.resolve(this, this.code.length, this.code.data);
if ((label.status & Label.DEBUG) !== 0) {
return;
}
if (this.compute === MethodWriter.FRAMES) {
if (this.currentBlock != null) {
if (label.position === this.currentBlock.position) {
this.currentBlock.status |= (label.status & Label.TARGET);
label.frame = this.currentBlock.frame;
return;
}
this.addSuccessor(Edge.NORMAL, label);
}
this.currentBlock = label;
if (label.frame == null) {
label.frame = new Frame(label);
}
if (this.previousBlock != null) {
if (label.position === this.previousBlock.position) {
this.previousBlock.status |= (label.status & Label.TARGET);
label.frame = this.previousBlock.frame;
this.currentBlock = this.previousBlock;
return;
}
this.previousBlock.successor = label;
}
this.previousBlock = label;
} else if (this.compute === MethodWriter.INSERTED_FRAMES) {
if (this.currentBlock == null) {
this.currentBlock = label;
} else {
assert(this.currentBlock.frame);
this.currentBlock.frame.owner = label;
}
} else if (this.compute === MethodWriter.MAXS) {
if (this.currentBlock != null) {
this.currentBlock.outputStackMax = this.maxStackSize;
this.addSuccessor(this.stackSize, label);
}
this.currentBlock = label;
this.stackSize = 0;
this.maxStackSize = 0;
if (this.previousBlock != null) {
this.previousBlock.successor = label;
}
this.previousBlock = label;
}
}
public visitLdcInsn(cst: any) {
this.lastCodeOffset = this.code.length;
let i: Item = this.cw.newConstItem(cst);
if (this.currentBlock != null) {
if (this.compute === MethodWriter.FRAMES || this.compute === MethodWriter.INSERTED_FRAMES) {
this.currentBlock.frame!.execute(Opcodes.LDC, 0, this.cw, i);
} else {
let size: number;
if (i.type === ClassWriter.LONG || i.type === ClassWriter.DOUBLE) {
size = this.stackSize + 2;
} else {
size = this.stackSize + 1;
}
if (size > this.maxStackSize) {
this.maxStackSize = size;
}
this.stackSize = size;
}
}
let index: number = i.index;
if (i.type === ClassWriter.LONG || i.type === ClassWriter.DOUBLE) {
this.code.put12(20, index);
} else if (index >= 256) {
this.code.put12(19, index);
} else {
this.code.put11(Opcodes.LDC, index);
}
}
public visitIincInsn(__var: number, increment: number) {
this.lastCodeOffset = this.code.length;
if (this.currentBlock != null) {
if (this.compute === MethodWriter.FRAMES || this.compute === MethodWriter.INSERTED_FRAMES) {
this.currentBlock.frame!.execute(Opcodes.IINC, __var, null, null);
}
}
if (this.compute !== MethodWriter.NOTHING) {
let n: number = __var + 1;
if (n > this.maxLocals) {
this.maxLocals = n;
}
}
if ((__var > 255) || (increment > 127) || (increment < -128)) {
this.code.putByte(196).put12(Opcodes.IINC, __var).putShort(increment);
} else {
this.code.putByte(Opcodes.IINC).put11(__var, increment);
}
}
public visitTableSwitchInsn(min: number, max: number, dflt: Label, ...labels: Label[]) {
this.lastCodeOffset = this.code.length;
let source: number = this.code.length;
this.code.putByte(Opcodes.TABLESWITCH);
this.code.putByteArray(null, 0, (4 - this.code.length % 4) % 4);
dflt.put(this, this.code, source, true);
this.code.putInt(min).putInt(max);
for (let i: number = 0; i < labels.length; ++i) {
labels[i].put(this, this.code, source, true);
}
this.visitSwitchInsn(dflt, labels);
}
public visitLookupSwitchInsn(dflt: Label, keys: number[], labels: Label[]) {
this.lastCodeOffset = this.code.length;
let source: number = this.code.length;
this.code.putByte(Opcodes.LOOKUPSWITCH);
this.code.putByteArray(null, 0, (4 - this.code.length % 4) % 4);
dflt.put(this, this.code, source, true);
this.code.putInt(labels.length);
for (let i: number = 0; i < labels.length; ++i) {
this.code.putInt(keys[i]);
labels[i].put(this, this.code, source, true);
}
this.visitSwitchInsn(dflt, labels);
}
private visitSwitchInsn(dflt: Label, labels: Label[]) {
if (this.currentBlock != null) {
if (this.compute === MethodWriter.FRAMES) {
assert(this.currentBlock.frame);
this.currentBlock.frame.execute(Opcodes.LOOKUPSWITCH, 0, null, null);
this.addSuccessor(Edge.NORMAL, dflt);
dflt.getFirst().status |= Label.TARGET;
for (let i: number = 0; i < labels.length; ++i) {
this.addSuccessor(Edge.NORMAL, labels[i]);
labels[i].getFirst().status |= Label.TARGET;
}
} else {
--this.stackSize;
this.addSuccessor(this.stackSize, dflt);
for (let i: number = 0; i < labels.length; ++i) {
this.addSuccessor(this.stackSize, labels[i]);
}
}
this.noSuccessor();
}
}
public visitMultiANewArrayInsn(desc: string, dims: number) {
this.lastCodeOffset = this.code.length;
let i: Item = this.cw.newClassItem(desc);
if (this.currentBlock != null) {
if (this.compute === MethodWriter.FRAMES || this.compute === MethodWriter.INSERTED_FRAMES) {
assert(this.currentBlock.frame);
this.currentBlock.frame.execute(Opcodes.MULTIANEWARRAY, dims, this.cw, i);
} else {
this.stackSize += 1 - dims;
}
}
this.code.put12(Opcodes.MULTIANEWARRAY, i.index).putByte(dims);
}
public visitInsnAnnotation(typeRef: number, typePath: TypePath, desc: string, visible: boolean): AnnotationVisitor | null {
if (!ClassReader.ANNOTATIONS) {
return null;
}
let bv: ByteVector = new ByteVector();
typeRef = (typeRef & -16776961) | (this.lastCodeOffset << 8);
AnnotationWriter.putTarget(typeRef, typePath, bv);
bv.putShort(this.cw.newUTF8(desc)).putShort(0);
let aw: AnnotationWriter = new AnnotationWriter(this.cw, true, bv, bv, bv.length - 2);
if (visible) {
aw.next = this.ctanns;
this.ctanns = aw;
} else {
aw.next = this.ictanns;
this.ictanns = aw;
}
return aw;
}
public visitTryCatchBlock(start: Label, end: Label, handler: Label, type: string) {
++this.handlerCount;
let h: Handler = new Handler();
h.start = start;
h.end = end;
h.handler = handler;
h.desc = type;
h.type = type != null ? this.cw.newClass(type) : 0;
if (this.lastHandler == null) {
this.firstHandler = h;
} else {
this.lastHandler.next = h;
}
this.lastHandler = h;
}
public visitTryCatchAnnotation(typeRef: number, typePath: TypePath, desc: string, visible: boolean): AnnotationVisitor | null {
if (!ClassReader.ANNOTATIONS) {
return null;
}
let bv: ByteVector = new ByteVector();
AnnotationWriter.putTarget(typeRef, typePath, bv);
bv.putShort(this.cw.newUTF8(desc)).putShort(0);
let aw: AnnotationWriter = new AnnotationWriter(this.cw, true, bv, bv, bv.length - 2);
if (visible) {
aw.next = this.ctanns;
this.ctanns = aw;
} else {
aw.next = this.ictanns;
this.ictanns = aw;
}
return aw;
}
public visitLocalVariable(name: string, desc: string, signature: string, start: Label, end: Label, index: number) {
if (signature != null) {
if (this.localVarType == null) {
this.localVarType = new ByteVector();
}
++this.localVarTypeCount;
this.localVarType.putShort(start.position).putShort(end.position - start.position).putShort(this.cw.newUTF8(name)).putShort(this.cw.newUTF8(signature)).putShort(index);
}
if (this.localVar == null) {
this.localVar = new ByteVector();
}
++this.localVarCount;
this.localVar.putShort(start.position).putShort(end.position - start.position).putShort(this.cw.newUTF8(name)).putShort(this.cw.newUTF8(desc)).putShort(index);
if (this.compute !== MethodWriter.NOTHING) {
let c: string = desc.charAt(0);
let n: number = index + (c === "J" || c === "D" ? 2 : 1);
if (n > this.maxLocals) {
this.maxLocals = n;
}
}
}
public visitLocalVariableAnnotation(typeRef: number, typePath: TypePath, start: Label[], end: Label[], index: number[], desc: string, visible: boolean): AnnotationVisitor | null {
if (!ClassReader.ANNOTATIONS) {
return null;
}
let bv: ByteVector = new ByteVector();
bv.putByte(typeRef >>> 24).putShort(start.length);
for (let i: number = 0; i < start.length; ++i) {
bv.putShort(start[i].position).putShort(end[i].position - start[i].position).putShort(index[i]);
}
if (typePath == null) {
bv.putByte(0);
} else {
let length: number = typePath.buf[typePath.offset] * 2 + 1;
bv.putByteArray(typePath.buf, typePath.offset, length);
}
bv.putShort(this.cw.newUTF8(desc)).putShort(0);
let aw: AnnotationWriter = new AnnotationWriter(this.cw, true, bv, bv, bv.length - 2);
if (visible) {
aw.next = this.ctanns;
this.ctanns = aw;
} else {
aw.next = this.ictanns;
this.ictanns = aw;
}
return aw;
}
public visitLineNumber(line: number, start: Label) {
if (this.lineNumber == null) {
this.lineNumber = new ByteVector();
}
++this.lineNumberCount;
this.lineNumber.putShort(start.position);
this.lineNumber.putShort(line);
}
public visitMaxs(maxStack: number, maxLocals: number) {
if (ClassReader.FRAMES && this.compute === MethodWriter.FRAMES) {
let handler: Handler | null = this.firstHandler;
while ((handler != null)) {
assert(handler.start)
assert(handler.handler)
assert(handler.end)
let l: Label = handler.start.getFirst();
let h: Label = handler.handler.getFirst();
let e: Label = handler.end.getFirst();
let t: string = handler.desc == null ? "java/lang/Throwable" : handler.desc;
let kind: number = Frame.OBJECT_$LI$() | this.cw.addType(t);
h.status |= Label.TARGET;
while ((l !== e)) {
let b: Edge = new Edge();
b.info = kind;
b.successor = h;
b.next = l.successors;
l.successors = b;
l = l.successor;
};
handler = handler.next;
};
assert(this.labels);
assert(this.labels.frame);
let f: Frame | null = this.labels.frame;
f.initInputFrame(this.cw, this.access, Type.getArgumentTypes(this.descriptor), this.maxLocals);
this.visitFrame(f);
let max: number = 0;
let changed: Label | null = this.labels;
while ((changed != null)) {
let l: Label = changed;
changed = changed.next;
l.next = null;
f = l.frame;
if ((l.status & Label.TARGET) !== 0) {
l.status |= Label.STORE;
}
assert(f);
l.status |= Label.REACHABLE;
let blockMax: number = f.inputStack.length + l.outputStackMax;
if (blockMax > max) {
max = blockMax;
}
let e: Edge | null = l.successors;
while ((e != null)) {
let n: Label = e.successor!.getFirst();
let change: boolean = f.merge(this.cw, n.frame!, e.info);
if (change && n.next == null) {
n.next = changed;
changed = n;
}
e = e.next;
};
};
let l: Label | null = this.labels;
while ((l != null)) {
f = l.frame;
if ((l.status & Label.STORE) !== 0) {
this.visitFrame(f);
}
if ((l.status & Label.REACHABLE) === 0) {
let k: Label | null = l.successor;
let start: number = l.position;
let end: number = (k == null ? this.code.length : k.position) - 1;
if (end >= start) {
max = Math.max(max, 1);
for (let i: number = start; i < end; ++i) {
this.code.data[i] = Opcodes.NOP;
}
this.code.data[end] = (Opcodes.ATHROW | 0);
let frameIndex: number = this.startFrame(start, 0, 1);
assert(this.frame);
this.frame[frameIndex] = Frame.OBJECT_$LI$() | this.cw.addType("java/lang/Throwable");
this.endFrame();
this.firstHandler = Handler.remove(this.firstHandler, l, k);
}
}
l = l.successor;
};
handler = this.firstHandler;
this.handlerCount = 0;
while ((handler != null)) {
this.handlerCount += 1;
handler = handler.next;
};
this.maxStack = max;
} else if (this.compute === MethodWriter.MAXS) {
let handler: Handler | null = this.firstHandler;
while ((handler != null)) {
let l: Label | null = handler.start;
let h: Label | null = handler.handler;
let e: Label | null = handler.end;
while ((l !== e)) {
let b: Edge = new Edge();
b.info = Edge.EXCEPTION;
b.successor = h;
if ((l!.status & Label.JSR) === 0) {
b.next = l!.successors;
l!.successors = b;
} else {
b.next = l!.successors.next!.next;
l!.successors.next!.next = b;
}
l = l!.successor;
};
handler = handler.next;
};
if (this.subroutines > 0) {
let id: number = 0;
assert(this.labels);
this.labels.visitSubroutine(null, 1, this.subroutines);
let l: Label | null = this.labels;
while ((l != null)) {
if ((l.status & Label.JSR) !== 0) {
let subroutine: Label | null = l.successors.next!.successor;
assert(subroutine);
if ((subroutine.status & Label.VISITED) === 0) {
id += 1;
subroutine.visitSubroutine(null, (Math.round(id / 32)) << 32 | (1 << (id % 32)), this.subroutines);
}
}
l = l.successor;
};
l = this.labels;
while ((l != null)) {
if ((l.status & Label.JSR) !== 0) {
let L: Label | null = this.labels;
while ((L != null)) {
L.status &= ~Label.VISITED2;
L = L.successor;
};
let subroutine = l.successors.next!.successor;
subroutine!.visitSubroutine(l, 0, this.subroutines);
}
l = l.successor;
};
}
let max: number = 0;
let stack: Label | null = this.labels;
while ((stack != null)) {
let l: Label | null = stack;
stack = stack.next;
let start: number = l.inputStackTop;
let blockMax: number = start + l.outputStackMax;
if (blockMax > max) {
max = blockMax;
}
let b: Edge | null = l.successors;
if ((l.status & Label.JSR) !== 0) {
b = b.next;
}
while ((b != null)) {
l = b.successor;
if (l && (l.status & Label.PUSHED) === 0) {
l.inputStackTop = b.info === Edge.EXCEPTION ? 1 : start + b.info;
l.status |= Label.PUSHED;
l.next = stack;
stack = l;
}
b = b.next;
};
};
this.maxStack = Math.max(maxStack, max);
} else {
this.maxStack = maxStack;
this.maxLocals = maxLocals;
}
}
public visitEnd() {
}
/**
* Adds a successor to the {@link #currentBlock currentBlock} block.
*
* @param info
* information about the control flow edge to be added.
* @param successor
* the successor block to be added to the current block.
*/
private addSuccessor(info: number, successor: Label) {
let b: Edge = new Edge();
b.info = info;
b.successor = successor;
assert(this.currentBlock);
b.next = this.currentBlock.successors;
this.currentBlock.successors = b;
}
/**
* Ends the current basic block. This method must be used in the case where
* the current basic block does not have any successor.
*/
private noSuccessor() {
if (this.compute === MethodWriter.FRAMES) {
let l: Label = new Label();
l.frame = new Frame(l);
l.resolve(this, this.code.length, this.code.data);
this.previousBlock!.successor = l;
this.previousBlock = l;
} else {
assert(this.currentBlock);
this.currentBlock.outputStackMax = this.maxStackSize;
}
if (this.compute !== MethodWriter.INSERTED_FRAMES) {
this.currentBlock = null;
}
}
/**
* Visits a frame that has been computed from scratch.
*
* @param f
* the frame that must be visited.
*/
private visitFrame$Frame(f: Frame) {
let i: number;
let t: number;
let nTop: number = 0;
let nLocal: number = 0;
let nStack: number = 0;
let locals: number[] = f.inputLocals;
let stacks: number[] = f.inputStack;
for (i = 0; i < locals.length; ++i) {
t = locals[i];
if (t === Frame.TOP_$LI$()) {
++nTop;
} else {
nLocal += nTop + 1;
nTop = 0;
}
if (t === Frame.LONG_$LI$() || t === Frame.DOUBLE_$LI$()) {
++i;
}
}
for (i = 0; i < stacks.length; ++i) {
t = stacks[i];
++nStack;
if (t === Frame.LONG_$LI$() || t === Frame.DOUBLE_$LI$()) {
++i;
}
}
let frameIndex: number = this.startFrame(f.owner.position, nLocal, nStack);
assert(this.frame)
for (i = 0; nLocal > 0; ++i, --nLocal) {
t = locals[i];
this.frame[frameIndex++] = t;
if (t === Frame.LONG_$LI$() || t === Frame.DOUBLE_$LI$()) {
++i;
}
}
for (i = 0; i < stacks.length; ++i) {
t = stacks[i];
this.frame[frameIndex++] = t;
if (t === Frame.LONG_$LI$() || t === Frame.DOUBLE_$LI$()) {
++i;
}
}
this.endFrame();
}
/**
* Visit the implicit first frame of this method.
*/
private visitImplicitFirstFrame() {
assert(this.frame)
let frameIndex: number = this.startFrame(0, this.descriptor.length + 1, 0);
if ((this.access & Opcodes.ACC_STATIC) === 0) {
if ((this.access & MethodWriter.ACC_CONSTRUCTOR) === 0) {
this.frame[frameIndex++] = Frame.OBJECT_$LI$() | this.cw.addType(this.cw.thisName);
} else {
this.frame[frameIndex++] = 6;
}
}
let i: number = 1;
loop: while ((true)) {
let j: number = i;
switch ((this.descriptor.charAt(i++))) {
case "Z":
case "C":
case "B":
case "S":
case "I":
this.frame[frameIndex++] = 1;
break;
case "F":
this.frame[frameIndex++] = 2;
break;
case "J":
this.frame[frameIndex++] = 4;
break;
case "D":
this.frame[frameIndex++] = 3;
break;
case "[":
while ((this.descriptor.charAt(i) === "[")) {
++i;
};
if (this.descriptor.charAt(i) === "L") {
++i;
while ((this.descriptor.charAt(i) !== ";")) {
++i;
};
}
this.frame[frameIndex++] = Frame.OBJECT_$LI$() | this.cw.addType(this.descriptor.substring(j, ++i));
break;
case "L":
while ((this.descriptor.charAt(i) !== ";")) {
++i;
};
this.frame[frameIndex++] = Frame.OBJECT_$LI$() | this.cw.addType(this.descriptor.substring(j + 1, i++));
break;
default:
break loop;
}
};
this.frame[1] = frameIndex - 3;
this.endFrame();
}
/**
* Starts the visit of a stack map frame.
*
* @param offset
* the offset of the instruction to which the frame corresponds.
* @param nLocal
* the number of local variables in the frame.
* @param nStack
* the number of stack elements in the frame.
* @return the index of the next element to be written in this frame.
*/
private startFrame(offset: number, nLocal: number, nStack: number): number {
let n: number = 3 + nLocal + nStack;
if (this.frame == null || this.frame.length < n) {
this.frame = new Array(n);
}
this.frame[0] = offset;
this.frame[1] = nLocal;
this.frame[2] = nStack;
return 3;
}
/**
* Checks if the visit of the current frame {@link #frame} is finished, and
* if yes, write it in the StackMapTable attribute.
*/
private endFrame() {
if (this.previousFrame != null) {
if (this.stackMap == null) {
this.stackMap = new ByteVector();
}
this.writeFrame();
++this.frameCount;
}
this.previousFrame = this.frame;
this.frame = null;
}
/**
* Compress and writes the current frame {@link #frame} in the StackMapTable
* attribute.
*/
private writeFrame() {
assert(this.frame);
assert(this.previousFrame);
assert(this.stackMap);
let clocalsSize: number = this.frame[1];
let cstackSize: number = this.frame[2];
if ((this.cw.version & 65535) < Opcodes.V1_6) {
this.stackMap.putShort(this.frame[0]).putShort(clocalsSize);
this.writeFrameTypes(3, 3 + clocalsSize);
this.stackMap.putShort(cstackSize);
this.writeFrameTypes(3 + clocalsSize, 3 + clocalsSize + cstackSize);
return;
}
let localsSize: number = this.previousFrame[1];
let type: number = MethodWriter.FULL_FRAME;
let k: number = 0;
let delta: number;
if (this.frameCount === 0) {
delta = this.frame[0];
} else {
delta = this.frame[0] - this.previousFrame[0] - 1;
}
if (cstackSize === 0) {
k = clocalsSize - localsSize;
switch ((k)) {
case -3:
case -2:
case -1:
type = MethodWriter.CHOP_FRAME;
localsSize = clocalsSize;
break;
case 0:
type = delta < 64 ? MethodWriter.SAME_FRAME : MethodWriter.SAME_FRAME_EXTENDED;
break;
case 1:
case 2:
case 3:
type = MethodWriter.APPEND_FRAME;
break;
}
} else if (clocalsSize === localsSize && cstackSize === 1) {
type = delta < 63 ? MethodWriter.SAME_LOCALS_1_STACK_ITEM_FRAME : MethodWriter.SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED;
}
if (type !== MethodWriter.FULL_FRAME) {
let l: number = 3;
for (let j: number = 0; j < localsSize; j++) {
if (this.frame[l] !== this.previousFrame[l]) {
type = MethodWriter.FULL_FRAME;
break;
}
l++;
}
}
switch ((type)) {
case MethodWriter.SAME_FRAME:
this.stackMap.putByte(delta);
break;
case MethodWriter.SAME_LOCALS_1_STACK_ITEM_FRAME:
this.stackMap.putByte(MethodWriter.SAME_LOCALS_1_STACK_ITEM_FRAME + delta);
this.writeFrameTypes(3 + clocalsSize, 4 + clocalsSize);
break;
case MethodWriter.SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED:
this.stackMap.putByte(MethodWriter.SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED).putShort(delta);
this.writeFrameTypes(3 + clocalsSize, 4 + clocalsSize);
break;
case MethodWriter.SAME_FRAME_EXTENDED:
this.stackMap.putByte(MethodWriter.SAME_FRAME_EXTENDED).putShort(delta);
break;
case MethodWriter.CHOP_FRAME:
this.stackMap.putByte(MethodWriter.SAME_FRAME_EXTENDED + k).putShort(delta);
break;
case MethodWriter.APPEND_FRAME:
this.stackMap.putByte(MethodWriter.SAME_FRAME_EXTENDED + k).putShort(delta);
this.writeFrameTypes(3 + localsSize, 3 + clocalsSize);
break;
default:
this.stackMap.putByte(MethodWriter.FULL_FRAME).putShort(delta).putShort(clocalsSize);
this.writeFrameTypes(3, 3 + clocalsSize);
this.stackMap.putShort(cstackSize);
this.writeFrameTypes(3 + clocalsSize, 3 + clocalsSize + cstackSize);
}
}
/**
* Writes some types of the current frame {@link #frame} into the
* StackMapTableAttribute. This method converts types from the format used
* in {@link Label} to the format used in StackMapTable attributes. In
* particular, it converts type table indexes to constant pool indexes.
*
* @param start
* index of the first type in {@link #frame} to write.
* @param end
* index of last type in {@link #frame} to write (exclusive).
*/
private writeFrameTypes(start: number, end: number) {
assert(this.frame);
assert(this.stackMap);
for (let i: number = start; i < end; ++i) {
let t: number = this.frame[i];
let d: number = t & Frame.DIM;
if (d === 0) {
let v: number = t & Frame.BASE_VALUE;
switch ((t & Frame.BASE_KIND)) {
case Frame.OBJECT_$LI$():
this.stackMap.putByte(7).putShort(this.cw.newClass(this.cw.typeTable[v].strVal1));
break;
case Frame.UNINITIALIZED_$LI$():
this.stackMap.putByte(8).putShort(this.cw.typeTable[v].intVal);
break;
default:
this.stackMap.putByte(v);
}
} else {
let sb: string = "";
d >>= 28;
while ((d-- > 0)) {
sb += "[";
};
if ((t & Frame.BASE_KIND) === Frame.OBJECT_$LI$()) {
sb += "L";
sb += this.cw.typeTable[t & Frame.BASE_VALUE].strVal1;
sb += ";";
} else {
switch ((t & 15)) {
case 1:
sb += "I";
break;
case 2:
sb += "F";
break;
case 3:
sb += "D";
break;
case 9:
sb += "Z";
break;
case 10:
sb += "B";
break;
case 11:
sb += "C";
break;
case 12:
sb += "S";
break;
default:
sb += "J";
}
}
this.stackMap.putByte(7).putShort(this.cw.newClass(sb.toString()));
}
}
}
private writeFrameType(type: any) {
assert(this.stackMap);
if (typeof type === "string") {
this.stackMap.putByte(7).putShort(this.cw.newClass(type));
} else if (typeof type === "number") {
this.stackMap.putByte(/* intValue */((type) | 0));
} else {
this.stackMap.putByte(8).putShort((<Label>type).position);
}
}
/**
* Returns the size of the bytecode of this method.
*
* @return the size of the bytecode of this method.
*/
getSize(): number {
if (this.classReaderOffset !== 0) {
return 6 + this.classReaderLength;
}
let size: number = 8;
if (this.code.length > 0) {
if (this.code.length > 65535) {
throw new Error("Method code too large!");
}
this.cw.newUTF8("Code");
size += 18 + this.code.length + 8 * this.handlerCount;
if (this.localVar != null) {
this.cw.newUTF8("LocalVariableTable");
size += 8 + this.localVar.length;
}
if (this.localVarType != null) {
this.cw.newUTF8("LocalVariableTypeTable");
size += 8 + this.localVarType.length;
}
if (this.lineNumber != null) {
this.cw.newUTF8("LineNumberTable");
size += 8 + this.lineNumber.length;
}
if (this.stackMap != null) {
let zip: boolean = (this.cw.version & 65535) >= Opcodes.V1_6;
this.cw.newUTF8(zip ? "StackMapTable" : "StackMap");
size += 8 + this.stackMap.length;
}
if (ClassReader.ANNOTATIONS && this.ctanns != null) {
this.cw.newUTF8("RuntimeVisibleTypeAnnotations");
size += 8 + this.ctanns.getSize();
}
if (ClassReader.ANNOTATIONS && this.ictanns != null) {
this.cw.newUTF8("RuntimeInvisibleTypeAnnotations");
size += 8 + this.ictanns.getSize();
}
if (this.cattrs != null) {
size += this.cattrs.getSize(this.cw, this.code.data, this.code.length, this.maxStack, this.maxLocals);
}
}
if (this.exceptionCount > 0) {
this.cw.newUTF8("Exceptions");
size += 8 + 2 * this.exceptionCount;
}
if ((this.access & Opcodes.ACC_SYNTHETIC) !== 0) {
if ((this.cw.version & 65535) < Opcodes.V1_5 || (this.access & ClassWriter.ACC_SYNTHETIC_ATTRIBUTE) !== 0) {
this.cw.newUTF8("Synthetic");
size += 6;
}
}
if ((this.access & Opcodes.ACC_DEPRECATED) !== 0) {
this.cw.newUTF8("Deprecated");
size += 6;
}
if (ClassReader.SIGNATURES && this.signature != null) {
this.cw.newUTF8("Signature");
this.cw.newUTF8(this.signature);
size += 8;
}
if (this.methodParameters != null) {
this.cw.newUTF8("MethodParameters");
size += 7 + this.methodParameters.length;
}
if (ClassReader.ANNOTATIONS && this.annd != null) {
this.cw.newUTF8("AnnotationDefault");
size += 6 + this.annd.length;
}
if (ClassReader.ANNOTATIONS && this.anns != null) {
this.cw.newUTF8("RuntimeVisibleAnnotations");
size += 8 + this.anns.getSize();
}
if (ClassReader.ANNOTATIONS && this.ianns != null) {
this.cw.newUTF8("RuntimeInvisibleAnnotations");
size += 8 + this.ianns.getSize();
}
if (ClassReader.ANNOTATIONS && this.tanns != null) {
this.cw.newUTF8("RuntimeVisibleTypeAnnotations");
size += 8 + this.tanns.getSize();
}
if (ClassReader.ANNOTATIONS && this.itanns != null) {
this.cw.newUTF8("RuntimeInvisibleTypeAnnotations");
size += 8 + this.itanns.getSize();
}
if (ClassReader.ANNOTATIONS && this.panns != null) {
this.cw.newUTF8("RuntimeVisibleParameterAnnotations");
size += 7 + 2 * (this.panns.length - this.synthetics);
for (let i: number = this.panns.length - 1; i >= this.synthetics; --i) {
size += this.panns[i] == null ? 0 : this.panns[i].getSize();
}
}
if (ClassReader.ANNOTATIONS && this.ipanns != null) {
this.cw.newUTF8("RuntimeInvisibleParameterAnnotations");
size += 7 + 2 * (this.ipanns.length - this.synthetics);
for (let i: number = this.ipanns.length - 1; i >= this.synthetics; --i) {
size += this.ipanns[i] == null ? 0 : this.ipanns[i].getSize();
}
}
if (this.attrs != null) {
size += this.attrs.getSize(this.cw, null, 0, -1, -1);
}
return size;
}
/**
* Puts the bytecode of this method in the given byte vector.
*
* @param out
* the byte vector into which the bytecode of this method must be
* copied.
*/
put(out: ByteVector) {
let FACTOR: number = ClassWriter.TO_ACC_SYNTHETIC_$LI$();
let mask: number = MethodWriter.ACC_CONSTRUCTOR | Opcodes.ACC_DEPRECATED | ClassWriter.ACC_SYNTHETIC_ATTRIBUTE | (((this.access & ClassWriter.ACC_SYNTHETIC_ATTRIBUTE) / FACTOR | 0));
out.putShort(this.access & ~mask).putShort(this.name).putShort(this.desc);
if (this.classReaderOffset !== 0) {
out.putByteArray(this.cw.cr.buf, this.classReaderOffset, this.classReaderLength);
return;
}
let attributeCount: number = 0;
if (this.code.length > 0) {
++attributeCount;
}
if (this.exceptionCount > 0) {
++attributeCount;
}
if ((this.access & Opcodes.ACC_SYNTHETIC) !== 0) {
if ((this.cw.version & 65535) < Opcodes.V1_5 || (this.access & ClassWriter.ACC_SYNTHETIC_ATTRIBUTE) !== 0) {
++attributeCount;
}
}
if ((this.access & Opcodes.ACC_DEPRECATED) !== 0) {
++attributeCount;
}
if (ClassReader.SIGNATURES && this.signature != null) {
++attributeCount;
}
if (this.methodParameters != null) {
++attributeCount;
}
if (ClassReader.ANNOTATIONS && this.annd != null) {
++attributeCount;
}
if (ClassReader.ANNOTATIONS && this.anns != null) {
++attributeCount;
}
if (ClassReader.ANNOTATIONS && this.ianns != null) {
++attributeCount;
}
if (ClassReader.ANNOTATIONS && this.tanns != null) {
++attributeCount;
}
if (ClassReader.ANNOTATIONS && this.itanns != null) {
++attributeCount;
}
if (ClassReader.ANNOTATIONS && this.panns != null) {
++attributeCount;
}
if (ClassReader.ANNOTATIONS && this.ipanns != null) {
++attributeCount;
}
if (this.attrs != null) {
attributeCount += this.attrs.getCount();
}
out.putShort(attributeCount);
if (this.code.length > 0) {
let size: number = 12 + this.code.length + 8 * this.handlerCount;
if (this.localVar != null) {
size += 8 + this.localVar.length;
}
if (this.localVarType != null) {
size += 8 + this.localVarType.length;
}
if (this.lineNumber != null) {
size += 8 + this.lineNumber.length;
}
if (this.stackMap != null) {
size += 8 + this.stackMap.length;
}
if (ClassReader.ANNOTATIONS && this.ctanns != null) {
size += 8 + this.ctanns.getSize();
}
if (ClassReader.ANNOTATIONS && this.ictanns != null) {
size += 8 + this.ictanns.getSize();
}
if (this.cattrs != null) {
size += this.cattrs.getSize(this.cw, this.code.data, this.code.length, this.maxStack, this.maxLocals);
}
out.putShort(this.cw.newUTF8("Code")).putInt(size);
out.putShort(this.maxStack).putShort(this.maxLocals);
out.putInt(this.code.length).putByteArray(this.code.data, 0, this.code.length);
out.putShort(this.handlerCount);
if (this.handlerCount > 0) {
let h: Handler | null = this.firstHandler;
while ((h != null)) {
out.putShort(h.start!.position).putShort(h.end!.position).putShort(h.handler!.position).putShort(h.type);
h = h.next;
};
}
attributeCount = 0;
if (this.localVar != null) {
++attributeCount;
}
if (this.localVarType != null) {
++attributeCount;
}
if (this.lineNumber != null) {
++attributeCount;
}
if (this.stackMap != null) {
++attributeCount;
}
if (ClassReader.ANNOTATIONS && this.ctanns != null) {
++attributeCount;
}
if (ClassReader.ANNOTATIONS && this.ictanns != null) {
++attributeCount;
}
if (this.cattrs != null) {
attributeCount += this.cattrs.getCount();
}
out.putShort(attributeCount);
if (this.localVar != null) {
out.putShort(this.cw.newUTF8("LocalVariableTable"));
out.putInt(this.localVar.length + 2).putShort(this.localVarCount);
out.putByteArray(this.localVar.data, 0, this.localVar.length);
}
if (this.localVarType != null) {
out.putShort(this.cw.newUTF8("LocalVariableTypeTable"));
out.putInt(this.localVarType.length + 2).putShort(this.localVarTypeCount);
out.putByteArray(this.localVarType.data, 0, this.localVarType.length);
}
if (this.lineNumber != null) {
out.putShort(this.cw.newUTF8("LineNumberTable"));
out.putInt(this.lineNumber.length + 2).putShort(this.lineNumberCount);
out.putByteArray(this.lineNumber.data, 0, this.lineNumber.length);
}
if (this.stackMap != null) {
let zip: boolean = (this.cw.version & 65535) >= Opcodes.V1_6;
out.putShort(this.cw.newUTF8(zip ? "StackMapTable" : "StackMap"));
out.putInt(this.stackMap.length + 2).putShort(this.frameCount);
out.putByteArray(this.stackMap.data, 0, this.stackMap.length);
}
if (ClassReader.ANNOTATIONS && this.ctanns != null) {
out.putShort(this.cw.newUTF8("RuntimeVisibleTypeAnnotations"));
this.ctanns.put(out);
}
if (ClassReader.ANNOTATIONS && this.ictanns != null) {
out.putShort(this.cw.newUTF8("RuntimeInvisibleTypeAnnotations"));
this.ictanns.put(out);
}
if (this.cattrs != null) {
this.cattrs.put(this.cw, this.code.data, this.code.length, this.maxLocals, this.maxStack, out);
}
}
if (this.exceptionCount > 0) {
assert(this.exceptions);
out.putShort(this.cw.newUTF8("Exceptions")).putInt(2 * this.exceptionCount + 2);
out.putShort(this.exceptionCount);
for (let i: number = 0; i < this.exceptionCount; ++i) {
out.putShort(this.exceptions[i]);
}
}
if ((this.access & Opcodes.ACC_SYNTHETIC) !== 0) {
if ((this.cw.version & 65535) < Opcodes.V1_5 || (this.access & ClassWriter.ACC_SYNTHETIC_ATTRIBUTE) !== 0) {
out.putShort(this.cw.newUTF8("Synthetic")).putInt(0);
}
}
if ((this.access & Opcodes.ACC_DEPRECATED) !== 0) {
out.putShort(this.cw.newUTF8("Deprecated")).putInt(0);
}
if (ClassReader.SIGNATURES && this.signature != null) {
out.putShort(this.cw.newUTF8("Signature")).putInt(2).putShort(this.cw.newUTF8(this.signature));
}
if (this.methodParameters != null) {
out.putShort(this.cw.newUTF8("MethodParameters"));
out.putInt(this.methodParameters.length + 1).putByte(this.methodParametersCount);
out.putByteArray(this.methodParameters.data, 0, this.methodParameters.length);
}
if (ClassReader.ANNOTATIONS && this.annd != null) {
out.putShort(this.cw.newUTF8("AnnotationDefault"));
out.putInt(this.annd.length);
out.putByteArray(this.annd.data, 0, this.annd.length);
}
if (ClassReader.ANNOTATIONS && this.anns != null) {
out.putShort(this.cw.newUTF8("RuntimeVisibleAnnotations"));
this.anns.put(out);
}
if (ClassReader.ANNOTATIONS && this.ianns != null) {
out.putShort(this.cw.newUTF8("RuntimeInvisibleAnnotations"));
this.ianns.put(out);
}
if (ClassReader.ANNOTATIONS && this.tanns != null) {
out.putShort(this.cw.newUTF8("RuntimeVisibleTypeAnnotations"));
this.tanns.put(out);
}
if (ClassReader.ANNOTATIONS && this.itanns != null) {
out.putShort(this.cw.newUTF8("RuntimeInvisibleTypeAnnotations"));
this.itanns.put(out);
}
if (ClassReader.ANNOTATIONS && this.panns != null) {
out.putShort(this.cw.newUTF8("RuntimeVisibleParameterAnnotations"));
AnnotationWriter.put(this.panns, this.synthetics, out);
}
if (ClassReader.ANNOTATIONS && this.ipanns != null) {
out.putShort(this.cw.newUTF8("RuntimeInvisibleParameterAnnotations"));
AnnotationWriter.put(this.ipanns, this.synthetics, out);
}
if (this.attrs != null) {
this.attrs.put(this.cw, null, 0, -1, -1, out);
}
}
}
class Handler {
/**
* Beginning of the exception handler's scope (inclusive).
*/
start: Label | null = null;
/**
* End of the exception handler's scope (exclusive).
*/
end: Label | null = null;
/**
* Beginning of the exception handler's code.
*/
handler: Label | null = null;
/**
* Internal name of the type of exceptions handled by this handler, or
* <tt>null</tt> to catch any exceptions.
*/
desc: string = "";
/**
* Constant pool index of the internal name of the type of exceptions
* handled by this handler, or 0 to catch any exceptions.
*/
type: number;
/**
* Next exception handler block info.
*/
next: Handler | null = null;
/**
* Removes the range between start and end from the given exception
* handlers.
*
* @param h
* an exception handler list.
* @param start
* the start of the range to be removed.
* @param end
* the end of the range to be removed. Maybe null.
* @return the exception handler list with the start-end range removed.
*/
static remove(h: Handler | null, start: Label, end: Label): Handler | null {
if (h == null) {
return null;
} else {
h.next = Handler.remove(h.next, start, end);
}
assert(h.start)
assert(h.end)
let hstart: number = h.start.position;
let hend: number = h.end.position;
let s: number = start.position;
// let e : number = end == null?javaemul.internal.IntegerHelper.MAX_VALUE:end.position;
let e: number = end == null ? Number.MAX_VALUE : end.position;
if (s < hend && e > hstart) {
if (s <= hstart) {
if (e >= hend) {
h = h.next;
} else {
h.start = end;
}
} else if (e >= hend) {
h.end = start;
} else {
let g: Handler = new Handler();
g.start = end;
g.end = h.end;
g.handler = h.handler;
g.desc = h.desc;
g.type = h.type;
g.next = h.next;
h.end = start;
h.next = g;
}
}
return h;
}
constructor() {
this.type = 0;
}
} | the_stack |
import { imageSize as getImageData } from 'image-size';
import { ISizeCalculationResult } from 'image-size/dist/types/interface';
import { normalizeString } from '@hint/utils-string';
import { isRegularProtocol } from '@hint/utils-network';
import { debug as d } from '@hint/utils-debug';
import { HintContext, IHint, NetworkData, TraverseEnd } from 'hint';
import { HTMLDocument, HTMLElement } from '@hint/utils-dom';
import { Severity } from '@hint/utils-types';
import meta from './meta';
import { getMessage } from './i18n.import';
const debug: debug.IDebugger = d(__filename);
const recommendedSizes = [
'120x120', /* iPhone 120px x 120px (60pt x 60pt @2x) */
'152x152', /* iPhone 152px x 152px (76pt x 76pt @2x) */
'167x167', /* iPhone 167px x 167px (83.5pt x 83.5pt @2x) */
'180x180' /* iPhone 180px x 180px (60pt x 60pt @3x) */
];
type Image = {
data: ISizeCalculationResult;
element: HTMLElement;
};
/*
* ------------------------------------------------------------------------------
* Public
* ------------------------------------------------------------------------------
*/
export default class AppleTouchIconsHint implements IHint {
public static readonly meta = meta;
public constructor(context: HintContext) {
/*
* This function exists because not all connector (e.g.: jsdom)
* support matching attribute values case-insensitively.
*
* https://www.w3.org/TR/selectors4/#attribute-case
*/
const getAppleTouchIcons = (elements: HTMLElement[]): HTMLElement[] => {
return elements.filter((element) => {
/*
* `apple-touch-icon`s can be defined either by using:
*
* <link rel="apple-touch-icon" href="...">
*
* or
*
* <link rel="apple-touch-icon-precomposed" href="...">
*
* or, since the `rel` attribute accepts a space
* separated list of values in HTML, theoretically:
*
* <link rel="apple-touch-icon-precomposed apple-touch-icon" href="...">
*
* but that doesn't work in practice.
*/
const relValue = element.getAttribute('rel');
if (relValue === null) {
return false;
}
// `normalizeString` won't return null since `relValue` isn't null.
const relValues = normalizeString(relValue)!.split(' ');
return relValues.includes('apple-touch-icon') || relValues.includes('apple-touch-icon-precomposed');
});
};
const getImage = async (appleTouchIcon: HTMLElement, resource: string) => {
const appleTouchIconHref = normalizeString(appleTouchIcon.getAttribute('href'));
/*
* Check if `href` doesn't exist, or it has the
* value of empty string.
*/
if (!appleTouchIconHref) {
const message = getMessage('noEmptyHref', context.language);
context.report(
resource,
message,
{ element: appleTouchIcon, severity: Severity.error });
return null;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
/*
* The following checks don't make sense for non-HTTP(S).
*/
if (!isRegularProtocol(resource)) {
return null;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
/*
* If `href` exists and is not an empty string, try
* to figure out the full URL of the `apple-touch-icon`.
*/
const appleTouchIconURL = appleTouchIcon.resolveUrl(appleTouchIconHref);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
let networkData: NetworkData;
/*
* Try to see if the `apple-touch-icon` file actually
* exists and is accesible.
*/
try {
networkData = await context.fetchContent(appleTouchIconURL);
} catch (e) {
debug(`Failed to fetch the ${appleTouchIconHref} file`);
const message = getMessage('couldNotBeFetch', context.language);
context.report(
resource,
message,
{ element: appleTouchIcon, severity: Severity.error }
);
return null;
}
const response = networkData.response;
if (response.statusCode !== 200) {
const message = getMessage('couldNotBeFetchErrorStatusCode', context.language, response.statusCode.toString());
context.report(
resource,
message,
{ element: appleTouchIcon, severity: Severity.error }
);
return null;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
let image;
/*
* Notes:
*
* * Async version of `image-size` doesn't work if the
* input is a Buffer.
*
* https://github.com/image-size/image-size/tree/4c527ba608d742fbb29f6d9b3c77b831b069cbb2#asynchronous
*
* * `image-size` will throw a `TypeError` error if it does
* not understand the file type or the image is invalid
* or corrupted.
*/
try {
image = getImageData(response.body.rawContent);
} catch (e) {
if (e instanceof TypeError) {
const message = getMessage('invalidPNG', context.language);
context.report(
resource,
message,
{ element: appleTouchIcon, severity: Severity.error }
);
} else {
debug(`'getImageData' failed for '${appleTouchIconURL}'`);
}
return null;
}
return image;
};
const checkImage = (image: Image, someRecommended: boolean, resource: string) => {
// Check if the image is a PNG.
if (image.data.type !== 'png') {
const message = getMessage('shouldBePNG', context.language);
context.report(
resource,
message,
{ element: image.element, severity: Severity.error }
);
}
// Check the size of the image.
const sizeString = `${image.data.width}x${image.data.height}`;
if (!recommendedSizes.includes(sizeString)) {
const message = getMessage('wrongResolution', context.language, recommendedSizes.toString());
context.report(
resource,
message,
{ element: image.element, severity: someRecommended ? Severity.warning : Severity.error }
);
}
// TODO: Check if the image has some kind of transparency.
};
const validate = async ({ resource }: TraverseEnd) => {
const pageDOM = context.pageDOM as HTMLDocument;
const appleTouchIcons = getAppleTouchIcons(pageDOM.querySelectorAll('link'));
const linksToManifest = pageDOM.querySelectorAll('link[rel="manifest"]').length > 0;
if (appleTouchIcons.length === 0) {
if (linksToManifest) {
context.report(
resource,
getMessage('noElement', context.language),
{ severity: Severity.error });
}
return;
}
const images: Image[] = [];
for (const appleTouchIcon of appleTouchIcons) {
/*
* Check if `rel='apple-touch-icon'`.
* See `getAppleTouchIcons` function for more details.
*/
if (normalizeString(appleTouchIcon.getAttribute('rel')) !== 'apple-touch-icon') {
const message = getMessage('wrongRelAttribute', context.language);
context.report(
resource,
message,
{ element: appleTouchIcon, severity: Severity.warning }
);
}
/*
* Check if the `apple-touch-icon` exists, and
* returns the image information.
*/
const image = await getImage(appleTouchIcon, resource);
if (image) {
images.push({
data: image,
element: appleTouchIcon
});
}
}
/*
* Check if any of the images has a recommended size
*/
const someRecommended = images.some(({data}) => {
const sizeString = `${data.width}x${data.height}`;
return recommendedSizes.includes(sizeString);
});
for (const image of images) {
/*
* Check image format and size.
*/
checkImage(image, someRecommended, resource);
}
/*
* Check if the `apple-touch-icon` is included in the `<body>`.
*/
const bodyAppleTouchIcons: HTMLElement[] = getAppleTouchIcons(pageDOM.querySelectorAll('body link'));
for (const icon of bodyAppleTouchIcons) {
const message = getMessage('elementNotInHead', context.language);
context.report(
resource,
message,
{ element: icon, severity: Severity.error }
);
}
/*
* Look for duplicated `apple-touch-icon`s.
*/
const iconsHref: Set<string> = new Set();
for (const appleTouchIcon of appleTouchIcons) {
const href = appleTouchIcon.getAttribute('href');
if (!href) {
continue;
}
if (iconsHref.has(href)) {
const message = getMessage('elementDuplicated', context.language);
context.report(
resource,
message,
{ element: appleTouchIcon, severity: Severity.warning }
);
}
iconsHref.add(href);
}
};
context.on('traverse::end', validate);
}
} | the_stack |
import type { MapSeries } from "./MapSeries";
import type { GeoProjection, GeoPath } from "d3-geo";
import type { IPoint } from "../../core/util/IPoint";
import type { IGeoPoint } from "../../core/util/IGeoPoint";
import type { Time } from "../../core/util/Animation";
import type { ZoomControl } from "./ZoomControl";
import type { Animation } from "../../core/util/Entity";
import { MapChartDefaultTheme } from "./MapChartDefaultTheme";
import { SerialChart, ISerialChartPrivate, ISerialChartSettings, ISerialChartEvents } from "../../core/render/SerialChart";
import { Rectangle } from "../../core/render/Rectangle";
import { geoPath } from "d3-geo";
import { Color } from "../../core/util/Color";
import { registry } from "../../core/Registry";
import * as $math from "../../core/util/Math";
import * as $array from "../../core/util/Array";
import * as $type from "../../core/util/Type";
import * as $mapUtils from "./MapUtils";
import * as $object from "../../core/util/Object";
import * as $utils from "../../core/util/Utils";
import type { IDisposer } from "../../core/util/Disposer";
import type { ISpritePointerEvent } from "../../core/render/Sprite";
export interface IMapChartSettings extends ISerialChartSettings {
/**
* A projection to use when plotting the map.
*
* @see {@link https://www.amcharts.com/docs/v5/charts/map-chart/#Projections} for more info
*/
projection?: GeoProjection;
/**
* Current zoom level.
*/
zoomLevel?: number;
/**
* @ignore
*/
translateX?: number;
/**
* @ignore
*/
translateY?: number;
/**
* Vertical centering of the map.
*
* @see {@link https://www.amcharts.com/docs/v5/charts/map-chart/#Centering_the_map} for more info
*/
rotationY?: number;
/**
* Horizontal centering of the map.
*
* @see {@link https://www.amcharts.com/docs/v5/charts/map-chart/#Centering_the_map} for more info
*/
rotationX?: number;
/**
* Depth centering of the map.
*
* @see {@link https://www.amcharts.com/docs/v5/charts/map-chart/#Centering_the_map} for more info
*/
rotationZ?: number;
/**
* Highest zoom level map is allowed to zoom in to.
*
* @deault 32
*/
maxZoomLevel?: number;
/**
* Lowest zoom level map is allowed to zoom in to.
*
* @deault 1
*/
minZoomLevel?: number;
/**
* Increment zoom level by `zoomStep` when user zooms in via [[ZoomControl]] or
* API.
*
* @default 2
*/
zoomStep?: number;
/**
* Defines what happens when map is being dragged horizontally.
*
* @see {@link https://www.amcharts.com/docs/v5/charts/map-chart/map-pan-zoom/#Panning} for more info
* @default "translateX"
*/
panX?: "none" | "rotateX" | "translateX";
/**
* Defines what happens when map is being dragged vertically.
*
* @see {@link https://www.amcharts.com/docs/v5/charts/map-chart/map-pan-zoom/#Panning} for more info
* @default "translateY"
*/
panY?: "none" | "rotateY" | "translateY";
/**
* Enables pinch-zooming of the map on multi-touch devices.
*
* @see {@link https://www.amcharts.com/docs/v5/charts/map-chart/map-pan-zoom/#Pinch_zoom} for more info
* @default true
*/
pinchZoom?: boolean;
/**
* Defines what happens when mouse wheel is turned horizontally.
*
* @see {@link https://www.amcharts.com/docs/v5/charts/map-chart/map-pan-zoom/#Mouse_wheel_behavior} for more info
* @default "none"
*/
wheelX?: "none" | "zoom" | "rotateX" | "rotateY";
/**
* Defines what happens when mouse wheel is turned vertically.
*
* @see {@link https://www.amcharts.com/docs/v5/charts/map-chart/map-pan-zoom/#Mouse_wheel_behavior} for more info
* @default "zoom"
*/
wheelY?: "none" | "zoom" | "rotateX" | "rotateY";
/**
* Sensitivity of a mouse wheel.
*
* @default 1
*/
wheelSensitivity?: number;
/**
* Duration of mouse-wheel action animation, in milliseconds.
*/
wheelDuration?: number;
/**
* An easing function to use for mouse wheel action animations.
*
* @see {@link https://www.amcharts.com/docs/v5/concepts/animations/#Easing_functions} for more info
* @default am5.ease.out($ease.cubic)
*/
wheelEasing?: (t: Time) => Time;
/**
* Duration of zoom/pan animations, in milliseconds.
*/
animationDuration?: number;
/**
* An easing function to use for zoom/pan animations.
*
* @see {@link https://www.amcharts.com/docs/v5/concepts/animations/#Easing_functions} for more info
* @default am5.ease.out($ease.cubic)
*/
animationEasing?: (t: Time) => Time;
/**
* A [[ZoomControl]] instance.
*
* @see {@link https://www.amcharts.com/docs/v5/charts/map-chart/#Zoom_control} for more info
*/
zoomControl?: ZoomControl;
/**
* Initial/home zoom level.
*
* @see {@link https://www.amcharts.com/docs/v5/charts/map-chart/map-pan-zoom/#Initial_position_and_zoom} for more info
*/
homeZoomLevel?: number;
/**
* Initial coordinates to center map on load or `goHome()` call.
*
* @see {@link https://www.amcharts.com/docs/v5/charts/map-chart/map-pan-zoom/#Initial_position_and_zoom} for more info
*/
homeGeoPoint?: IGeoPoint;
/**
* How much of a map can go outside the viewport.
*
* @default 0.4
* @see {@link https://www.amcharts.com/docs/v5/charts/map-chart/map-pan-zoom/#Panning_outside_viewport} for more info
*/
maxPanOut?: number;
}
export interface IMapChartPrivate extends ISerialChartPrivate {
/**
* @ignore
*/
geoPath: GeoPath;
/**
* @ignore
*/
mapScale: number;
}
export interface IMapChartEvents extends ISerialChartEvents {
/**
* Invoked when geo bounds of the map change, usually after map is iniitalized
*/
geoboundschanged: {};
}
export class MapChart extends SerialChart {
public static className: string = "MapChart";
public static classNames: Array<string> = SerialChart.classNames.concat([MapChart.className]);
declare public _settings: IMapChartSettings;
declare public _privateSettings: IMapChartPrivate;
declare public _seriesType: MapSeries;
declare public _events: IMapChartEvents;
protected _downTranslateX: number | undefined;
protected _downTranslateY: number | undefined;
protected _downRotationX: number | undefined;
protected _downRotationY: number | undefined;
protected _downRotationZ: number | undefined;
protected _pLat: number = 0;
protected _pLon: number = 0;
protected _movePoints: { [index: number]: IPoint } = {};
protected _downZoomLevel: number = 1;
protected _doubleDownDistance: number = 0;
protected _dirtyGeometries: boolean = false;
protected _geometryColection: GeoJSON.GeometryCollection = { type: "GeometryCollection", geometries: [] };
protected _centerLocation: [number, number] | null = null;
protected _za?: Animation<this["_settings"]["zoomLevel"]>;
protected _rxa?: Animation<this["_settings"]["rotationX"]>;
protected _rya?: Animation<this["_settings"]["rotationY"]>;
protected _txa?: Animation<this["_settings"]["translateX"]>;
protected _tya?: Animation<this["_settings"]["translateY"]>;
protected _mapBounds = [[0, 0], [0, 0]];
protected _geoCentroid: IGeoPoint = { longitude: 0, latitude: 0 };
protected _geoBounds: { left: number, right: number, top: number, bottom: number } = { left: 0, right: 0, top: 0, bottom: 0 };
protected _prevGeoBounds: { left: number, right: number, top: number, bottom: number } = { left: 0, right: 0, top: 0, bottom: 0 };
protected _dispatchBounds: boolean = false;
protected _wheelDp: IDisposer | undefined;
protected _pw?: number;
protected _ph?: number;
protected _mapFitted:boolean = false;
protected _makeGeoPath() {
const projection = this.get("projection")!;
const path = geoPath();
path.projection(projection);
this.setPrivateRaw("geoPath", path);
}
/**
* Returns coordinates to geographical center of the map.
*/
public geoCentroid() {
return this._geoCentroid;
}
/**
* Returns geographical bounds of the map.
*/
public geoBounds() {
return this._geoBounds;
}
protected _handleSetWheel() {
const wheelX = this.get("wheelX");
const wheelY = this.get("wheelY");
const chartContainer = this.chartContainer;
if (wheelX != "none" || wheelY != "none") {
this._wheelDp = chartContainer.events.on("wheel", (event) => {
const wheelEasing = this.get("wheelEasing")!;
const wheelSensitivity = this.get("wheelSensitivity", 1);
const wheelDuration = this.get("wheelDuration", 0);
const wheelEvent = event.originalEvent;
wheelEvent.preventDefault();
const chartContainer = this.chartContainer;
const point = chartContainer._display.toLocal(event.point);
if ((wheelY == "zoom")) {
this._handleWheelZoom(wheelEvent.deltaY, point);
}
else if (wheelY == "rotateY") {
this._handleWheelRotateY(wheelEvent.deltaY / 5 * wheelSensitivity, wheelDuration, wheelEasing);
}
else if (wheelY == "rotateX") {
this._handleWheelRotateX(wheelEvent.deltaY / 5 * wheelSensitivity, wheelDuration, wheelEasing);
}
if ((wheelX == "zoom")) {
this._handleWheelZoom(wheelEvent.deltaX, point);
}
else if (wheelX == "rotateY") {
this._handleWheelRotateY(wheelEvent.deltaX / 5 * wheelSensitivity, wheelDuration, wheelEasing);
}
else if (wheelX == "rotateX") {
this._handleWheelRotateX(wheelEvent.deltaX / 5 * wheelSensitivity, wheelDuration, wheelEasing);
}
});
this._disposers.push(this._wheelDp);
}
else {
if (this._wheelDp) {
this._wheelDp.dispose();
}
}
}
public _prepareChildren() {
super._prepareChildren();
const projection = this.get("projection")!;
const w = this.innerWidth();
const h = this.innerHeight();
if (this.isDirty("projection")) {
this._makeGeoPath();
this.markDirtyProjection();
this._fitMap();
projection.scale(this.getPrivate("mapScale") * this.get("zoomLevel", 1));
if (projection.rotate) {
projection.rotate([this.get("rotationX", 0), this.get("rotationY", 0), this.get("rotationZ", 0)])
}
let prev = this._prevSettings.projection;
if (prev && prev != projection) {
let hw = w / 2;
let hh = h / 2;
if (prev.invert) {
let centerLocation = prev.invert([hw, hh]);
if (centerLocation) {
let xy = projection(centerLocation);
if (xy) {
let translate = projection.translate();
let xx = hw - ((xy[0] - translate[0]));
let yy = hh - ((xy[1] - translate[1]));
projection.translate([xx, yy])
this.setRaw("translateX", xx);
this.setRaw("translateY", yy);
}
}
}
}
}
if (this.isDirty("wheelX") || this.isDirty("wheelY")) {
this._handleSetWheel();
}
var previousGeometries = this._geometryColection.geometries;
if (this._dirtyGeometries) {
this._geometryColection.geometries = [];
this.series.each((series) => {
$array.pushAll(this._geometryColection.geometries, series._geometries);
})
this._fitMap();
}
if (previousGeometries.length != 0 && (w != this._pw || h != this._ph || this._dirtyGeometries)) {
if (w > 0 && h > 0) {
let hw = w / 2;
let hh = h / 2;
projection.fitSize([w, h], this._geometryColection);
const newScale = projection.scale();
this.setPrivateRaw("mapScale", newScale);
projection.scale(newScale * this.get("zoomLevel", 1));
if (this._centerLocation) {
let xy = projection(this._centerLocation);
if (xy) {
let translate = projection.translate();
let xx = hw - ((xy[0] - translate[0]));
let yy = hh - ((xy[1] - translate[1]));
projection.translate([xx, yy])
this.setRaw("translateX", xx);
this.setRaw("translateY", yy);
}
}
this.markDirtyProjection();
}
}
this._pw = w;
this._ph = h;
if (this.isDirty("zoomControl")) {
const previous = this._prevSettings.zoomControl;
const zoomControl = this.get("zoomControl")!;
if (zoomControl !== previous) {
this._disposeProperty("zoomControl");
if (previous) {
previous.dispose();
}
if (zoomControl) {
zoomControl.setPrivate("chart", this);
this.children.push(zoomControl);
}
this.setRaw("zoomControl", zoomControl);
}
}
if (this.isDirty("zoomLevel")) {
projection.scale(this.getPrivate("mapScale") * this.get("zoomLevel", 1));
this.markDirtyProjection();
}
if (this.isDirty("translateX") || this.isDirty("translateY")) {
projection.translate([this.get("translateX", this.width() / 2), this.get("translateY", this.height() / 2)])
this.markDirtyProjection();
}
if (projection.rotate) {
if (this.isDirty("rotationX") || this.isDirty("rotationY") || this.isDirty("rotationZ")) {
projection.rotate([this.get("rotationX", 0), this.get("rotationY", 0), this.get("rotationZ", 0)])
this.markDirtyProjection();
}
}
}
protected _fitMap() {
const projection = this.get("projection")!;
let w = this.innerWidth();
let h = this.innerHeight();
if (w > 0 && h > 0) {
projection.fitSize([w, h], this._geometryColection);
this.setPrivateRaw("mapScale", projection.scale());
const translate = projection.translate();
this.setRaw("translateX", translate[0]);
this.setRaw("translateY", translate[1]);
const geoPath = this.getPrivate("geoPath");
this._mapBounds = geoPath.bounds(this._geometryColection);
this._geoCentroid = $mapUtils.getGeoCentroid(this._geometryColection);
const bounds = $mapUtils.getGeoBounds(this._geometryColection);
this._geoBounds = bounds;
if (this._geometryColection.geometries.length > 0) {
bounds.left = $math.round(this._geoBounds.left, 3);
bounds.right = $math.round(this._geoBounds.right, 3);
bounds.top = $math.round(this._geoBounds.top, 3);
bounds.bottom = $math.round(this._geoBounds.bottom, 3);
const prevGeoBounds = this._prevGeoBounds;
if (prevGeoBounds && !$utils.sameBounds(bounds, prevGeoBounds)) {
this._dispatchBounds = true;
this._prevGeoBounds = bounds;
}
}
this._mapFitted = true;
}
}
/**
* Repositions the map to the "home" zoom level and center coordinates.
*
* @see {@link https://www.amcharts.com/docs/v5/charts/map-chart/map-pan-zoom/#Resetting_position_level} for more info
* @param duration Animation duration in milliseconds
*/
public goHome(duration?: number) {
let homeGeoPoint = this.get("homeGeoPoint");
const homeZoomLevel = this.get("homeZoomLevel", 1);
if (!homeGeoPoint) {
const geoPath = this.getPrivate("geoPath");
const bounds = geoPath.bounds(this._geometryColection);
const left = bounds[0][0];
const top = bounds[0][1];
const right = bounds[1][0];
const bottom = bounds[1][1];
homeGeoPoint = this.invert({ x: left + (right - left) / 2, y: top + (bottom - top) / 2 });
}
this.zoomToGeoPoint(homeGeoPoint, homeZoomLevel, true, duration);
}
public _updateChildren() {
const projection = this.get("projection")!;
if (projection.invert) {
let w = this.innerWidth();
let h = this.innerHeight();
if (w > 0 && h > 0) {
this._centerLocation = projection.invert([this.innerWidth() / 2, this.innerHeight() / 2]);
}
}
}
public _afterChanged() {
super._afterChanged();
if (this._dispatchBounds) {
this._dispatchBounds = false;
const type = "geoboundschanged";
if (this.events.isEnabled(type)) {
this.events.dispatch(type, { type: type, target: this });
}
}
}
/**
* @ignore
*/
public markDirtyGeometries() {
this._dirtyGeometries = true;
this.markDirty();
}
/**
* @ignore
*/
public markDirtyProjection() {
this.series.each((series) => {
series.markDirtyProjection();
})
}
protected _afterNew() {
this._defaultThemes.push(MapChartDefaultTheme.new(this._root));
this._settings.themeTags = $utils.mergeTags(this._settings.themeTags, ["map"]);
super._afterNew();
this._makeGeoPath();
this.chartContainer.children.push(this.seriesContainer);
if (this.get("translateX") == null) {
this.set("translateX", this.width() / 2);
}
if (this.get("translateY") == null) {
this.set("translateY", this.height() / 2);
}
// Setting trasnparent background so that full body of the plot container
// is interactive
this.chartContainer.set("interactive", true);
this.chartContainer.set("interactiveChildren", false);
this.chartContainer.set("background", Rectangle.new(this._root, {
themeTags: ["map", "background"],
fill: Color.fromHex(0x000000),
fillOpacity: 0
}));
this._disposers.push(this.chartContainer.events.on("pointerdown", (event) => {
this._handleChartDown(event);
}));
this._disposers.push(this.chartContainer.events.on("globalpointerup", (event) => {
this._handleChartUp(event);
}));
this._disposers.push(this.chartContainer.events.on("globalpointermove", (event) => {
this._handleChartMove(event);
}));
let license = false;
for (let i = 0; i < registry.licenses.length; i++) {
if (registry.licenses[i].match(/^AM5M.{5,}/i)) {
license = true;
}
}
if (!license) {
this._root._showBranding();
}
}
protected _handleChartDown(event: ISpritePointerEvent) {
this._downZoomLevel = this.get("zoomLevel", 1);
let count = $object.keys(this.chartContainer._downPoints).length;
if (count > 0) {
this._downTranslateX = this.get("translateX");
this._downTranslateY = this.get("translateY");
this._downRotationX = this.get("rotationX");
this._downRotationY = this.get("rotationY");
this._downRotationZ = this.get("rotationZ");
const downId = this.chartContainer._getDownPointId();
if (downId) {
let movePoint = this._movePoints[downId];
if (movePoint) {
this.chartContainer._downPoints[downId] = movePoint;
}
}
}
else if (count == 0) {
let bg = this.chartContainer.get("background");
if (bg) {
bg.events.enableType("click");
}
if (this.get("panX") || this.get("panY")) {
if (this._za) {
this._za.stop();
}
if (this._txa) {
this._txa.stop();
}
if (this._tya) {
this._tya.stop();
}
if (this._rxa) {
this._rxa.stop();
}
if (this._rya) {
this._rya.stop();
}
const downPoint = this.chartContainer._display.toLocal(event.point);
this._downTranslateX = this.get("translateX");
this._downTranslateY = this.get("translateY");
this._downRotationX = this.get("rotationX");
this._downRotationY = this.get("rotationY");
this._downRotationZ = this.get("rotationZ");
let projection = this.get("projection")!;
if (projection.invert) {
let l0 = projection.invert([downPoint.x, downPoint.y]);
let l1 = projection.invert([downPoint.x + 1, downPoint.y + 1]);
if (l0 && l1) {
this._pLon = Math.abs(l1[0] - l0[0]);
this._pLat = Math.abs(l1[1] - l0[1]);
}
}
}
}
}
/**
* Converts screen coordinates (X and Y) within chart to latitude and
* longitude.
*
* @param point Screen coordinates
* @return Geographical coordinates
*/
public invert(point: IPoint): IGeoPoint {
let projection = this.get("projection")!;
if (projection.invert) {
const ll = projection.invert([point.x, point.y]);
if (ll) {
return { longitude: ll[0], latitude: ll[1] };
}
}
return { longitude: 0, latitude: 0 };
}
/**
* Converts latitude/longitude to screen coordinates (X and Y).
*
* @param point Geographical coordinates
* @return Screen coordinates
*/
public convert(point: IGeoPoint): IPoint {
let projection = this.get("projection")!;
const xy = projection([point.longitude, point.latitude]);
if (xy) {
return { x: xy[0], y: xy[1] };
}
return { x: 0, y: 0 };
}
protected _handleChartUp(_event: ISpritePointerEvent) {
this.chartContainer._downPoints = {}
}
protected _handlePinch() {
const chartContainer = this.chartContainer;
let i = 0;
let downPoints: Array<IPoint> = [];
let movePoints: Array<IPoint> = [];
$object.each(chartContainer._downPoints, (k, point) => {
downPoints[i] = point;
let movePoint = this._movePoints[k];
if (movePoint) {
movePoints[i] = this._movePoints[k];
}
i++;
});
if (downPoints.length > 1 && movePoints.length > 1) {
const display = chartContainer._display;
let downPoint0 = downPoints[0];
let downPoint1 = downPoints[1];
let movePoint0 = movePoints[0];
let movePoint1 = movePoints[1];
if (downPoint0 && downPoint1 && movePoint0 && movePoint1) {
downPoint0 = display.toLocal(downPoint0);
downPoint1 = display.toLocal(downPoint1);
movePoint0 = display.toLocal(movePoint0);
movePoint1 = display.toLocal(movePoint1);
let initialDistance = Math.hypot(downPoint1.x - downPoint0.x, downPoint1.y - downPoint0.y);
let currentDistance = Math.hypot(movePoint1.x - movePoint0.x, movePoint1.y - movePoint0.y);
let level = currentDistance / initialDistance * this._downZoomLevel;
let moveCenter = { x: movePoint0.x + (movePoint1.x - movePoint0.x) / 2, y: movePoint0.y + (movePoint1.y - movePoint0.y) / 2 };
let downCenter = { x: downPoint0.x + (downPoint1.x - downPoint0.x) / 2, y: downPoint0.y + (downPoint1.y - downPoint0.y) / 2 };
let tx = this._downTranslateX || 0;
let ty = this._downTranslateY || 0;
let zoomLevel = this._downZoomLevel;
let xx = moveCenter.x - (moveCenter.x - tx - moveCenter.x + downCenter.x) / zoomLevel * level;
let yy = moveCenter.y - (moveCenter.y - ty - moveCenter.y + downCenter.y) / zoomLevel * level;
this.set("zoomLevel", level);
this.set("translateX", xx);
this.set("translateY", yy);
}
}
}
protected _handleChartMove(event: ISpritePointerEvent) {
const chartContainer = this.chartContainer;
let downPoint = chartContainer._getDownPoint();
const downPointId = chartContainer._getDownPointId();
const originalEvent = event.originalEvent as any;
const pointerId = originalEvent.pointerId;
if (this.get("pinchZoom")) {
if (pointerId) {
this._movePoints[pointerId] = event.point;
if ($object.keys(chartContainer._downPoints).length > 1) {
this._handlePinch();
return;
}
}
}
if (downPointId && pointerId && pointerId != downPointId) {
return;
}
else {
if (downPoint) {
const panX = this.get("panX");
const panY = this.get("panY");
if (panX != "none" || panY != "none") {
const display = chartContainer._display;
let local = display.toLocal(event.point);
downPoint = display.toLocal(downPoint);
let x = this._downTranslateX;
let y = this._downTranslateY;
if (Math.hypot(downPoint.x - local.x, downPoint.y - local.y) > 5) {
let bg = chartContainer.get("background");
if (bg) {
bg.events.disableType("click");
}
if ($type.isNumber(x) && $type.isNumber(y)) {
let projection = this.get("projection")!;
if (panX == "translateX") {
x += local.x - downPoint.x;
}
if (panY == "translateY") {
y += local.y - downPoint.y;
}
this.set("translateX", x);
this.set("translateY", y);
if (projection.invert) {
let downLocation = projection.invert([downPoint.x, downPoint.y]);
if (location && downLocation) {
if (panX == "rotateX") {
this.set("rotationX", this._downRotationX! - (downPoint.x - local.x) * this._pLon);
}
if (panY == "rotateY") {
this.set("rotationY", this._downRotationY! + (downPoint.y - local.y) * this._pLat);
}
}
}
}
}
}
}
}
}
protected _handleWheelRotateY(delta: number, duration: number, easing: (t: Time) => Time) {
this._rya = this.animate({ key: "rotationY", to: this.get("rotationY", 0) - delta, duration: duration, easing: easing });
}
protected _handleWheelRotateX(delta: number, duration: number, easing: (t: Time) => Time) {
this._rxa = this.animate({ key: "rotationX", to: this.get("rotationX", 0) - delta, duration: duration, easing: easing });
}
protected _handleWheelZoom(delta: number, point: IPoint) {
let step = this.get("zoomStep", 2);
let zoomLevel = this.get("zoomLevel", 1);
let newZoomLevel = zoomLevel;
if (delta > 0) {
newZoomLevel = zoomLevel / step;
}
else if (delta < 0) {
newZoomLevel = zoomLevel * step;
}
if (newZoomLevel != zoomLevel) {
this.zoomToPoint(point, newZoomLevel)
}
}
/**
* Zoom the map to geographical bounds.
*
* @param geoBounds Bounds
* @param duration Animation duration in milliseconds
*/
public zoomToGeoBounds(geoBounds: { left: number, right: number, top: number, bottom: number }, duration?: number): Animation<this["_settings"]["zoomLevel"]> | undefined {
if (geoBounds.right < geoBounds.left) {
geoBounds.right = 180;
geoBounds.left = -180;
}
const geoPath = this.getPrivate("geoPath");
const mapBounds = geoPath.bounds(this._geometryColection);
let p0 = this.convert({ longitude: geoBounds.left, latitude: geoBounds.top });
let p1 = this.convert({ longitude: geoBounds.right, latitude: geoBounds.bottom });
if (p0.y < mapBounds[0][1]) {
p0.y = mapBounds[0][1];
}
if (p1.y > mapBounds[1][1]) {
p1.y = mapBounds[1][1];
}
let zl = this.get("zoomLevel", 1);
let bounds = { left: p0.x, right: p1.x, top: p0.y, bottom: p1.y };
let seriesContainer = this.seriesContainer;
let zoomLevel = .9 * Math.min(seriesContainer.innerWidth() / (bounds.right - bounds.left) * zl, seriesContainer.innerHeight() / (bounds.bottom - bounds.top) * zl);
let x = bounds.left + (bounds.right - bounds.left) / 2;
let y = bounds.top + (bounds.bottom - bounds.top) / 2;
let geoPoint = this.invert({ x, y });
return this.zoomToGeoPoint(geoPoint, zoomLevel, true, duration);
}
/**
* Zooms the map to specific screen point.
*
* @param point Point
* @param level Zoom level
* @param center Center the map
* @param duration Duration of the animation in milliseconds
*/
public zoomToPoint(point: IPoint, level: number, center?: boolean, duration?: number): Animation<this["_settings"]["zoomLevel"]> | undefined {
if (level) {
level = $math.fitToRange(level, this.get("minZoomLevel", 1), this.get("maxZoomLevel", 32));
}
if (!$type.isNumber(duration)) {
duration = this.get("animationDuration", 0);
}
const easing = this.get("animationEasing");
const zoomLevel = this.get("zoomLevel", 1);
let x = point.x;
let y = point.y;
let tx = this.get("translateX", 0);
let ty = this.get("translateY", 0);
let cx = x;
let cy = y;
if (center) {
cx = this.width() / 2;
cy = this.height() / 2;
}
let xx = cx - ((x - tx) / zoomLevel * level);
let yy = cy - ((y - ty) / zoomLevel * level);
this._txa = this.animate({ key: "translateX", to: xx, duration: duration, easing: easing });
this._tya = this.animate({ key: "translateY", to: yy, duration: duration, easing: easing });
this._za = this.animate({ key: "zoomLevel", to: level, duration: duration, easing: easing });
if (zoomLevel != level) {
this._root.readerAlert(this._t("Zoom level changed to %1", this._root.locale, $type.numberToString(level)));
}
return this._za;
}
/**
* Zooms the map to specific geographical point.
*
* @param geoPoint Point
* @param level Zoom level
* @param center Center the map
* @param duration Duration of the animation in milliseconds
*/
public zoomToGeoPoint(geoPoint: IGeoPoint, level: number, center?: boolean, duration?: number): Animation<this["_settings"]["zoomLevel"]> | undefined {
const xy = this.convert(geoPoint);
if (xy) {
return this.zoomToPoint(xy, level, center, duration);
}
}
/**
* Zooms the map in.
*/
public zoomIn(): Animation<this["_settings"]["zoomLevel"]> | undefined {
return this.zoomToPoint({ x: this.width() / 2, y: this.height() / 2 }, this.get("zoomLevel", 1) * this.get("zoomStep", 2));
}
/**
* Zooms the map out.
*/
public zoomOut(): Animation<this["_settings"]["zoomLevel"]> | undefined {
return this.zoomToPoint({ x: this.width() / 2, y: this.height() / 2 }, this.get("zoomLevel", 1) / this.get("zoomStep", 2));
}
public _clearDirty() {
super._clearDirty();
this._dirtyGeometries = false;
this._mapFitted = false;
}
} | the_stack |
import * as anchor from '@project-serum/anchor';
import { AnchorProvider, BN } from '@project-serum/anchor';
import { Keypair, LAMPORTS_PER_SOL, PublicKey } from '@solana/web3.js';
import {
BankFlags,
GemBankClient,
ITokenData,
NodeWallet,
stringifyPKsAndBNs,
stringToBytes,
WhitelistType,
} from '../../src';
import chai, { assert, expect } from 'chai';
import chaiAsPromised from 'chai-as-promised';
import { describe } from 'mocha';
import { createMetadata } from '../metaplex';
chai.use(chaiAsPromised);
describe('gem bank', () => {
const _provider = AnchorProvider.local();
const gb = new GemBankClient(_provider.connection, _provider.wallet as any);
const nw = new NodeWallet(_provider.connection, _provider.wallet as any);
// --------------------------------------- bank + vault
//global state
let randomWallet: Keypair; //used to test bad transactions with wrong account passed in
const bank = Keypair.generate();
let bankManager: Keypair;
let vaultCreator: Keypair;
let vaultOwner: Keypair;
let vault: PublicKey;
function printBankVaultState() {
console.log('randomWallet', randomWallet.publicKey.toBase58());
console.log('bank', bank.publicKey.toBase58());
console.log('manager', bankManager.publicKey.toBase58());
console.log('vaultCreator', vaultCreator.publicKey.toBase58());
console.log('vaultOwner', vaultOwner.publicKey.toBase58());
console.log('vault', vault.toBase58());
}
before('configures accounts', async () => {
randomWallet = await nw.createFundedWallet(100 * LAMPORTS_PER_SOL);
bankManager = await nw.createFundedWallet(100 * LAMPORTS_PER_SOL);
vaultCreator = await nw.createFundedWallet(100 * LAMPORTS_PER_SOL);
vaultOwner = await nw.createFundedWallet(100 * LAMPORTS_PER_SOL);
});
it('inits bank', async () => {
await gb.initBank(bank, bankManager, bankManager);
const bankAcc = await gb.fetchBankAcc(bank.publicKey);
assert.equal(
bankAcc.bankManager.toBase58(),
bankManager.publicKey.toBase58()
);
assert(bankAcc.vaultCount.eq(new BN(0)));
});
it('inits vault', async () => {
//intentionally setting creator as owner, so that we can change later
({ vault } = await gb.initVault(
bank.publicKey,
vaultCreator,
vaultCreator,
vaultCreator.publicKey,
'test_vault'
));
const bankAcc = await gb.fetchBankAcc(bank.publicKey);
assert(bankAcc.vaultCount.eq(new BN(1)));
const vaultAcc = await gb.fetchVaultAcc(vault);
expect(vaultAcc.name).to.deep.include.members(stringToBytes('test_vault'));
assert.equal(vaultAcc.bank.toBase58(), bank.publicKey.toBase58());
assert.equal(vaultAcc.owner.toBase58(), vaultCreator.publicKey.toBase58());
assert.equal(
vaultAcc.creator.toBase58(),
vaultCreator.publicKey.toBase58()
);
});
it('updates bank manager', async () => {
const newManager = Keypair.generate();
await gb.updateBankManager(
bank.publicKey,
bankManager,
newManager.publicKey
);
const bankAcc = await gb.fetchBankAcc(bank.publicKey);
assert.equal(
bankAcc.bankManager.toBase58(),
newManager.publicKey.toBase58()
);
//reset back
await gb.updateBankManager(
bank.publicKey,
newManager,
bankManager.publicKey
);
});
it('FAILS to update bank manager w/ wrong existing manager', async () => {
const newManager = Keypair.generate();
await expect(
gb.updateBankManager(bank.publicKey, randomWallet, newManager.publicKey)
).to.be.rejectedWith('ConstraintHasOne');
});
it('updates vault owner', async () => {
await gb.updateVaultOwner(
bank.publicKey,
vault,
vaultCreator,
vaultOwner.publicKey
);
const vaultAcc = await gb.fetchVaultAcc(vault);
assert.equal(vaultAcc.owner.toBase58(), vaultOwner.publicKey.toBase58());
});
it('FAILS to update vault owner w/ wrong existing owner', async () => {
await expect(
gb.updateVaultOwner(
bank.publicKey,
vault,
randomWallet,
vaultOwner.publicKey
)
).to.be.rejectedWith('ConstraintHasOne');
});
// --------------------------------------- gem boxes
describe('gem operations', () => {
//global state
let gemAmount: anchor.BN;
let gem: ITokenData;
let gemBox: PublicKey;
let GDR: PublicKey;
function printGemBoxState() {
console.log('amount', gemAmount.toString());
console.log('gem', stringifyPKsAndBNs(gem as any));
console.log('gemBox', gemBox.toBase58());
console.log('GDR', GDR.toBase58());
}
async function prepDeposit(
owner: Keypair,
mintProof?: PublicKey,
metadata?: PublicKey,
creatorProof?: PublicKey
) {
return gb.depositGem(
bank.publicKey,
vault,
owner,
gemAmount,
gem.tokenMint,
gem.tokenAcc,
mintProof,
metadata,
creatorProof
);
}
async function prepWithdrawal(
owner: Keypair,
receiver: PublicKey,
gemAmount: BN
) {
return gb.withdrawGem(
bank.publicKey,
vault,
owner,
gemAmount,
gem.tokenMint,
receiver
);
}
async function prepGem(owner?: Keypair) {
const gemAmount = new BN(1 + Math.ceil(Math.random() * 100)); //min 2
const gemOwner =
owner ?? (await nw.createFundedWallet(100 * LAMPORTS_PER_SOL));
const gem = await nw.createMintAndFundATA(gemOwner.publicKey, gemAmount);
return { gemAmount, gemOwner, gem };
}
beforeEach('creates a fresh gem', async () => {
//many gems, different amounts, but same owner (who also owns the vault)
({ gemAmount, gem } = await prepGem(vaultOwner));
});
it('deposits gem', async () => {
let vaultAuth;
({ vaultAuth, gemBox, GDR } = await prepDeposit(vaultOwner));
const vaultAcc = await gb.fetchVaultAcc(vault);
assert(vaultAcc.gemBoxCount.eq(new BN(1)));
assert(vaultAcc.gemCount.eq(gemAmount));
assert(vaultAcc.rarityPoints.eq(gemAmount));
const gemBoxAcc = await gb.fetchGemAcc(gem.tokenMint, gemBox);
assert(gemBoxAcc.amount.eq(gemAmount));
assert.equal(gemBoxAcc.mint.toBase58(), gem.tokenMint.toBase58());
assert.equal(gemBoxAcc.owner.toBase58(), vaultAuth.toBase58());
const GDRAcc = await gb.fetchGDRAcc(GDR);
assert.equal(GDRAcc.vault.toBase58(), vault.toBase58());
assert.equal(GDRAcc.gemBoxAddress.toBase58(), gemBox.toBase58());
assert.equal(GDRAcc.gemMint.toBase58(), gem.tokenMint.toBase58());
assert(GDRAcc.gemCount.eq(gemAmount));
});
it('FAILS to deposit gem w/ wrong owner', async () => {
await expect(prepDeposit(randomWallet)).to.be.rejectedWith(
'ConstraintHasOne'
);
});
it('withdraws gem to existing ATA', async () => {
({ gemBox, GDR } = await prepDeposit(vaultOwner)); //make a fresh deposit
const vaultAcc = await gb.fetchVaultAcc(vault);
const oldBoxCount = vaultAcc.gemBoxCount;
const oldGemCount = vaultAcc.gemCount;
await prepWithdrawal(vaultOwner, gem.owner, gemAmount);
const vaultAcc2 = await gb.fetchVaultAcc(vault);
assert(vaultAcc2.gemBoxCount.eq(oldBoxCount.sub(new BN(1))));
assert(vaultAcc2.gemCount.eq(oldGemCount.sub(gemAmount)));
assert(vaultAcc2.rarityPoints.eq(oldGemCount.sub(gemAmount)));
const gemAcc = await gb.fetchGemAcc(gem.tokenMint, gem.tokenAcc);
assert(gemAcc.amount.eq(gemAmount));
//these accounts are expected to close on emptying the gem box
await expect(gb.fetchGemAcc(gem.tokenMint, gemBox)).to.be.rejectedWith(
'Failed to find account'
);
await expect(gb.fetchGDRAcc(GDR)).to.be.rejectedWith(
'Account does not exist'
);
});
it('withdraws gem to existing ATA (but does not empty)', async () => {
const smallerAmount = gemAmount.sub(new BN(1));
({ gemBox, GDR } = await prepDeposit(vaultOwner)); //make a fresh deposit
await prepWithdrawal(vaultOwner, gem.owner, smallerAmount);
const gemAcc = await gb.fetchGemAcc(gem.tokenMint, gem.tokenAcc);
assert(gemAcc.amount.eq(smallerAmount));
const gemBoxAcc = await gb.fetchGemAcc(gem.tokenMint, gemBox);
assert(gemBoxAcc.amount.eq(new BN(1)));
const GDRAcc = await gb.fetchGDRAcc(GDR);
assert(GDRAcc.gemCount.eq(new BN(1)));
});
it('withdraws gem to missing ATA', async () => {
({ gemBox, GDR } = await prepDeposit(vaultOwner)); //make a fresh deposit
const missingATA = await gb.findATA(
gem.tokenMint,
randomWallet.publicKey
);
await prepWithdrawal(vaultOwner, randomWallet.publicKey, gemAmount);
const gemAcc = await gb.fetchGemAcc(gem.tokenMint, missingATA);
assert(gemAcc.amount.eq(gemAmount));
//these accounts are expected to close on emptying the gem box
await expect(gb.fetchGemAcc(gem.tokenMint, gemBox)).to.be.rejectedWith(
'Failed to find account'
);
await expect(gb.fetchGDRAcc(GDR)).to.be.rejectedWith(
'Account does not exist'
);
});
it('FAILS to withdraw gem w/ wrong owner', async () => {
await prepDeposit(vaultOwner); //make a fresh deposit
await expect(
prepWithdrawal(randomWallet, gem.owner, gemAmount)
).to.be.rejectedWith('ConstraintHasOne');
});
// --------------------------------------- vault lock
async function prepLock(vaultLocked: boolean) {
return gb.setVaultLock(bank.publicKey, vault, bankManager, vaultLocked);
}
it('un/locks vault successfully', async () => {
//lock the vault
await prepLock(true);
let vaultAcc = await gb.fetchVaultAcc(vault);
assert.equal(vaultAcc.locked, true);
//deposit should fail
await expect(prepDeposit(vaultOwner)).to.be.rejectedWith(
'VaultAccessSuspended.'
);
//unlock the vault
await prepLock(false);
vaultAcc = await gb.fetchVaultAcc(vault);
assert.equal(vaultAcc.locked, false);
//make a real deposit, we need this to try to withdraw later
await prepDeposit(vaultOwner);
//lock the vault
await prepLock(true);
//withdraw should fail
await expect(
prepWithdrawal(vaultOwner, gem.owner, gemAmount)
).to.be.rejectedWith('VaultAccessSuspended.');
//finally unlock the vault
await prepLock(false);
//should be able to withdraw
await prepWithdrawal(vaultOwner, gem.owner, gemAmount);
});
// --------------------------------------- bank flags
async function prepFlags(manager: Keypair, flags: number) {
return gb.setBankFlags(bank.publicKey, manager, flags);
}
it('sets bank flags', async () => {
//freeze vaults
await prepFlags(bankManager, BankFlags.FreezeVaults);
const bankAcc = await gb.fetchBankAcc(bank.publicKey);
assert.equal(bankAcc.flags, BankFlags.FreezeVaults);
await expect(
gb.updateVaultOwner(
bank.publicKey,
vault,
vaultOwner,
vaultCreator.publicKey
)
).to.be.rejectedWith('VaultAccessSuspended.');
await expect(prepLock(true)).to.be.rejectedWith('VaultAccessSuspended.');
await expect(prepDeposit(vaultOwner)).to.be.rejectedWith(
'VaultAccessSuspended.'
);
//remove flags to be able to do a real deposit - else can't withdraw
await prepFlags(bankManager, 0);
await prepDeposit(vaultOwner);
//freeze vaults again
await prepFlags(bankManager, BankFlags.FreezeVaults);
await expect(
prepWithdrawal(vaultOwner, gem.owner, gemAmount)
).to.be.rejectedWith('VaultAccessSuspended.');
//unfreeze vault in the end
await prepFlags(bankManager, 0);
});
it('FAILS to set bank flags w/ wrong manager', async () => {
await expect(
prepFlags(randomWallet, BankFlags.FreezeVaults)
).to.be.rejectedWith('ConstraintHasOne');
});
// --------------------------------------- whitelists
describe('whitelists', () => {
async function prepAddToWhitelist(addr: PublicKey, type: WhitelistType) {
return gb.addToWhitelist(bank.publicKey, bankManager, addr, type);
}
async function prepRemoveFromWhitelist(addr: PublicKey) {
return gb.removeFromWhitelist(bank.publicKey, bankManager, addr);
}
async function whitelistMint(whitelistedMint: PublicKey) {
const { whitelistProof } = await prepAddToWhitelist(
whitelistedMint,
WhitelistType.Mint
);
return { whitelistedMint, whitelistProof };
}
async function whitelistCreator(whitelistedCreator: PublicKey) {
const { whitelistProof } = await prepAddToWhitelist(
whitelistedCreator,
WhitelistType.Creator
);
return { whitelistedCreator, whitelistProof };
}
async function assertWhitelistClean() {
const pdas = await gb.fetchAllWhitelistProofPDAs();
assert.equal(pdas.length, 0);
const bankAcc = await gb.fetchBankAcc(bank.publicKey);
assert.equal(bankAcc.whitelistedMints, 0);
assert.equal(bankAcc.whitelistedCreators, 0);
}
beforeEach('checks whitelists are clean', async () => {
await assertWhitelistClean();
});
// --------------- successes
it('adds/removes mint from whitelist', async () => {
const { whitelistedMint, whitelistProof } = await whitelistMint(
gem.tokenMint
);
const proofAcc = await gb.fetchWhitelistProofAcc(whitelistProof);
assert.equal(proofAcc.whitelistType, WhitelistType.Mint);
assert.equal(proofAcc.bank.toBase58(), bank.publicKey.toBase58());
assert.equal(
proofAcc.whitelistedAddress.toBase58(),
whitelistedMint.toBase58()
);
await prepRemoveFromWhitelist(whitelistedMint);
await expect(
gb.fetchWhitelistProofAcc(whitelistProof)
).to.be.rejectedWith('Account does not exist');
});
it('adds/removes creator from whitelist', async () => {
const { whitelistedCreator, whitelistProof } = await whitelistCreator(
randomWallet.publicKey
);
const proofAcc = await gb.fetchWhitelistProofAcc(whitelistProof);
assert.equal(proofAcc.whitelistType, WhitelistType.Creator);
assert.equal(proofAcc.bank.toBase58(), bank.publicKey.toBase58());
assert.equal(
proofAcc.whitelistedAddress.toBase58(),
whitelistedCreator.toBase58()
);
await prepRemoveFromWhitelist(whitelistedCreator);
await expect(
gb.fetchWhitelistProofAcc(whitelistProof)
).to.be.rejectedWith('Account does not exist');
});
it('tries to whitelist same mint twice', async () => {
await whitelistMint(gem.tokenMint);
const { whitelistedMint } = await whitelistMint(gem.tokenMint);
const bankAcc = await gb.fetchBankAcc(bank.publicKey);
assert.equal(bankAcc.whitelistedMints, 1);
await prepRemoveFromWhitelist(whitelistedMint);
});
it('tries to whitelist same creator twice', async () => {
await whitelistCreator(randomWallet.publicKey);
const { whitelistedCreator } = await whitelistCreator(
randomWallet.publicKey
);
const bankAcc = await gb.fetchBankAcc(bank.publicKey);
assert.equal(bankAcc.whitelistedCreators, 1);
await prepRemoveFromWhitelist(whitelistedCreator);
});
it('changes whitelist from mint to creator', async () => {
await whitelistMint(randomWallet.publicKey);
const { whitelistedCreator, whitelistProof } = await whitelistCreator(
randomWallet.publicKey
);
const proofAcc = await gb.fetchWhitelistProofAcc(whitelistProof);
assert.equal(proofAcc.whitelistType, WhitelistType.Creator);
assert.equal(proofAcc.bank.toBase58(), bank.publicKey.toBase58());
assert.equal(
proofAcc.whitelistedAddress.toBase58(),
whitelistedCreator.toBase58()
);
const bankAcc = await gb.fetchBankAcc(bank.publicKey);
assert.equal(bankAcc.whitelistedCreators, 1);
assert.equal(bankAcc.whitelistedMints, 0);
await prepRemoveFromWhitelist(whitelistedCreator);
await expect(
gb.fetchWhitelistProofAcc(whitelistProof)
).to.be.rejectedWith('Account does not exist');
});
// unlikely to be ever needed, but protocol supports this
it('sets both mint and creator whitelists for same pk', async () => {
const { whitelistProof } = await gb.addToWhitelist(
bank.publicKey,
bankManager,
randomWallet.publicKey,
3
);
const proofAcc = await gb.fetchWhitelistProofAcc(whitelistProof);
assert.equal(proofAcc.whitelistType, 3);
assert.equal(proofAcc.bank.toBase58(), bank.publicKey.toBase58());
assert.equal(
proofAcc.whitelistedAddress.toBase58(),
randomWallet.publicKey.toBase58()
);
const bankAcc = await gb.fetchBankAcc(bank.publicKey);
assert.equal(bankAcc.whitelistedCreators, 1);
assert.equal(bankAcc.whitelistedMints, 1);
await prepRemoveFromWhitelist(randomWallet.publicKey);
await expect(
gb.fetchWhitelistProofAcc(whitelistProof)
).to.be.rejectedWith('Account does not exist');
});
//no need to deserialize anything, if ix goes through w/o error, the deposit succeeds
it('allows a deposit if mint whitelisted, and creators WL empty', async () => {
const { whitelistedMint, whitelistProof } = await whitelistMint(
gem.tokenMint
);
await prepDeposit(vaultOwner, whitelistProof);
//clean up after
await prepRemoveFromWhitelist(whitelistedMint);
});
//this is expected behavior since we're doing an OR check
it('allows a deposit if mint whitelisted, and creators WL NOT empty', async () => {
const { whitelistedMint, whitelistProof } = await whitelistMint(
gem.tokenMint
);
const { whitelistedCreator } = await whitelistCreator(
randomWallet.publicKey //intentionally a random creator
);
await prepDeposit(vaultOwner, whitelistProof);
//clean up after
await prepRemoveFromWhitelist(whitelistedMint);
await prepRemoveFromWhitelist(whitelistedCreator);
});
it('allows a deposit if creator verified + whitelisted, and mint WL empty', async () => {
const gemMetadata = await createMetadata(
nw.conn,
nw.wallet,
gem.tokenMint
);
const { whitelistedCreator, whitelistProof } = await whitelistCreator(
nw.wallet.publicKey //this is the address used to create the metadata
);
await prepDeposit(
vaultOwner,
PublicKey.default, // since we're not relying on mint whitelist for tx to pass, we simply pass in a dummy PK
gemMetadata,
whitelistProof
);
//clean up after
await prepRemoveFromWhitelist(whitelistedCreator);
});
//again we're simply checking OR behavior
it('allows a deposit if creator verified + whitelisted, and mint WL NOT empty', async () => {
const gemMetadata = await createMetadata(
nw.conn,
nw.wallet,
gem.tokenMint
);
const { gem: randomGem } = await prepGem();
const { whitelistedMint } = await whitelistMint(randomGem.tokenMint); //random mint intentionally
const { whitelistedCreator, whitelistProof } = await whitelistCreator(
nw.wallet.publicKey //this is the address used to create the metadata
);
await prepDeposit(
vaultOwner,
PublicKey.default,
gemMetadata,
whitelistProof
);
//clean up after
await prepRemoveFromWhitelist(whitelistedMint);
await prepRemoveFromWhitelist(whitelistedCreator);
});
it('allows a deposit if creator verified + whitelisted, but listed LAST', async () => {
const gemMetadata = await createMetadata(
nw.conn,
nw.wallet,
gem.tokenMint,
5,
5
);
const { whitelistedCreator, whitelistProof } = await whitelistCreator(
nw.wallet.publicKey //this is the address used to create the metadata
);
await prepDeposit(
vaultOwner,
PublicKey.default,
gemMetadata,
whitelistProof
);
//clean up after
await prepRemoveFromWhitelist(whitelistedCreator);
});
// --------------- failures
it('FAILS a deposit if creator whitelisted but not verified (signed off)', async () => {
const gemMetadata = await createMetadata(
nw.conn,
nw.wallet,
gem.tokenMint,
5,
1,
true
);
const { whitelistedCreator, whitelistProof } = await whitelistCreator(
nw.wallet.publicKey //this is the address used to create the metadata
);
await expect(
prepDeposit(
vaultOwner,
PublicKey.default,
gemMetadata,
whitelistProof
)
).to.be.rejectedWith('NotWhitelisted');
//clean up after
await prepRemoveFromWhitelist(whitelistedCreator);
});
it('FAILS a deposit if mint whitelist exists, but mint not whitelisted', async () => {
//setup the whitelist for the WRONG gem
const { gem: randomGem } = await prepGem();
const { whitelistedMint, whitelistProof } = await whitelistMint(
randomGem.tokenMint
);
await expect(
prepDeposit(vaultOwner, whitelistProof)
).to.be.rejectedWith('NotWhitelisted');
//clean up after
await prepRemoveFromWhitelist(whitelistedMint);
});
it('FAILS a deposit if creator whitelist exists, but creator not whitelisted', async () => {
const gemMetadata = await createMetadata(
nw.conn,
nw.wallet,
gem.tokenMint
);
//setup the whitelist for the WRONG creator
const { whitelistedCreator, whitelistProof } = await whitelistCreator(
randomWallet.publicKey
);
await expect(
prepDeposit(
vaultOwner,
PublicKey.default,
gemMetadata,
whitelistProof
)
).to.be.rejectedWith('NotWhitelisted');
//clean up after
await prepRemoveFromWhitelist(whitelistedCreator);
});
it('FAILS to verify when proof is marked as "mint", but is actually for creator', async () => {
const gemMetadata = await createMetadata(
nw.conn,
nw.wallet,
gem.tokenMint
);
//intentionally passing in the wallet's address not the mint's
//now the creator has a proof, but it's marked as "mint"
const { whitelistedMint, whitelistProof } = await whitelistMint(
nw.wallet.publicKey
);
//let's also whitelist a random creator, so that both branches of checks are triggered
const { whitelistedCreator } = await whitelistCreator(
randomWallet.publicKey
);
await expect(
prepDeposit(
vaultOwner,
PublicKey.default,
gemMetadata,
whitelistProof
)
).to.be.rejectedWith('NotWhitelisted');
//clean up after
await prepRemoveFromWhitelist(whitelistedMint);
await prepRemoveFromWhitelist(whitelistedCreator);
});
it('FAILS to verify when proof is marked as "creator", but is actually for mint', async () => {
const gemMetadata = await createMetadata(
nw.conn,
nw.wallet,
gem.tokenMint
);
//intentionally passing in the mint's address not the creator's
//now the mint has a proof, but it's marked as "creator"
const { whitelistedCreator, whitelistProof } = await whitelistCreator(
gem.tokenMint
);
//let's also whitelist a random mint, so that both branches of checks are triggered
const { whitelistedMint } = await whitelistMint(
Keypair.generate().publicKey
);
//unfortunately it's rejected not with the error we'd like
//the issue is that when mint branch fails (as it should, with the correct error),
//it falls back to checking creator branch, which fails with the wrong error
await expect(
prepDeposit(
vaultOwner,
whitelistProof,
gemMetadata,
PublicKey.default
)
).to.be.rejectedWith('NotWhitelisted');
//clean up after
await prepRemoveFromWhitelist(whitelistedMint);
await prepRemoveFromWhitelist(whitelistedCreator);
});
it('correctly fetches proof PDAs by type', async () => {
// create 3 mint proofs
const { whitelistedMint: m1 } = await whitelistMint(
Keypair.generate().publicKey
);
const { whitelistedMint: m2 } = await whitelistMint(
Keypair.generate().publicKey
);
const { whitelistedMint: m3 } = await whitelistMint(
Keypair.generate().publicKey
);
// and 1 creator proof
const { whitelistedCreator: c1 } = await whitelistCreator(
Keypair.generate().publicKey
);
// verify counts
let pdas = await gb.fetchAllWhitelistProofPDAs();
assert.equal(pdas.length, 4);
pdas = await gb.fetchAllWhitelistProofPDAs(bank.publicKey);
assert.equal(pdas.length, 4);
//clean up after
await prepRemoveFromWhitelist(m1);
await prepRemoveFromWhitelist(m2);
await prepRemoveFromWhitelist(m3);
await prepRemoveFromWhitelist(c1);
});
});
});
}); | the_stack |
import {initMockFileSystem} from '../../file_system/testing';
import {TypeCheckingConfig} from '../api';
import {ALL_ENABLED_CONFIG, tcb, TestDeclaration, TestDirective} from '../testing';
describe('type check blocks', () => {
beforeEach(() => initMockFileSystem('Native'));
it('should generate a basic block for a binding', () => {
expect(tcb('{{hello}} {{world}}')).toContain('"" + (((ctx).hello)) + (((ctx).world));');
});
it('should generate literal map expressions', () => {
const TEMPLATE = '{{ method({foo: a, bar: b}) }}';
expect(tcb(TEMPLATE)).toContain('(((ctx).method))({ "foo": ((ctx).a), "bar": ((ctx).b) })');
});
it('should generate literal array expressions', () => {
const TEMPLATE = '{{ method([a, b]) }}';
expect(tcb(TEMPLATE)).toContain('(((ctx).method))([((ctx).a), ((ctx).b)])');
});
it('should handle non-null assertions', () => {
const TEMPLATE = `{{a!}}`;
expect(tcb(TEMPLATE)).toContain('((((ctx).a))!)');
});
it('should handle unary - operator', () => {
const TEMPLATE = `{{-1}}`;
expect(tcb(TEMPLATE)).toContain('(-1)');
});
it('should handle keyed property access', () => {
const TEMPLATE = `{{a[b]}}`;
expect(tcb(TEMPLATE)).toContain('(((ctx).a))[((ctx).b)]');
});
it('should handle nested ternary expressions', () => {
const TEMPLATE = `{{a ? b : c ? d : e}}`;
expect(tcb(TEMPLATE))
.toContain('(((ctx).a) ? ((ctx).b) : ((((ctx).c) ? ((ctx).d) : (((ctx).e)))))');
});
it('should handle nullish coalescing operator', () => {
expect(tcb('{{ a ?? b }}')).toContain('((((ctx).a)) ?? (((ctx).b)))');
expect(tcb('{{ a ?? b ?? c }}')).toContain('(((((ctx).a)) ?? (((ctx).b))) ?? (((ctx).c)))');
expect(tcb('{{ (a ?? b) + (c ?? e) }}'))
.toContain('(((((ctx).a)) ?? (((ctx).b))) + ((((ctx).c)) ?? (((ctx).e))))');
});
it('should handle quote expressions as any type', () => {
const TEMPLATE = `<span [quote]="sql:expression"></span>`;
expect(tcb(TEMPLATE)).toContain('null as any');
});
it('should handle attribute values for directive inputs', () => {
const TEMPLATE = `<div dir inputA="value"></div>`;
const DIRECTIVES: TestDeclaration[] = [{
type: 'directive',
name: 'DirA',
selector: '[dir]',
inputs: {inputA: 'inputA'},
}];
expect(tcb(TEMPLATE, DIRECTIVES)).toContain('_t1: i0.DirA = null!; _t1.inputA = ("value");');
});
it('should handle multiple bindings to the same property', () => {
const TEMPLATE = `<div dir-a [inputA]="1" [inputA]="2"></div>`;
const DIRECTIVES: TestDeclaration[] = [{
type: 'directive',
name: 'DirA',
selector: '[dir-a]',
inputs: {inputA: 'inputA'},
}];
const block = tcb(TEMPLATE, DIRECTIVES);
expect(block).toContain('_t1.inputA = (1);');
expect(block).toContain('_t1.inputA = (2);');
});
it('should handle empty bindings', () => {
const TEMPLATE = `<div dir-a [inputA]=""></div>`;
const DIRECTIVES: TestDeclaration[] = [{
type: 'directive',
name: 'DirA',
selector: '[dir-a]',
inputs: {inputA: 'inputA'},
}];
expect(tcb(TEMPLATE, DIRECTIVES)).toContain('_t1.inputA = (undefined);');
});
it('should handle bindings without value', () => {
const TEMPLATE = `<div dir-a [inputA]></div>`;
const DIRECTIVES: TestDeclaration[] = [{
type: 'directive',
name: 'DirA',
selector: '[dir-a]',
inputs: {inputA: 'inputA'},
}];
expect(tcb(TEMPLATE, DIRECTIVES)).toContain('_t1.inputA = (undefined);');
});
it('should handle implicit vars on ng-template', () => {
const TEMPLATE = `<ng-template let-a></ng-template>`;
expect(tcb(TEMPLATE)).toContain('var _t2 = _t1.$implicit;');
});
it('should handle method calls of template variables', () => {
const TEMPLATE = `<ng-template let-a>{{a(1)}}</ng-template>`;
expect(tcb(TEMPLATE)).toContain('var _t2 = _t1.$implicit;');
expect(tcb(TEMPLATE)).toContain('(_t2)(1)');
});
it('should handle implicit vars when using microsyntax', () => {
const TEMPLATE = `<div *ngFor="let user of users"></div>`;
expect(tcb(TEMPLATE)).toContain('var _t2 = _t1.$implicit;');
});
it('should handle direct calls of an implicit template variable', () => {
const TEMPLATE = `<div *ngFor="let a of letters">{{a(1)}}</div>`;
expect(tcb(TEMPLATE)).toContain('var _t2 = _t1.$implicit;');
expect(tcb(TEMPLATE)).toContain('(_t2)(1)');
});
describe('type constructors', () => {
it('should handle missing property bindings', () => {
const TEMPLATE = `<div dir [inputA]="foo"></div>`;
const DIRECTIVES: TestDeclaration[] = [{
type: 'directive',
name: 'Dir',
selector: '[dir]',
inputs: {
fieldA: 'inputA',
fieldB: 'inputB',
},
isGeneric: true,
}];
const actual = tcb(TEMPLATE, DIRECTIVES);
expect(actual).toContain(
'const _ctor1: <T extends string = any>(init: Pick<i0.Dir<T>, "fieldA" | "fieldB">) => i0.Dir<T> = null!;');
expect(actual).toContain(
'var _t1 = _ctor1({ "fieldA": (((ctx).foo)), "fieldB": null as any });');
});
it('should handle multiple bindings to the same property', () => {
const TEMPLATE = `<div dir [inputA]="1" [inputA]="2"></div>`;
const DIRECTIVES: TestDeclaration[] = [{
type: 'directive',
name: 'Dir',
selector: '[dir]',
inputs: {
fieldA: 'inputA',
},
isGeneric: true,
}];
const block = tcb(TEMPLATE, DIRECTIVES);
expect(block).toContain('"fieldA": (1)');
expect(block).not.toContain('"fieldA": (2)');
});
it('should only apply property bindings to directives', () => {
const TEMPLATE = `
<div dir [style.color]="'blue'" [class.strong]="false" [attr.enabled]="true"></div>
`;
const DIRECTIVES: TestDeclaration[] = [{
type: 'directive',
name: 'Dir',
selector: '[dir]',
inputs: {'color': 'color', 'strong': 'strong', 'enabled': 'enabled'},
isGeneric: true,
}];
const block = tcb(TEMPLATE, DIRECTIVES);
expect(block).not.toContain('Dir.ngTypeCtor');
expect(block).toContain('"blue"; false; true;');
});
it('should generate a circular directive reference correctly', () => {
const TEMPLATE = `
<div dir #d="dir" [input]="d"></div>
`;
const DIRECTIVES: TestDirective[] = [{
type: 'directive',
name: 'Dir',
selector: '[dir]',
exportAs: ['dir'],
inputs: {input: 'input'},
isGeneric: true,
}];
const actual = tcb(TEMPLATE, DIRECTIVES);
expect(actual).toContain(
'const _ctor1: <T extends string = any>(init: Pick<i0.Dir<T>, "input">) => i0.Dir<T> = null!;');
expect(actual).toContain(
'var _t2 = _ctor1({ "input": (null!) }); ' +
'var _t1 = _t2; ' +
'_t2.input = (_t1);');
});
it('should generate circular references between two directives correctly', () => {
const TEMPLATE = `
<div #a="dirA" dir-a [inputA]="b">A</div>
<div #b="dirB" dir-b [inputB]="a">B</div>
`;
const DIRECTIVES: TestDirective[] = [
{
type: 'directive',
name: 'DirA',
selector: '[dir-a]',
exportAs: ['dirA'],
inputs: {inputA: 'inputA'},
isGeneric: true,
},
{
type: 'directive',
name: 'DirB',
selector: '[dir-b]',
exportAs: ['dirB'],
inputs: {inputB: 'inputB'},
isGeneric: true,
}
];
const actual = tcb(TEMPLATE, DIRECTIVES);
expect(actual).toContain(
'const _ctor1: <T extends string = any>(init: Pick<i0.DirA<T>, "inputA">) => i0.DirA<T> = null!; const _ctor2: <T extends string = any>(init: Pick<i0.DirB<T>, "inputB">) => i0.DirB<T> = null!;');
expect(actual).toContain(
'var _t4 = _ctor1({ "inputA": (null!) }); ' +
'var _t3 = _t4; ' +
'var _t2 = _ctor2({ "inputB": (_t3) }); ' +
'var _t1 = _t2; ' +
'_t4.inputA = (_t1); ' +
'_t2.inputB = (_t3);');
});
it('should handle empty bindings', () => {
const TEMPLATE = `<div dir-a [inputA]=""></div>`;
const DIRECTIVES: TestDeclaration[] = [{
type: 'directive',
name: 'DirA',
selector: '[dir-a]',
inputs: {inputA: 'inputA'},
isGeneric: true,
}];
expect(tcb(TEMPLATE, DIRECTIVES)).toContain('"inputA": (undefined)');
});
it('should handle bindings without value', () => {
const TEMPLATE = `<div dir-a [inputA]></div>`;
const DIRECTIVES: TestDeclaration[] = [{
type: 'directive',
name: 'DirA',
selector: '[dir-a]',
inputs: {inputA: 'inputA'},
isGeneric: true,
}];
expect(tcb(TEMPLATE, DIRECTIVES)).toContain('"inputA": (undefined)');
});
it('should use coercion types if declared', () => {
const TEMPLATE = `<div dir [inputA]="foo"></div>`;
const DIRECTIVES: TestDeclaration[] = [{
type: 'directive',
name: 'Dir',
selector: '[dir]',
inputs: {
fieldA: 'inputA',
},
isGeneric: true,
coercedInputFields: ['fieldA'],
}];
expect(tcb(TEMPLATE, DIRECTIVES))
.toContain(
'var _t1: typeof i0.Dir.ngAcceptInputType_fieldA = null!; ' +
'_t1 = (((ctx).foo));');
});
});
it('should only generate code for DOM elements that are actually referenced', () => {
const TEMPLATE = `
<div></div>
<button #me (click)="handle(me)"></button>
`;
const block = tcb(TEMPLATE);
expect(block).not.toContain('"div"');
expect(block).toContain(
'var _t2 = document.createElement("button"); ' +
'var _t1 = _t2; ' +
'_t2.addEventListener');
});
it('should only generate directive declarations that have bindings or are referenced', () => {
const TEMPLATE = `
<div
hasInput [input]="value"
hasOutput (output)="handle()"
hasReference #ref="ref"
noReference
noBindings>{{ref.a}}</div>
`;
const DIRECTIVES: TestDeclaration[] = [
{
type: 'directive',
name: 'HasInput',
selector: '[hasInput]',
inputs: {input: 'input'},
},
{
type: 'directive',
name: 'HasOutput',
selector: '[hasOutput]',
outputs: {output: 'output'},
},
{
type: 'directive',
name: 'HasReference',
selector: '[hasReference]',
exportAs: ['ref'],
},
{
type: 'directive',
name: 'NoReference',
selector: '[noReference]',
exportAs: ['no-ref'],
},
{
type: 'directive',
name: 'NoBindings',
selector: '[noBindings]',
inputs: {unset: 'unset'},
},
];
const block = tcb(TEMPLATE, DIRECTIVES);
expect(block).toContain('var _t1: i0.HasInput = null!');
expect(block).toContain('_t1.input = (((ctx).value));');
expect(block).toContain('var _t2: i0.HasOutput = null!');
expect(block).toContain('_t2["output"]');
expect(block).toContain('var _t4: i0.HasReference = null!');
expect(block).toContain('var _t3 = _t4;');
expect(block).toContain('(_t3).a');
expect(block).not.toContain('NoBindings');
expect(block).not.toContain('NoReference');
});
it('should generate a forward element reference correctly', () => {
const TEMPLATE = `
{{ i.value }}
<input #i>
`;
expect(tcb(TEMPLATE))
.toContain(
'var _t2 = document.createElement("input"); var _t1 = _t2; "" + (((_t1).value));');
});
it('should generate a forward directive reference correctly', () => {
const TEMPLATE = `
{{d.value}}
<div dir #d="dir"></div>
`;
const DIRECTIVES: TestDeclaration[] = [{
type: 'directive',
name: 'Dir',
selector: '[dir]',
exportAs: ['dir'],
}];
expect(tcb(TEMPLATE, DIRECTIVES))
.toContain(
'var _t2: i0.Dir = null!; ' +
'var _t1 = _t2; ' +
'"" + (((_t1).value));');
});
it('should handle style and class bindings specially', () => {
const TEMPLATE = `
<div [style]="a" [class]="b"></div>
`;
const block = tcb(TEMPLATE);
expect(block).toContain('((ctx).a); ((ctx).b);');
// There should be no assignments to the class or style properties.
expect(block).not.toContain('.class = ');
expect(block).not.toContain('.style = ');
});
it('should only apply property bindings to directives', () => {
const TEMPLATE = `
<div dir [style.color]="'blue'" [class.strong]="false" [attr.enabled]="true"></div>
`;
const DIRECTIVES: TestDeclaration[] = [{
type: 'directive',
name: 'Dir',
selector: '[dir]',
inputs: {'color': 'color', 'strong': 'strong', 'enabled': 'enabled'},
}];
const block = tcb(TEMPLATE, DIRECTIVES);
expect(block).not.toContain('var _t1: Dir = null!;');
expect(block).not.toContain('"color"');
expect(block).not.toContain('"strong"');
expect(block).not.toContain('"enabled"');
expect(block).toContain('"blue"; false; true;');
});
it('should generate a circular directive reference correctly', () => {
const TEMPLATE = `
<div dir #d="dir" [input]="d"></div>
`;
const DIRECTIVES: TestDirective[] = [{
type: 'directive',
name: 'Dir',
selector: '[dir]',
exportAs: ['dir'],
inputs: {input: 'input'},
}];
expect(tcb(TEMPLATE, DIRECTIVES))
.toContain(
'var _t2: i0.Dir = null!; ' +
'var _t1 = _t2; ' +
'_t2.input = (_t1);');
});
it('should generate circular references between two directives correctly', () => {
const TEMPLATE = `
<div #a="dirA" dir-a [inputA]="b">A</div>
<div #b="dirB" dir-b [inputB]="a">B</div>
`;
const DIRECTIVES: TestDirective[] = [
{
type: 'directive',
name: 'DirA',
selector: '[dir-a]',
exportAs: ['dirA'],
inputs: {inputA: 'inputA'},
},
{
type: 'directive',
name: 'DirB',
selector: '[dir-b]',
exportAs: ['dirB'],
inputs: {inputA: 'inputB'},
}
];
expect(tcb(TEMPLATE, DIRECTIVES))
.toContain(
'var _t2: i0.DirB = null!; ' +
'var _t1 = _t2; ' +
'var _t3: i0.DirA = null!; ' +
'_t3.inputA = (_t1); ' +
'var _t4 = _t3; ' +
'_t2.inputA = (_t4);');
});
it('should handle undeclared properties', () => {
const TEMPLATE = `<div dir [inputA]="foo"></div>`;
const DIRECTIVES: TestDeclaration[] = [{
type: 'directive',
name: 'Dir',
selector: '[dir]',
inputs: {
fieldA: 'inputA',
},
undeclaredInputFields: ['fieldA']
}];
const block = tcb(TEMPLATE, DIRECTIVES);
expect(block).not.toContain('var _t1: Dir = null!;');
expect(block).toContain('(((ctx).foo)); ');
});
it('should assign restricted properties to temp variables by default', () => {
const TEMPLATE = `<div dir [inputA]="foo"></div>`;
const DIRECTIVES: TestDeclaration[] = [{
type: 'directive',
name: 'Dir',
selector: '[dir]',
inputs: {
fieldA: 'inputA',
},
restrictedInputFields: ['fieldA']
}];
expect(tcb(TEMPLATE, DIRECTIVES))
.toContain(
'var _t1: i0.Dir = null!; ' +
'var _t2: typeof _t1["fieldA"] = null!; ' +
'_t2 = (((ctx).foo)); ');
});
it('should assign properties via element access for field names that are not JS identifiers',
() => {
const TEMPLATE = `<div dir [inputA]="foo"></div>`;
const DIRECTIVES: TestDeclaration[] = [{
type: 'directive',
name: 'Dir',
selector: '[dir]',
inputs: {
'some-input.xs': 'inputA',
},
stringLiteralInputFields: ['some-input.xs'],
}];
const block = tcb(TEMPLATE, DIRECTIVES);
expect(block).toContain(
'var _t1: i0.Dir = null!; ' +
'_t1["some-input.xs"] = (((ctx).foo)); ');
});
it('should handle a single property bound to multiple fields', () => {
const TEMPLATE = `<div dir [inputA]="foo"></div>`;
const DIRECTIVES: TestDeclaration[] = [{
type: 'directive',
name: 'Dir',
selector: '[dir]',
inputs: {
field1: 'inputA',
field2: 'inputA',
},
}];
expect(tcb(TEMPLATE, DIRECTIVES))
.toContain(
'var _t1: i0.Dir = null!; ' +
'_t1.field2 = _t1.field1 = (((ctx).foo));');
});
it('should handle a single property bound to multiple fields, where one of them is coerced',
() => {
const TEMPLATE = `<div dir [inputA]="foo"></div>`;
const DIRECTIVES: TestDeclaration[] = [{
type: 'directive',
name: 'Dir',
selector: '[dir]',
inputs: {
field1: 'inputA',
field2: 'inputA',
},
coercedInputFields: ['field1'],
}];
expect(tcb(TEMPLATE, DIRECTIVES))
.toContain(
'var _t1: typeof i0.Dir.ngAcceptInputType_field1 = null!; ' +
'var _t2: i0.Dir = null!; ' +
'_t2.field2 = _t1 = (((ctx).foo));');
});
it('should handle a single property bound to multiple fields, where one of them is undeclared',
() => {
const TEMPLATE = `<div dir [inputA]="foo"></div>`;
const DIRECTIVES: TestDeclaration[] = [{
type: 'directive',
name: 'Dir',
selector: '[dir]',
inputs: {
field1: 'inputA',
field2: 'inputA',
},
undeclaredInputFields: ['field1'],
}];
expect(tcb(TEMPLATE, DIRECTIVES))
.toContain(
'var _t1: i0.Dir = null!; ' +
'_t1.field2 = (((ctx).foo));');
});
it('should use coercion types if declared', () => {
const TEMPLATE = `<div dir [inputA]="foo"></div>`;
const DIRECTIVES: TestDeclaration[] = [{
type: 'directive',
name: 'Dir',
selector: '[dir]',
inputs: {
fieldA: 'inputA',
},
coercedInputFields: ['fieldA'],
}];
const block = tcb(TEMPLATE, DIRECTIVES);
expect(block).not.toContain('var _t1: Dir = null!;');
expect(block).toContain(
'var _t1: typeof i0.Dir.ngAcceptInputType_fieldA = null!; ' +
'_t1 = (((ctx).foo));');
});
it('should use coercion types if declared, even when backing field is not declared', () => {
const TEMPLATE = `<div dir [inputA]="foo"></div>`;
const DIRECTIVES: TestDeclaration[] = [{
type: 'directive',
name: 'Dir',
selector: '[dir]',
inputs: {
fieldA: 'inputA',
},
coercedInputFields: ['fieldA'],
undeclaredInputFields: ['fieldA'],
}];
const block = tcb(TEMPLATE, DIRECTIVES);
expect(block).not.toContain('var _t1: Dir = null!;');
expect(block).toContain(
'var _t1: typeof i0.Dir.ngAcceptInputType_fieldA = null!; ' +
'_t1 = (((ctx).foo));');
});
it('should handle $any casts', () => {
const TEMPLATE = `{{$any(a)}}`;
const block = tcb(TEMPLATE);
expect(block).toContain('(((ctx).a) as any)');
});
it('should handle $any accessed through `this`', () => {
const TEMPLATE = `{{this.$any(a)}}`;
const block = tcb(TEMPLATE);
expect(block).toContain('((((ctx).$any))(((ctx).a)))');
});
describe('experimental DOM checking via lib.dom.d.ts', () => {
it('should translate unclaimed bindings to their property equivalent', () => {
const TEMPLATE = `<label [for]="'test'"></label>`;
const CONFIG = {...ALL_ENABLED_CONFIG, checkTypeOfDomBindings: true};
expect(tcb(TEMPLATE, /* declarations */ undefined, CONFIG))
.toContain('_t1["htmlFor"] = ("test");');
});
});
describe('template guards', () => {
it('should emit invocation guards', () => {
const DIRECTIVES: TestDeclaration[] = [{
type: 'directive',
name: 'NgIf',
selector: '[ngIf]',
inputs: {'ngIf': 'ngIf'},
ngTemplateGuards: [{
inputName: 'ngIf',
type: 'invocation',
}]
}];
const TEMPLATE = `<div *ngIf="person">{{person.name}}</div>`;
const block = tcb(TEMPLATE, DIRECTIVES);
expect(block).toContain('if (i0.NgIf.ngTemplateGuard_ngIf(_t1, ((ctx).person)))');
});
it('should emit binding guards', () => {
const DIRECTIVES: TestDeclaration[] = [{
type: 'directive',
name: 'NgIf',
selector: '[ngIf]',
inputs: {'ngIf': 'ngIf'},
ngTemplateGuards: [{
inputName: 'ngIf',
type: 'binding',
}]
}];
const TEMPLATE = `<div *ngIf="person !== null">{{person.name}}</div>`;
const block = tcb(TEMPLATE, DIRECTIVES);
expect(block).toContain('if ((((ctx).person)) !== (null))');
});
it('should not emit guards when the child scope is empty', () => {
const DIRECTIVES: TestDeclaration[] = [{
type: 'directive',
name: 'NgIf',
selector: '[ngIf]',
inputs: {'ngIf': 'ngIf'},
ngTemplateGuards: [{
inputName: 'ngIf',
type: 'invocation',
}]
}];
const TEMPLATE = `<div *ngIf="person">static</div>`;
const block = tcb(TEMPLATE, DIRECTIVES);
expect(block).not.toContain('NgIf.ngTemplateGuard_ngIf');
});
});
describe('outputs', () => {
it('should emit subscribe calls for directive outputs', () => {
const DIRECTIVES: TestDeclaration[] = [{
type: 'directive',
name: 'Dir',
selector: '[dir]',
outputs: {'outputField': 'dirOutput'},
}];
const TEMPLATE = `<div dir (dirOutput)="foo($event)"></div>`;
const block = tcb(TEMPLATE, DIRECTIVES);
expect(block).toContain(
'_t1["outputField"].subscribe(function ($event): any { (((ctx).foo))($event); });');
});
it('should emit a listener function with AnimationEvent for animation events', () => {
const TEMPLATE = `<div (@animation.done)="foo($event)"></div>`;
const block = tcb(TEMPLATE);
expect(block).toContain(
'function ($event: i1.AnimationEvent): any { (((ctx).foo))($event); }');
});
it('should emit addEventListener calls for unclaimed outputs', () => {
const TEMPLATE = `<div (event)="foo($event)"></div>`;
const block = tcb(TEMPLATE);
expect(block).toContain(
'_t1.addEventListener("event", function ($event): any { (((ctx).foo))($event); });');
});
it('should allow to cast $event using $any', () => {
const TEMPLATE = `<div (event)="foo($any($event))"></div>`;
const block = tcb(TEMPLATE);
expect(block).toContain(
'_t1.addEventListener("event", function ($event): any { (((ctx).foo))(($event as any)); });');
});
it('should detect writes to template variables', () => {
const TEMPLATE = `<ng-template let-v><div (event)="v = 3"></div></ng-template>`;
const block = tcb(TEMPLATE);
expect(block).toContain(
'_t3.addEventListener("event", function ($event): any { (_t2 = 3); });');
});
it('should ignore accesses to $event through `this`', () => {
const TEMPLATE = `<div (event)="foo(this.$event)"></div>`;
const block = tcb(TEMPLATE);
expect(block).toContain(
'_t1.addEventListener("event", function ($event): any { (((ctx).foo))(((ctx).$event)); });');
});
});
describe('config', () => {
const DIRECTIVES: TestDeclaration[] = [{
type: 'directive',
name: 'Dir',
selector: '[dir]',
exportAs: ['dir'],
inputs: {'dirInput': 'dirInput'},
outputs: {'outputField': 'dirOutput'},
hasNgTemplateContextGuard: true,
}];
const BASE_CONFIG: TypeCheckingConfig = {
applyTemplateContextGuards: true,
checkQueries: false,
checkTemplateBodies: true,
alwaysCheckSchemaInTemplateBodies: true,
checkTypeOfInputBindings: true,
honorAccessModifiersForInputBindings: false,
strictNullInputBindings: true,
checkTypeOfAttributes: true,
checkTypeOfDomBindings: false,
checkTypeOfOutputEvents: true,
checkTypeOfAnimationEvents: true,
checkTypeOfDomEvents: true,
checkTypeOfDomReferences: true,
checkTypeOfNonDomReferences: true,
checkTypeOfPipes: true,
strictSafeNavigationTypes: true,
useContextGenericType: true,
strictLiteralTypes: true,
enableTemplateTypeChecker: false,
useInlineTypeConstructors: true,
suggestionsForSuboptimalTypeInference: false,
};
describe('config.applyTemplateContextGuards', () => {
const TEMPLATE = `<div *dir>{{ value }}</div>`;
const GUARD_APPLIED = 'if (i0.Dir.ngTemplateContextGuard(';
it('should apply template context guards when enabled', () => {
const block = tcb(TEMPLATE, DIRECTIVES);
expect(block).toContain(GUARD_APPLIED);
});
it('should not apply template context guards when disabled', () => {
const DISABLED_CONFIG:
TypeCheckingConfig = {...BASE_CONFIG, applyTemplateContextGuards: false};
const block = tcb(TEMPLATE, DIRECTIVES, DISABLED_CONFIG);
expect(block).not.toContain(GUARD_APPLIED);
});
});
describe('config.checkTemplateBodies', () => {
const TEMPLATE = `<ng-template #ref>{{a}}</ng-template>{{ref}}`;
it('should descend into template bodies when enabled', () => {
const block = tcb(TEMPLATE, DIRECTIVES);
expect(block).toContain('((ctx).a)');
});
it('should not descend into template bodies when disabled', () => {
const DISABLED_CONFIG: TypeCheckingConfig = {...BASE_CONFIG, checkTemplateBodies: false};
const block = tcb(TEMPLATE, DIRECTIVES, DISABLED_CONFIG);
expect(block).not.toContain('((ctx).a)');
});
it('generates a references var when enabled', () => {
const block = tcb(TEMPLATE, DIRECTIVES);
expect(block).toContain('var _t1 = (_t2 as any as i1.TemplateRef<any>);');
});
it('generates a reference var when disabled', () => {
const DISABLED_CONFIG: TypeCheckingConfig = {...BASE_CONFIG, checkTemplateBodies: false};
const block = tcb(TEMPLATE, DIRECTIVES, DISABLED_CONFIG);
expect(block).toContain('var _t1 = (_t2 as any as i1.TemplateRef<any>);');
});
});
describe('config.strictNullInputBindings', () => {
const TEMPLATE = `<div dir [dirInput]="a" [nonDirInput]="b"></div>`;
it('should include null and undefined when enabled', () => {
const block = tcb(TEMPLATE, DIRECTIVES);
expect(block).toContain('_t1.dirInput = (((ctx).a));');
expect(block).toContain('((ctx).b);');
});
it('should use the non-null assertion operator when disabled', () => {
const DISABLED_CONFIG:
TypeCheckingConfig = {...BASE_CONFIG, strictNullInputBindings: false};
const block = tcb(TEMPLATE, DIRECTIVES, DISABLED_CONFIG);
expect(block).toContain('_t1.dirInput = (((ctx).a)!);');
expect(block).toContain('((ctx).b)!;');
});
});
describe('config.checkTypeOfBindings', () => {
it('should check types of bindings when enabled', () => {
const TEMPLATE = `<div dir [dirInput]="a" [nonDirInput]="b"></div>`;
const block = tcb(TEMPLATE, DIRECTIVES);
expect(block).toContain('_t1.dirInput = (((ctx).a));');
expect(block).toContain('((ctx).b);');
});
it('should not check types of bindings when disabled', () => {
const TEMPLATE = `<div dir [dirInput]="a" [nonDirInput]="b"></div>`;
const DISABLED_CONFIG:
TypeCheckingConfig = {...BASE_CONFIG, checkTypeOfInputBindings: false};
const block = tcb(TEMPLATE, DIRECTIVES, DISABLED_CONFIG);
expect(block).toContain('_t1.dirInput = ((((ctx).a) as any));');
expect(block).toContain('(((ctx).b) as any);');
});
it('should wrap the cast to any in parentheses when required', () => {
const TEMPLATE = `<div dir [dirInput]="a === b"></div>`;
const DISABLED_CONFIG:
TypeCheckingConfig = {...BASE_CONFIG, checkTypeOfInputBindings: false};
const block = tcb(TEMPLATE, DIRECTIVES, DISABLED_CONFIG);
expect(block).toContain('_t1.dirInput = ((((((ctx).a)) === (((ctx).b))) as any));');
});
});
describe('config.checkTypeOfOutputEvents', () => {
const TEMPLATE = `<div dir (dirOutput)="foo($event)" (nonDirOutput)="foo($event)"></div>`;
it('should check types of directive outputs when enabled', () => {
const block = tcb(TEMPLATE, DIRECTIVES);
expect(block).toContain(
'_t1["outputField"].subscribe(function ($event): any { (((ctx).foo))($event); });');
expect(block).toContain(
'_t2.addEventListener("nonDirOutput", function ($event): any { (((ctx).foo))($event); });');
});
it('should not check types of directive outputs when disabled', () => {
const DISABLED_CONFIG:
TypeCheckingConfig = {...BASE_CONFIG, checkTypeOfOutputEvents: false};
const block = tcb(TEMPLATE, DIRECTIVES, DISABLED_CONFIG);
expect(block).toContain('function ($event: any): any { (((ctx).foo))($event); }');
// Note that DOM events are still checked, that is controlled by `checkTypeOfDomEvents`
expect(block).toContain(
'addEventListener("nonDirOutput", function ($event): any { (((ctx).foo))($event); });');
});
});
describe('config.checkTypeOfAnimationEvents', () => {
const TEMPLATE = `<div (@animation.done)="foo($event)"></div>`;
it('should check types of animation events when enabled', () => {
const block = tcb(TEMPLATE, DIRECTIVES);
expect(block).toContain(
'function ($event: i1.AnimationEvent): any { (((ctx).foo))($event); }');
});
it('should not check types of animation events when disabled', () => {
const DISABLED_CONFIG:
TypeCheckingConfig = {...BASE_CONFIG, checkTypeOfAnimationEvents: false};
const block = tcb(TEMPLATE, DIRECTIVES, DISABLED_CONFIG);
expect(block).toContain('function ($event: any): any { (((ctx).foo))($event); }');
});
});
describe('config.checkTypeOfDomEvents', () => {
const TEMPLATE = `<div dir (dirOutput)="foo($event)" (nonDirOutput)="foo($event)"></div>`;
it('should check types of DOM events when enabled', () => {
const block = tcb(TEMPLATE, DIRECTIVES);
expect(block).toContain(
'_t1["outputField"].subscribe(function ($event): any { (((ctx).foo))($event); });');
expect(block).toContain(
'_t2.addEventListener("nonDirOutput", function ($event): any { (((ctx).foo))($event); });');
});
it('should not check types of DOM events when disabled', () => {
const DISABLED_CONFIG: TypeCheckingConfig = {...BASE_CONFIG, checkTypeOfDomEvents: false};
const block = tcb(TEMPLATE, DIRECTIVES, DISABLED_CONFIG);
// Note that directive outputs are still checked, that is controlled by
// `checkTypeOfOutputEvents`
expect(block).toContain(
'_t1["outputField"].subscribe(function ($event): any { (((ctx).foo))($event); });');
expect(block).toContain('function ($event: any): any { (((ctx).foo))($event); }');
});
});
describe('config.checkTypeOfDomReferences', () => {
const TEMPLATE = `<input #ref>{{ref.value}}`;
it('should trace references when enabled', () => {
const block = tcb(TEMPLATE);
expect(block).toContain('(_t1).value');
});
it('should use any for reference types when disabled', () => {
const DISABLED_CONFIG:
TypeCheckingConfig = {...BASE_CONFIG, checkTypeOfDomReferences: false};
const block = tcb(TEMPLATE, [], DISABLED_CONFIG);
expect(block).toContain(
'var _t1 = _t2 as any; ' +
'"" + (((_t1).value));');
});
});
describe('config.checkTypeOfNonDomReferences', () => {
const DIRECTIVES: TestDeclaration[] = [{
type: 'directive',
name: 'Dir',
selector: '[dir]',
exportAs: ['dir'],
inputs: {'dirInput': 'dirInput'},
outputs: {'outputField': 'dirOutput'},
hasNgTemplateContextGuard: true,
}];
const TEMPLATE =
`<div dir #ref="dir">{{ref.value}}</div><ng-template #ref2></ng-template>{{ref2.value2}}`;
it('should trace references to a directive when enabled', () => {
const block = tcb(TEMPLATE, DIRECTIVES);
expect(block).toContain('(_t1).value');
});
it('should trace references to an <ng-template> when enabled', () => {
const block = tcb(TEMPLATE, DIRECTIVES);
expect(block).toContain(
'var _t3 = (_t4 as any as i1.TemplateRef<any>); ' +
'"" + (((_t3).value2));');
});
it('should use any for reference types when disabled', () => {
const DISABLED_CONFIG:
TypeCheckingConfig = {...BASE_CONFIG, checkTypeOfNonDomReferences: false};
const block = tcb(TEMPLATE, DIRECTIVES, DISABLED_CONFIG);
expect(block).toContain(
'var _t1 = _t2 as any; ' +
'"" + (((_t1).value));');
});
});
describe('config.checkTypeOfAttributes', () => {
const TEMPLATE = `<textarea dir disabled cols="3" [rows]="2">{{ref.value}}</textarea>`;
const DIRECTIVES: TestDeclaration[] = [{
type: 'directive',
name: 'Dir',
selector: '[dir]',
inputs: {'disabled': 'disabled', 'cols': 'cols', 'rows': 'rows'},
}];
it('should assign string value to the input when enabled', () => {
const block = tcb(TEMPLATE, DIRECTIVES);
expect(block).toContain('_t1.disabled = ("");');
expect(block).toContain('_t1.cols = ("3");');
expect(block).toContain('_t1.rows = (2);');
});
it('should use any for attributes but still check bound attributes when disabled', () => {
const DISABLED_CONFIG: TypeCheckingConfig = {...BASE_CONFIG, checkTypeOfAttributes: false};
const block = tcb(TEMPLATE, DIRECTIVES, DISABLED_CONFIG);
expect(block).not.toContain('"disabled"');
expect(block).not.toContain('"cols"');
expect(block).toContain('_t1.rows = (2);');
});
});
describe('config.checkTypeOfPipes', () => {
const TEMPLATE = `{{a | test:b:c}}`;
const PIPES: TestDeclaration[] = [{
type: 'pipe',
name: 'TestPipe',
pipeName: 'test',
}];
it('should check types of pipes when enabled', () => {
const block = tcb(TEMPLATE, PIPES);
expect(block).toContain('var _pipe1: i0.TestPipe = null!;');
expect(block).toContain('(_pipe1.transform(((ctx).a), ((ctx).b), ((ctx).c)));');
});
it('should not check types of pipes when disabled', () => {
const DISABLED_CONFIG: TypeCheckingConfig = {...BASE_CONFIG, checkTypeOfPipes: false};
const block = tcb(TEMPLATE, PIPES, DISABLED_CONFIG);
expect(block).toContain('var _pipe1: i0.TestPipe = null!;');
expect(block).toContain('((_pipe1.transform as any)(((ctx).a), ((ctx).b), ((ctx).c))');
});
});
describe('config.strictSafeNavigationTypes', () => {
const TEMPLATE = `{{a?.b}} {{a?.method()}} {{a?.[0]}}`;
it('should use undefined for safe navigation operations when enabled', () => {
const block = tcb(TEMPLATE, DIRECTIVES);
expect(block).toContain(
'(null as any ? ((null as any ? (((ctx).a))!.method : undefined))!() : undefined)');
expect(block).toContain('(null as any ? (((ctx).a))!.b : undefined)');
expect(block).toContain('(null as any ? (((ctx).a))![0] : undefined)');
});
it('should use an \'any\' type for safe navigation operations when disabled', () => {
const DISABLED_CONFIG:
TypeCheckingConfig = {...BASE_CONFIG, strictSafeNavigationTypes: false};
const block = tcb(TEMPLATE, DIRECTIVES, DISABLED_CONFIG);
expect(block).toContain('(((((((ctx).a))!.method as any)) as any)())');
expect(block).toContain('((((ctx).a))!.b as any)');
expect(block).toContain('(((((ctx).a))![0] as any)');
});
});
describe('config.strictSafeNavigationTypes (View Engine bug emulation)', () => {
const TEMPLATE = `{{a.method()?.b}} {{a()?.method()}} {{a.method()?.[0]}}`;
it('should check the presence of a property/method on the receiver when enabled', () => {
const block = tcb(TEMPLATE, DIRECTIVES);
expect(block).toContain('(null as any ? ((((((ctx).a)).method))())!.b : undefined)');
expect(block).toContain(
'(null as any ? ((null as any ? ((((ctx).a))())!.method : undefined))!() : undefined)');
expect(block).toContain('(null as any ? ((((((ctx).a)).method))())![0] : undefined)');
});
it('should not check the presence of a property/method on the receiver when disabled', () => {
const DISABLED_CONFIG:
TypeCheckingConfig = {...BASE_CONFIG, strictSafeNavigationTypes: false};
const block = tcb(TEMPLATE, DIRECTIVES, DISABLED_CONFIG);
expect(block).toContain('((((((((ctx).a)).method))()) as any).b)');
expect(block).toContain('((((((((ctx).a))()) as any).method) as any)())');
expect(block).toContain('((((((((ctx).a)).method))()) as any)[0])');
});
});
describe('config.strictContextGenerics', () => {
const TEMPLATE = `Test`;
it('should use the generic type of the context when enabled', () => {
const block = tcb(TEMPLATE);
expect(block).toContain('function _tcb1<T extends string>(ctx: i0.Test<T>)');
});
it('should use any for the context generic type when disabled', () => {
const DISABLED_CONFIG: TypeCheckingConfig = {...BASE_CONFIG, useContextGenericType: false};
const block = tcb(TEMPLATE, undefined, DISABLED_CONFIG);
expect(block).toContain('function _tcb1(ctx: i0.Test<any>)');
});
});
describe('config.checkAccessModifiersForInputBindings', () => {
const TEMPLATE = `<div dir [inputA]="foo"></div>`;
it('should assign restricted properties via element access for field names that are not JS identifiers',
() => {
const DIRECTIVES: TestDeclaration[] = [{
type: 'directive',
name: 'Dir',
selector: '[dir]',
inputs: {
'some-input.xs': 'inputA',
},
restrictedInputFields: ['some-input.xs'],
stringLiteralInputFields: ['some-input.xs'],
}];
const enableChecks:
TypeCheckingConfig = {...BASE_CONFIG, honorAccessModifiersForInputBindings: true};
const block = tcb(TEMPLATE, DIRECTIVES, enableChecks);
expect(block).toContain(
'var _t1: i0.Dir = null!; ' +
'_t1["some-input.xs"] = (((ctx).foo)); ');
});
it('should assign restricted properties via property access', () => {
const DIRECTIVES: TestDeclaration[] = [{
type: 'directive',
name: 'Dir',
selector: '[dir]',
inputs: {
fieldA: 'inputA',
},
restrictedInputFields: ['fieldA']
}];
const enableChecks:
TypeCheckingConfig = {...BASE_CONFIG, honorAccessModifiersForInputBindings: true};
const block = tcb(TEMPLATE, DIRECTIVES, enableChecks);
expect(block).toContain(
'var _t1: i0.Dir = null!; ' +
'_t1.fieldA = (((ctx).foo)); ');
});
});
});
it('should use `any` type for type constructors with bound generic params ' +
'when `useInlineTypeConstructors` is `false`',
() => {
const template = `
<div dir
[inputA]='foo'
[inputB]='bar'
></div>
`;
const declarations: TestDeclaration[] = [{
code: `
interface PrivateInterface{};
export class Dir<T extends PrivateInterface, U extends string> {};
`,
type: 'directive',
name: 'Dir',
selector: '[dir]',
inputs: {
inputA: 'inputA',
inputB: 'inputB',
},
isGeneric: true
}];
const renderedTcb = tcb(template, declarations, {useInlineTypeConstructors: false});
expect(renderedTcb).toContain(`var _t1: i0.Dir<any, any> = null!;`);
expect(renderedTcb).toContain(`_t1.inputA = (((ctx).foo));`);
expect(renderedTcb).toContain(`_t1.inputB = (((ctx).bar));`);
});
}); | the_stack |
import { DatePipe } from '@angular/common';
import { Injectable, OnDestroy } from '@angular/core';
import { select, Store } from '@ngrx/store';
import { shell } from 'electron';
import * as path from 'path';
import { Observable, Subject, Subscription, zip } from 'rxjs';
import { map, switchMap, take } from 'rxjs/operators';
import { makeNoteContentFileName, Note, NoteSnippetTypes } from '../../../core/note';
import { VcsFileChange, VcsFileChangeStatusTypes } from '../../../core/vcs';
import { isOutsidePath } from '../../../libs/path';
import { toPromise } from '../../../libs/rx';
import { uuid } from '../../../libs/uuid';
import { FsService, WorkspaceService } from '../../shared';
import { NoteContentFileAlreadyExistsError, NoteOutsideWorkspaceError } from '../note-errors';
import { convertToNoteSnippets, NoteParser } from '../note-shared';
import { NoteStateWithRoot } from '../note.state';
import {
AddNoteAction,
ChangeNoteStacksAction,
ChangeNoteTitleAction,
DeleteNoteAction,
DeselectNoteAction,
LoadNoteCollectionAction,
LoadNoteCollectionCompleteAction,
SelectNoteAction,
} from './note-collection.actions';
import { NoteItem } from './note-item.model';
@Injectable()
export class NoteCollectionService implements OnDestroy {
private toggleNoteSelectionSubscription = Subscription.EMPTY;
private readonly _toggleNoteSelection = new Subject<NoteItem>();
// noinspection JSMismatchedCollectionQueryUpdate
private vcsFileChanges: VcsFileChange[] = [];
private vcsFileChangesSubscription = Subscription.EMPTY;
constructor(
private store: Store<NoteStateWithRoot>,
private parser: NoteParser,
private fs: FsService,
private workspace: WorkspaceService,
private datePipe: DatePipe,
) {
this.subscribeToggles();
}
ngOnDestroy(): void {
this.toggleNoteSelectionSubscription.unsubscribe();
this.vcsFileChangesSubscription.unsubscribe();
}
provideVcsFileChanges(fileChanges: Observable<VcsFileChange[]>): void {
this.vcsFileChangesSubscription = fileChanges.subscribe(changes => this.vcsFileChanges = changes);
}
/**
* Load all notes and dispatch loadOnce note events.
* @returns {Promise<void>}
*/
async loadOnce(): Promise<void> {
const notesDirPath = this.workspace.configs.notesDirPath;
// 1) Dispatch 'LOAD_COLLECTION' action.
this.store.dispatch(new LoadNoteCollectionAction());
// 2) Get all notes.
const noteFileNames = await toPromise(this.fs.readDirectory(notesDirPath));
const filteredNoteFileNames = noteFileNames.filter(
fileName => path.extname(fileName) === '.json',
);
const readingNotes: Promise<Note | null>[] = [];
filteredNoteFileNames.forEach((fileName) => {
const filePath = path.resolve(notesDirPath, fileName);
readingNotes.push(toPromise(this.fs.readJsonFile<Note>(filePath)));
});
// 3) Change notes to note items.
const results = await Promise.all(readingNotes);
const notes: NoteItem[] = results
.filter(note => note !== null)
.map((note: Note, index) => ({
...note,
fileName: filteredNoteFileNames[index],
filePath: path.resolve(notesDirPath, filteredNoteFileNames[index]),
contentFilePath: note.label
? path.resolve(
this.workspace.configs.rootDirPath,
note.label,
note.contentFileName,
)
: path.resolve(
this.workspace.configs.rootDirPath,
note.contentFileName,
),
}));
// 4) Dispatch 'LOAD_COLLECTION_COMPLETE' action.
this.store.dispatch(new LoadNoteCollectionCompleteAction({ notes }));
}
getFilteredAndSortedNoteList(): Observable<NoteItem[]> {
return this.store.pipe(
select(state => state.note.collection.filteredAndSortedNotes),
);
}
getSelectedNote(): Observable<NoteItem | null> {
return this.store.pipe(
select(state => state.note.collection.selectedNote),
);
}
getNoteVcsFileChanges(note: NoteItem): VcsFileChange[] {
const { contentFilePath, filePath } = note;
const matchedFilePaths = [contentFilePath, filePath];
return this.vcsFileChanges.filter(change => matchedFilePaths.includes(change.absoluteFilePath));
}
getNoteVcsFileChangeStatus(note: NoteItem): VcsFileChangeStatusTypes | null {
const fileChanges = this.getNoteVcsFileChanges(note);
// TODO(@seokju-na): Currently, because note has 2 files, we cannot
// determine one status for one note.
return fileChanges.length ? fileChanges[0].status : null;
}
toggleNoteSelection(note: NoteItem): void {
this._toggleNoteSelection.next(note);
}
selectNote(note: NoteItem): void {
this.store.dispatch(new SelectNoteAction({ note }));
}
deselectNote(): void {
this.store.dispatch(new DeselectNoteAction());
}
async createNewNote(title: string, directory: string = ''): Promise<void> {
const rootDirPath = this.workspace.configs.rootDirPath;
const createdAt = new Date().getTime();
const contentFileName = makeNoteContentFileName(createdAt, title);
const contentFilePath = path.resolve(rootDirPath, directory, contentFileName);
if (isOutsidePath(contentFilePath, rootDirPath)) {
throw new NoteOutsideWorkspaceError();
}
if (await toPromise(this.fs.isPathExists(contentFilePath))) {
throw new NoteContentFileAlreadyExistsError();
}
const content = {
snippets: [
{
type: NoteSnippetTypes.TEXT,
value: 'Write some content...',
},
],
};
const result = this.parser.parseNoteContent(content, {
metadata: {
title,
date: this.datePipe.transform(new Date(), 'E, d MMM yyyy HH:mm:ss Z'),
stacks: [],
},
});
const id = uuid();
const noteFileName = `${id}.json`;
const noteFilePath = path.resolve(this.workspace.configs.notesDirPath, noteFileName);
const contentRawValue = result.contentRawValue;
const note: Note = {
id,
title,
snippets: convertToNoteSnippets(result.parsedSnippets),
createdDatetime: createdAt,
stackIds: [],
label: directory,
contentFileName,
};
/**
* Make sure to ensure the directory where content file will saved.
*/
await toPromise(this.fs.ensureDirectory(path.dirname(contentFilePath)));
await toPromise(zip(
this.fs.writeJsonFile<Note>(noteFilePath, note),
this.fs.writeFile(contentFilePath, contentRawValue),
));
// Dispatch 'ADD_NOTE' action.
const noteItem: NoteItem = {
...note,
fileName: noteFileName,
filePath: noteFilePath,
contentFilePath,
};
this.store.dispatch(new AddNoteAction({ note: noteItem }));
}
async changeNoteTitle(noteItem: NoteItem, newTitle: string): Promise<void> {
const dirName = path.dirname(noteItem.contentFilePath);
let newContentFileName: string;
let newContentFilePath: string;
const allNotes = await toPromise(this.store.pipe(
select(state => state.note.collection.notes),
take(1),
));
const allNoteContentFilePaths = allNotes.map(item => item.contentFilePath);
let index = 0;
const isNoteTitleDuplicated = title => allNoteContentFilePaths.includes(title);
// Check title duplication.
do {
const title = index === 0 ? newTitle : `${newTitle}(${index})`;
newContentFileName = makeNoteContentFileName(noteItem.createdDatetime, title);
newContentFilePath = path.resolve(dirName, newContentFileName);
index++;
} while (isNoteTitleDuplicated(newContentFilePath));
// If content file name is same, just ignore.
if (newContentFileName === noteItem.contentFileName) {
return;
}
// Rename file.
try {
await toPromise(this.fs.renameFile(noteItem.contentFilePath, newContentFilePath));
} catch (error) {
throw new NoteContentFileAlreadyExistsError();
}
this.store.dispatch(new ChangeNoteTitleAction({
note: noteItem,
title: newTitle,
contentFileName: newContentFileName,
contentFilePath: newContentFilePath,
}));
}
changeNoteStacks(noteItem: NoteItem, stacks: string[]): void {
this.store.dispatch(new ChangeNoteStacksAction({ note: noteItem, stacks }));
}
deleteNote(noteItem: NoteItem): void {
const allRemoved = shell.moveItemToTrash(noteItem.filePath)
&& shell.moveItemToTrash(noteItem.contentFilePath);
if (!allRemoved) {
// TODO(@seokju-na): Might need rollback...?
return;
}
this.getSelectedNote().pipe(take(1)).subscribe((selectedNote: NoteItem) => {
if (selectedNote && selectedNote.id === noteItem.id) {
this.store.dispatch(new DeselectNoteAction());
}
this.store.dispatch(new DeleteNoteAction({ note: noteItem }));
});
}
private subscribeToggles(): void {
this.toggleNoteSelectionSubscription =
this._toggleNoteSelection.asObservable().pipe(
switchMap(note =>
this.getSelectedNote().pipe(
take(1),
map(selectedNote => ([selectedNote, note])),
),
),
).subscribe(([selectedNote, note]) =>
this.handleNoteSelectionToggling(selectedNote, note),
);
}
private handleNoteSelectionToggling(selectedNote: NoteItem, note: NoteItem): void {
if (selectedNote && selectedNote.id === note.id) {
this.deselectNote();
} else {
this.selectNote(note);
}
}
} | the_stack |
const AssociativeArray = Cesium.AssociativeArray;
const Color = Cesium.Color;
const ColorGeometryInstanceAttribute = Cesium.ColorGeometryInstanceAttribute;
const defined = Cesium.defined;
const DistanceDisplayCondition = Cesium.DistanceDisplayCondition;
const DistanceDisplayConditionGeometryInstanceAttribute = Cesium.DistanceDisplayConditionGeometryInstanceAttribute;
const ShowGeometryInstanceAttribute = Cesium.ShowGeometryInstanceAttribute;
const Primitive = Cesium.Primitive;
const ShadowMode = Cesium.ShadowMode;
const BoundingSphereState = Cesium.BoundingSphereState;
const ColorMaterialProperty = Cesium.ColorMaterialProperty;
const MaterialProperty = Cesium.MaterialProperty;
const Property = Cesium.Property;
var colorScratch = new Color();
var distanceDisplayConditionScratch = new DistanceDisplayCondition();
var defaultDistanceDisplayCondition = new DistanceDisplayCondition();
function Batch(primitives, translucent, appearanceType, depthFailAppearanceType, depthFailMaterialProperty, closed, shadows) {
this.translucent = translucent;
this.appearanceType = appearanceType;
this.depthFailAppearanceType = depthFailAppearanceType;
this.depthFailMaterialProperty = depthFailMaterialProperty;
this.depthFailMaterial = undefined;
this.closed = closed;
this.shadows = shadows;
this.primitives = primitives;
this.createPrimitive = false;
this.waitingOnCreate = false;
this.primitive = undefined;
this.oldPrimitive = undefined;
this.geometry = new AssociativeArray();
this.updaters = new AssociativeArray();
this.updatersWithAttributes = new AssociativeArray();
this.attributes = new AssociativeArray();
this.subscriptions = new AssociativeArray();
this.showsUpdated = new AssociativeArray();
this.itemsToRemove = [];
this.invalidated = false;
var removeMaterialSubscription;
if (defined(depthFailMaterialProperty)) {
removeMaterialSubscription = depthFailMaterialProperty.definitionChanged.addEventListener(Batch.prototype.onMaterialChanged, this);
}
this.removeMaterialSubscription = removeMaterialSubscription;
}
Batch.prototype.onMaterialChanged = function () {
this.invalidated = true;
};
Batch.prototype.isMaterial = function (updater) {
var material = this.depthFailMaterialProperty;
var updaterMaterial = updater.depthFailMaterialProperty;
if (updaterMaterial === material) {
return true;
}
if (defined(material)) {
return material.equals(updaterMaterial);
}
return false;
};
Batch.prototype.add = function (updater, instance) {
var id = updater.id;
this.createPrimitive = true;
this.geometry.set(id, instance);
this.updaters.set(id, updater);
if (!updater.hasConstantFill || !updater.fillMaterialProperty.isConstant || !Property.isConstant(updater.distanceDisplayConditionProperty)) {
this.updatersWithAttributes.set(id, updater);
} else {
var that = this;
this.subscriptions.set(id, updater.entity.definitionChanged.addEventListener(function (entity, propertyName, newValue, oldValue) {
if (propertyName === 'isShowing') {
that.showsUpdated.set(updater.id, updater);
}
}));
}
};
Batch.prototype.remove = function (updater) {
var id = updater.id;
this.createPrimitive = this.geometry.remove(id) || this.createPrimitive;
if (this.updaters.remove(id)) {
this.updatersWithAttributes.remove(id);
var unsubscribe = this.subscriptions.get(id);
if (defined(unsubscribe)) {
unsubscribe();
this.subscriptions.remove(id);
}
}
};
Batch.prototype.update = function (time) {
var isUpdated = true;
var removedCount = 0;
var primitive = this.primitive;
var primitives = this.primitives;
var attributes;
var i;
if (this.createPrimitive) {
var geometries = this.geometry.values;
var geometriesLength = geometries.length;
if (geometriesLength > 0) {
if (defined(primitive)) {
if (!defined(this.oldPrimitive)) {
this.oldPrimitive = primitive;
} else {
primitives.remove(primitive);
}
}
for (i = 0; i < geometriesLength; i++) {
var geometryItem = geometries[i];
var originalAttributes = geometryItem.attributes;
attributes = this.attributes.get(geometryItem.id.id);
if (defined(attributes)) {
if (defined(originalAttributes.show)) {
originalAttributes.show.value = attributes.show;
}
if (defined(originalAttributes.color)) {
originalAttributes.color.value = attributes.color;
}
if (defined(originalAttributes.depthFailColor)) {
originalAttributes.depthFailColor.value = attributes.depthFailColor;
}
}
}
var depthFailAppearance;
if (defined(this.depthFailAppearanceType)) {
if (defined(this.depthFailMaterialProperty)) {
this.depthFailMaterial = MaterialProperty.getValue(time, this.depthFailMaterialProperty, this.depthFailMaterial);
}
depthFailAppearance = new this.depthFailAppearanceType({
material: this.depthFailMaterial,
translucent: this.translucent,
closed: this.closed
});
}
primitive = new Primitive({
show: false,
asynchronous: true,
geometryInstances: geometries,
appearance: new this.appearanceType({
flat: this.shadows === ShadowMode.DISABLED || this.shadows === ShadowMode.CAST_ONLY,
translucent: this.translucent,
closed: this.closed
}),
depthFailAppearance: depthFailAppearance,
shadows: this.shadows
});
primitives.add(primitive);
isUpdated = false;
} else {
if (defined(primitive)) {
primitives.remove(primitive);
primitive = undefined;
}
var oldPrimitive = this.oldPrimitive;
if (defined(oldPrimitive)) {
primitives.remove(oldPrimitive);
this.oldPrimitive = undefined;
}
}
this.attributes.removeAll();
this.primitive = primitive;
this.createPrimitive = false;
this.waitingOnCreate = true;
} else if (defined(primitive) && primitive.ready) {
primitive.show = true;
if (defined(this.oldPrimitive)) {
primitives.remove(this.oldPrimitive);
this.oldPrimitive = undefined;
}
if (defined(this.depthFailAppearanceType) && !(this.depthFailMaterialProperty instanceof ColorMaterialProperty)) {
this.depthFailMaterial = MaterialProperty.getValue(time, this.depthFailMaterialProperty, this.depthFailMaterial);
this.primitive.depthFailAppearance.material = this.depthFailMaterial;
}
var updatersWithAttributes = this.updatersWithAttributes.values;
var length = updatersWithAttributes.length;
var waitingOnCreate = this.waitingOnCreate;
for (i = 0; i < length; i++) {
var updater = updatersWithAttributes[i];
var instance = this.geometry.get(updater.id);
attributes = this.attributes.get(instance.id.id);
if (!defined(attributes)) {
attributes = primitive.getGeometryInstanceAttributes(instance.id);
this.attributes.set(instance.id.id, attributes);
}
if (!updater.fillMaterialProperty.isConstant || waitingOnCreate) {
var colorProperty = updater.fillMaterialProperty.color;
var resultColor = Property.getValueOrDefault(colorProperty, time, Color.WHITE, colorScratch);
if (!Color.equals(attributes._lastColor, resultColor)) {
attributes._lastColor = Color.clone(resultColor, attributes._lastColor);
attributes.color = ColorGeometryInstanceAttribute.toValue(resultColor, attributes.color);
if ((this.translucent && attributes.color[3] === 255) || (!this.translucent && attributes.color[3] !== 255)) {
this.itemsToRemove[removedCount++] = updater;
}
}
}
if (defined(this.depthFailAppearanceType) && updater.depthFailMaterialProperty instanceof ColorMaterialProperty && (!updater.depthFailMaterialProperty.isConstant || waitingOnCreate)) {
var depthFailColorProperty = updater.depthFailMaterialProperty.color;
var depthColor = Property.getValueOrDefault(depthFailColorProperty, time, Color.WHITE, colorScratch);
if (!Color.equals(attributes._lastDepthFailColor, depthColor)) {
attributes._lastDepthFailColor = Color.clone(depthColor, attributes._lastDepthFailColor);
attributes.depthFailColor = ColorGeometryInstanceAttribute.toValue(depthColor, attributes.depthFailColor);
}
}
var show = updater.entity.isShowing && (updater.hasConstantFill || updater.isFilled(time));
var currentShow = attributes.show[0] === 1;
if (show !== currentShow) {
attributes.show = ShowGeometryInstanceAttribute.toValue(show, attributes.show);
}
var distanceDisplayConditionProperty = updater.distanceDisplayConditionProperty;
if (!Property.isConstant(distanceDisplayConditionProperty)) {
var distanceDisplayCondition = Property.getValueOrDefault(distanceDisplayConditionProperty, time, defaultDistanceDisplayCondition, distanceDisplayConditionScratch);
if (!DistanceDisplayCondition.equals(distanceDisplayCondition, attributes._lastDistanceDisplayCondition)) {
attributes._lastDistanceDisplayCondition = DistanceDisplayCondition.clone(distanceDisplayCondition, attributes._lastDistanceDisplayCondition);
attributes.distanceDisplayCondition = DistanceDisplayConditionGeometryInstanceAttribute.toValue(distanceDisplayCondition, attributes.distanceDisplayCondition);
}
}
}
this.updateShows(primitive);
this.waitingOnCreate = false;
} else if (defined(primitive) && !primitive.ready) {
isUpdated = false;
}
this.itemsToRemove.length = removedCount;
return isUpdated;
};
Batch.prototype.updateShows = function (primitive) {
var showsUpdated = this.showsUpdated.values;
var length = showsUpdated.length;
for (var i = 0; i < length; i++) {
var updater = showsUpdated[i];
var instance = this.geometry.get(updater.id);
var attributes = this.attributes.get(instance.id.id);
if (!defined(attributes)) {
attributes = primitive.getGeometryInstanceAttributes(instance.id);
this.attributes.set(instance.id.id, attributes);
}
var show = updater.entity.isShowing;
var currentShow = attributes.show[0] === 1;
if (show !== currentShow) {
attributes.show = ShowGeometryInstanceAttribute.toValue(show, attributes.show);
}
}
this.showsUpdated.removeAll();
};
Batch.prototype.contains = function (updater) {
return this.updaters.contains(updater.id);
};
Batch.prototype.getBoundingSphere = function (updater, result) {
var primitive = this.primitive;
if (!primitive.ready) {
return BoundingSphereState.PENDING;
}
var attributes = primitive.getGeometryInstanceAttributes(updater.entity);
if (!defined(attributes) || !defined(attributes.boundingSphere) ||//
(defined(attributes.show) && attributes.show[0] === 0)) {
return BoundingSphereState.FAILED;
}
attributes.boundingSphere.clone(result);
return BoundingSphereState.DONE;
};
Batch.prototype.removeAllPrimitives = function () {
var primitives = this.primitives;
var primitive = this.primitive;
if (defined(primitive)) {
primitives.remove(primitive);
this.primitive = undefined;
this.geometry.removeAll();
this.updaters.removeAll();
}
var oldPrimitive = this.oldPrimitive;
if (defined(oldPrimitive)) {
primitives.remove(oldPrimitive);
this.oldPrimitive = undefined;
}
};
Batch.prototype.destroy = function () {
var primitive = this.primitive;
var primitives = this.primitives;
if (defined(primitive)) {
primitives.remove(primitive);
}
var oldPrimitive = this.oldPrimitive;
if (defined(oldPrimitive)) {
primitives.remove(oldPrimitive);
}
if (defined(this.removeMaterialSubscription)) {
this.removeMaterialSubscription();
}
};
let wasFixed = false;
export function fixCesiumEntitiesShadows() {
if (wasFixed) {
return;
}
Cesium.StaticGeometryColorBatch.prototype.add = function (time: any, updater: any) {
var items;
var translucent;
var instance = updater.createFillGeometryInstance(time);
if (instance.attributes.color.value[3] === 255) {
items = this._solidItems;
translucent = false;
} else {
items = this._translucentItems;
translucent = true;
}
var length = items.length;
for (var i = 0; i < length; i++) {
var item = items[i];
if (item.isMaterial(updater)) {
item.add(updater, instance);
return;
}
}
var batch: any = new Batch(this._primitives, translucent, this._appearanceType, this._depthFailAppearanceType, updater.depthFailMaterialProperty, this._closed, this._shadows);
batch.add(updater, instance);
items.push(batch);
};
wasFixed = true;
} | the_stack |
import { window, commands, env, QuickPickItem, ExtensionContext, Terminal, Uri, workspace } from 'vscode';
import { Command } from '../odo/command';
import OpenShiftItem, { clusterRequired } from './openshiftItem';
import { CliExitData, CliChannel } from '../cli';
import { TokenStore } from '../util/credentialManager';
import { KubeConfigUtils } from '../util/kubeUtils';
import { Filters } from '../util/filters';
import { Progress } from '../util/progress';
import { Platform } from '../util/platform';
import { WindowUtil } from '../util/windowUtils';
import { vsCommand, VsCommandError } from '../vscommand';
import ClusterViewLoader from '../webview/cluster/clusterViewLoader';
interface Versions {
'openshift_version': string;
'kubernetes_version': string;
}
export class Cluster extends OpenShiftItem {
public static extensionContext: ExtensionContext;
@vsCommand('openshift.explorer.logout')
static async logout(): Promise<string> {
const value = await window.showWarningMessage('Do you want to logout of cluster?', 'Logout', 'Cancel');
if (value === 'Logout') {
return Cluster.odo.execute(Command.odoLogout())
.catch((error) => Promise.reject(new VsCommandError(`Failed to logout of the current cluster with '${error}'!`, 'Failed to logout of the current cluster')))
.then(async (result) => {
if (result.stderr === '') {
Cluster.explorer.refresh();
commands.executeCommand('setContext', 'isLoggedIn', false);
const logoutInfo = await window.showInformationMessage('Successfully logged out. Do you want to login to a new cluster', 'Yes', 'No');
if (logoutInfo === 'Yes') {
return Cluster.login(undefined, true);
}
return null;
}
throw new VsCommandError(`Failed to logout of the current cluster with '${result.stderr}'!`, 'Failed to logout of the current cluster');
});
}
return null;
}
@vsCommand('openshift.explorer.refresh')
static refresh(): void {
Cluster.explorer.refresh();
}
@vsCommand('openshift.about')
static async about(): Promise<void> {
await Cluster.odo.executeInTerminal(Command.printOdoVersion(), undefined, 'OpenShift: Show odo Version');
}
@vsCommand('openshift.oc.about')
static async ocAbout(): Promise<void> {
await Cluster.odo.executeInTerminal(Command.printOcVersion(), undefined, 'OpenShift: Show OKD CLI Tool Version');
}
@vsCommand('openshift.output')
static showOpenShiftOutput(): void {
CliChannel.getInstance().showOutput();
}
@vsCommand('openshift.openshiftConsole', true)
@clusterRequired()
static async openshiftConsole(): Promise<void> {
let consoleUrl: string;
try {
const getUrlObj = await Cluster.odo.execute(Command.showConsoleUrl());
consoleUrl = JSON.parse(getUrlObj.stdout).data.consoleURL;
} catch (ignore) {
const serverUrl = await Cluster.odo.execute(Command.showServerUrl());
consoleUrl = `${serverUrl.stdout}/console`;
}
return commands.executeCommand('vscode.open', Uri.parse(consoleUrl));
}
@vsCommand('openshift.explorer.switchContext')
static async switchContext(): Promise<string> {
const k8sConfig = new KubeConfigUtils();
const contexts = k8sConfig.contexts.filter((item) => item.name !== k8sConfig.currentContext);
const contextName: QuickPickItem[] = contexts.map((ctx) => ({ label: `${ctx.name}`}));
const choice = await window.showQuickPick(contextName, {placeHolder: 'Select a new OpenShift context'});
if (!choice) return null;
await Cluster.odo.execute(Command.setOpenshiftContext(choice.label));
return `Cluster context is changed to: ${choice.label}`;
}
static async getUrl(): Promise<string | null> {
const k8sConfig = new KubeConfigUtils();
const clusterURl = await Cluster.getUrlFromClipboard();
const createUrl: QuickPickItem = { label: '$(plus) Provide new URL...'};
const clusterItems = k8sConfig.getServers();
const choice = await window.showQuickPick([createUrl, ...clusterItems], {placeHolder: 'Provide Cluster URL to connect', ignoreFocusOut: true});
if (!choice) return null;
return (choice.label === createUrl.label) ?
window.showInputBox({
value: clusterURl,
ignoreFocusOut: true,
prompt: 'Provide new Cluster URL to connect',
validateInput: (value: string) => Cluster.validateUrl('Invalid URL provided', value)
}) : choice.label;
}
@vsCommand('openshift.explorer.addCluster')
static add(): void {
ClusterViewLoader.loadView('Add OpenShift Cluster');
}
@vsCommand('openshift.explorer.stopCluster')
static async stop(): Promise<void> {
let pathSelectionDialog;
let newPathPrompt;
let crcBinary;
const crcPath = workspace.getConfiguration('openshiftConnector').get('crcBinaryLocation');
if(crcPath) {
newPathPrompt = { label: '$(plus) Provide different crc binary path'};
pathSelectionDialog = await window.showQuickPick([{label:`${crcPath}`, description: 'Fetched from settings'}, newPathPrompt], {placeHolder: 'Select CRC binary path', ignoreFocusOut: true});
}
if(!pathSelectionDialog) return;
if (pathSelectionDialog.label === newPathPrompt.label) {
const crcBinaryLocation = await window.showOpenDialog({
canSelectFiles: true,
canSelectFolders: false,
canSelectMany: false,
defaultUri: Uri.file(Platform.getUserHomePath()),
openLabel: 'Add crc binary path.',
});
if (!crcBinaryLocation) return null;
crcBinary = crcBinaryLocation[0].fsPath;
} else {
crcBinary = crcPath;
}
const terminal: Terminal = WindowUtil.createTerminal('OpenShift: Stop CRC', undefined);
terminal.sendText(`${crcBinary} stop`);
terminal.show();
return;
}
public static async getVersions(): Promise<Versions> {
const result = await Cluster.odo.execute(Command.printOcVersionJson(), undefined, false);
const versions: Versions = {
'kubernetes_version': undefined,
'openshift_version': undefined
};
if (!result.error) {
try {
// try to fetch versions for stdout
const versionsJson = JSON.parse(result.stdout);
if (versionsJson?.serverVersion?.major && versionsJson?.serverVersion?.minor) {
// eslint-disable-next-line camelcase
versions.kubernetes_version = `${versionsJson.serverVersion.major}.${versionsJson.serverVersion.minor}`;
}
if (versionsJson?.openshiftVersion) {
// eslint-disable-next-line camelcase
versions.openshift_version = versionsJson.openshiftVersion;
}
} catch(err) {
// ignore and return undefined
}
}
return versions;
}
@vsCommand('openshift.explorer.login')
static async login(context?: any, skipConfirmation = false): Promise<string> {
const response = await Cluster.requestLoginConfirmation(skipConfirmation);
if (response !== 'Yes') return null;
const clusterURL = await Cluster.getUrl();
if (!clusterURL) return null;
const loginActions = [
{
label: 'Credentials',
description: 'Log in to the given server using credentials'
},
{
label: 'Token',
description: 'Log in to the given server using bearer token'
}
];
const loginActionSelected = await window.showQuickPick(loginActions, {placeHolder: 'Select a way to log in to the cluster.', ignoreFocusOut: true});
if (!loginActionSelected) return null;
let result:any = loginActionSelected.label === 'Credentials' ? await Cluster.credentialsLogin(true, clusterURL) : await Cluster.tokenLogin(clusterURL, true);
if (result) {
const versions = await Cluster.getVersions();
if (versions) {
result = new String(result);
// get cluster information using 'oc version'
result.properties = versions;
}
}
return result;
}
private static async requestLoginConfirmation(skipConfirmation = false): Promise<string> {
let response = 'Yes';
if (!skipConfirmation && !await Cluster.odo.requireLogin()) {
const cluster = new KubeConfigUtils().getCurrentCluster();
response = await window.showInformationMessage(`You are already logged into ${cluster.server} cluster. Do you want to login to a different cluster?`, 'Yes', 'No');
}
return response;
}
private static async save(username: string, password: string, checkpassword: string, result: CliExitData): Promise<CliExitData> {
if (password === checkpassword) return result;
const response = await window.showInformationMessage('Do you want to save username and password?', 'Yes', 'No');
if (response === 'Yes') {
await TokenStore.setUserName(username);
await TokenStore.setItem('login', username, password);
}
return result;
}
@vsCommand('openshift.explorer.login.credentialsLogin')
static async credentialsLogin(skipConfirmation = false, userClusterUrl?: string, userName?: string, userPassword?: string): Promise<string> {
let password: string;
const response = await Cluster.requestLoginConfirmation(skipConfirmation);
if (response !== 'Yes') return null;
let clusterURL = userClusterUrl;
if (!clusterURL) {
clusterURL = await Cluster.getUrl();
}
if (!clusterURL) return null;
let username = userName;
const getUserName = await TokenStore.getUserName();
if (!username) {
const k8sConfig = new KubeConfigUtils();
const users = k8sConfig.getClusterUsers(clusterURL);
const addUser: QuickPickItem = { label: '$(plus) Add new user...'};
const choice = await window.showQuickPick([addUser, ...users], {placeHolder: 'Select username for basic authentication to the API server', ignoreFocusOut: true});
if (!choice) return null;
if (choice.label === addUser.label) {
username = await window.showInputBox({
ignoreFocusOut: true,
prompt: 'Provide Username for basic authentication to the API server',
value: '',
validateInput: (value: string) => Cluster.emptyName('User name cannot be empty', value)
})
} else {
username = choice.label;
}
}
if (!username) return null;
if (getUserName) password = await TokenStore.getItem('login', username);
let passwd = userPassword;
if (!passwd) {
passwd = await window.showInputBox({
ignoreFocusOut: true,
password: true,
prompt: 'Provide Password for basic authentication to the API server',
value: password
});
}
if (!passwd) return null;
try {
const result = await Progress.execFunctionWithProgress(
`Login to the cluster: ${clusterURL}`,
() => Cluster.odo.execute(Command.odoLoginWithUsernamePassword(clusterURL, username, passwd)));
await Cluster.save(username, passwd, password, result);
return await Cluster.loginMessage(clusterURL, result);
} catch (error) {
if (error instanceof VsCommandError) {
throw new VsCommandError(`Failed to login to cluster '${clusterURL}' with '${Filters.filterPassword(error.message)}'!`, `Failed to login to cluster. ${error.telemetryMessage}`);
} else {
throw new VsCommandError(`Failed to login to cluster '${clusterURL}' with '${Filters.filterPassword(error.message)}'!`, 'Failed to login to cluster');
}
}
}
static async readFromClipboard(): Promise<string> {
let r = '';
try {
r = await env.clipboard.readText();
} catch (ignore) {
// ignore exceptions and return empty string
}
return r;
}
static async getUrlFromClipboard(): Promise<string | null> {
const clipboard = await Cluster.readFromClipboard();
if (Cluster.ocLoginCommandMatches(clipboard)) return Cluster.clusterURL(clipboard);
return null;
}
@vsCommand('openshift.explorer.login.tokenLogin')
static async tokenLogin(userClusterUrl: string, skipConfirmation = false, userToken?: string): Promise<string | null> {
let token: string;
const response = await Cluster.requestLoginConfirmation(skipConfirmation);
if (response !== 'Yes') return null;
let clusterURL = userClusterUrl;
let clusterUrlFromClipboard: string;
if (!clusterURL) {
clusterUrlFromClipboard = await Cluster.getUrlFromClipboard();
}
if (!clusterURL && clusterUrlFromClipboard || clusterURL?.trim() === clusterUrlFromClipboard) {
token = Cluster.getToken(await Cluster.readFromClipboard());
clusterURL = clusterUrlFromClipboard;
}
if (!clusterURL) {
clusterURL = await Cluster.getUrl();
}
let ocToken: string;
if (!userToken) {
ocToken = await window.showInputBox({
value: token,
prompt: 'Provide Bearer token for authentication to the API server',
ignoreFocusOut: true,
password: true
});
if (!ocToken) return null;
} else {
ocToken = userToken;
}
return Progress.execFunctionWithProgress(`Login to the cluster: ${clusterURL}`,
() => Cluster.odo.execute(Command.odoLoginWithToken(clusterURL, ocToken.trim()))
.then((result) => Cluster.loginMessage(clusterURL, result))
.catch((error) => Promise.reject(new VsCommandError(`Failed to login to cluster '${clusterURL}' with '${Filters.filterToken(error.message)}'!`, 'Failed to login to cluster')))
);
}
@vsCommand('openshift.explorer.login.clipboard')
static async loginUsingClipboardInfo(): Promise<string | null> {
const clipboard = await Cluster.readFromClipboard();
if(!Cluster.ocLoginCommandMatches(clipboard)) {
throw new VsCommandError('Cannot parse login command in clipboard.')
}
const url = Cluster.clusterURL(clipboard);
const token = Cluster.getToken(clipboard);
return Cluster.tokenLogin(url, true, token);
}
static async loginMessage(clusterURL: string, result: CliExitData): Promise<string | undefined> {
if (result.stderr === '') {
Cluster.explorer.refresh();
await commands.executeCommand('setContext', 'isLoggedIn', true);
return `Successfully logged in to '${clusterURL}'`;
}
throw new VsCommandError(result.stderr, 'Failed to login to cluster with output in stderr');
}
} | the_stack |
import {
ApplicationCommandHandler,
ApplicationCommandHandlerCallback,
AutocompleteHandler,
AutocompleteHandlerCallback,
InteractionsClient
} from './client.ts'
import type { Client } from '../client/mod.ts'
import { ApplicationCommandsModule } from './commandModule.ts'
import { ApplicationCommandInteraction } from '../structures/applicationCommand.ts'
import { GatewayIntents } from '../types/gateway.ts'
import { ApplicationCommandType } from '../types/applicationCommand.ts'
/** Type extension that adds the `_decoratedAppCmd` list. */
interface DecoratedAppExt {
_decoratedAppCmd?: ApplicationCommandHandler[]
_decoratedAutocomplete?: AutocompleteHandler[]
}
// Maybe a better name for this would be `ApplicationCommandBase` or `ApplicationCommandObject` or something else
type ApplicationCommandClient =
| Client
| InteractionsClient
| ApplicationCommandsModule
// See above
type ApplicationCommandClientExt = ApplicationCommandClient & DecoratedAppExt
type CommandValidationCondition = (
i: ApplicationCommandInteraction
) => boolean | Promise<boolean>
interface CommandValidation {
condition: CommandValidationCondition
action?: string | ApplicationCommandHandlerCallback
}
type ApplicationCommandDecorator = (
client: ApplicationCommandClientExt,
prop: string,
desc: TypedPropertyDescriptor<ApplicationCommandHandlerCallback>
) => void
type AutocompleteDecorator = (
client: ApplicationCommandClientExt,
prop: string,
desc: TypedPropertyDescriptor<AutocompleteHandlerCallback>
) => void
/**
* Wraps the command handler with a validation function.
* @param desc property descriptor
* @param validation validation function and action to show or call if validation fails
* @returns wrapped function
*/
function wrapConditionApplicationCommandHandler(
desc: TypedPropertyDescriptor<ApplicationCommandHandlerCallback>,
validation: CommandValidation
): ApplicationCommandHandlerCallback {
if (typeof desc.value !== 'function') {
throw new Error('The decorator requires a function')
}
const { condition, action } = validation
const original = desc.value
return async function (
this: ApplicationCommandClient,
i: ApplicationCommandInteraction
) {
if (!(await condition(i))) {
// condition not met
if (typeof action === 'string') {
i.reply(action)
} else if (typeof action === 'function') {
action(i)
}
return
} // condition met
return original.call(this, i)
}
}
/**
* Decorator to add a autocomplete interaction handler.
*
* @param command Command name of which options' to provide autocompletions for. Can be `*` (all).
* @param option Option name to handle autocompletions for. Can be `*` (all).
*/
export function autocomplete(
command: string,
option: string
): AutocompleteDecorator {
return function (
client: ApplicationCommandClientExt,
_prop: string,
desc: TypedPropertyDescriptor<AutocompleteHandlerCallback>
) {
if (client._decoratedAutocomplete === undefined)
client._decoratedAutocomplete = []
if (typeof desc.value !== 'function') {
throw new Error('@autocomplete decorator requires a function')
} else
client._decoratedAutocomplete.push({
cmd: command,
option,
handler: desc.value
})
}
}
/** Decorator to create a Slash Command handler */
export function slash(
name?: string,
guild?: string
): ApplicationCommandDecorator {
return function (
client: ApplicationCommandClientExt,
prop: string,
desc: TypedPropertyDescriptor<ApplicationCommandHandlerCallback>
) {
if (client._decoratedAppCmd === undefined) client._decoratedAppCmd = []
if (typeof desc.value !== 'function') {
throw new Error('@slash decorator requires a function')
} else
client._decoratedAppCmd.push({
name: name ?? prop,
guild,
handler: desc.value
})
}
}
/** Decorator to create a Sub-Slash Command handler */
export function subslash(
parent: string,
name?: string,
guild?: string
): ApplicationCommandDecorator {
return function (
client: ApplicationCommandClientExt,
prop: string,
desc: TypedPropertyDescriptor<ApplicationCommandHandlerCallback>
) {
if (client._decoratedAppCmd === undefined) client._decoratedAppCmd = []
if (typeof desc.value !== 'function') {
throw new Error('@subslash decorator requires a function')
} else
client._decoratedAppCmd.push({
parent,
name: name ?? prop,
guild,
handler: desc.value
})
}
}
/** Decorator to create a Grouped Slash Command handler */
export function groupslash(
parent: string,
group: string,
name?: string,
guild?: string
): ApplicationCommandDecorator {
return function (
client: ApplicationCommandClientExt,
prop: string,
desc: TypedPropertyDescriptor<ApplicationCommandHandlerCallback>
) {
if (client._decoratedAppCmd === undefined) client._decoratedAppCmd = []
if (typeof desc.value !== 'function') {
throw new Error('@groupslash decorator requires a function')
} else
client._decoratedAppCmd.push({
group,
parent,
name: name ?? prop,
guild,
handler: desc.value
})
}
}
/** Decorator to create a Message Context Menu Command handler */
export function messageContextMenu(name?: string): ApplicationCommandDecorator {
return function (
client: ApplicationCommandClientExt,
prop: string,
desc: TypedPropertyDescriptor<ApplicationCommandHandlerCallback>
) {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
if (client._decoratedAppCmd === undefined) client._decoratedAppCmd = []
if (typeof desc.value !== 'function') {
throw new Error('@messageContextMenu decorator requires a function')
} else
client._decoratedAppCmd.push({
name: name ?? prop,
type: ApplicationCommandType.MESSAGE,
handler: desc.value
})
}
}
/** Decorator to create a User Context Menu Command handler */
export function userContextMenu(name?: string): ApplicationCommandDecorator {
return function (
client: ApplicationCommandClientExt,
prop: string,
desc: TypedPropertyDescriptor<ApplicationCommandHandlerCallback>
) {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
if (client._decoratedAppCmd === undefined) client._decoratedAppCmd = []
if (typeof desc.value !== 'function') {
throw new Error('@userContextMenu decorator requires a function')
} else
client._decoratedAppCmd.push({
name: name ?? prop,
type: ApplicationCommandType.USER,
handler: desc.value
})
}
}
/**
* The command can only be called from a guild.
* @param action message or function called when the condition is not met
* @returns wrapped function
*/
export function isInGuild(message: string): ApplicationCommandDecorator
export function isInGuild(
callback: ApplicationCommandHandlerCallback
): ApplicationCommandDecorator
export function isInGuild(
action: string | ApplicationCommandHandlerCallback
): ApplicationCommandDecorator {
return function (
_client: ApplicationCommandClient,
_prop: string,
desc: TypedPropertyDescriptor<ApplicationCommandHandlerCallback>
) {
const validation: CommandValidation = {
condition: (i: ApplicationCommandInteraction) => {
return Boolean(i.guild)
},
action
}
desc.value = wrapConditionApplicationCommandHandler(desc, validation)
}
}
/**
* The command can only be called if the bot is currently in a voice channel.
* `GatewayIntents.GUILD_VOICE_STATES` needs to be set.
* @param action message or function called when the condition is not met
* @returns wrapped function
*/
export function isBotInVoiceChannel(
message: string
): ApplicationCommandDecorator
export function isBotInVoiceChannel(
callback: ApplicationCommandHandlerCallback
): ApplicationCommandDecorator
export function isBotInVoiceChannel(
action: string | ApplicationCommandHandlerCallback
): ApplicationCommandDecorator {
return function (
_client: ApplicationCommandClient,
_prop: string,
desc: TypedPropertyDescriptor<ApplicationCommandHandlerCallback>
) {
const validation: CommandValidation = {
condition: async (i: ApplicationCommandInteraction) => {
// eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
if (!i.client.intents?.includes(GatewayIntents.GUILD_VOICE_STATES)) {
const err =
'@isBotInVoiceChannel: GatewayIntents.GUILD_VOICE_STATES needs to be set.'
console.error(err)
throw new Error(err)
}
return Boolean(await i.guild?.voiceStates.get(i.client.user!.id))
},
action
}
desc.value = wrapConditionApplicationCommandHandler(desc, validation)
}
}
/**
* The command can only be called if the user is currently in a voice channel.
* `GatewayIntents.GUILD_VOICE_STATES` needs to be set.
* @param action message or function called when the condition is not met
* @returns wrapped function
*/
export function isUserInVoiceChannel(
message: string
): ApplicationCommandDecorator
export function isUserInVoiceChannel(
callback: ApplicationCommandHandlerCallback
): ApplicationCommandDecorator
export function isUserInVoiceChannel(
action: string | ApplicationCommandHandlerCallback
): ApplicationCommandDecorator {
return function (
_client: ApplicationCommandClient,
_prop: string,
desc: TypedPropertyDescriptor<ApplicationCommandHandlerCallback>
) {
const validation: CommandValidation = {
condition: async (i: ApplicationCommandInteraction): Promise<boolean> => {
// eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
if (!i.client.intents?.includes(GatewayIntents.GUILD_VOICE_STATES)) {
const err =
'@isUserInVoiceChannel: GatewayIntents.GUILD_VOICE_STATES needs to be set.'
console.error(err)
throw new Error(err)
}
return Boolean(await i.guild?.voiceStates.get(i.user.id))
},
action
}
desc.value = wrapConditionApplicationCommandHandler(desc, validation)
}
}
/**
* Cusomizable command validation.
* @param condition condition that need to succede for the command to be called
* @param action message or function called when the condition is not met
* @returns wrapped function
*/
export function customValidation(
condition: CommandValidationCondition,
message: string
): ApplicationCommandDecorator
export function customValidation(
condition: CommandValidationCondition,
callback: ApplicationCommandHandlerCallback
): ApplicationCommandDecorator
export function customValidation(
condition: CommandValidationCondition,
action: string | ApplicationCommandHandlerCallback
): ApplicationCommandDecorator {
return function (
_client: ApplicationCommandClient,
_prop: string,
desc: TypedPropertyDescriptor<ApplicationCommandHandlerCallback>
) {
desc.value = wrapConditionApplicationCommandHandler(desc, {
condition,
action
})
}
} | the_stack |
import { IConstruct } from 'constructs';
import { DefaultTokenResolver, IPostProcessor, IResolvable, IResolveContext, ITokenResolver, ResolveChangeContextOptions, StringConcat } from '../resolvable';
import { TokenizedStringFragments } from '../string-fragments';
import { containsListTokenElement, TokenString, unresolved } from './encoding';
import { TokenMap } from './token-map';
// This file should not be exported to consumers, resolving should happen through Construct.resolve()
const tokenMap = TokenMap.instance();
/**
* Resolved complex values will have a type hint applied.
*
* The type hint will be based on the type of the input value that was resolved.
*
* If the value was encoded, the type hint will be the type of the encoded value. In case
* of a plain `IResolvable`, a type hint of 'string' will be assumed.
*/
const RESOLUTION_TYPEHINT_SYM = Symbol.for('@aws-cdk/core.resolvedTypeHint');
/**
* Prefix used for intrinsic keys
*
* If a key with this prefix is found in an object, the actual value of the
* key doesn't matter. The value of this key will be an `[ actualKey, actualValue ]`
* tuple, and the `actualKey` will be a value which otherwise couldn't be represented
* in the types of `string | number | symbol`, which are the only possible JavaScript
* object keys.
*/
export const INTRINSIC_KEY_PREFIX = '$IntrinsicKey$';
/**
* Type hints for resolved values
*/
export enum ResolutionTypeHint {
STRING = 'string',
NUMBER = 'number',
LIST = 'list',
}
/**
* Options to the resolve() operation
*
* NOT the same as the ResolveContext; ResolveContext is exposed to Token
* implementors and resolution hooks, whereas this struct is just to bundle
* a number of things that would otherwise be arguments to resolve() in a
* readable way.
*/
export interface IResolveOptions {
scope: IConstruct;
preparing: boolean;
resolver: ITokenResolver;
prefix?: string[];
/**
* Whether or not to allow intrinsics in keys of an object
*
* Because keys of an object must be strings, a (resolved) intrinsic, which
* is an object, cannot be stored in that position. By default, we reject these
* intrinsics if we encounter them.
*
* If this is set to `true`, in order to store the complex value in a map,
* keys that happen to evaluate to intrinsics will be added with a unique key
* identified by an uncomming prefix, mapped to a tuple that represents the
* actual key/value-pair. The map will look like this:
*
* {
* '$IntrinsicKey$0': [ { Ref: ... }, 'value1' ],
* '$IntrinsicKey$1': [ { Ref: ... }, 'value2' ],
* 'regularKey': 'value3',
* ...
* }
*
* Callers should only set this option to `true` if they are prepared to deal with
* the object in this weird shape, and massage it back into a correct object afterwards.
*
* (A regular but uncommon string was chosen over something like symbols or
* other ways of tagging the extra values in order to simplify the implementation which
* maintains the desired behavior `resolve(resolve(x)) == resolve(x)`).
*
* @default false
*/
allowIntrinsicKeys?: boolean;
/**
* Whether to remove undefined elements from arrays and objects when resolving.
*
* @default true
*/
removeEmpty?: boolean;
}
/**
* Resolves an object by evaluating all tokens and removing any undefined or empty objects or arrays.
* Values can only be primitives, arrays or tokens. Other objects (i.e. with methods) will be rejected.
*
* @param obj The object to resolve.
* @param prefix Prefix key path components for diagnostics.
*/
export function resolve(obj: any, options: IResolveOptions): any {
const prefix = options.prefix || [];
const pathName = '/' + prefix.join('/');
/**
* Make a new resolution context
*/
function makeContext(appendPath?: string): [IResolveContext, IPostProcessor] {
const newPrefix = appendPath !== undefined ? prefix.concat([appendPath]) : options.prefix;
let postProcessor: IPostProcessor | undefined;
const context: IResolveContext = {
preparing: options.preparing,
scope: options.scope as IConstruct,
documentPath: newPrefix ?? [],
registerPostProcessor(pp) { postProcessor = pp; },
resolve(x: any, changeOptions?: ResolveChangeContextOptions) { return resolve(x, { ...options, ...changeOptions, prefix: newPrefix }); },
};
return [context, { postProcess(x) { return postProcessor ? postProcessor.postProcess(x, context) : x; } }];
}
// protect against cyclic references by limiting depth.
if (prefix.length > 200) {
throw new Error('Unable to resolve object tree with circular reference. Path: ' + pathName);
}
// whether to leave the empty elements when resolving - false by default
const leaveEmpty = options.removeEmpty === false;
//
// undefined
//
if (typeof(obj) === 'undefined') {
return undefined;
}
//
// null
//
if (obj === null) {
return null;
}
//
// functions - not supported (only tokens are supported)
//
if (typeof(obj) === 'function') {
throw new Error(`Trying to resolve a non-data object. Only token are supported for lazy evaluation. Path: ${pathName}. Object: ${obj}`);
}
//
// string - potentially replace all stringified Tokens
//
if (typeof(obj) === 'string') {
// If this is a "list element" Token, it should never occur by itself in string context
if (TokenString.forListToken(obj).test()) {
throw new Error('Found an encoded list token string in a scalar string context. Use \'Fn.select(0, list)\' (not \'list[0]\') to extract elements from token lists.');
}
// Otherwise look for a stringified Token in this object
const str = TokenString.forString(obj);
if (str.test()) {
const fragments = str.split(tokenMap.lookupToken.bind(tokenMap));
return tagResolvedValue(options.resolver.resolveString(fragments, makeContext()[0]), ResolutionTypeHint.STRING);
}
return obj;
}
//
// number - potentially decode Tokenized number
//
if (typeof(obj) === 'number') {
return tagResolvedValue(resolveNumberToken(obj, makeContext()[0]), ResolutionTypeHint.NUMBER);
}
//
// primitives - as-is
//
if (typeof(obj) !== 'object' || obj instanceof Date) {
return obj;
}
//
// arrays - resolve all values, remove undefined and remove empty arrays
//
if (Array.isArray(obj)) {
if (containsListTokenElement(obj)) {
return tagResolvedValue(options.resolver.resolveList(obj, makeContext()[0]), ResolutionTypeHint.LIST);
}
const arr = obj
.map((x, i) => makeContext(`${i}`)[0].resolve(x))
.filter(x => leaveEmpty || typeof(x) !== 'undefined');
return arr;
}
//
// tokens - invoke 'resolve' and continue to resolve recursively
//
if (unresolved(obj)) {
const [context, postProcessor] = makeContext();
const ret = tagResolvedValue(options.resolver.resolveToken(obj, context, postProcessor), ResolutionTypeHint.STRING);
return ret;
}
//
// objects - deep-resolve all values
//
// Must not be a Construct at this point, otherwise you probably made a typo
// mistake somewhere and resolve will get into an infinite loop recursing into
// child.parent <---> parent.children
if (isConstruct(obj)) {
throw new Error('Trying to resolve() a Construct at ' + pathName);
}
const result: any = { };
let intrinsicKeyCtr = 0;
for (const key of Object.keys(obj)) {
const value = makeContext(String(key))[0].resolve(obj[key]);
// skip undefined
if (typeof(value) === 'undefined') {
if (leaveEmpty) {
result[key] = undefined;
}
continue;
}
// Simple case -- not an unresolved key
if (!unresolved(key)) {
result[key] = value;
continue;
}
const resolvedKey = makeContext()[0].resolve(key);
if (typeof(resolvedKey) === 'string') {
result[resolvedKey] = value;
} else {
if (!options.allowIntrinsicKeys) {
// eslint-disable-next-line max-len
throw new Error(`"${String(key)}" is used as the key in a map so must resolve to a string, but it resolves to: ${JSON.stringify(resolvedKey)}. Consider using "CfnJson" to delay resolution to deployment-time`);
}
// Can't represent this object in a JavaScript key position, but we can store it
// in value position. Use a unique symbol as the key.
result[`${INTRINSIC_KEY_PREFIX}${intrinsicKeyCtr++}`] = [resolvedKey, value];
}
}
// Because we may be called to recurse on already resolved values (that already have type hints applied)
// and we just copied those values into a fresh object, be sure to retain any type hints.
const previousTypeHint = resolvedTypeHint(obj);
return previousTypeHint ? tagResolvedValue(result, previousTypeHint) : result;
}
/**
* Find all Tokens that are used in the given structure
*/
export function findTokens(scope: IConstruct, fn: () => any): IResolvable[] {
const resolver = new RememberingTokenResolver(new StringConcat());
resolve(fn(), { scope, prefix: [], resolver, preparing: true });
return resolver.tokens;
}
/**
* Remember all Tokens encountered while resolving
*/
export class RememberingTokenResolver extends DefaultTokenResolver {
private readonly tokensSeen = new Set<IResolvable>();
public resolveToken(t: IResolvable, context: IResolveContext, postProcessor: IPostProcessor) {
this.tokensSeen.add(t);
return super.resolveToken(t, context, postProcessor);
}
public resolveString(s: TokenizedStringFragments, context: IResolveContext) {
const ret = super.resolveString(s, context);
return ret;
}
public get tokens(): IResolvable[] {
return Array.from(this.tokensSeen);
}
}
/**
* Determine whether an object is a Construct
*
* Not in 'construct.ts' because that would lead to a dependency cycle via 'uniqueid.ts',
* and this is a best-effort protection against a common programming mistake anyway.
*/
function isConstruct(x: any): boolean {
return x._children !== undefined && x._metadata !== undefined;
}
function resolveNumberToken(x: number, context: IResolveContext): any {
const token = TokenMap.instance().lookupNumberToken(x);
if (token === undefined) { return x; }
return context.resolve(token);
}
/**
* Apply a type hint to a resolved value
*
* The type hint will only be applied to objects.
*
* These type hints are used for correct JSON-ification of intrinsic values.
*/
function tagResolvedValue(value: any, typeHint: ResolutionTypeHint): any {
if (typeof value !== 'object' || value == null) { return value; }
Object.defineProperty(value, RESOLUTION_TYPEHINT_SYM, {
value: typeHint,
configurable: true,
});
return value;
}
/**
* Return the type hint from the given value
*
* If the value is not a resolved value (i.e, the result of resolving a token),
* `undefined` will be returned.
*
* These type hints are used for correct JSON-ification of intrinsic values.
*/
export function resolvedTypeHint(value: any): ResolutionTypeHint | undefined {
if (typeof value !== 'object' || value == null) { return undefined; }
return value[RESOLUTION_TYPEHINT_SYM];
} | the_stack |
import {ProviderToken} from '../di/provider_token';
import {createElementRef, ElementRef as ViewEngine_ElementRef, unwrapElementRef} from '../linker/element_ref';
import {QueryList} from '../linker/query_list';
import {createTemplateRef, TemplateRef as ViewEngine_TemplateRef} from '../linker/template_ref';
import {createContainerRef, ViewContainerRef} from '../linker/view_container_ref';
import {assertDefined, assertIndexInRange, assertNumber, throwError} from '../util/assert';
import {stringify} from '../util/stringify';
import {assertFirstCreatePass, assertLContainer} from './assert';
import {getNodeInjectable, locateDirectiveOrProvider} from './di';
import {storeCleanupWithContext} from './instructions/shared';
import {CONTAINER_HEADER_OFFSET, LContainer, MOVED_VIEWS} from './interfaces/container';
import {unusedValueExportToPlacateAjd as unused1} from './interfaces/definition';
import {unusedValueExportToPlacateAjd as unused2} from './interfaces/injector';
import {TContainerNode, TElementContainerNode, TElementNode, TNode, TNodeType, unusedValueExportToPlacateAjd as unused3} from './interfaces/node';
import {LQueries, LQuery, QueryFlags, TQueries, TQuery, TQueryMetadata, unusedValueExportToPlacateAjd as unused4} from './interfaces/query';
import {DECLARATION_LCONTAINER, LView, PARENT, QUERIES, TVIEW, TView} from './interfaces/view';
import {assertTNodeType} from './node_assert';
import {getCurrentQueryIndex, getCurrentTNode, getLView, getTView, setCurrentQueryIndex} from './state';
import {isCreationMode} from './util/view_utils';
const unusedValueToPlacateAjd = unused1 + unused2 + unused3 + unused4;
class LQuery_<T> implements LQuery<T> {
matches: (T|null)[]|null = null;
constructor(public queryList: QueryList<T>) {}
clone(): LQuery<T> {
return new LQuery_(this.queryList);
}
setDirty(): void {
this.queryList.setDirty();
}
}
class LQueries_ implements LQueries {
constructor(public queries: LQuery<any>[] = []) {}
createEmbeddedView(tView: TView): LQueries|null {
const tQueries = tView.queries;
if (tQueries !== null) {
const noOfInheritedQueries =
tView.contentQueries !== null ? tView.contentQueries[0] : tQueries.length;
const viewLQueries: LQuery<any>[] = [];
// An embedded view has queries propagated from a declaration view at the beginning of the
// TQueries collection and up until a first content query declared in the embedded view. Only
// propagated LQueries are created at this point (LQuery corresponding to declared content
// queries will be instantiated from the content query instructions for each directive).
for (let i = 0; i < noOfInheritedQueries; i++) {
const tQuery = tQueries.getByIndex(i);
const parentLQuery = this.queries[tQuery.indexInDeclarationView];
viewLQueries.push(parentLQuery.clone());
}
return new LQueries_(viewLQueries);
}
return null;
}
insertView(tView: TView): void {
this.dirtyQueriesWithMatches(tView);
}
detachView(tView: TView): void {
this.dirtyQueriesWithMatches(tView);
}
private dirtyQueriesWithMatches(tView: TView) {
for (let i = 0; i < this.queries.length; i++) {
if (getTQuery(tView, i).matches !== null) {
this.queries[i].setDirty();
}
}
}
}
class TQueryMetadata_ implements TQueryMetadata {
constructor(
public predicate: ProviderToken<unknown>|string[], public flags: QueryFlags,
public read: any = null) {}
}
class TQueries_ implements TQueries {
constructor(private queries: TQuery[] = []) {}
elementStart(tView: TView, tNode: TNode): void {
ngDevMode &&
assertFirstCreatePass(
tView, 'Queries should collect results on the first template pass only');
for (let i = 0; i < this.queries.length; i++) {
this.queries[i].elementStart(tView, tNode);
}
}
elementEnd(tNode: TNode): void {
for (let i = 0; i < this.queries.length; i++) {
this.queries[i].elementEnd(tNode);
}
}
embeddedTView(tNode: TNode): TQueries|null {
let queriesForTemplateRef: TQuery[]|null = null;
for (let i = 0; i < this.length; i++) {
const childQueryIndex = queriesForTemplateRef !== null ? queriesForTemplateRef.length : 0;
const tqueryClone = this.getByIndex(i).embeddedTView(tNode, childQueryIndex);
if (tqueryClone) {
tqueryClone.indexInDeclarationView = i;
if (queriesForTemplateRef !== null) {
queriesForTemplateRef.push(tqueryClone);
} else {
queriesForTemplateRef = [tqueryClone];
}
}
}
return queriesForTemplateRef !== null ? new TQueries_(queriesForTemplateRef) : null;
}
template(tView: TView, tNode: TNode): void {
ngDevMode &&
assertFirstCreatePass(
tView, 'Queries should collect results on the first template pass only');
for (let i = 0; i < this.queries.length; i++) {
this.queries[i].template(tView, tNode);
}
}
getByIndex(index: number): TQuery {
ngDevMode && assertIndexInRange(this.queries, index);
return this.queries[index];
}
get length(): number {
return this.queries.length;
}
track(tquery: TQuery): void {
this.queries.push(tquery);
}
}
class TQuery_ implements TQuery {
matches: number[]|null = null;
indexInDeclarationView = -1;
crossesNgTemplate = false;
/**
* A node index on which a query was declared (-1 for view queries and ones inherited from the
* declaration template). We use this index (alongside with _appliesToNextNode flag) to know
* when to apply content queries to elements in a template.
*/
private _declarationNodeIndex: number;
/**
* A flag indicating if a given query still applies to nodes it is crossing. We use this flag
* (alongside with _declarationNodeIndex) to know when to stop applying content queries to
* elements in a template.
*/
private _appliesToNextNode = true;
constructor(public metadata: TQueryMetadata, nodeIndex: number = -1) {
this._declarationNodeIndex = nodeIndex;
}
elementStart(tView: TView, tNode: TNode): void {
if (this.isApplyingToNode(tNode)) {
this.matchTNode(tView, tNode);
}
}
elementEnd(tNode: TNode): void {
if (this._declarationNodeIndex === tNode.index) {
this._appliesToNextNode = false;
}
}
template(tView: TView, tNode: TNode): void {
this.elementStart(tView, tNode);
}
embeddedTView(tNode: TNode, childQueryIndex: number): TQuery|null {
if (this.isApplyingToNode(tNode)) {
this.crossesNgTemplate = true;
// A marker indicating a `<ng-template>` element (a placeholder for query results from
// embedded views created based on this `<ng-template>`).
this.addMatch(-tNode.index, childQueryIndex);
return new TQuery_(this.metadata);
}
return null;
}
private isApplyingToNode(tNode: TNode): boolean {
if (this._appliesToNextNode &&
(this.metadata.flags & QueryFlags.descendants) !== QueryFlags.descendants) {
const declarationNodeIdx = this._declarationNodeIndex;
let parent = tNode.parent;
// Determine if a given TNode is a "direct" child of a node on which a content query was
// declared (only direct children of query's host node can match with the descendants: false
// option). There are 3 main use-case / conditions to consider here:
// - <needs-target><i #target></i></needs-target>: here <i #target> parent node is a query
// host node;
// - <needs-target><ng-template [ngIf]="true"><i #target></i></ng-template></needs-target>:
// here <i #target> parent node is null;
// - <needs-target><ng-container><i #target></i></ng-container></needs-target>: here we need
// to go past `<ng-container>` to determine <i #target> parent node (but we shouldn't traverse
// up past the query's host node!).
while (parent !== null && (parent.type & TNodeType.ElementContainer) &&
parent.index !== declarationNodeIdx) {
parent = parent.parent;
}
return declarationNodeIdx === (parent !== null ? parent.index : -1);
}
return this._appliesToNextNode;
}
private matchTNode(tView: TView, tNode: TNode): void {
const predicate = this.metadata.predicate;
if (Array.isArray(predicate)) {
for (let i = 0; i < predicate.length; i++) {
const name = predicate[i];
this.matchTNodeWithReadOption(tView, tNode, getIdxOfMatchingSelector(tNode, name));
// Also try matching the name to a provider since strings can be used as DI tokens too.
this.matchTNodeWithReadOption(
tView, tNode, locateDirectiveOrProvider(tNode, tView, name, false, false));
}
} else {
if ((predicate as any) === ViewEngine_TemplateRef) {
if (tNode.type & TNodeType.Container) {
this.matchTNodeWithReadOption(tView, tNode, -1);
}
} else {
this.matchTNodeWithReadOption(
tView, tNode, locateDirectiveOrProvider(tNode, tView, predicate, false, false));
}
}
}
private matchTNodeWithReadOption(tView: TView, tNode: TNode, nodeMatchIdx: number|null): void {
if (nodeMatchIdx !== null) {
const read = this.metadata.read;
if (read !== null) {
if (read === ViewEngine_ElementRef || read === ViewContainerRef ||
read === ViewEngine_TemplateRef && (tNode.type & TNodeType.Container)) {
this.addMatch(tNode.index, -2);
} else {
const directiveOrProviderIdx =
locateDirectiveOrProvider(tNode, tView, read, false, false);
if (directiveOrProviderIdx !== null) {
this.addMatch(tNode.index, directiveOrProviderIdx);
}
}
} else {
this.addMatch(tNode.index, nodeMatchIdx);
}
}
}
private addMatch(tNodeIdx: number, matchIdx: number) {
if (this.matches === null) {
this.matches = [tNodeIdx, matchIdx];
} else {
this.matches.push(tNodeIdx, matchIdx);
}
}
}
/**
* Iterates over local names for a given node and returns directive index
* (or -1 if a local name points to an element).
*
* @param tNode static data of a node to check
* @param selector selector to match
* @returns directive index, -1 or null if a selector didn't match any of the local names
*/
function getIdxOfMatchingSelector(tNode: TNode, selector: string): number|null {
const localNames = tNode.localNames;
if (localNames !== null) {
for (let i = 0; i < localNames.length; i += 2) {
if (localNames[i] === selector) {
return localNames[i + 1] as number;
}
}
}
return null;
}
function createResultByTNodeType(tNode: TNode, currentView: LView): any {
if (tNode.type & (TNodeType.AnyRNode | TNodeType.ElementContainer)) {
return createElementRef(tNode, currentView);
} else if (tNode.type & TNodeType.Container) {
return createTemplateRef(tNode, currentView);
}
return null;
}
function createResultForNode(lView: LView, tNode: TNode, matchingIdx: number, read: any): any {
if (matchingIdx === -1) {
// if read token and / or strategy is not specified, detect it using appropriate tNode type
return createResultByTNodeType(tNode, lView);
} else if (matchingIdx === -2) {
// read a special token from a node injector
return createSpecialToken(lView, tNode, read);
} else {
// read a token
return getNodeInjectable(lView, lView[TVIEW], matchingIdx, tNode as TElementNode);
}
}
function createSpecialToken(lView: LView, tNode: TNode, read: any): any {
if (read === ViewEngine_ElementRef) {
return createElementRef(tNode, lView);
} else if (read === ViewEngine_TemplateRef) {
return createTemplateRef(tNode, lView);
} else if (read === ViewContainerRef) {
ngDevMode && assertTNodeType(tNode, TNodeType.AnyRNode | TNodeType.AnyContainer);
return createContainerRef(
tNode as TElementNode | TContainerNode | TElementContainerNode, lView);
} else {
ngDevMode &&
throwError(
`Special token to read should be one of ElementRef, TemplateRef or ViewContainerRef but got ${
stringify(read)}.`);
}
}
/**
* A helper function that creates query results for a given view. This function is meant to do the
* processing once and only once for a given view instance (a set of results for a given view
* doesn't change).
*/
function materializeViewResults<T>(
tView: TView, lView: LView, tQuery: TQuery, queryIndex: number): (T|null)[] {
const lQuery = lView[QUERIES]!.queries![queryIndex];
if (lQuery.matches === null) {
const tViewData = tView.data;
const tQueryMatches = tQuery.matches!;
const result: T|null[] = [];
for (let i = 0; i < tQueryMatches.length; i += 2) {
const matchedNodeIdx = tQueryMatches[i];
if (matchedNodeIdx < 0) {
// we at the <ng-template> marker which might have results in views created based on this
// <ng-template> - those results will be in separate views though, so here we just leave
// null as a placeholder
result.push(null);
} else {
ngDevMode && assertIndexInRange(tViewData, matchedNodeIdx);
const tNode = tViewData[matchedNodeIdx] as TNode;
result.push(createResultForNode(lView, tNode, tQueryMatches[i + 1], tQuery.metadata.read));
}
}
lQuery.matches = result;
}
return lQuery.matches;
}
/**
* A helper function that collects (already materialized) query results from a tree of views,
* starting with a provided LView.
*/
function collectQueryResults<T>(tView: TView, lView: LView, queryIndex: number, result: T[]): T[] {
const tQuery = tView.queries!.getByIndex(queryIndex);
const tQueryMatches = tQuery.matches;
if (tQueryMatches !== null) {
const lViewResults = materializeViewResults<T>(tView, lView, tQuery, queryIndex);
for (let i = 0; i < tQueryMatches.length; i += 2) {
const tNodeIdx = tQueryMatches[i];
if (tNodeIdx > 0) {
result.push(lViewResults[i / 2] as T);
} else {
const childQueryIndex = tQueryMatches[i + 1];
const declarationLContainer = lView[-tNodeIdx] as LContainer;
ngDevMode && assertLContainer(declarationLContainer);
// collect matches for views inserted in this container
for (let i = CONTAINER_HEADER_OFFSET; i < declarationLContainer.length; i++) {
const embeddedLView = declarationLContainer[i];
if (embeddedLView[DECLARATION_LCONTAINER] === embeddedLView[PARENT]) {
collectQueryResults(embeddedLView[TVIEW], embeddedLView, childQueryIndex, result);
}
}
// collect matches for views created from this declaration container and inserted into
// different containers
if (declarationLContainer[MOVED_VIEWS] !== null) {
const embeddedLViews = declarationLContainer[MOVED_VIEWS]!;
for (let i = 0; i < embeddedLViews.length; i++) {
const embeddedLView = embeddedLViews[i];
collectQueryResults(embeddedLView[TVIEW], embeddedLView, childQueryIndex, result);
}
}
}
}
}
return result;
}
/**
* Refreshes a query by combining matches from all active views and removing matches from deleted
* views.
*
* @returns `true` if a query got dirty during change detection or if this is a static query
* resolving in creation mode, `false` otherwise.
*
* @codeGenApi
*/
export function ɵɵqueryRefresh(queryList: QueryList<any>): boolean {
const lView = getLView();
const tView = getTView();
const queryIndex = getCurrentQueryIndex();
setCurrentQueryIndex(queryIndex + 1);
const tQuery = getTQuery(tView, queryIndex);
if (queryList.dirty &&
(isCreationMode(lView) ===
((tQuery.metadata.flags & QueryFlags.isStatic) === QueryFlags.isStatic))) {
if (tQuery.matches === null) {
queryList.reset([]);
} else {
const result = tQuery.crossesNgTemplate ?
collectQueryResults(tView, lView, queryIndex, []) :
materializeViewResults(tView, lView, tQuery, queryIndex);
queryList.reset(result, unwrapElementRef);
queryList.notifyOnChanges();
}
return true;
}
return false;
}
/**
* Creates new QueryList, stores the reference in LView and returns QueryList.
*
* @param predicate The type for which the query will search
* @param flags Flags associated with the query
* @param read What to save in the query
*
* @codeGenApi
*/
export function ɵɵviewQuery<T>(
predicate: ProviderToken<unknown>|string[], flags: QueryFlags, read?: any): void {
ngDevMode && assertNumber(flags, 'Expecting flags');
const tView = getTView();
if (tView.firstCreatePass) {
createTQuery(tView, new TQueryMetadata_(predicate, flags, read), -1);
if ((flags & QueryFlags.isStatic) === QueryFlags.isStatic) {
tView.staticViewQueries = true;
}
}
createLQuery<T>(tView, getLView(), flags);
}
/**
* Registers a QueryList, associated with a content query, for later refresh (part of a view
* refresh).
*
* @param directiveIndex Current directive index
* @param predicate The type for which the query will search
* @param flags Flags associated with the query
* @param read What to save in the query
* @returns QueryList<T>
*
* @codeGenApi
*/
export function ɵɵcontentQuery<T>(
directiveIndex: number, predicate: ProviderToken<unknown>|string[], flags: QueryFlags,
read?: any): void {
ngDevMode && assertNumber(flags, 'Expecting flags');
const tView = getTView();
if (tView.firstCreatePass) {
const tNode = getCurrentTNode()!;
createTQuery(tView, new TQueryMetadata_(predicate, flags, read), tNode.index);
saveContentQueryAndDirectiveIndex(tView, directiveIndex);
if ((flags & QueryFlags.isStatic) === QueryFlags.isStatic) {
tView.staticContentQueries = true;
}
}
createLQuery<T>(tView, getLView(), flags);
}
/**
* Loads a QueryList corresponding to the current view or content query.
*
* @codeGenApi
*/
export function ɵɵloadQuery<T>(): QueryList<T> {
return loadQueryInternal<T>(getLView(), getCurrentQueryIndex());
}
function loadQueryInternal<T>(lView: LView, queryIndex: number): QueryList<T> {
ngDevMode &&
assertDefined(lView[QUERIES], 'LQueries should be defined when trying to load a query');
ngDevMode && assertIndexInRange(lView[QUERIES]!.queries, queryIndex);
return lView[QUERIES]!.queries[queryIndex].queryList;
}
function createLQuery<T>(tView: TView, lView: LView, flags: QueryFlags) {
const queryList = new QueryList<T>(
(flags & QueryFlags.emitDistinctChangesOnly) === QueryFlags.emitDistinctChangesOnly);
storeCleanupWithContext(tView, lView, queryList, queryList.destroy);
if (lView[QUERIES] === null) lView[QUERIES] = new LQueries_();
lView[QUERIES]!.queries.push(new LQuery_(queryList));
}
function createTQuery(tView: TView, metadata: TQueryMetadata, nodeIndex: number): void {
if (tView.queries === null) tView.queries = new TQueries_();
tView.queries.track(new TQuery_(metadata, nodeIndex));
}
function saveContentQueryAndDirectiveIndex(tView: TView, directiveIndex: number) {
const tViewContentQueries = tView.contentQueries || (tView.contentQueries = []);
const lastSavedDirectiveIndex =
tViewContentQueries.length ? tViewContentQueries[tViewContentQueries.length - 1] : -1;
if (directiveIndex !== lastSavedDirectiveIndex) {
tViewContentQueries.push(tView.queries!.length - 1, directiveIndex);
}
}
function getTQuery(tView: TView, index: number): TQuery {
ngDevMode && assertDefined(tView.queries, 'TQueries must be defined to retrieve a TQuery');
return tView.queries!.getByIndex(index);
} | the_stack |
/////////////////////////////
/// IE Worker APIs
/////////////////////////////
interface Algorithm {
name: string;
}
interface CacheQueryOptions {
ignoreSearch?: boolean;
ignoreMethod?: boolean;
ignoreVary?: boolean;
cacheName?: string;
}
interface CloseEventInit extends EventInit {
wasClean?: boolean;
code?: number;
reason?: string;
}
interface EventInit {
scoped?: boolean;
bubbles?: boolean;
cancelable?: boolean;
}
interface GetNotificationOptions {
tag?: string;
}
interface IDBIndexParameters {
multiEntry?: boolean;
unique?: boolean;
}
interface IDBObjectStoreParameters {
autoIncrement?: boolean;
keyPath?: IDBKeyPath;
}
interface KeyAlgorithm {
name?: string;
}
interface MessageEventInit extends EventInit {
lastEventId?: string;
channel?: string;
data?: any;
origin?: string;
source?: any;
ports?: MessagePort[];
}
interface NotificationOptions {
dir?: string;
lang?: string;
body?: string;
tag?: string;
icon?: string;
}
interface PushSubscriptionOptionsInit {
userVisibleOnly?: boolean;
applicationServerKey?: any;
}
interface RequestInit {
method?: string;
headers?: any;
body?: any;
referrer?: string;
referrerPolicy?: string;
mode?: string;
credentials?: string;
cache?: string;
redirect?: string;
integrity?: string;
keepalive?: boolean;
window?: any;
}
interface ResponseInit {
status?: number;
statusText?: string;
headers?: any;
}
interface ClientQueryOptions {
includeUncontrolled?: boolean;
type?: string;
}
interface ExtendableEventInit extends EventInit {
}
interface ExtendableMessageEventInit extends ExtendableEventInit {
data?: any;
origin?: string;
lastEventId?: string;
source?: Client | ServiceWorker | MessagePort;
ports?: MessagePort[];
}
interface FetchEventInit extends ExtendableEventInit {
request?: Request;
clientId?: string;
isReload?: boolean;
}
interface NotificationEventInit extends ExtendableEventInit {
notification?: Notification;
action?: string;
}
interface PushEventInit extends ExtendableEventInit {
data?: any;
}
interface SyncEventInit extends ExtendableEventInit {
tag?: string;
lastChance?: boolean;
}
interface EventListener {
(evt: Event): void;
}
interface WebKitEntriesCallback {
(evt: Event): void;
}
interface WebKitErrorCallback {
(evt: Event): void;
}
interface WebKitFileCallback {
(evt: Event): void;
}
interface AudioBuffer {
readonly duration: number;
readonly length: number;
readonly numberOfChannels: number;
readonly sampleRate: number;
copyFromChannel(destination: Float32Array, channelNumber: number, startInChannel?: number): void;
copyToChannel(source: Float32Array, channelNumber: number, startInChannel?: number): void;
getChannelData(channel: number): Float32Array;
}
declare var AudioBuffer: {
prototype: AudioBuffer;
new(): AudioBuffer;
}
interface Blob {
readonly size: number;
readonly type: string;
msClose(): void;
msDetachStream(): any;
slice(start?: number, end?: number, contentType?: string): Blob;
}
declare var Blob: {
prototype: Blob;
new (blobParts?: any[], options?: BlobPropertyBag): Blob;
}
interface Cache {
add(request: RequestInfo): Promise<void>;
addAll(requests: RequestInfo[]): Promise<void>;
delete(request: RequestInfo, options?: CacheQueryOptions): Promise<boolean>;
keys(request?: RequestInfo, options?: CacheQueryOptions): any;
match(request: RequestInfo, options?: CacheQueryOptions): Promise<Response>;
matchAll(request?: RequestInfo, options?: CacheQueryOptions): any;
put(request: RequestInfo, response: Response): Promise<void>;
}
declare var Cache: {
prototype: Cache;
new(): Cache;
}
interface CacheStorage {
delete(cacheName: string): Promise<boolean>;
has(cacheName: string): Promise<boolean>;
keys(): any;
match(request: RequestInfo, options?: CacheQueryOptions): Promise<any>;
open(cacheName: string): Promise<Cache>;
}
declare var CacheStorage: {
prototype: CacheStorage;
new(): CacheStorage;
}
interface CloseEvent extends Event {
readonly code: number;
readonly reason: string;
readonly wasClean: boolean;
initCloseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, wasCleanArg: boolean, codeArg: number, reasonArg: string): void;
}
declare var CloseEvent: {
prototype: CloseEvent;
new(typeArg: string, eventInitDict?: CloseEventInit): CloseEvent;
}
interface Console {
assert(test?: boolean, message?: string, ...optionalParams: any[]): void;
clear(): void;
count(countTitle?: string): void;
debug(message?: any, ...optionalParams: any[]): void;
dir(value?: any, ...optionalParams: any[]): void;
dirxml(value: any): void;
error(message?: any, ...optionalParams: any[]): void;
exception(message?: string, ...optionalParams: any[]): void;
group(groupTitle?: string): void;
groupCollapsed(groupTitle?: string): void;
groupEnd(): void;
info(message?: any, ...optionalParams: any[]): void;
log(message?: any, ...optionalParams: any[]): void;
msIsIndependentlyComposed(element: any): boolean;
profile(reportName?: string): void;
profileEnd(): void;
select(element: any): void;
table(...data: any[]): void;
time(timerName?: string): void;
timeEnd(timerName?: string): void;
trace(message?: any, ...optionalParams: any[]): void;
warn(message?: any, ...optionalParams: any[]): void;
}
declare var Console: {
prototype: Console;
new(): Console;
}
interface Coordinates {
readonly accuracy: number;
readonly altitude: number | null;
readonly altitudeAccuracy: number | null;
readonly heading: number | null;
readonly latitude: number;
readonly longitude: number;
readonly speed: number | null;
}
declare var Coordinates: {
prototype: Coordinates;
new(): Coordinates;
}
interface CryptoKey {
readonly algorithm: KeyAlgorithm;
readonly extractable: boolean;
readonly type: string;
readonly usages: string[];
}
declare var CryptoKey: {
prototype: CryptoKey;
new(): CryptoKey;
}
interface DOMError {
readonly name: string;
toString(): string;
}
declare var DOMError: {
prototype: DOMError;
new(): DOMError;
}
interface DOMException {
readonly code: number;
readonly message: string;
readonly name: string;
toString(): string;
readonly ABORT_ERR: number;
readonly DATA_CLONE_ERR: number;
readonly DOMSTRING_SIZE_ERR: number;
readonly HIERARCHY_REQUEST_ERR: number;
readonly INDEX_SIZE_ERR: number;
readonly INUSE_ATTRIBUTE_ERR: number;
readonly INVALID_ACCESS_ERR: number;
readonly INVALID_CHARACTER_ERR: number;
readonly INVALID_MODIFICATION_ERR: number;
readonly INVALID_NODE_TYPE_ERR: number;
readonly INVALID_STATE_ERR: number;
readonly NAMESPACE_ERR: number;
readonly NETWORK_ERR: number;
readonly NOT_FOUND_ERR: number;
readonly NOT_SUPPORTED_ERR: number;
readonly NO_DATA_ALLOWED_ERR: number;
readonly NO_MODIFICATION_ALLOWED_ERR: number;
readonly PARSE_ERR: number;
readonly QUOTA_EXCEEDED_ERR: number;
readonly SECURITY_ERR: number;
readonly SERIALIZE_ERR: number;
readonly SYNTAX_ERR: number;
readonly TIMEOUT_ERR: number;
readonly TYPE_MISMATCH_ERR: number;
readonly URL_MISMATCH_ERR: number;
readonly VALIDATION_ERR: number;
readonly WRONG_DOCUMENT_ERR: number;
}
declare var DOMException: {
prototype: DOMException;
new(): DOMException;
readonly ABORT_ERR: number;
readonly DATA_CLONE_ERR: number;
readonly DOMSTRING_SIZE_ERR: number;
readonly HIERARCHY_REQUEST_ERR: number;
readonly INDEX_SIZE_ERR: number;
readonly INUSE_ATTRIBUTE_ERR: number;
readonly INVALID_ACCESS_ERR: number;
readonly INVALID_CHARACTER_ERR: number;
readonly INVALID_MODIFICATION_ERR: number;
readonly INVALID_NODE_TYPE_ERR: number;
readonly INVALID_STATE_ERR: number;
readonly NAMESPACE_ERR: number;
readonly NETWORK_ERR: number;
readonly NOT_FOUND_ERR: number;
readonly NOT_SUPPORTED_ERR: number;
readonly NO_DATA_ALLOWED_ERR: number;
readonly NO_MODIFICATION_ALLOWED_ERR: number;
readonly PARSE_ERR: number;
readonly QUOTA_EXCEEDED_ERR: number;
readonly SECURITY_ERR: number;
readonly SERIALIZE_ERR: number;
readonly SYNTAX_ERR: number;
readonly TIMEOUT_ERR: number;
readonly TYPE_MISMATCH_ERR: number;
readonly URL_MISMATCH_ERR: number;
readonly VALIDATION_ERR: number;
readonly WRONG_DOCUMENT_ERR: number;
}
interface DOMStringList {
readonly length: number;
contains(str: string): boolean;
item(index: number): string | null;
[index: number]: string;
}
declare var DOMStringList: {
prototype: DOMStringList;
new(): DOMStringList;
}
interface ErrorEvent extends Event {
readonly colno: number;
readonly error: any;
readonly filename: string;
readonly lineno: number;
readonly message: string;
initErrorEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, messageArg: string, filenameArg: string, linenoArg: number): void;
}
declare var ErrorEvent: {
prototype: ErrorEvent;
new(type: string, errorEventInitDict?: ErrorEventInit): ErrorEvent;
}
interface Event {
readonly bubbles: boolean;
cancelBubble: boolean;
readonly cancelable: boolean;
readonly currentTarget: EventTarget;
readonly defaultPrevented: boolean;
readonly eventPhase: number;
readonly isTrusted: boolean;
returnValue: boolean;
readonly srcElement: any;
readonly target: EventTarget;
readonly timeStamp: number;
readonly type: string;
readonly scoped: boolean;
initEvent(eventTypeArg: string, canBubbleArg: boolean, cancelableArg: boolean): void;
preventDefault(): void;
stopImmediatePropagation(): void;
stopPropagation(): void;
deepPath(): EventTarget[];
readonly AT_TARGET: number;
readonly BUBBLING_PHASE: number;
readonly CAPTURING_PHASE: number;
}
declare var Event: {
prototype: Event;
new(typeArg: string, eventInitDict?: EventInit): Event;
readonly AT_TARGET: number;
readonly BUBBLING_PHASE: number;
readonly CAPTURING_PHASE: number;
}
interface EventTarget {
addEventListener(type: string, listener?: EventListenerOrEventListenerObject, useCapture?: boolean): void;
dispatchEvent(evt: Event): boolean;
removeEventListener(type: string, listener?: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
declare var EventTarget: {
prototype: EventTarget;
new(): EventTarget;
}
interface File extends Blob {
readonly lastModifiedDate: any;
readonly name: string;
readonly webkitRelativePath: string;
}
declare var File: {
prototype: File;
new (parts: (ArrayBuffer | ArrayBufferView | Blob | string)[], filename: string, properties?: FilePropertyBag): File;
}
interface FileList {
readonly length: number;
item(index: number): File;
[index: number]: File;
}
declare var FileList: {
prototype: FileList;
new(): FileList;
}
interface FileReader extends EventTarget, MSBaseReader {
readonly error: DOMError;
readAsArrayBuffer(blob: Blob): void;
readAsBinaryString(blob: Blob): void;
readAsDataURL(blob: Blob): void;
readAsText(blob: Blob, encoding?: string): void;
addEventListener<K extends keyof MSBaseReaderEventMap>(type: K, listener: (this: FileReader, ev: MSBaseReaderEventMap[K]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
declare var FileReader: {
prototype: FileReader;
new(): FileReader;
}
interface Headers {
append(name: string, value: string): void;
delete(name: string): void;
forEach(callback: ForEachCallback): void;
get(name: string): string | null;
has(name: string): boolean;
set(name: string, value: string): void;
}
declare var Headers: {
prototype: Headers;
new(init?: any): Headers;
}
interface IDBCursor {
readonly direction: string;
key: IDBKeyRange | IDBValidKey;
readonly primaryKey: any;
source: IDBObjectStore | IDBIndex;
advance(count: number): void;
continue(key?: IDBKeyRange | IDBValidKey): void;
delete(): IDBRequest;
update(value: any): IDBRequest;
readonly NEXT: string;
readonly NEXT_NO_DUPLICATE: string;
readonly PREV: string;
readonly PREV_NO_DUPLICATE: string;
}
declare var IDBCursor: {
prototype: IDBCursor;
new(): IDBCursor;
readonly NEXT: string;
readonly NEXT_NO_DUPLICATE: string;
readonly PREV: string;
readonly PREV_NO_DUPLICATE: string;
}
interface IDBCursorWithValue extends IDBCursor {
readonly value: any;
}
declare var IDBCursorWithValue: {
prototype: IDBCursorWithValue;
new(): IDBCursorWithValue;
}
interface IDBDatabaseEventMap {
"abort": Event;
"error": Event;
}
interface IDBDatabase extends EventTarget {
readonly name: string;
readonly objectStoreNames: DOMStringList;
onabort: (this: IDBDatabase, ev: Event) => any;
onerror: (this: IDBDatabase, ev: Event) => any;
version: number;
onversionchange: (ev: IDBVersionChangeEvent) => any;
close(): void;
createObjectStore(name: string, optionalParameters?: IDBObjectStoreParameters): IDBObjectStore;
deleteObjectStore(name: string): void;
transaction(storeNames: string | string[], mode?: string): IDBTransaction;
addEventListener(type: "versionchange", listener: (ev: IDBVersionChangeEvent) => any, useCapture?: boolean): void;
addEventListener<K extends keyof IDBDatabaseEventMap>(type: K, listener: (this: IDBDatabase, ev: IDBDatabaseEventMap[K]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
declare var IDBDatabase: {
prototype: IDBDatabase;
new(): IDBDatabase;
}
interface IDBFactory {
cmp(first: any, second: any): number;
deleteDatabase(name: string): IDBOpenDBRequest;
open(name: string, version?: number): IDBOpenDBRequest;
}
declare var IDBFactory: {
prototype: IDBFactory;
new(): IDBFactory;
}
interface IDBIndex {
keyPath: string | string[];
readonly name: string;
readonly objectStore: IDBObjectStore;
readonly unique: boolean;
multiEntry: boolean;
count(key?: IDBKeyRange | IDBValidKey): IDBRequest;
get(key: IDBKeyRange | IDBValidKey): IDBRequest;
getKey(key: IDBKeyRange | IDBValidKey): IDBRequest;
openCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest;
openKeyCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest;
}
declare var IDBIndex: {
prototype: IDBIndex;
new(): IDBIndex;
}
interface IDBKeyRange {
readonly lower: any;
readonly lowerOpen: boolean;
readonly upper: any;
readonly upperOpen: boolean;
}
declare var IDBKeyRange: {
prototype: IDBKeyRange;
new(): IDBKeyRange;
bound(lower: any, upper: any, lowerOpen?: boolean, upperOpen?: boolean): IDBKeyRange;
lowerBound(lower: any, open?: boolean): IDBKeyRange;
only(value: any): IDBKeyRange;
upperBound(upper: any, open?: boolean): IDBKeyRange;
}
interface IDBObjectStore {
readonly indexNames: DOMStringList;
keyPath: string | string[];
readonly name: string;
readonly transaction: IDBTransaction;
autoIncrement: boolean;
add(value: any, key?: IDBKeyRange | IDBValidKey): IDBRequest;
clear(): IDBRequest;
count(key?: IDBKeyRange | IDBValidKey): IDBRequest;
createIndex(name: string, keyPath: string | string[], optionalParameters?: IDBIndexParameters): IDBIndex;
delete(key: IDBKeyRange | IDBValidKey): IDBRequest;
deleteIndex(indexName: string): void;
get(key: any): IDBRequest;
index(name: string): IDBIndex;
openCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest;
put(value: any, key?: IDBKeyRange | IDBValidKey): IDBRequest;
}
declare var IDBObjectStore: {
prototype: IDBObjectStore;
new(): IDBObjectStore;
}
interface IDBOpenDBRequestEventMap extends IDBRequestEventMap {
"blocked": Event;
"upgradeneeded": IDBVersionChangeEvent;
}
interface IDBOpenDBRequest extends IDBRequest {
onblocked: (this: IDBOpenDBRequest, ev: Event) => any;
onupgradeneeded: (this: IDBOpenDBRequest, ev: IDBVersionChangeEvent) => any;
addEventListener<K extends keyof IDBOpenDBRequestEventMap>(type: K, listener: (this: IDBOpenDBRequest, ev: IDBOpenDBRequestEventMap[K]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
declare var IDBOpenDBRequest: {
prototype: IDBOpenDBRequest;
new(): IDBOpenDBRequest;
}
interface IDBRequestEventMap {
"error": Event;
"success": Event;
}
interface IDBRequest extends EventTarget {
readonly error: DOMError;
onerror: (this: IDBRequest, ev: Event) => any;
onsuccess: (this: IDBRequest, ev: Event) => any;
readonly readyState: string;
readonly result: any;
source: IDBObjectStore | IDBIndex | IDBCursor;
readonly transaction: IDBTransaction;
addEventListener<K extends keyof IDBRequestEventMap>(type: K, listener: (this: IDBRequest, ev: IDBRequestEventMap[K]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
declare var IDBRequest: {
prototype: IDBRequest;
new(): IDBRequest;
}
interface IDBTransactionEventMap {
"abort": Event;
"complete": Event;
"error": Event;
}
interface IDBTransaction extends EventTarget {
readonly db: IDBDatabase;
readonly error: DOMError;
readonly mode: string;
onabort: (this: IDBTransaction, ev: Event) => any;
oncomplete: (this: IDBTransaction, ev: Event) => any;
onerror: (this: IDBTransaction, ev: Event) => any;
abort(): void;
objectStore(name: string): IDBObjectStore;
readonly READ_ONLY: string;
readonly READ_WRITE: string;
readonly VERSION_CHANGE: string;
addEventListener<K extends keyof IDBTransactionEventMap>(type: K, listener: (this: IDBTransaction, ev: IDBTransactionEventMap[K]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
declare var IDBTransaction: {
prototype: IDBTransaction;
new(): IDBTransaction;
readonly READ_ONLY: string;
readonly READ_WRITE: string;
readonly VERSION_CHANGE: string;
}
interface IDBVersionChangeEvent extends Event {
readonly newVersion: number | null;
readonly oldVersion: number;
}
declare var IDBVersionChangeEvent: {
prototype: IDBVersionChangeEvent;
new(): IDBVersionChangeEvent;
}
interface ImageData {
data: Uint8ClampedArray;
readonly height: number;
readonly width: number;
}
declare var ImageData: {
prototype: ImageData;
new(width: number, height: number): ImageData;
new(array: Uint8ClampedArray, width: number, height: number): ImageData;
}
interface MessageChannel {
readonly port1: MessagePort;
readonly port2: MessagePort;
}
declare var MessageChannel: {
prototype: MessageChannel;
new(): MessageChannel;
}
interface MessageEvent extends Event {
readonly data: any;
readonly origin: string;
readonly ports: any;
readonly source: any;
initMessageEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, dataArg: any, originArg: string, lastEventIdArg: string, sourceArg: any): void;
}
declare var MessageEvent: {
prototype: MessageEvent;
new(type: string, eventInitDict?: MessageEventInit): MessageEvent;
}
interface MessagePortEventMap {
"message": MessageEvent;
}
interface MessagePort extends EventTarget {
onmessage: (this: MessagePort, ev: MessageEvent) => any;
close(): void;
postMessage(message?: any, transfer?: any[]): void;
start(): void;
addEventListener<K extends keyof MessagePortEventMap>(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
declare var MessagePort: {
prototype: MessagePort;
new(): MessagePort;
}
interface NotificationEventMap {
"click": Event;
"close": Event;
"error": Event;
"show": Event;
}
interface Notification extends EventTarget {
readonly body: string;
readonly dir: string;
readonly icon: string;
readonly lang: string;
onclick: (this: Notification, ev: Event) => any;
onclose: (this: Notification, ev: Event) => any;
onerror: (this: Notification, ev: Event) => any;
onshow: (this: Notification, ev: Event) => any;
readonly permission: string;
readonly tag: string;
readonly title: string;
close(): void;
addEventListener<K extends keyof NotificationEventMap>(type: K, listener: (this: Notification, ev: NotificationEventMap[K]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
declare var Notification: {
prototype: Notification;
new(title: string, options?: NotificationOptions): Notification;
requestPermission(callback?: NotificationPermissionCallback): Promise<string>;
}
interface Performance {
readonly navigation: PerformanceNavigation;
readonly timing: PerformanceTiming;
clearMarks(markName?: string): void;
clearMeasures(measureName?: string): void;
clearResourceTimings(): void;
getEntries(): any;
getEntriesByName(name: string, entryType?: string): any;
getEntriesByType(entryType: string): any;
getMarks(markName?: string): any;
getMeasures(measureName?: string): any;
mark(markName: string): void;
measure(measureName: string, startMarkName?: string, endMarkName?: string): void;
now(): number;
setResourceTimingBufferSize(maxSize: number): void;
toJSON(): any;
}
declare var Performance: {
prototype: Performance;
new(): Performance;
}
interface PerformanceNavigation {
readonly redirectCount: number;
readonly type: number;
toJSON(): any;
readonly TYPE_BACK_FORWARD: number;
readonly TYPE_NAVIGATE: number;
readonly TYPE_RELOAD: number;
readonly TYPE_RESERVED: number;
}
declare var PerformanceNavigation: {
prototype: PerformanceNavigation;
new(): PerformanceNavigation;
readonly TYPE_BACK_FORWARD: number;
readonly TYPE_NAVIGATE: number;
readonly TYPE_RELOAD: number;
readonly TYPE_RESERVED: number;
}
interface PerformanceTiming {
readonly connectEnd: number;
readonly connectStart: number;
readonly domComplete: number;
readonly domContentLoadedEventEnd: number;
readonly domContentLoadedEventStart: number;
readonly domInteractive: number;
readonly domLoading: number;
readonly domainLookupEnd: number;
readonly domainLookupStart: number;
readonly fetchStart: number;
readonly loadEventEnd: number;
readonly loadEventStart: number;
readonly msFirstPaint: number;
readonly navigationStart: number;
readonly redirectEnd: number;
readonly redirectStart: number;
readonly requestStart: number;
readonly responseEnd: number;
readonly responseStart: number;
readonly unloadEventEnd: number;
readonly unloadEventStart: number;
readonly secureConnectionStart: number;
toJSON(): any;
}
declare var PerformanceTiming: {
prototype: PerformanceTiming;
new(): PerformanceTiming;
}
interface Position {
readonly coords: Coordinates;
readonly timestamp: number;
}
declare var Position: {
prototype: Position;
new(): Position;
}
interface PositionError {
readonly code: number;
readonly message: string;
toString(): string;
readonly PERMISSION_DENIED: number;
readonly POSITION_UNAVAILABLE: number;
readonly TIMEOUT: number;
}
declare var PositionError: {
prototype: PositionError;
new(): PositionError;
readonly PERMISSION_DENIED: number;
readonly POSITION_UNAVAILABLE: number;
readonly TIMEOUT: number;
}
interface ProgressEvent extends Event {
readonly lengthComputable: boolean;
readonly loaded: number;
readonly total: number;
initProgressEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, lengthComputableArg: boolean, loadedArg: number, totalArg: number): void;
}
declare var ProgressEvent: {
prototype: ProgressEvent;
new(type: string, eventInitDict?: ProgressEventInit): ProgressEvent;
}
interface PushManager {
getSubscription(): Promise<PushSubscription>;
permissionState(options?: PushSubscriptionOptionsInit): Promise<string>;
subscribe(options?: PushSubscriptionOptionsInit): Promise<PushSubscription>;
}
declare var PushManager: {
prototype: PushManager;
new(): PushManager;
}
interface PushSubscription {
readonly endpoint: USVString;
readonly options: PushSubscriptionOptions;
getKey(name: string): ArrayBuffer | null;
toJSON(): any;
unsubscribe(): Promise<boolean>;
}
declare var PushSubscription: {
prototype: PushSubscription;
new(): PushSubscription;
}
interface PushSubscriptionOptions {
readonly applicationServerKey: ArrayBuffer | null;
readonly userVisibleOnly: boolean;
}
declare var PushSubscriptionOptions: {
prototype: PushSubscriptionOptions;
new(): PushSubscriptionOptions;
}
interface ReadableStream {
readonly locked: boolean;
cancel(): Promise<void>;
getReader(): ReadableStreamReader;
}
declare var ReadableStream: {
prototype: ReadableStream;
new(): ReadableStream;
}
interface ReadableStreamReader {
cancel(): Promise<void>;
read(): Promise<any>;
releaseLock(): void;
}
declare var ReadableStreamReader: {
prototype: ReadableStreamReader;
new(): ReadableStreamReader;
}
interface Request extends Object, Body {
readonly cache: string;
readonly credentials: string;
readonly destination: string;
readonly headers: Headers;
readonly integrity: string;
readonly keepalive: boolean;
readonly method: string;
readonly mode: string;
readonly redirect: string;
readonly referrer: string;
readonly referrerPolicy: string;
readonly type: string;
readonly url: string;
clone(): Request;
}
declare var Request: {
prototype: Request;
new(input: Request | string, init?: RequestInit): Request;
}
interface Response extends Object, Body {
readonly body: ReadableStream | null;
readonly headers: Headers;
readonly ok: boolean;
readonly status: number;
readonly statusText: string;
readonly type: string;
readonly url: string;
clone(): Response;
}
declare var Response: {
prototype: Response;
new(body?: any, init?: ResponseInit): Response;
}
interface ServiceWorkerEventMap extends AbstractWorkerEventMap {
"statechange": Event;
}
interface ServiceWorker extends EventTarget, AbstractWorker {
onstatechange: (this: ServiceWorker, ev: Event) => any;
readonly scriptURL: USVString;
readonly state: string;
postMessage(message: any, transfer?: any[]): void;
addEventListener<K extends keyof ServiceWorkerEventMap>(type: K, listener: (this: ServiceWorker, ev: ServiceWorkerEventMap[K]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
declare var ServiceWorker: {
prototype: ServiceWorker;
new(): ServiceWorker;
}
interface ServiceWorkerRegistrationEventMap {
"updatefound": Event;
}
interface ServiceWorkerRegistration extends EventTarget {
readonly active: ServiceWorker | null;
readonly installing: ServiceWorker | null;
onupdatefound: (this: ServiceWorkerRegistration, ev: Event) => any;
readonly pushManager: PushManager;
readonly scope: USVString;
readonly sync: SyncManager;
readonly waiting: ServiceWorker | null;
getNotifications(filter?: GetNotificationOptions): any;
showNotification(title: string, options?: NotificationOptions): Promise<void>;
unregister(): Promise<boolean>;
update(): Promise<void>;
addEventListener<K extends keyof ServiceWorkerRegistrationEventMap>(type: K, listener: (this: ServiceWorkerRegistration, ev: ServiceWorkerRegistrationEventMap[K]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
declare var ServiceWorkerRegistration: {
prototype: ServiceWorkerRegistration;
new(): ServiceWorkerRegistration;
}
interface SyncManager {
getTags(): any;
register(tag: string): Promise<void>;
}
declare var SyncManager: {
prototype: SyncManager;
new(): SyncManager;
}
interface WebSocketEventMap {
"close": CloseEvent;
"error": Event;
"message": MessageEvent;
"open": Event;
}
interface WebSocket extends EventTarget {
binaryType: string;
readonly bufferedAmount: number;
readonly extensions: string;
onclose: (this: WebSocket, ev: CloseEvent) => any;
onerror: (this: WebSocket, ev: Event) => any;
onmessage: (this: WebSocket, ev: MessageEvent) => any;
onopen: (this: WebSocket, ev: Event) => any;
readonly protocol: string;
readonly readyState: number;
readonly url: string;
close(code?: number, reason?: string): void;
send(data: any): void;
readonly CLOSED: number;
readonly CLOSING: number;
readonly CONNECTING: number;
readonly OPEN: number;
addEventListener<K extends keyof WebSocketEventMap>(type: K, listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
declare var WebSocket: {
prototype: WebSocket;
new(url: string, protocols?: string | string[]): WebSocket;
readonly CLOSED: number;
readonly CLOSING: number;
readonly CONNECTING: number;
readonly OPEN: number;
}
interface WorkerEventMap extends AbstractWorkerEventMap {
"message": MessageEvent;
}
interface Worker extends EventTarget, AbstractWorker {
onmessage: (this: Worker, ev: MessageEvent) => any;
postMessage(message: any, transfer?: any[]): void;
terminate(): void;
addEventListener<K extends keyof WorkerEventMap>(type: K, listener: (this: Worker, ev: WorkerEventMap[K]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
declare var Worker: {
prototype: Worker;
new(stringUrl: string): Worker;
}
interface XMLHttpRequestEventMap extends XMLHttpRequestEventTargetEventMap {
"readystatechange": Event;
}
interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget {
onreadystatechange: (this: XMLHttpRequest, ev: Event) => any;
readonly readyState: number;
readonly response: any;
readonly responseText: string;
responseType: string;
readonly responseURL: string;
readonly responseXML: any;
readonly status: number;
readonly statusText: string;
timeout: number;
readonly upload: XMLHttpRequestUpload;
withCredentials: boolean;
msCaching?: string;
abort(): void;
getAllResponseHeaders(): string;
getResponseHeader(header: string): string | null;
msCachingEnabled(): boolean;
open(method: string, url: string, async?: boolean, user?: string, password?: string): void;
overrideMimeType(mime: string): void;
send(data?: string): void;
send(data?: any): void;
setRequestHeader(header: string, value: string): void;
readonly DONE: number;
readonly HEADERS_RECEIVED: number;
readonly LOADING: number;
readonly OPENED: number;
readonly UNSENT: number;
addEventListener<K extends keyof XMLHttpRequestEventMap>(type: K, listener: (this: XMLHttpRequest, ev: XMLHttpRequestEventMap[K]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
declare var XMLHttpRequest: {
prototype: XMLHttpRequest;
new(): XMLHttpRequest;
readonly DONE: number;
readonly HEADERS_RECEIVED: number;
readonly LOADING: number;
readonly OPENED: number;
readonly UNSENT: number;
}
interface XMLHttpRequestUpload extends EventTarget, XMLHttpRequestEventTarget {
addEventListener<K extends keyof XMLHttpRequestEventTargetEventMap>(type: K, listener: (this: XMLHttpRequestUpload, ev: XMLHttpRequestEventTargetEventMap[K]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
declare var XMLHttpRequestUpload: {
prototype: XMLHttpRequestUpload;
new(): XMLHttpRequestUpload;
}
interface AbstractWorkerEventMap {
"error": ErrorEvent;
}
interface AbstractWorker {
onerror: (this: AbstractWorker, ev: ErrorEvent) => any;
addEventListener<K extends keyof AbstractWorkerEventMap>(type: K, listener: (this: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
interface Body {
readonly bodyUsed: boolean;
arrayBuffer(): Promise<ArrayBuffer>;
blob(): Promise<Blob>;
json(): Promise<any>;
text(): Promise<string>;
}
interface GlobalFetch {
fetch(input: RequestInfo, init?: RequestInit): Promise<Response>;
}
interface MSBaseReaderEventMap {
"abort": Event;
"error": ErrorEvent;
"load": Event;
"loadend": ProgressEvent;
"loadstart": Event;
"progress": ProgressEvent;
}
interface MSBaseReader {
onabort: (this: MSBaseReader, ev: Event) => any;
onerror: (this: MSBaseReader, ev: ErrorEvent) => any;
onload: (this: MSBaseReader, ev: Event) => any;
onloadend: (this: MSBaseReader, ev: ProgressEvent) => any;
onloadstart: (this: MSBaseReader, ev: Event) => any;
onprogress: (this: MSBaseReader, ev: ProgressEvent) => any;
readonly readyState: number;
readonly result: any;
abort(): void;
readonly DONE: number;
readonly EMPTY: number;
readonly LOADING: number;
addEventListener<K extends keyof MSBaseReaderEventMap>(type: K, listener: (this: MSBaseReader, ev: MSBaseReaderEventMap[K]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
interface NavigatorBeacon {
sendBeacon(url: USVString, data?: BodyInit): boolean;
}
interface NavigatorConcurrentHardware {
readonly hardwareConcurrency: number;
}
interface NavigatorID {
readonly appCodeName: string;
readonly appName: string;
readonly appVersion: string;
readonly platform: string;
readonly product: string;
readonly productSub: string;
readonly userAgent: string;
readonly vendor: string;
readonly vendorSub: string;
}
interface NavigatorOnLine {
readonly onLine: boolean;
}
interface WindowBase64 {
atob(encodedString: string): string;
btoa(rawString: string): string;
}
interface WindowConsole {
readonly console: Console;
}
interface XMLHttpRequestEventTargetEventMap {
"abort": Event;
"error": ErrorEvent;
"load": Event;
"loadend": ProgressEvent;
"loadstart": Event;
"progress": ProgressEvent;
"timeout": ProgressEvent;
}
interface XMLHttpRequestEventTarget {
onabort: (this: XMLHttpRequestEventTarget, ev: Event) => any;
onerror: (this: XMLHttpRequestEventTarget, ev: ErrorEvent) => any;
onload: (this: XMLHttpRequestEventTarget, ev: Event) => any;
onloadend: (this: XMLHttpRequestEventTarget, ev: ProgressEvent) => any;
onloadstart: (this: XMLHttpRequestEventTarget, ev: Event) => any;
onprogress: (this: XMLHttpRequestEventTarget, ev: ProgressEvent) => any;
ontimeout: (this: XMLHttpRequestEventTarget, ev: ProgressEvent) => any;
addEventListener<K extends keyof XMLHttpRequestEventTargetEventMap>(type: K, listener: (this: XMLHttpRequestEventTarget, ev: XMLHttpRequestEventTargetEventMap[K]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
interface Client {
readonly frameType: string;
readonly id: string;
readonly url: USVString;
postMessage(message: any, transfer?: any[]): void;
}
declare var Client: {
prototype: Client;
new(): Client;
}
interface Clients {
claim(): Promise<void>;
get(id: string): Promise<any>;
matchAll(options?: ClientQueryOptions): any;
openWindow(url: USVString): Promise<WindowClient>;
}
declare var Clients: {
prototype: Clients;
new(): Clients;
}
interface DedicatedWorkerGlobalScopeEventMap extends WorkerGlobalScopeEventMap {
"message": MessageEvent;
}
interface DedicatedWorkerGlobalScope extends WorkerGlobalScope {
onmessage: (this: DedicatedWorkerGlobalScope, ev: MessageEvent) => any;
close(): void;
postMessage(message: any, transfer?: any[]): void;
addEventListener<K extends keyof DedicatedWorkerGlobalScopeEventMap>(type: K, listener: (this: DedicatedWorkerGlobalScope, ev: DedicatedWorkerGlobalScopeEventMap[K]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
declare var DedicatedWorkerGlobalScope: {
prototype: DedicatedWorkerGlobalScope;
new(): DedicatedWorkerGlobalScope;
}
interface ExtendableEvent extends Event {
waitUntil(f: Promise<any>): void;
}
declare var ExtendableEvent: {
prototype: ExtendableEvent;
new(type: string, eventInitDict?: ExtendableEventInit): ExtendableEvent;
}
interface ExtendableMessageEvent extends ExtendableEvent {
readonly data: any;
readonly lastEventId: string;
readonly origin: string;
readonly ports: MessagePort[] | null;
readonly source: Client | ServiceWorker | MessagePort | null;
}
declare var ExtendableMessageEvent: {
prototype: ExtendableMessageEvent;
new(type: string, eventInitDict?: ExtendableMessageEventInit): ExtendableMessageEvent;
}
interface FetchEvent extends ExtendableEvent {
readonly clientId: string | null;
readonly isReload: boolean;
readonly request: Request;
respondWith(r: Promise<Response>): void;
}
declare var FetchEvent: {
prototype: FetchEvent;
new(type: string, eventInitDict: FetchEventInit): FetchEvent;
}
interface FileReaderSync {
readAsArrayBuffer(blob: Blob): any;
readAsBinaryString(blob: Blob): void;
readAsDataURL(blob: Blob): string;
readAsText(blob: Blob, encoding?: string): string;
}
declare var FileReaderSync: {
prototype: FileReaderSync;
new(): FileReaderSync;
}
interface NotificationEvent extends ExtendableEvent {
readonly action: string;
readonly notification: Notification;
}
declare var NotificationEvent: {
prototype: NotificationEvent;
new(type: string, eventInitDict: NotificationEventInit): NotificationEvent;
}
interface PushEvent extends ExtendableEvent {
readonly data: PushMessageData | null;
}
declare var PushEvent: {
prototype: PushEvent;
new(type: string, eventInitDict?: PushEventInit): PushEvent;
}
interface PushMessageData {
arrayBuffer(): ArrayBuffer;
blob(): Blob;
json(): JSON;
text(): USVString;
}
declare var PushMessageData: {
prototype: PushMessageData;
new(): PushMessageData;
}
interface ServiceWorkerGlobalScopeEventMap extends WorkerGlobalScopeEventMap {
"activate": ExtendableEvent;
"fetch": FetchEvent;
"install": ExtendableEvent;
"message": ExtendableMessageEvent;
"notificationclick": NotificationEvent;
"notificationclose": NotificationEvent;
"push": PushEvent;
"pushsubscriptionchange": ExtendableEvent;
"sync": SyncEvent;
}
interface ServiceWorkerGlobalScope extends WorkerGlobalScope {
readonly clients: Clients;
onactivate: (this: ServiceWorkerGlobalScope, ev: ExtendableEvent) => any;
onfetch: (this: ServiceWorkerGlobalScope, ev: FetchEvent) => any;
oninstall: (this: ServiceWorkerGlobalScope, ev: ExtendableEvent) => any;
onmessage: (this: ServiceWorkerGlobalScope, ev: ExtendableMessageEvent) => any;
onnotificationclick: (this: ServiceWorkerGlobalScope, ev: NotificationEvent) => any;
onnotificationclose: (this: ServiceWorkerGlobalScope, ev: NotificationEvent) => any;
onpush: (this: ServiceWorkerGlobalScope, ev: PushEvent) => any;
onpushsubscriptionchange: (this: ServiceWorkerGlobalScope, ev: ExtendableEvent) => any;
onsync: (this: ServiceWorkerGlobalScope, ev: SyncEvent) => any;
readonly registration: ServiceWorkerRegistration;
skipWaiting(): Promise<void>;
addEventListener<K extends keyof ServiceWorkerGlobalScopeEventMap>(type: K, listener: (this: ServiceWorkerGlobalScope, ev: ServiceWorkerGlobalScopeEventMap[K]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
declare var ServiceWorkerGlobalScope: {
prototype: ServiceWorkerGlobalScope;
new(): ServiceWorkerGlobalScope;
}
interface SyncEvent extends ExtendableEvent {
readonly lastChance: boolean;
readonly tag: string;
}
declare var SyncEvent: {
prototype: SyncEvent;
new(type: string, init: SyncEventInit): SyncEvent;
}
interface WindowClient extends Client {
readonly focused: boolean;
readonly visibilityState: string;
focus(): Promise<WindowClient>;
navigate(url: USVString): Promise<WindowClient>;
}
declare var WindowClient: {
prototype: WindowClient;
new(): WindowClient;
}
interface WorkerGlobalScopeEventMap {
"error": ErrorEvent;
}
interface WorkerGlobalScope extends EventTarget, WorkerUtils, WindowConsole, GlobalFetch {
readonly caches: CacheStorage;
readonly isSecureContext: boolean;
readonly location: WorkerLocation;
onerror: (this: WorkerGlobalScope, ev: ErrorEvent) => any;
readonly performance: Performance;
readonly self: WorkerGlobalScope;
msWriteProfilerMark(profilerMarkName: string): void;
addEventListener<K extends keyof WorkerGlobalScopeEventMap>(type: K, listener: (this: WorkerGlobalScope, ev: WorkerGlobalScopeEventMap[K]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
declare var WorkerGlobalScope: {
prototype: WorkerGlobalScope;
new(): WorkerGlobalScope;
}
interface WorkerLocation {
readonly hash: string;
readonly host: string;
readonly hostname: string;
readonly href: string;
readonly origin: string;
readonly pathname: string;
readonly port: string;
readonly protocol: string;
readonly search: string;
toString(): string;
}
declare var WorkerLocation: {
prototype: WorkerLocation;
new(): WorkerLocation;
}
interface WorkerNavigator extends Object, NavigatorID, NavigatorOnLine, NavigatorBeacon, NavigatorConcurrentHardware {
readonly hardwareConcurrency: number;
}
declare var WorkerNavigator: {
prototype: WorkerNavigator;
new(): WorkerNavigator;
}
interface WorkerUtils extends Object, WindowBase64 {
readonly indexedDB: IDBFactory;
readonly msIndexedDB: IDBFactory;
readonly navigator: WorkerNavigator;
clearImmediate(handle: number): void;
clearInterval(handle: number): void;
clearTimeout(handle: number): void;
importScripts(...urls: string[]): void;
setImmediate(handler: (...args: any[]) => void): number;
setImmediate(handler: any, ...args: any[]): number;
setInterval(handler: (...args: any[]) => void, timeout: number): number;
setInterval(handler: any, timeout?: any, ...args: any[]): number;
setTimeout(handler: (...args: any[]) => void, timeout: number): number;
setTimeout(handler: any, timeout?: any, ...args: any[]): number;
}
interface ErrorEventInit {
message?: string;
filename?: string;
lineno?: number;
conlno?: number;
error?: any;
}
interface BlobPropertyBag {
type?: string;
endings?: string;
}
interface FilePropertyBag {
type?: string;
lastModified?: number;
}
interface EventListenerObject {
handleEvent(evt: Event): void;
}
interface ProgressEventInit extends EventInit {
lengthComputable?: boolean;
loaded?: number;
total?: number;
}
interface IDBArrayKey extends Array<IDBValidKey> {
}
interface RsaKeyGenParams extends Algorithm {
modulusLength: number;
publicExponent: Uint8Array;
}
interface RsaHashedKeyGenParams extends RsaKeyGenParams {
hash: AlgorithmIdentifier;
}
interface RsaKeyAlgorithm extends KeyAlgorithm {
modulusLength: number;
publicExponent: Uint8Array;
}
interface RsaHashedKeyAlgorithm extends RsaKeyAlgorithm {
hash: AlgorithmIdentifier;
}
interface RsaHashedImportParams {
hash: AlgorithmIdentifier;
}
interface RsaPssParams {
saltLength: number;
}
interface RsaOaepParams extends Algorithm {
label?: BufferSource;
}
interface EcdsaParams extends Algorithm {
hash: AlgorithmIdentifier;
}
interface EcKeyGenParams extends Algorithm {
namedCurve: string;
}
interface EcKeyAlgorithm extends KeyAlgorithm {
typedCurve: string;
}
interface EcKeyImportParams {
namedCurve: string;
}
interface EcdhKeyDeriveParams extends Algorithm {
public: CryptoKey;
}
interface AesCtrParams extends Algorithm {
counter: BufferSource;
length: number;
}
interface AesKeyAlgorithm extends KeyAlgorithm {
length: number;
}
interface AesKeyGenParams extends Algorithm {
length: number;
}
interface AesDerivedKeyParams extends Algorithm {
length: number;
}
interface AesCbcParams extends Algorithm {
iv: BufferSource;
}
interface AesCmacParams extends Algorithm {
length: number;
}
interface AesGcmParams extends Algorithm {
iv: BufferSource;
additionalData?: BufferSource;
tagLength?: number;
}
interface AesCfbParams extends Algorithm {
iv: BufferSource;
}
interface HmacImportParams extends Algorithm {
hash?: AlgorithmIdentifier;
length?: number;
}
interface HmacKeyAlgorithm extends KeyAlgorithm {
hash: AlgorithmIdentifier;
length: number;
}
interface HmacKeyGenParams extends Algorithm {
hash: AlgorithmIdentifier;
length?: number;
}
interface DhKeyGenParams extends Algorithm {
prime: Uint8Array;
generator: Uint8Array;
}
interface DhKeyAlgorithm extends KeyAlgorithm {
prime: Uint8Array;
generator: Uint8Array;
}
interface DhKeyDeriveParams extends Algorithm {
public: CryptoKey;
}
interface DhImportKeyParams extends Algorithm {
prime: Uint8Array;
generator: Uint8Array;
}
interface ConcatParams extends Algorithm {
hash?: AlgorithmIdentifier;
algorithmId: Uint8Array;
partyUInfo: Uint8Array;
partyVInfo: Uint8Array;
publicInfo?: Uint8Array;
privateInfo?: Uint8Array;
}
interface HkdfCtrParams extends Algorithm {
hash: AlgorithmIdentifier;
label: BufferSource;
context: BufferSource;
}
interface Pbkdf2Params extends Algorithm {
salt: BufferSource;
iterations: number;
hash: AlgorithmIdentifier;
}
interface RsaOtherPrimesInfo {
r: string;
d: string;
t: string;
}
interface JsonWebKey {
kty: string;
use?: string;
key_ops?: string[];
alg?: string;
kid?: string;
x5u?: string;
x5c?: string;
x5t?: string;
ext?: boolean;
crv?: string;
x?: string;
y?: string;
d?: string;
n?: string;
e?: string;
p?: string;
q?: string;
dp?: string;
dq?: string;
qi?: string;
oth?: RsaOtherPrimesInfo[];
k?: string;
}
declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject;
interface ErrorEventHandler {
(message: string, filename?: string, lineno?: number, colno?: number, error?:Error): void;
}
interface PositionCallback {
(position: Position): void;
}
interface PositionErrorCallback {
(error: PositionError): void;
}
interface DecodeSuccessCallback {
(decodedData: AudioBuffer): void;
}
interface DecodeErrorCallback {
(error: DOMException): void;
}
interface FunctionStringCallback {
(data: string): void;
}
interface ForEachCallback {
(keyId: any, status: string): void;
}
interface NotificationPermissionCallback {
(permission: string): void;
}
declare var onmessage: (this: DedicatedWorkerGlobalScope, ev: MessageEvent) => any;
declare function close(): void;
declare function postMessage(message: any, transfer?: any[]): void;
declare var caches: CacheStorage;
declare var isSecureContext: boolean;
declare var location: WorkerLocation;
declare var onerror: (this: DedicatedWorkerGlobalScope, ev: ErrorEvent) => any;
declare var performance: Performance;
declare var self: WorkerGlobalScope;
declare function msWriteProfilerMark(profilerMarkName: string): void;
declare function dispatchEvent(evt: Event): boolean;
declare function removeEventListener(type: string, listener?: EventListenerOrEventListenerObject, useCapture?: boolean): void;
declare var indexedDB: IDBFactory;
declare var msIndexedDB: IDBFactory;
declare var navigator: WorkerNavigator;
declare function clearImmediate(handle: number): void;
declare function clearInterval(handle: number): void;
declare function clearTimeout(handle: number): void;
declare function importScripts(...urls: string[]): void;
declare function setImmediate(handler: (...args: any[]) => void): number;
declare function setImmediate(handler: any, ...args: any[]): number;
declare function setInterval(handler: (...args: any[]) => void, timeout: number): number;
declare function setInterval(handler: any, timeout?: any, ...args: any[]): number;
declare function setTimeout(handler: (...args: any[]) => void, timeout: number): number;
declare function setTimeout(handler: any, timeout?: any, ...args: any[]): number;
declare function atob(encodedString: string): string;
declare function btoa(rawString: string): string;
declare var console: Console;
declare function fetch(input: RequestInfo, init?: RequestInit): Promise<Response>;
declare function dispatchEvent(evt: Event): boolean;
declare function removeEventListener(type: string, listener?: EventListenerOrEventListenerObject, useCapture?: boolean): void;
declare function addEventListener<K extends keyof DedicatedWorkerGlobalScopeEventMap>(type: K, listener: (this: DedicatedWorkerGlobalScope, ev: DedicatedWorkerGlobalScopeEventMap[K]) => any, useCapture?: boolean): void;
declare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
type AlgorithmIdentifier = string | Algorithm;
type BodyInit = any;
type IDBKeyPath = string;
type RequestInfo = Request | string;
type USVString = string;
type IDBValidKey = number | string | Date | IDBArrayKey;
type BufferSource = ArrayBuffer | ArrayBufferView; | the_stack |
import { IGroup, IShape, IElement, Point } from '@antv/g-base';
import { deepMix, mix, each, isNil, isNumber, isArray } from '@antv/util';
import { ILabelConfig, ShapeOptions } from '../interface/shape';
import { EdgeConfig, EdgeData, IPoint, LabelStyle, ShapeStyle, Item, ModelConfig, UpdateType } from '../types';
import { getLabelPosition, getLoopCfgs } from '../util/graphic';
import { distance, getCircleCenterByPoints } from '../util/math';
import { getControlPoint, getSpline } from '../util/path';
import Global from '../global';
import Shape from './shape';
import { shapeBase, CLS_LABEL_BG_SUFFIX } from './shapeBase';
const CLS_SHAPE = 'edge-shape';
// start,end 倒置,center 不变
function revertAlign(labelPosition: string): string {
let textAlign = labelPosition;
if (labelPosition === 'start') {
textAlign = 'end';
} else if (labelPosition === 'end') {
textAlign = 'start';
}
return textAlign;
}
const singleEdge: ShapeOptions = {
itemType: 'edge',
/**
* 文本的位置
* @type {String}
*/
labelPosition: 'center', // start, end, center
/**
* 文本的 x 偏移
* @type {Number}
*/
refX: 0,
/**
* 文本的 y 偏移
* @type {Number}
*/
refY: 0,
/**
* 文本是否跟着线自动旋转,默认 false
* @type {Boolean}
*/
labelAutoRotate: false,
// 自定义边时的配置
options: {
size: Global.defaultEdge.size,
style: {
x: 0,
y: 0,
stroke: Global.defaultEdge.style.stroke,
lineAppendWidth: Global.defaultEdge.style.lineAppendWidth,
},
labelCfg: {
style: {
fill: Global.edgeLabel.style.fill,
fontSize: Global.edgeLabel.style.fontSize,
fontFamily: Global.windowFontFamily
},
},
stateStyles: {
...Global.edgeStateStyles,
},
},
/**
* 获取边的 path
* @internal 供扩展的边覆盖
* @param {Array} points 构成边的点的集合
* @return {Array} 构成 path 的数组
*/
getPath(points: Point[]): Array<Array<string | number>> {
const path: Array<Array<string | number>> = [];
each(points, (point: Point, index: number) => {
if (index === 0) {
path.push(['M', point.x, point.y]);
} else {
path.push(['L', point.x, point.y]);
}
});
return path;
},
getShapeStyle(cfg: EdgeConfig): ShapeStyle {
const { style: defaultStyle } = this.options as ModelConfig;
const strokeStyle: ShapeStyle = {
stroke: cfg.color,
};
// 如果设置了color,则覆盖默认的stroke属性
const style: ShapeStyle = mix({}, defaultStyle, strokeStyle, cfg.style);
const size = cfg.size || Global.defaultEdge.size;
cfg = this.getPathPoints!(cfg);
const { startPoint, endPoint } = cfg;
const controlPoints = this.getControlPoints!(cfg);
let points = [startPoint]; // 添加起始点
// 添加控制点
if (controlPoints) {
points = points.concat(controlPoints);
}
// 添加结束点
points.push(endPoint);
const path = (this as any).getPath(points);
const styles = mix(
{},
Global.defaultEdge.style as ShapeStyle,
{
stroke: Global.defaultEdge.color,
lineWidth: size,
path,
} as ShapeStyle,
style,
);
return styles;
},
updateShapeStyle(cfg: EdgeConfig, item: Item, updateType?: UpdateType) {
const group = item.getContainer();
// const strokeStyle: ShapeStyle = {
// stroke: cfg.color,
// };
const shape =
item.getKeyShape?.() || group['shapeMap']['edge-shape']; // group.find((element) => element.get('className') === 'edge-shape');
const { size } = cfg;
cfg = this.getPathPoints!(cfg);
const { startPoint, endPoint } = cfg;
const controlPoints = this.getControlPoints!(cfg); // || cfg.controlPoints;
let points = [startPoint]; // 添加起始点
// 添加控制点
if (controlPoints) {
points = points.concat(controlPoints);
}
// 添加结束点
points.push(endPoint);
const currentAttr = shape.attr();
// const previousStyle = mix({}, strokeStyle, currentAttr, cfg.style);
const previousStyle = cfg.style || {};
if (previousStyle.stroke === undefined) {
previousStyle.stroke = cfg.color
}
const source = cfg.sourceNode;
const target = cfg.targetNode;
let routeCfg: { [key: string]: unknown } = { radius: previousStyle.radius };
if (!controlPoints) {
routeCfg = { source, target, offset: previousStyle.offset, radius: previousStyle.radius };
}
const path = (this as any).getPath(points, routeCfg);
let style: any = {};
if (updateType === 'move') {
style = { path };
} else {
if (currentAttr.endArrow && previousStyle.endArrow === false) {
cfg.style.endArrow = {
path: '',
};
}
if (currentAttr.startArrow && previousStyle.startArrow === false) {
cfg.style.startArrow = {
path: '',
};
}
style = { ...cfg.style };
if (style.lineWidth === undefined) style.lineWdith = (isNumber(size) ? size : size?.[0]) || currentAttr.lineWidth
if (style.path === undefined) style.path = path;
if (style.stroke === undefined) style.stroke = currentAttr.stroke || cfg.color;
}
if (shape) {
shape.attr(style);
}
},
getLabelStyleByPosition(cfg: EdgeConfig, labelCfg: ILabelConfig, group?: IGroup): LabelStyle {
const labelPosition = labelCfg.position || this.labelPosition; // 文本的位置用户可以传入
const style: LabelStyle = {};
const pathShape = group?.['shapeMap'][CLS_SHAPE]; // group?.find((element) => element.get('className') === CLS_SHAPE);
// 不对 pathShape 进行判空,如果线不存在,说明有问题了
let pointPercent;
if (labelPosition === 'start') {
pointPercent = 0;
} else if (labelPosition === 'end') {
pointPercent = 1;
} else {
pointPercent = 0.5;
}
// 偏移量
const offsetX = labelCfg.refX || (this.refX as number);
const offsetY = labelCfg.refY || (this.refY as number);
// 如果两个节点重叠,线就变成了一个点,这时候label的位置,就是这个点 + 绝对偏移
if (cfg.startPoint!.x === cfg.endPoint!.x && cfg.startPoint!.y === cfg.endPoint!.y) {
style.x = cfg.startPoint!.x + offsetX;
style.y = cfg.startPoint!.y + offsetY;
style.text = cfg.label as string;
return style;
}
let autoRotate;
if (isNil(labelCfg.autoRotate)) autoRotate = this.labelAutoRotate;
else autoRotate = labelCfg.autoRotate;
const offsetStyle = getLabelPosition(
pathShape,
pointPercent,
offsetX,
offsetY,
autoRotate as boolean,
);
style.x = offsetStyle.x;
style.y = offsetStyle.y;
style.rotate = offsetStyle.rotate;
style.textAlign = this._getTextAlign!(labelPosition as string, offsetStyle.angle as number);
style.text = cfg.label as string;
return style;
},
getLabelBgStyleByPosition(
label: IElement,
labelCfg?: ILabelConfig,
) {
if (!label) {
return {};
}
const bbox = label.getBBox();
const backgroundStyle = labelCfg.style && labelCfg.style.background;
if (!backgroundStyle) {
return {};
}
const { padding } = backgroundStyle;
const backgroundWidth = bbox.width + padding[1] + padding[3];
const backgroundHeight = bbox.height + padding[0] + padding[2];
const style = {
...backgroundStyle,
width: backgroundWidth,
height: backgroundHeight,
x: bbox.minX - padding[3],
y: bbox.minY - padding[0],
matrix: [1, 0, 0, 0, 1, 0, 0, 0, 1]
};
let autoRotate;
if (isNil(labelCfg.autoRotate)) autoRotate = this.labelAutoRotate;
else autoRotate = labelCfg.autoRotate;
if (autoRotate) {
style.matrix = label.attr('matrix') || [1, 0, 0, 0, 1, 0, 0, 0, 1];
}
return style;
},
// 获取文本对齐方式
_getTextAlign(labelPosition: string, angle: number): string {
let textAlign = 'center';
if (!angle) {
return labelPosition;
}
angle = angle % (Math.PI * 2); // 取模
if (labelPosition !== 'center') {
if (
(angle >= 0 && angle <= Math.PI / 2) ||
(angle >= (3 / 2) * Math.PI && angle < 2 * Math.PI)
) {
textAlign = labelPosition;
} else {
textAlign = revertAlign(labelPosition);
}
}
return textAlign;
},
/**
* @internal 获取边的控制点
* @param {Object} cfg 边的配置项
* @return {Array} 控制点的数组
*/
getControlPoints(cfg: EdgeConfig): IPoint[] | undefined {
return cfg.controlPoints;
},
/**
* @internal 处理需要重计算点和边的情况
* @param {Object} cfg 边的配置项
* @return {Object} 边的配置项
*/
getPathPoints(cfg: EdgeConfig): EdgeConfig {
return cfg;
},
/**
* 绘制边
* @override
* @param {Object} cfg 边的配置项
* @param {G.Group} group 边的容器
* @return {IShape} 图形
*/
drawShape(cfg: EdgeConfig, group: IGroup): IShape {
const shapeStyle = this.getShapeStyle!(cfg);
const shape = group.addShape('path', {
className: CLS_SHAPE,
name: CLS_SHAPE,
attrs: shapeStyle,
});
group['shapeMap'][CLS_SHAPE] = shape;
return shape;
},
drawLabel(cfg: EdgeConfig, group: IGroup): IShape {
const { labelCfg: defaultLabelCfg } = this.options as ModelConfig;
const labelCfg = deepMix(
{},
defaultLabelCfg,
cfg.labelCfg,
);
const labelStyle = this.getLabelStyle!(cfg, labelCfg, group);
const rotate = labelStyle.rotate;
delete labelStyle.rotate;
const label = group.addShape('text', {
attrs: labelStyle,
name: 'text-shape',
labelRelated: true
});
group['shapeMap']['text-shape'] = label;
if (!isNaN(rotate) && rotate !== '') {
label.rotateAtStart(rotate);
}
if (labelStyle.background) {
const rect = this.drawLabelBg(cfg, group, label, labelStyle, rotate);
const labelBgClassname = this.itemType + CLS_LABEL_BG_SUFFIX;
rect.set('classname', labelBgClassname);
group['shapeMap'][labelBgClassname] = rect;
label.toFront();
}
return label;
},
drawLabelBg(cfg: ModelConfig, group: IGroup, label: IElement, labelStyle: any, rotate: number) {
const { labelCfg: defaultLabelCfg } = this.options as ModelConfig;
const labelCfg = deepMix({}, defaultLabelCfg, cfg.labelCfg);
const style = this.getLabelBgStyleByPosition(label, labelCfg);
const rect = group.addShape('rect', { name: 'text-bg-shape', attrs: style, labelRelated: true });
group['shapeMap']['text-bg-shape'] = rect;
return rect;
},
};
const singleEdgeDef = { ...shapeBase, ...singleEdge };
Shape.registerEdge('single-edge', singleEdgeDef);
// 直线, 不支持控制点
Shape.registerEdge(
'line',
{
// 控制点不生效
getControlPoints() {
return undefined;
},
},
'single-edge',
);
// 直线
Shape.registerEdge(
'spline',
{
getPath(points: Point[]): Array<Array<string | number>> {
const path = getSpline(points);
return path;
},
},
'single-edge',
);
Shape.registerEdge(
'arc',
{
curveOffset: 20,
clockwise: 1,
getControlPoints(cfg: EdgeConfig): IPoint[] {
const { startPoint, endPoint } = cfg;
const midPoint = {
x: (startPoint.x + endPoint.x) / 2,
y: (startPoint.y + endPoint.y) / 2,
};
let center;
let arcPoint;
// 根据给定点计算圆弧
if (cfg.controlPoints !== undefined) {
arcPoint = cfg.controlPoints[0];
center = getCircleCenterByPoints(startPoint, arcPoint, endPoint);
// 根据控制点和直线关系决定 clockwise值
if (startPoint.x <= endPoint.x && startPoint.y > endPoint.y) {
this.clockwise = center.x > arcPoint.x ? 0 : 1;
} else if (startPoint.x <= endPoint.x && startPoint.y < endPoint.y) {
this.clockwise = center.x > arcPoint.x ? 1 : 0;
} else if (startPoint.x > endPoint.x && startPoint.y <= endPoint.y) {
this.clockwise = center.y < arcPoint.y ? 0 : 1;
} else {
this.clockwise = center.y < arcPoint.y ? 1 : 0;
}
// 若给定点和两端点共线,无法生成圆弧,绘制直线
if (
(arcPoint.x - startPoint.x) / (arcPoint.y - startPoint.y) ===
(endPoint.x - startPoint.x) / (endPoint.y - startPoint.y)
) {
return [];
}
} else {
// 根据直线连线中点的的偏移计算圆弧
// 若用户给定偏移量则根据其计算,否则按照默认偏移值计算
if (cfg.curveOffset === undefined) {
cfg.curveOffset = this.curveOffset;
}
if (isArray(cfg.curveOffset)) {
cfg.curveOffset = cfg.curveOffset[0];
}
if (cfg.curveOffset < 0) {
this.clockwise = 0;
} else {
this.clockwise = 1;
}
const vec = {
x: endPoint.x - startPoint.x,
y: endPoint.y - startPoint.y,
};
const edgeAngle = Math.atan2(vec.y, vec.x);
arcPoint = {
x: cfg.curveOffset * Math.cos(-Math.PI / 2 + edgeAngle) + midPoint.x,
y: cfg.curveOffset * Math.sin(-Math.PI / 2 + edgeAngle) + midPoint.y,
};
center = getCircleCenterByPoints(startPoint, arcPoint, endPoint);
}
const radius = distance(startPoint, center);
const controlPoints = [{ x: radius, y: radius }];
return controlPoints;
},
getPath(points: Point[]): Array<Array<string | number>> {
const path: Array<Array<string | number>> = [];
path.push(['M', points[0].x, points[0].y]);
// 控制点与端点共线
if (points.length === 2) {
path.push(['L', points[1].x, points[1].y]);
} else {
path.push([
'A',
points[1].x,
points[1].y,
0,
0,
this.clockwise as number,
points[2].x,
points[2].y,
]);
}
return path;
},
},
'single-edge',
);
Shape.registerEdge(
'quadratic',
{
curvePosition: 0.5, // 弯曲的默认位置
curveOffset: -20, // 弯曲度,沿着 startPoint, endPoint 的垂直向量(顺时针)方向,距离线的距离,距离越大越弯曲
getControlPoints(cfg: EdgeConfig): IPoint[] {
let { controlPoints } = cfg; // 指定controlPoints
if (!controlPoints || !controlPoints.length) {
const { startPoint, endPoint } = cfg;
if (cfg.curveOffset === undefined) cfg.curveOffset = this.curveOffset;
if (cfg.curvePosition === undefined) cfg.curvePosition = this.curvePosition;
if (isArray(this.curveOffset)) cfg.curveOffset = cfg.curveOffset[0];
if (isArray(this.curvePosition)) cfg.curvePosition = cfg.curveOffset[0];
const innerPoint = getControlPoint(
startPoint as Point,
endPoint as Point,
cfg.curvePosition as number,
cfg.curveOffset as number,
);
controlPoints = [innerPoint];
}
return controlPoints;
},
getPath(points: Point[]): Array<Array<string | number>> {
const path = [];
path.push(['M', points[0].x, points[0].y]);
path.push(['Q', points[1].x, points[1].y, points[2].x, points[2].y]);
return path;
},
},
'single-edge',
);
Shape.registerEdge(
'cubic',
{
curvePosition: [1 / 2, 1 / 2],
curveOffset: [-20, 20],
getControlPoints(cfg: EdgeConfig): IPoint[] {
let { controlPoints } = cfg; // 指定 controlPoints
if (cfg.curveOffset === undefined) cfg.curveOffset = this.curveOffset;
if (cfg.curvePosition === undefined) cfg.curvePosition = this.curvePosition;
if (isNumber(cfg.curveOffset)) cfg.curveOffset = [cfg.curveOffset, -cfg.curveOffset];
if (isNumber(cfg.curvePosition))
cfg.curvePosition = [cfg.curvePosition, 1 - cfg.curvePosition];
if (!controlPoints || !controlPoints.length || controlPoints.length < 2) {
const { startPoint, endPoint } = cfg;
const innerPoint1 = getControlPoint(
startPoint as Point,
endPoint as Point,
cfg.curvePosition[0],
cfg.curveOffset[0],
);
const innerPoint2 = getControlPoint(
startPoint as Point,
endPoint as Point,
cfg.curvePosition[1],
cfg.curveOffset[1],
);
controlPoints = [innerPoint1, innerPoint2];
}
return controlPoints;
},
getPath(points: Point[]): Array<Array<string | number>> {
const path = [];
path.push(['M', points[0].x, points[0].y]);
path.push([
'C',
points[1].x,
points[1].y,
points[2].x,
points[2].y,
points[3].x,
points[3].y,
]);
return path;
},
},
'single-edge',
);
// 垂直方向的三阶贝塞尔曲线,不再考虑用户外部传入的控制点
Shape.registerEdge(
'cubic-vertical',
{
curvePosition: [1 / 2, 1 / 2],
minCurveOffset: [0, 0],
curveOffset: undefined,
getControlPoints(cfg: EdgeConfig): IPoint[] {
const { startPoint, endPoint } = cfg;
if (cfg.curvePosition === undefined) cfg.curvePosition = this.curvePosition;
if (cfg.curveOffset === undefined) cfg.curveOffset = this.curveOffset;
if (cfg.minCurveOffset === undefined) cfg.minCurveOffset = this.minCurveOffset;
if (isNumber(cfg.curveOffset)) cfg.curveOffset = [cfg.curveOffset, -cfg.curveOffset];
if (isNumber(cfg.minCurveOffset))
cfg.minCurveOffset = [cfg.minCurveOffset, -cfg.minCurveOffset];
if (isNumber(cfg.curvePosition))
cfg.curvePosition = [cfg.curvePosition, 1 - cfg.curvePosition];
const yDist = endPoint!.y - startPoint!.y;
let curveOffset: number[] = [0, 0];
if (cfg.curveOffset) {
curveOffset = cfg.curveOffset;
} else if (Math.abs(yDist) < Math.abs(cfg.minCurveOffset[0])) {
curveOffset = cfg.minCurveOffset;
}
const innerPoint1 = {
x: startPoint!.x,
y: startPoint!.y + yDist * (this as any).curvePosition[0] + curveOffset[0],
};
const innerPoint2 = {
x: endPoint!.x,
y: endPoint!.y - yDist * (this as any).curvePosition[1] + curveOffset[1],
};
return [innerPoint1, innerPoint2];
},
},
'cubic',
);
// 水平方向的三阶贝塞尔曲线,不再考虑用户外部传入的控制点
Shape.registerEdge(
'cubic-horizontal',
{
curvePosition: [1 / 2, 1 / 2],
minCurveOffset: [0, 0],
curveOffset: undefined,
getControlPoints(cfg: EdgeConfig): IPoint[] {
const { startPoint, endPoint } = cfg;
if (cfg.curvePosition === undefined) cfg.curvePosition = this.curvePosition;
if (cfg.curveOffset === undefined) cfg.curveOffset = this.curveOffset;
if (cfg.minCurveOffset === undefined) cfg.minCurveOffset = this.minCurveOffset;
if (isNumber(cfg.curveOffset)) cfg.curveOffset = [cfg.curveOffset, -cfg.curveOffset];
if (isNumber(cfg.minCurveOffset))
cfg.minCurveOffset = [cfg.minCurveOffset, -cfg.minCurveOffset];
if (isNumber(cfg.curvePosition))
cfg.curvePosition = [cfg.curvePosition, 1 - cfg.curvePosition];
const xDist = endPoint!.x - startPoint!.x;
let curveOffset: number[] = [0, 0];
if (cfg.curveOffset) {
curveOffset = cfg.curveOffset;
} else if (Math.abs(xDist) < Math.abs(cfg.minCurveOffset[0])) {
curveOffset = cfg.minCurveOffset;
}
const innerPoint1 = {
x: startPoint!.x + xDist * (this as any).curvePosition[0] + curveOffset[0],
y: startPoint!.y,
};
const innerPoint2 = {
x: endPoint!.x - xDist * (this as any).curvePosition[1] + curveOffset[1],
y: endPoint!.y,
};
const controlPoints = [innerPoint1, innerPoint2];
return controlPoints;
},
},
'cubic',
);
Shape.registerEdge(
'loop',
{
getPathPoints(cfg: ModelConfig): EdgeData {
return getLoopCfgs(cfg as EdgeData);
},
getControlPoints(cfg: EdgeConfig): IPoint[] | undefined {
return cfg.controlPoints;
},
afterDraw(cfg: EdgeConfig) {
cfg.controlPoints = undefined;
},
afterUpdate(cfg: EdgeConfig) {
cfg.controlPoints = undefined;
},
},
'cubic',
); | the_stack |
import type { DefaultThemeRenderContext } from "../DefaultThemeRenderContext";
import { LiteralType, ReferenceType, ReflectionKind, Type, TypeKindMap } from "../../../../models";
import { JSX } from "../../../../utils";
import { join, stringify } from "../../lib";
type TypeInlinePartialsOptions = { needsParens?: boolean };
// The type helper accepts an optional needsParens parameter that is checked
// if an inner type may result in invalid output without them. For example:
// 1 | 2[] !== (1 | 2)[]
// () => 1 | 2 !== (() => 1) | 2
const typeRenderers: {
[K in keyof TypeKindMap]: (
context: DefaultThemeRenderContext,
type: TypeKindMap[K],
options: TypeInlinePartialsOptions
) => JSX.Element;
} = {
array(context, type) {
return (
<>
{renderType(context, type.elementType, { needsParens: true })}
<span class="tsd-signature-symbol">[]</span>
</>
);
},
conditional(context, type, { needsParens }) {
return (
<>
{needsParens && <span class="tsd-signature-symbol">(</span>}
{renderType(context, type.checkType, { needsParens: true })}
<span class="tsd-signature-symbol"> extends </span>
{renderType(context, type.extendsType)}
<span class="tsd-signature-symbol"> ? </span>
{renderType(context, type.trueType)}
<span class="tsd-signature-symbol"> : </span>
{renderType(context, type.falseType)}
{needsParens && <span class="tsd-signature-symbol">)</span>}
</>
);
},
indexedAccess(context, type) {
let indexType: JSX.Element = renderType(context, type.indexType);
if (
type.objectType instanceof ReferenceType &&
type.objectType.reflection &&
type.indexType instanceof LiteralType &&
typeof type.indexType.value === "string"
) {
const childReflection = type.objectType.reflection.getChildByName([type.indexType.value]);
if (childReflection) {
indexType = <a href={context.urlTo(childReflection)}>{indexType}</a>;
}
}
return (
<>
{renderType(context, type.objectType)}
<span class="tsd-signature-symbol">[</span>
{indexType}
<span class="tsd-signature-symbol">]</span>
</>
);
},
inferred(_context, type) {
return (
<>
<span class="tsd-signature-symbol">infer </span> {type.name}
</>
);
},
intersection(context, type, { needsParens }) {
return (
<>
{needsParens && <span class="tsd-signature-symbol">(</span>}
{join(<span class="tsd-signature-symbol"> & </span>, type.types, (item) =>
renderType(context, item, { needsParens: true })
)}
{needsParens && <span class="tsd-signature-symbol">)</span>}
</>
);
},
intrinsic(_context, type) {
return <span class="tsd-signature-type">{type.name}</span>;
},
literal(_context, type) {
return <span class="tsd-signature-type">{stringify(type.value)}</span>;
},
mapped(context, type) {
const children: JSX.Element[] = [];
switch (type.readonlyModifier) {
case "+":
children.push(<span class="tsd-signature-symbol">readonly </span>);
break;
case "-":
children.push(<span class="tsd-signature-symbol">-readonly </span>);
break;
}
children.push(
<span class="tsd-signature-symbol">[ </span>,
<span class="tsd-signature-type">{type.parameter}</span>,
<span class="tsd-signature-symbol"> in </span>,
renderType(context, type.parameterType)
);
if (type.nameType) {
children.push(<span class="tsd-signature-symbol"> as </span>, renderType(context, type.nameType));
}
children.push(<span class="tsd-signature-symbol">]</span>);
switch (type.optionalModifier) {
case "+":
children.push(<span class="tsd-signature-symbol">?: </span>);
break;
case "-":
children.push(<span class="tsd-signature-symbol">-?: </span>);
break;
default:
children.push(<span class="tsd-signature-symbol">: </span>);
}
children.push(renderType(context, type.templateType));
return (
<>
<span class="tsd-signature-symbol">{"{"}</span> {children}{" "}
<span class="tsd-signature-symbol">{"}"}</span>
</>
);
},
"named-tuple-member"(context, type) {
return (
<>
{type.name}
{type.isOptional ? (
<span class="tsd-signature-symbol">?: </span>
) : (
<span class="tsd-signature-symbol">: </span>
)}
{renderType(context, type.element)}
</>
);
},
optional(context, type) {
return (
<>
{renderType(context, type.elementType)}
<span class="tsd-signature-symbol">?</span>
</>
);
},
predicate(context, type) {
return (
<>
{!!type.asserts && <span class="tsd-signature-symbol">asserts </span>}
<span class="tsd-signature-type">{type.name}</span>
{!!type.targetType && (
<>
<span class="tsd-signature-symbol"> is </span>
{renderType(context, type.targetType)}
</>
)}
</>
);
},
query(context, type) {
return (
<>
<span class="tsd-signature-symbol">typeof </span>
{renderType(context, type.queryType)}
</>
);
},
reference(context, type) {
const reflection = type.reflection;
let name: JSX.Element;
if (reflection) {
if (reflection.kindOf(ReflectionKind.TypeParameter)) {
// Don't generate a link will always point to this page, but do set the kind.
name = (
<span class="tsd-signature-type" data-tsd-kind={reflection.kindString}>
{reflection.name}
</span>
);
} else {
name = (
<a
href={context.urlTo(reflection)}
class="tsd-signature-type"
data-tsd-kind={reflection.kindString}
>
{reflection.name}
</a>
);
}
} else {
const externalUrl = context.attemptExternalResolution(type.getSymbol());
if (externalUrl) {
name = (
<a href={externalUrl} class="tsd-signature-type external" target="_blank">
{type.name}
</a>
);
} else {
name = <span class="tsd-signature-type">{type.name}</span>;
}
}
if (type.typeArguments?.length) {
return (
<>
{name}
<span class="tsd-signature-symbol">{"<"}</span>
{join(<span class="tsd-signature-symbol">, </span>, type.typeArguments, (item) =>
renderType(context, item)
)}
<span class="tsd-signature-symbol">{">"}</span>
</>
);
}
return name;
},
reflection(context, type, { needsParens }) {
if (type.declaration.children) {
// Object literal
return (
<>
<span class="tsd-signature-symbol">{"{ "}</span>
{join(<span class="tsd-signature-symbol">; </span>, type.declaration.children, (item) => {
if (item.getSignature && item.setSignature) {
return (
<>
{item.name}
<span class="tsd-signature-symbol">: </span>
{renderType(context, item.getSignature.type)}
</>
);
}
if (item.getSignature) {
return (
<>
<span class="tsd-signature-symbol">get </span>
{item.name}
<span class="tsd-signature-symbol">(): </span>
{renderType(context, item.getSignature.type)}
</>
);
}
if (item.setSignature) {
return (
<>
<span class="tsd-signature-symbol">set </span>
{item.name}
<span class="tsd-signature-symbol">(</span>
{item.setSignature.parameters?.map((item) => (
<>
{item.name}
<span class="tsd-signature-symbol">: </span>
{renderType(context, item.type)}
</>
))}
<span class="tsd-signature-symbol">)</span>
</>
);
}
return (
<>
{item.name}
<span class="tsd-signature-symbol">{item.flags.isOptional ? "?: " : ": "}</span>
{renderType(context, item.type)}
</>
);
})}
<span class="tsd-signature-symbol">{" }"}</span>
</>
);
}
if (type.declaration.signatures?.length === 1) {
return (
<>
{needsParens && <span class="tsd-signature-symbol">(</span>}
{context.memberSignatureTitle(type.declaration.signatures[0], {
hideName: true,
arrowStyle: true,
})}
{needsParens && <span class="tsd-signature-symbol">)</span>}
</>
);
}
if (type.declaration.signatures) {
return (
<>
<span class="tsd-signature-symbol">{"{"} </span>
{join(<span class="tsd-signature-symbol">; </span>, type.declaration.signatures, (item) =>
context.memberSignatureTitle(item, { hideName: true })
)}
<span class="tsd-signature-symbol">{" }"}</span>
</>
);
}
return <span class="tsd-signature-symbol">{"{}"}</span>;
},
rest(context, type) {
return (
<>
<span class="tsd-signature-symbol">...</span>
{renderType(context, type.elementType)}
</>
);
},
"template-literal"(context, type) {
return (
<>
<span class="tsd-signature-symbol">`</span>
{type.head && <span class="tsd-signature-type">{type.head}</span>}
{type.tail.map((item) => (
<>
<span class="tsd-signature-symbol">{"${"}</span>
{renderType(context, item[0])}
<span class="tsd-signature-symbol">{"}"}</span>
{item[1] && <span class="tsd-signature-type">{item[1]}</span>}
</>
))}
<span class="tsd-signature-symbol">`</span>
</>
);
},
tuple(context, type) {
return (
<>
<span class="tsd-signature-symbol">[</span>
{join(<span class="tsd-signature-symbol">, </span>, type.elements, (item) => renderType(context, item))}
<span class="tsd-signature-symbol">]</span>
</>
);
},
typeOperator(context, type) {
return (
<>
<span class="tsd-signature-symbol">{type.operator} </span>
{renderType(context, type.target)}
</>
);
},
union(context, type, { needsParens }) {
return (
<>
{!!needsParens && <span class="tsd-signature-symbol">(</span>}
{join(<span class="tsd-signature-symbol"> | </span>, type.types, (item) =>
renderType(context, item, { needsParens: true })
)}
{!!needsParens && <span class="tsd-signature-symbol">)</span>}
</>
);
},
unknown(_context, type) {
return <>{type.name}</>;
},
};
function renderType(context: DefaultThemeRenderContext, type: Type | undefined, options?: TypeInlinePartialsOptions) {
if (!type) {
return <span class="tsd-signature-type">any</span>;
}
const renderFn = typeRenderers[type.type];
return renderFn(context, type as never, options ?? {});
}
export function type(context: DefaultThemeRenderContext, type: Type | undefined) {
return renderType(context, type, {});
} | the_stack |
'use strict';
import { Uri, commands, scm, Disposable, window, workspace, QuickPickItem, OutputChannel, Range, WorkspaceEdit, Position, LineChange, SourceControlResourceState } from 'vscode';
import { Ref, RefType, Git, GitErrorCodes } from './git';
import { Model, Resource, Status, CommitOptions, WorkingTreeGroup, IndexGroup, MergeGroup } from './model';
import { toGitUri, fromGitUri } from './uri';
import { applyLineChanges, intersectDiffWithRange, toLineRanges, invertLineChange } from './staging';
import * as path from 'path';
import * as os from 'os';
import TelemetryReporter from 'vscode-extension-telemetry';
import * as nls from 'vscode-nls';
const localize = nls.loadMessageBundle();
class CheckoutItem implements QuickPickItem {
protected get shortCommit(): string { return (this.ref.commit || '').substr(0, 8); }
protected get treeish(): string | undefined { return this.ref.name; }
get label(): string { return this.ref.name || this.shortCommit; }
get description(): string { return this.shortCommit; }
constructor(protected ref: Ref) { }
async run(model: Model): Promise<void> {
const ref = this.treeish;
if (!ref) {
return;
}
await model.checkout(ref);
}
}
class CheckoutTagItem extends CheckoutItem {
get description(): string {
return localize('tag at', "Tag at {0}", this.shortCommit);
}
}
class CheckoutRemoteHeadItem extends CheckoutItem {
get description(): string {
return localize('remote branch at', "Remote branch at {0}", this.shortCommit);
}
protected get treeish(): string | undefined {
if (!this.ref.name) {
return;
}
const match = /^[^/]+\/(.*)$/.exec(this.ref.name);
return match ? match[1] : this.ref.name;
}
}
interface Command {
commandId: string;
key: string;
method: Function;
skipModelCheck: boolean;
requiresDiffInformation: boolean;
}
const Commands: Command[] = [];
function command(commandId: string, skipModelCheck = false, requiresDiffInformation = false): Function {
return (target: any, key: string, descriptor: any) => {
if (!(typeof descriptor.value === 'function')) {
throw new Error('not supported');
}
Commands.push({ commandId, key, method: descriptor.value, skipModelCheck, requiresDiffInformation });
};
}
export class CommandCenter {
private model: Model;
private disposables: Disposable[];
constructor(
private git: Git,
model: Model | undefined,
private outputChannel: OutputChannel,
private telemetryReporter: TelemetryReporter
) {
if (model) {
this.model = model;
}
this.disposables = Commands
.map(({ commandId, key, method, skipModelCheck, requiresDiffInformation }) => {
const command = this.createCommand(commandId, key, method, skipModelCheck);
if (requiresDiffInformation) {
return commands.registerDiffInformationCommand(commandId, command);
} else {
return commands.registerCommand(commandId, command);
}
});
}
@command('git.refresh')
async refresh(): Promise<void> {
await this.model.status();
}
@command('git.openResource')
async openResource(resource: Resource): Promise<void> {
await this._openResource(resource);
}
private async _openResource(resource: Resource): Promise<void> {
const left = this.getLeftResource(resource);
const right = this.getRightResource(resource);
const title = this.getTitle(resource);
if (!right) {
// TODO
console.error('oh no');
return;
}
if (!left) {
return await commands.executeCommand<void>('vscode.open', right);
}
return await commands.executeCommand<void>('vscode.diff', left, right, title);
}
private getLeftResource(resource: Resource): Uri | undefined {
switch (resource.type) {
case Status.INDEX_MODIFIED:
case Status.INDEX_RENAMED:
return toGitUri(resource.original, 'HEAD');
case Status.MODIFIED:
return toGitUri(resource.resourceUri, '~');
}
}
private getRightResource(resource: Resource): Uri | undefined {
switch (resource.type) {
case Status.INDEX_MODIFIED:
case Status.INDEX_ADDED:
case Status.INDEX_COPIED:
case Status.INDEX_RENAMED:
return toGitUri(resource.resourceUri, '');
case Status.INDEX_DELETED:
case Status.DELETED:
return toGitUri(resource.resourceUri, 'HEAD');
case Status.MODIFIED:
case Status.UNTRACKED:
case Status.IGNORED:
const uriString = resource.resourceUri.toString();
const [indexStatus] = this.model.indexGroup.resources.filter(r => r.resourceUri.toString() === uriString);
if (indexStatus && indexStatus.renameResourceUri) {
return indexStatus.renameResourceUri;
}
return resource.resourceUri;
case Status.BOTH_MODIFIED:
return resource.resourceUri;
}
}
private getTitle(resource: Resource): string {
const basename = path.basename(resource.resourceUri.fsPath);
switch (resource.type) {
case Status.INDEX_MODIFIED:
case Status.INDEX_RENAMED:
return `${basename} (Index)`;
case Status.MODIFIED:
return `${basename} (Working Tree)`;
}
return '';
}
@command('git.clone', true)
async clone(): Promise<void> {
const url = await window.showInputBox({
prompt: localize('repourl', "Repository URL"),
ignoreFocusOut: true
});
if (!url) {
this.telemetryReporter.sendTelemetryEvent('clone', { outcome: 'no_URL' });
return;
}
const parentPath = await window.showInputBox({
prompt: localize('parent', "Parent Directory"),
value: os.homedir(),
ignoreFocusOut: true
});
if (!parentPath) {
this.telemetryReporter.sendTelemetryEvent('clone', { outcome: 'no_directory' });
return;
}
const clonePromise = this.git.clone(url, parentPath);
window.setStatusBarMessage(localize('cloning', "Cloning git repository..."), clonePromise);
try {
const repositoryPath = await clonePromise;
const open = localize('openrepo', "Open Repository");
const result = await window.showInformationMessage(localize('proposeopen', "Would you like to open the cloned repository?"), open);
const openFolder = result === open;
this.telemetryReporter.sendTelemetryEvent('clone', { outcome: 'success' }, { openFolder: openFolder ? 1 : 0 });
if (openFolder) {
commands.executeCommand('vscode.openFolder', Uri.file(repositoryPath));
}
} catch (err) {
if (/already exists and is not an empty directory/.test(err && err.stderr || '')) {
this.telemetryReporter.sendTelemetryEvent('clone', { outcome: 'directory_not_empty' });
} else {
this.telemetryReporter.sendTelemetryEvent('clone', { outcome: 'error' });
}
throw err;
}
}
@command('git.init')
async init(): Promise<void> {
await this.model.init();
}
@command('git.openFile')
async openFile(arg?: Resource | Uri): Promise<void> {
let uri: Uri | undefined;
if (arg instanceof Uri) {
if (arg.scheme === 'git') {
uri = Uri.file(fromGitUri(arg).path);
} else if (arg.scheme === 'file') {
uri = arg;
}
} else {
let resource = arg;
if (!(resource instanceof Resource)) {
// can happen when called from a keybinding
resource = this.getSCMResource();
}
if (resource) {
uri = resource.resourceUri;
}
}
if (!uri) {
return;
}
return await commands.executeCommand<void>('vscode.open', uri);
}
@command('git.openChange')
async openChange(arg?: Resource | Uri): Promise<void> {
let resource: Resource | undefined = undefined;
if (arg instanceof Resource) {
resource = arg;
} else if (arg instanceof Uri) {
resource = this.getSCMResource(arg);
} else {
resource = this.getSCMResource();
}
if (!resource) {
return;
}
return await this._openResource(resource);
}
@command('git.openFileFromUri')
async openFileFromUri(uri?: Uri): Promise<void> {
const resource = this.getSCMResource(uri);
let uriToOpen: Uri | undefined;
if (resource) {
uriToOpen = resource.resourceUri;
} else if (uri && uri.scheme === 'git') {
const { path } = fromGitUri(uri);
uriToOpen = Uri.file(path);
} else if (uri && uri.scheme === 'file') {
uriToOpen = uri;
}
if (!uriToOpen) {
return;
}
return await commands.executeCommand<void>('vscode.open', uriToOpen);
}
@command('git.stage')
async stage(...resourceStates: SourceControlResourceState[]): Promise<void> {
if (resourceStates.length === 0 || !(resourceStates[0].resourceUri instanceof Uri)) {
const resource = this.getSCMResource();
if (!resource) {
return;
}
resourceStates = [resource];
}
const resources = resourceStates
.filter(s => s instanceof Resource && (s.resourceGroup instanceof WorkingTreeGroup || s.resourceGroup instanceof MergeGroup)) as Resource[];
if (!resources.length) {
return;
}
return await this.model.add(...resources);
}
@command('git.stageAll')
async stageAll(): Promise<void> {
return await this.model.add();
}
@command('git.stageSelectedRanges', false, true)
async stageSelectedRanges(diffs: LineChange[]): Promise<void> {
const textEditor = window.activeTextEditor;
if (!textEditor) {
return;
}
const modifiedDocument = textEditor.document;
const modifiedUri = modifiedDocument.uri;
if (modifiedUri.scheme !== 'file') {
return;
}
const originalUri = toGitUri(modifiedUri, '~');
const originalDocument = await workspace.openTextDocument(originalUri);
const selectedLines = toLineRanges(textEditor.selections, modifiedDocument);
const selectedDiffs = diffs
.map(diff => selectedLines.reduce<LineChange | null>((result, range) => result || intersectDiffWithRange(modifiedDocument, diff, range), null))
.filter(d => !!d) as LineChange[];
if (!selectedDiffs.length) {
return;
}
const result = applyLineChanges(originalDocument, modifiedDocument, selectedDiffs);
await this.model.stage(modifiedUri, result);
}
@command('git.revertSelectedRanges', false, true)
async revertSelectedRanges(diffs: LineChange[]): Promise<void> {
const textEditor = window.activeTextEditor;
if (!textEditor) {
return;
}
const modifiedDocument = textEditor.document;
const modifiedUri = modifiedDocument.uri;
if (modifiedUri.scheme !== 'file') {
return;
}
const originalUri = toGitUri(modifiedUri, '~');
const originalDocument = await workspace.openTextDocument(originalUri);
const selections = textEditor.selections;
const selectedDiffs = diffs.filter(diff => {
const modifiedRange = diff.modifiedEndLineNumber === 0
? new Range(modifiedDocument.lineAt(diff.modifiedStartLineNumber - 1).range.end, modifiedDocument.lineAt(diff.modifiedStartLineNumber).range.start)
: new Range(modifiedDocument.lineAt(diff.modifiedStartLineNumber - 1).range.start, modifiedDocument.lineAt(diff.modifiedEndLineNumber - 1).range.end);
return selections.every(selection => !selection.intersection(modifiedRange));
});
if (selectedDiffs.length === diffs.length) {
return;
}
const basename = path.basename(modifiedUri.fsPath);
const message = localize('confirm revert', "Are you sure you want to revert the selected changes in {0}?", basename);
const yes = localize('revert', "Revert Changes");
const pick = await window.showWarningMessage(message, { modal: true }, yes);
if (pick !== yes) {
return;
}
const result = applyLineChanges(originalDocument, modifiedDocument, selectedDiffs);
const edit = new WorkspaceEdit();
edit.replace(modifiedUri, new Range(new Position(0, 0), modifiedDocument.lineAt(modifiedDocument.lineCount - 1).range.end), result);
workspace.applyEdit(edit);
}
@command('git.unstage')
async unstage(...resourceStates: SourceControlResourceState[]): Promise<void> {
if (resourceStates.length === 0 || !(resourceStates[0].resourceUri instanceof Uri)) {
const resource = this.getSCMResource();
if (!resource) {
return;
}
resourceStates = [resource];
}
const resources = resourceStates
.filter(s => s instanceof Resource && s.resourceGroup instanceof IndexGroup) as Resource[];
if (!resources.length) {
return;
}
return await this.model.revertFiles(...resources);
}
@command('git.unstageAll')
async unstageAll(): Promise<void> {
return await this.model.revertFiles();
}
@command('git.unstageSelectedRanges', false, true)
async unstageSelectedRanges(diffs: LineChange[]): Promise<void> {
const textEditor = window.activeTextEditor;
if (!textEditor) {
return;
}
const modifiedDocument = textEditor.document;
const modifiedUri = modifiedDocument.uri;
if (modifiedUri.scheme !== 'git') {
return;
}
const { ref } = fromGitUri(modifiedUri);
if (ref !== '') {
return;
}
const originalUri = toGitUri(modifiedUri, 'HEAD');
const originalDocument = await workspace.openTextDocument(originalUri);
const selectedLines = toLineRanges(textEditor.selections, modifiedDocument);
const selectedDiffs = diffs
.map(diff => selectedLines.reduce<LineChange | null>((result, range) => result || intersectDiffWithRange(modifiedDocument, diff, range), null))
.filter(d => !!d) as LineChange[];
if (!selectedDiffs.length) {
return;
}
const invertedDiffs = selectedDiffs.map(invertLineChange);
const result = applyLineChanges(modifiedDocument, originalDocument, invertedDiffs);
await this.model.stage(modifiedUri, result);
}
@command('git.clean')
async clean(...resourceStates: SourceControlResourceState[]): Promise<void> {
if (resourceStates.length === 0 || !(resourceStates[0].resourceUri instanceof Uri)) {
const resource = this.getSCMResource();
if (!resource) {
return;
}
resourceStates = [resource];
}
const resources = resourceStates
.filter(s => s instanceof Resource && s.resourceGroup instanceof WorkingTreeGroup) as Resource[];
if (!resources.length) {
return;
}
const message = resources.length === 1
? localize('confirm discard', "Are you sure you want to discard changes in {0}?", path.basename(resources[0].resourceUri.fsPath))
: localize('confirm discard multiple', "Are you sure you want to discard changes in {0} files?", resources.length);
const yes = localize('discard', "Discard Changes");
const pick = await window.showWarningMessage(message, { modal: true }, yes);
if (pick !== yes) {
return;
}
await this.model.clean(...resources);
}
@command('git.cleanAll')
async cleanAll(): Promise<void> {
const message = localize('confirm discard all', "Are you sure you want to discard ALL changes? This is IRREVERSIBLE!");
const yes = localize('discardAll', "Discard ALL Changes");
const pick = await window.showWarningMessage(message, { modal: true }, yes);
if (pick !== yes) {
return;
}
await this.model.clean(...this.model.workingTreeGroup.resources);
}
private async smartCommit(
getCommitMessage: () => Promise<string | undefined>,
opts?: CommitOptions
): Promise<boolean> {
if (!opts) {
opts = { all: this.model.indexGroup.resources.length === 0 };
}
if (
// no changes
(this.model.indexGroup.resources.length === 0 && this.model.workingTreeGroup.resources.length === 0)
// or no staged changes and not `all`
|| (!opts.all && this.model.indexGroup.resources.length === 0)
) {
window.showInformationMessage(localize('no changes', "There are no changes to commit."));
return false;
}
const message = await getCommitMessage();
if (!message) {
// TODO@joao: show modal dialog to confirm empty message commit
return false;
}
await this.model.commit(message, opts);
return true;
}
private async commitWithAnyInput(opts?: CommitOptions): Promise<void> {
const message = scm.inputBox.value;
const getCommitMessage = async () => {
if (message) {
return message;
}
return await window.showInputBox({
placeHolder: localize('commit message', "Commit message"),
prompt: localize('provide commit message', "Please provide a commit message"),
ignoreFocusOut: true
});
};
const didCommit = await this.smartCommit(getCommitMessage, opts);
if (message && didCommit) {
scm.inputBox.value = await this.model.getCommitTemplate();
}
}
@command('git.commit')
async commit(): Promise<void> {
await this.commitWithAnyInput();
}
@command('git.commitWithInput')
async commitWithInput(): Promise<void> {
const didCommit = await this.smartCommit(async () => scm.inputBox.value);
if (didCommit) {
scm.inputBox.value = await this.model.getCommitTemplate();
}
}
@command('git.commitStaged')
async commitStaged(): Promise<void> {
await this.commitWithAnyInput({ all: false });
}
@command('git.commitStagedSigned')
async commitStagedSigned(): Promise<void> {
await this.commitWithAnyInput({ all: false, signoff: true });
}
@command('git.commitAll')
async commitAll(): Promise<void> {
await this.commitWithAnyInput({ all: true });
}
@command('git.commitAllSigned')
async commitAllSigned(): Promise<void> {
await this.commitWithAnyInput({ all: true, signoff: true });
}
@command('git.undoCommit')
async undoCommit(): Promise<void> {
const HEAD = this.model.HEAD;
if (!HEAD || !HEAD.commit) {
return;
}
const commit = await this.model.getCommit('HEAD');
await this.model.reset('HEAD~');
scm.inputBox.value = commit.message;
}
@command('git.checkout')
async checkout(treeish: string): Promise<void> {
if (typeof treeish === 'string') {
return await this.model.checkout(treeish);
}
const config = workspace.getConfiguration('git');
const checkoutType = config.get<string>('checkoutType') || 'all';
const includeTags = checkoutType === 'all' || checkoutType === 'tags';
const includeRemotes = checkoutType === 'all' || checkoutType === 'remote';
const heads = this.model.refs.filter(ref => ref.type === RefType.Head)
.map(ref => new CheckoutItem(ref));
const tags = (includeTags ? this.model.refs.filter(ref => ref.type === RefType.Tag) : [])
.map(ref => new CheckoutTagItem(ref));
const remoteHeads = (includeRemotes ? this.model.refs.filter(ref => ref.type === RefType.RemoteHead) : [])
.map(ref => new CheckoutRemoteHeadItem(ref));
const picks = [...heads, ...tags, ...remoteHeads];
const placeHolder = 'Select a ref to checkout';
const choice = await window.showQuickPick<CheckoutItem>(picks, { placeHolder });
if (!choice) {
return;
}
await choice.run(this.model);
}
@command('git.branch')
async branch(): Promise<void> {
const result = await window.showInputBox({
placeHolder: localize('branch name', "Branch name"),
prompt: localize('provide branch name', "Please provide a branch name"),
ignoreFocusOut: true
});
if (!result) {
return;
}
const name = result.replace(/^\.|\/\.|\.\.|~|\^|:|\/$|\.lock$|\.lock\/|\\|\*|\s|^\s*$|\.$/g, '-');
await this.model.branch(name);
}
@command('git.pull')
async pull(): Promise<void> {
const remotes = this.model.remotes;
if (remotes.length === 0) {
window.showWarningMessage(localize('no remotes to pull', "Your repository has no remotes configured to pull from."));
return;
}
await this.model.pull();
}
@command('git.pullRebase')
async pullRebase(): Promise<void> {
const remotes = this.model.remotes;
if (remotes.length === 0) {
window.showWarningMessage(localize('no remotes to pull', "Your repository has no remotes configured to pull from."));
return;
}
await this.model.pull(true);
}
@command('git.push')
async push(): Promise<void> {
const remotes = this.model.remotes;
if (remotes.length === 0) {
window.showWarningMessage(localize('no remotes to push', "Your repository has no remotes configured to push to."));
return;
}
await this.model.push();
}
@command('git.pushTo')
async pushTo(): Promise<void> {
const remotes = this.model.remotes;
if (remotes.length === 0) {
window.showWarningMessage(localize('no remotes to push', "Your repository has no remotes configured to push to."));
return;
}
if (!this.model.HEAD || !this.model.HEAD.name) {
window.showWarningMessage(localize('nobranch', "Please check out a branch to push to a remote."));
return;
}
const branchName = this.model.HEAD.name;
const picks = remotes.map(r => ({ label: r.name, description: r.url }));
const placeHolder = localize('pick remote', "Pick a remote to publish the branch '{0}' to:", branchName);
const pick = await window.showQuickPick(picks, { placeHolder });
if (!pick) {
return;
}
this.model.push(pick.label, branchName);
}
@command('git.sync')
async sync(): Promise<void> {
const HEAD = this.model.HEAD;
if (!HEAD || !HEAD.upstream) {
return;
}
const config = workspace.getConfiguration('git');
const shouldPrompt = config.get<boolean>('confirmSync') === true;
if (shouldPrompt) {
const message = localize('sync is unpredictable', "This action will push and pull commits to and from '{0}'.", HEAD.upstream);
const yes = localize('ok', "OK");
const neverAgain = localize('never again', "OK, Never Show Again");
const pick = await window.showWarningMessage(message, { modal: true }, yes, neverAgain);
if (pick === neverAgain) {
await config.update('confirmSync', false, true);
} else if (pick !== yes) {
return;
}
}
await this.model.sync();
}
@command('git.publish')
async publish(): Promise<void> {
const remotes = this.model.remotes;
if (remotes.length === 0) {
window.showWarningMessage(localize('no remotes to publish', "Your repository has no remotes configured to publish to."));
return;
}
const branchName = this.model.HEAD && this.model.HEAD.name || '';
const picks = this.model.remotes.map(r => r.name);
const placeHolder = localize('pick remote', "Pick a remote to publish the branch '{0}' to:", branchName);
const choice = await window.showQuickPick(picks, { placeHolder });
if (!choice) {
return;
}
await this.model.push(choice, branchName, { setUpstream: true });
}
@command('git.showOutput')
showOutput(): void {
this.outputChannel.show();
}
private createCommand(id: string, key: string, method: Function, skipModelCheck: boolean): (...args: any[]) => any {
const result = (...args) => {
if (!skipModelCheck && !this.model) {
window.showInformationMessage(localize('disabled', "Git is either disabled or not supported in this workspace"));
return;
}
this.telemetryReporter.sendTelemetryEvent('git.command', { command: id });
const result = Promise.resolve(method.apply(this, args));
return result.catch(async err => {
let message: string;
switch (err.gitErrorCode) {
case GitErrorCodes.DirtyWorkTree:
message = localize('clean repo', "Please clean your repository working tree before checkout.");
break;
case GitErrorCodes.PushRejected:
message = localize('cant push', "Can't push refs to remote. Run 'Pull' first to integrate your changes.");
break;
default:
const hint = (err.stderr || err.message || String(err))
.replace(/^error: /mi, '')
.replace(/^> husky.*$/mi, '')
.split(/[\r\n]/)
.filter(line => !!line)
[0];
message = hint
? localize('git error details', "Git: {0}", hint)
: localize('git error', "Git error");
break;
}
if (!message) {
console.error(err);
return;
}
const outputChannel = this.outputChannel as OutputChannel;
const openOutputChannelChoice = localize('open git log', "Open Git Log");
const choice = await window.showErrorMessage(message, openOutputChannelChoice);
if (choice === openOutputChannelChoice) {
outputChannel.show();
}
});
};
// patch this object, so people can call methods directly
this[key] = result;
return result;
}
private getSCMResource(uri?: Uri): Resource | undefined {
uri = uri ? uri : window.activeTextEditor && window.activeTextEditor.document.uri;
if (!uri) {
return undefined;
}
if (uri.scheme === 'git') {
const { path } = fromGitUri(uri);
uri = Uri.file(path);
}
if (uri.scheme === 'file') {
const uriString = uri.toString();
return this.model.workingTreeGroup.resources.filter(r => r.resourceUri.toString() === uriString)[0]
|| this.model.indexGroup.resources.filter(r => r.resourceUri.toString() === uriString)[0];
}
}
dispose(): void {
this.disposables.forEach(d => d.dispose());
}
} | the_stack |
import {
Item,
Collection,
Agile,
StateObserver,
EnhancedState,
CollectionPersistent,
} from '../../../src';
import { LogMock } from '../../helper/logMock';
describe('Item Tests', () => {
interface ItemInterface {
id: string;
name: string;
}
let dummyAgile: Agile;
let dummyCollection: Collection<ItemInterface>;
beforeEach(() => {
LogMock.mockLogs();
dummyAgile = new Agile();
dummyCollection = new Collection<ItemInterface>(dummyAgile);
jest.spyOn(Item.prototype, 'addRebuildGroupThatIncludeItemKeySideEffect');
jest.clearAllMocks();
});
it('should create Item (default config)', () => {
// Overwrite addRebuildGroupThatIncludeItemKeySideEffect once to not call it
jest
.spyOn(Item.prototype, 'addRebuildGroupThatIncludeItemKeySideEffect')
.mockReturnValueOnce(undefined);
const dummyData = { id: 'dummyId', name: 'dummyName' };
const item = new Item(dummyCollection, dummyData);
expect(item.collection()).toBe(dummyCollection);
expect(
item.addRebuildGroupThatIncludeItemKeySideEffect
).toHaveBeenCalledWith('dummyId');
expect(item._key).toBe(dummyData[dummyCollection.config.primaryKey]);
expect(item.isSet).toBeFalsy();
expect(item.isPlaceholder).toBeFalsy();
expect(item.initialStateValue).toStrictEqual(dummyData);
expect(item._value).toStrictEqual(dummyData);
expect(item.previousStateValue).toStrictEqual(dummyData);
expect(item.nextStateValue).toStrictEqual(dummyData);
expect(item.observers['value']).toBeInstanceOf(StateObserver);
expect(Array.from(item.observers['value'].dependents)).toStrictEqual([]);
expect(item.observers['value'].key).toBe(
dummyData[dummyCollection.config.primaryKey]
);
expect(item.sideEffects).toStrictEqual({});
expect(item.computeValueMethod).toBeUndefined();
expect(item.computeExistsMethod).toBeInstanceOf(Function);
expect(item.isPersisted).toBeFalsy();
expect(item.persistent).toBeUndefined();
expect(item.selectedBy.size).toBe(0);
});
it('should create Item (specific config)', () => {
// Overwrite addRebuildGroupThatIncludeItemKeySideEffect once to not call it
jest
.spyOn(Item.prototype, 'addRebuildGroupThatIncludeItemKeySideEffect')
.mockReturnValueOnce(undefined);
const dummyData = { id: 'dummyId', name: 'dummyName' };
const item = new Item(dummyCollection, dummyData, {
isPlaceholder: true,
});
expect(item.collection()).toBe(dummyCollection);
expect(
item.addRebuildGroupThatIncludeItemKeySideEffect
).toHaveBeenCalledWith('dummyId');
// Check if State was called with correct parameters
expect(item._key).toBe(dummyData[dummyCollection.config.primaryKey]);
expect(item.isSet).toBeFalsy();
expect(item.isPlaceholder).toBeTruthy();
expect(item.initialStateValue).toStrictEqual(dummyData);
expect(item._value).toStrictEqual(dummyData);
expect(item.previousStateValue).toStrictEqual(dummyData);
expect(item.nextStateValue).toStrictEqual(dummyData);
expect(item.observers['value']).toBeInstanceOf(StateObserver);
expect(Array.from(item.observers['value'].dependents)).toStrictEqual([]);
expect(item.observers['value'].key).toBe(
dummyData[dummyCollection.config.primaryKey]
);
expect(item.sideEffects).toStrictEqual({});
expect(item.computeValueMethod).toBeUndefined();
expect(item.computeExistsMethod).toBeInstanceOf(Function);
expect(item.isPersisted).toBeFalsy();
expect(item.persistent).toBeUndefined();
expect(item.selectedBy.size).toBe(0);
});
it("should create Item and shouldn't add rebuild Group side effect to it if no itemKey was provided (default config)", () => {
// Overwrite addRebuildGroupThatIncludeItemKeySideEffect once to not call it
jest
.spyOn(Item.prototype, 'addRebuildGroupThatIncludeItemKeySideEffect')
.mockReturnValueOnce(undefined);
const dummyData = { name: 'dummyName' };
const item = new Item(dummyCollection, dummyData as any);
expect(item.collection()).toBe(dummyCollection);
expect(
item.addRebuildGroupThatIncludeItemKeySideEffect
).not.toHaveBeenCalled();
// Check if State was called with correct parameters
expect(item._key).toBeUndefined();
expect(item.isSet).toBeFalsy();
expect(item.isPlaceholder).toBeFalsy();
expect(item.initialStateValue).toStrictEqual(dummyData);
expect(item._value).toStrictEqual(dummyData);
expect(item.previousStateValue).toStrictEqual(dummyData);
expect(item.nextStateValue).toStrictEqual(dummyData);
expect(item.observers['value']).toBeInstanceOf(StateObserver);
expect(Array.from(item.observers['value'].dependents)).toStrictEqual([]);
expect(item.observers['value'].key).toBe(
dummyData[dummyCollection.config.primaryKey]
);
expect(item.sideEffects).toStrictEqual({});
expect(item.computeValueMethod).toBeUndefined();
expect(item.computeExistsMethod).toBeInstanceOf(Function);
expect(item.isPersisted).toBeFalsy();
expect(item.persistent).toBeUndefined();
expect(item.selectedBy.size).toBe(0);
});
describe('Item Function Tests', () => {
let item: Item<ItemInterface>;
beforeEach(() => {
item = new Item(dummyCollection, { id: 'dummyId', name: 'dummyName' });
});
describe('setKey function tests', () => {
beforeEach(() => {
item.removeSideEffect = jest.fn();
item.patch = jest.fn();
jest.spyOn(EnhancedState.prototype, 'setKey');
});
it('should call State setKey, add rebuildGroup sideEffect to Item and patch newItemKey into Item (default config)', () => {
item.setKey('myNewKey');
expect(EnhancedState.prototype.setKey).toHaveBeenCalledWith('myNewKey');
expect(item.removeSideEffect).toHaveBeenCalledWith(
Item.updateGroupSideEffectKey
);
expect(
item.addRebuildGroupThatIncludeItemKeySideEffect
).toHaveBeenCalledWith('myNewKey');
expect(item.patch).toHaveBeenCalledWith(
{
[dummyCollection.config.primaryKey]: 'myNewKey',
},
{
sideEffects: {
enabled: true,
exclude: [],
},
background: false,
force: false,
storage: true,
overwrite: false,
}
);
});
it('should call State setKey, add rebuildGroup sideEffect to Item and patch newItemKey into Item (specific config)', () => {
item.setKey('myNewKey', {
sideEffects: {
enabled: false,
},
background: true,
force: true,
});
expect(EnhancedState.prototype.setKey).toHaveBeenCalledWith('myNewKey');
expect(item.removeSideEffect).toHaveBeenCalledWith(
Item.updateGroupSideEffectKey
);
expect(
item.addRebuildGroupThatIncludeItemKeySideEffect
).toHaveBeenCalledWith('myNewKey');
expect(item.patch).toHaveBeenCalledWith(
{
[dummyCollection.config.primaryKey]: 'myNewKey',
},
{
sideEffects: {
enabled: false,
},
background: true,
force: true,
storage: true,
overwrite: false,
}
);
});
});
describe('persist function tests', () => {
beforeEach(() => {
jest.spyOn(EnhancedState.prototype, 'persist');
});
it('should persist Item with formatted itemKey (default config)', () => {
item.persist();
expect(EnhancedState.prototype.persist).toHaveBeenCalledWith({
key: CollectionPersistent.getItemStorageKey(
item._key,
dummyCollection._key
),
followCollectionPersistKeyPattern: true, // Not required but passed for simplicity
});
});
it('should persist Item with formatted key (specific config)', () => {
item.persist({
key: 'specificKey',
loadValue: false,
storageKeys: ['test1', 'test2'],
defaultStorageKey: 'test1',
});
expect(EnhancedState.prototype.persist).toHaveBeenCalledWith({
key: CollectionPersistent.getItemStorageKey(
'specificKey',
dummyCollection._key
),
loadValue: false,
storageKeys: ['test1', 'test2'],
defaultStorageKey: 'test1',
followCollectionPersistKeyPattern: true, // Not required but passed for simplicity
});
});
it('should persist Item with itemKey (config.followCollectionPersistKeyPattern = false)', () => {
item.persist({ followCollectionPersistKeyPattern: false });
expect(EnhancedState.prototype.persist).toHaveBeenCalledWith({
key: item._key,
followCollectionPersistKeyPattern: false, // Not required but passed for simplicity
});
});
it('should persist Item with specified key (config.followCollectionPersistKeyPattern = false)', () => {
item.persist({
key: 'specificKey',
followCollectionPersistKeyPattern: false,
});
expect(EnhancedState.prototype.persist).toHaveBeenCalledWith({
key: 'specificKey',
followCollectionPersistKeyPattern: false, // Not required but passed for simplicity
});
});
});
describe('addRebuildGroupThatIncludeItemKeySideEffect function tests', () => {
beforeEach(() => {
dummyCollection.rebuildGroupsThatIncludeItemKey = jest.fn();
jest.spyOn(item, 'addSideEffect');
});
it('should add rebuildGroupThatIncludeItemKey sideEffect to Item', () => {
item.addRebuildGroupThatIncludeItemKeySideEffect('itemKey');
expect(
item.addSideEffect
).toHaveBeenCalledWith(
Item.updateGroupSideEffectKey,
expect.any(Function),
{ weight: 100 }
);
});
describe('test added sideEffect called Item.updateGroupSideEffectKey', () => {
beforeEach(() => {
dummyCollection.rebuildGroupsThatIncludeItemKey = jest.fn();
});
it('should call rebuildGroupThatIncludeItemKey', () => {
item.addRebuildGroupThatIncludeItemKeySideEffect('itemKey');
item.sideEffects[Item.updateGroupSideEffectKey].callback(item, {
dummy: 'property',
});
expect(
dummyCollection.rebuildGroupsThatIncludeItemKey
).toHaveBeenCalledWith('itemKey', { dummy: 'property' });
});
});
});
});
}); | the_stack |
import * as React from "react";
import * as ReactDOM from "react-dom";
import SplitPane from "react-split-pane";
import { ConsoleComponent, FONT_INFO } from "./consoleComponent";
import { escaped } from "./vscodeComm";
import "./style.css";
import spinner from "./spinner.svg";
import {
IEvaluateMessage,
nextMessageSeq,
sendRequestToClient,
eventToHandler,
IOutputEvent,
sendEventToClient,
requestToHandler,
codeAsHtml,
} from "./vscodeComm";
import { configureMonacoLanguage } from "./monacoConf";
declare const initialState: object; // Set by rfinteractive.ts (in _getHtmlForWebview).
interface IExceptionInfo {
type: string;
description: string;
traceback: string;
}
interface ICellInfo {
id: number;
type: "code" | "stdout" | "stderr" | "info" | "exception";
cellCode: string;
cellCodeHtml: string;
exceptionInfo?: IExceptionInfo;
}
interface IJsonInfo {
"target"?: string; //the target robot.yaml (optional)
"path"?: string; //the path (used for cwd)
"sys.version"?: string;
"sys.executable"?: string;
"robot.version"?: string;
"initialization.finished"?: boolean; //received when the initialization should be considered complete.
}
interface IJsonInfoContainer {
jsonInfo: IJsonInfo;
}
interface IShowHelpContainer {
showHelp: boolean;
}
interface IHelpComponent extends IJsonInfoContainer, IShowHelpContainer {
handleToggleHelpContent: () => Promise<void>;
}
interface ICellsContainer {
cells: ICellInfo[];
jsonInfo: IJsonInfo;
}
interface IAppState extends ICellsContainer, IShowHelpContainer {
showProgress: number;
}
interface IHistoryProps extends ICellsContainer {
showProgress: number;
}
interface ICellProps {
cellInfo: ICellInfo;
}
interface IExceptionCellState {
showTraceback: boolean;
}
interface IEvaluateRequest {
uri: string;
code: string;
}
class CellComponent extends React.Component<ICellProps> {
render() {
let className = "cell_" + this.props.cellInfo.type;
if (this.props.cellInfo.cellCodeHtml) {
return (
<div className={className} dangerouslySetInnerHTML={{ __html: this.props.cellInfo.cellCodeHtml }}></div>
);
} else {
return (
<div className={className}>
<pre className="cell_output_content">{this.props.cellInfo.cellCode}</pre>
</div>
);
}
}
}
class ExceptionCellComponent extends React.Component<ICellProps, IExceptionCellState> {
constructor(props) {
super(props);
this.state = {
showTraceback: false,
};
this.onClick = this.onClick.bind(this);
}
onClick(e) {
this.setState((prevState, props) => {
return { "showTraceback": !prevState.showTraceback };
});
}
render() {
let exceptionInfo = this.props.cellInfo.exceptionInfo;
let traceback: string = exceptionInfo.traceback;
let lines: string[] = traceback.split(/\r?\n/);
let tracebackContent = "";
for (const line of lines) {
// TODO: Create links for traceback (group1 = file, group2 = line)
// Regexp: File\s\"([^"]+)\",\s+line\s+(\d+),\s+
tracebackContent += escaped(line);
tracebackContent += "<br/>";
}
let showLabel = "[+]";
if (this.state.showTraceback) {
showLabel = "[-]";
}
return (
<div>
<div className="cell_exception_title">
<span className="cell_exception_error_bt">Error</span>
{exceptionInfo.description}
<a href="#" onClick={this.onClick}>
{showLabel}
</a>
</div>
{this.state.showTraceback ? (
<div className="cell_exception">
<pre
className="cell_output_content"
dangerouslySetInnerHTML={{ __html: tracebackContent }}
></pre>
</div>
) : undefined}
</div>
);
}
}
let _lastCellId: number = 0;
function nextCellId(): number {
_lastCellId += 1;
return _lastCellId;
}
class HelpComponent extends React.Component<IHelpComponent> {
render() {
let helpContentClassName = "hidden";
let showHelp = "More";
if (this.props.showHelp) {
helpContentClassName = "";
showHelp = "Less";
}
return (
<div className="help">
<a href="#" className="toggleHelp" onClick={this.props.handleToggleHelpContent}>
{showHelp}
</a>
<div>
<p>INTERACTIVE CONSOLE (ROBOT FRAMEWORK {this.props.jsonInfo["robot.version"]}) </p>
</div>
<div className={helpContentClassName}>
<p>
Interactive Console is a REPL for running Robot Framework Code. <br />
Try it out by running:{" "}
<span className="helpExample">Log To Console Hello World</span> <br />
<a href="https://github.com/robocorp/robotframework-lsp/blob/master/robotframework-ls/docs/faq.md#how-to-use-the-interactive-console">
Learn more »
</a>
</p>
<div>
Notes:
<div>
<ul>
<li>
To use Keywords from Libraries or Resources run first the related{" "}
<span className="sectionHeader">*** Settings ***</span> block which imports the
needed Library or Resource in the Interactive Console.
</li>
<li>
Start new blocks with a header row, such as{" "}
<span className="sectionHeader">*** Keywords ***</span>.
</li>
</ul>
</div>
</div>
<div>
Keyboard shortcuts:
<div>
<ul>
<li>Shift-Enter - New Line</li>
<li>Enter - Run Code</li>
<li>Up/Down Arrow - Command history</li>
</ul>
</div>
</div>
<div className="helpExample">Python {this.props.jsonInfo["sys.version"]}</div>
<div className="helpExample">({this.props.jsonInfo["sys.executable"]})</div>
{this.props.jsonInfo["target"] ? (
<div className="helpExample">Environment - {this.props.jsonInfo["target"]}</div>
) : undefined}
{this.props.jsonInfo["path"] ? (
<div className="helpExample">
Target - {this.props.jsonInfo["path"]}
</div>
) : undefined}
</div>
</div>
);
}
}
class HistoryComponent extends React.Component<IHistoryProps> {
progressRef: any;
constructor(props) {
super(props);
this.progressRef = React.createRef();
}
render() {
const cells = this.props.cells.map((cellInfo: ICellInfo) =>
cellInfo.type === "exception" ? (
<ExceptionCellComponent key={cellInfo.id} cellInfo={cellInfo} />
) : (
<CellComponent key={cellInfo.id} cellInfo={cellInfo} />
)
);
return (
<div className="history">
{cells}
{this.props.showProgress ? (
<img src={spinner} width="50px;" height="50px;" ref={this.progressRef} />
) : null}
</div>
);
}
componentDidUpdate() {
if (this.props.showProgress) {
let curr = this.progressRef.current;
if (curr) {
let container = curr.closest(".Pane1");
if (container.scrollHeight > container.clientHeight) {
curr.scrollIntoView({ behavior: "smooth" });
}
}
}
}
}
function createExceptionCell(exceptionInfo: IExceptionInfo): ICellInfo {
let newCell: ICellInfo = {
id: nextCellId(),
type: "exception",
cellCode: undefined,
cellCodeHtml: undefined,
exceptionInfo: exceptionInfo,
};
return newCell;
}
class AppComponent extends React.Component<object, IAppState> {
constructor(props) {
super(props);
let initialShowHelp = true;
if (initialState !== undefined) {
if (initialState["showHelp"] !== undefined) {
initialShowHelp = initialState["showHelp"];
}
}
this.state = {
cells: [],
showProgress: 0,
jsonInfo: {},
showHelp: initialShowHelp,
};
this.handleEvaluate = this.handleEvaluate.bind(this);
this.handleToggleHelpContent = this.handleToggleHelpContent.bind(this);
eventToHandler["output"] = this.onEventOutput.bind(this);
requestToHandler["evaluate"] = this.onRequestEvaluate.bind(this);
sendEventToClient({
type: "event",
seq: nextMessageSeq(),
event: "initialized",
});
}
async onEventOutput(msg: IOutputEvent) {
this.setState((prevState, props) => {
if (msg.category == "json_info") {
// json_info are internal messages received to provide some information to the
// console.
let newJsonInfo: IJsonInfo = JSON.parse(msg.output);
let jsonInfo: IJsonInfo = { ...prevState.jsonInfo, ...newJsonInfo };
return { "jsonInfo": jsonInfo, "cells": prevState.cells };
}
if (msg.category == "exception") {
let exceptionInfo: IExceptionInfo = JSON.parse(msg.output);
return {
"jsonInfo": prevState.jsonInfo,
"cells": prevState.cells.concat([createExceptionCell(exceptionInfo)]),
};
}
if (!prevState.jsonInfo["initialization.finished"]) {
return; // Ignore any output until the initialization did actually finish
}
let type: "stdout" | "stderr" | "info" | "exception" = "stdout";
switch (msg.category) {
case "stderr":
case "stdout":
case "info":
type = msg.category;
}
if (prevState.cells.length > 0) {
// Let's see if it should be joined to the last one...
let lastCell: ICellInfo = prevState.cells[prevState.cells.length - 1];
if (lastCell.type == type) {
lastCell.cellCode += msg.output;
return {
"jsonInfo": prevState.jsonInfo,
"cells": prevState.cells,
};
}
}
let newCell: ICellInfo = {
id: nextCellId(),
type: type,
cellCode: msg.output,
cellCodeHtml: undefined,
};
return {
"jsonInfo": prevState.jsonInfo,
"cells": prevState.cells.concat([newCell]),
};
});
}
// i.e.: VSCode can send something to be evaluated in the webview.
async onRequestEvaluate(msg: IEvaluateRequest) {
let code = msg["body"].code;
await this.handleEvaluate(code, await codeAsHtml(code));
}
async handleToggleHelpContent() {
this.setState((prevState, props) => {
let msg: IEvaluateMessage = {
"type": "request",
"command": "persistState",
"seq": nextMessageSeq(),
"arguments": {
"state": {
"showHelp": !prevState.showHelp,
},
},
};
sendRequestToClient(msg);
return {
"showHelp": !prevState.showHelp,
};
});
}
async handleEvaluate(code: string, codeAsHtml: string) {
if (!code) {
return;
}
this.setState((prevState, props) => {
let newCell: ICellInfo = {
id: nextCellId(),
type: "code",
cellCode: code,
cellCodeHtml: codeAsHtml,
};
return {
"cells": prevState.cells.concat([newCell]),
"showProgress": prevState.showProgress + 1,
};
});
let msg: IEvaluateMessage = {
"type": "request",
"command": "evaluate",
"seq": nextMessageSeq(),
"arguments": {
"expression": code,
"context": "repl",
},
};
let response = await sendRequestToClient(msg);
console.log("response", response);
this.setState((prevState, props) => {
return {
"showProgress": prevState.showProgress - 1,
};
});
}
render() {
return (
<SplitPane split="horizontal" minSize={50} defaultSize={50} allowResize={true} primary="second">
<div>
<HelpComponent
jsonInfo={this.state.jsonInfo}
showHelp={this.state.showHelp}
handleToggleHelpContent={this.handleToggleHelpContent}
/>
<HistoryComponent
cells={this.state.cells}
jsonInfo={this.state.jsonInfo}
showProgress={this.state.showProgress}
/>
</div>
<ConsoleComponent handleEvaluate={this.handleEvaluate} />
</SplitPane>
);
}
}
// Create our initial div and render everything inside it.
const e = document.createElement("div");
document.body.appendChild(e);
configureMonacoLanguage();
ReactDOM.render(<AppComponent />, e); | the_stack |
import {
AfterViewInit,
ChangeDetectionStrategy,
Component,
ElementRef,
Output,
EventEmitter,
HostBinding,
Input,
Optional,
OnInit,
OnDestroy
} from '@angular/core';
import { ArgumentHelper } from '../utils/argument.helper';
import { SohoTreeService } from './soho-tree.service';
/**
* Valid list of tree types.
*/
export type SohoTreeType = 'auto' | 'content-only';
/**
* Angular Wrapper for the Soho Tree Component.
*
* This component searches for an unordered list (ul) with the attribute
* 'soho-tree' in the parent's DOM tree, initialising those found with
* the SoHo tree control.
*
* The data is provided either by the content (li elements), a dataset
* input or an implementation of the TreeService interface, by specifying
* an implementation on the hosting component, e.g.
*
* providers: [ provide: TreeService, useClass: TreeDemoService} ]
*
* @todo Content based version does not work due to lack of TreeNode.
* @todo Complete interface definition
*/
@Component({
selector: 'ul[soho-tree]', // eslint-disable-line
template: '<ng-content></ng-content>',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class SohoTreeComponent implements AfterViewInit, OnInit, OnDestroy {
// -------------------------------------------
// Soho Tree Types
// -------------------------------------------
// "auto" where nodes are obtained from an injected service (if defined) or via the Inputs if not.
public static AUTO: SohoTreeType = 'auto';
// 'content-only' where elements are used.
public static CONTENT_ONLY: SohoTreeType = 'content-only';
// -------------------------------------------
// Component Inputs
// -------------------------------------------
// The array of root tree nodes to display.
@Input() set dataset(dataset: SohoTreeNode[] | undefined) {
// @todo this is not fully working as the tree control does not
// replace the contents but looks to merge it.
this.options.dataset = dataset;
if (this.tree) {
this.tree?.loadData((dataset as any));
}
}
get dataset(): SohoTreeNode[] | undefined {
// If the Soho control has been created, then the dataset
// in the settings object will contain the rows currently
// on display.
if (this.tree) {
return (this.tree.settings as any).dataset;
}
// ... we've been called before the component has completed
// initialisation, so no data has been set (or potentially
// retrieved from a service), so the only option is the
// Input dataset, which may be undefined.
return this.options.dataset || [];
}
/** Defines the source type of the tree. */
// eslint-disable-next-line @angular-eslint/no-input-rename
@Input('soho-tree') set sohoTree(treeType: SohoTreeType) {
this.treeType = treeType ? treeType : SohoTreeComponent.AUTO;
}
/** Is the tree selectable? */
@Input() set selectable(selectable: SohoTreeSelectable | undefined) {
this.options.selectable = selectable;
if (this.tree) {
(this.tree.settings as any).selectable = selectable;
// @todo - make tree updatable when settings change,
// this.tree?.updated();
}
}
get selectable(): SohoTreeSelectable | undefined {
if (this.tree) {
return (this.tree.settings as any).selectable;
}
return this.options.selectable;
}
/** Show/hide selection checkboxe */
@Input() set hideCheckboxes(hideCheckboxes: boolean | undefined) {
this.options.hideCheckboxes = hideCheckboxes;
if (this.tree) {
(this.tree.settings as any).hideCheckboxes = hideCheckboxes;
}
}
@Input() set menuId(menuId: string | undefined) {
this.options.menuId = menuId;
if (this.tree) {
(this.tree.settings as any).menuId = menuId;
}
}
/** Set the source field, when not using a service or pre-defined data. */
@Input() set source(value: SohoTreeSourceFunction) {
this.options.source = value;
if (this.tree) {
(this.tree.settings as any).source = value;
// @todo - make tree updatable when settings change,
// this.tree?.updated();
}
}
/** Show icon on node opened */
@Input() set folderIconOpen(folderIconOpen: string) {
this.options.folderIconOpen = folderIconOpen;
if (this.tree) {
(this.tree.settings as any).folderIconOpen = folderIconOpen;
}
}
/** Show icon on node closed */
@Input() set folderIconClosed(folderIconClosed: string) {
this.options.folderIconClosed = folderIconClosed;
if (this.tree) {
(this.tree.settings as any).folderIconClosed = folderIconClosed;
}
}
// -------------------------------------------
// Component Output
// -------------------------------------------
/**
* This event is fired when a node is expanded, the SohoTreeNode
* expanded is passed in the argument passed to the handler.
*/
@Output() expand = new EventEmitter<SohoTreeEvent>();
/**
* This event is fired when a node is collapsed, the SohoTreeNode
* collapsed is passed in the argument passed to the handler.
*/
@Output() collapse = new EventEmitter<SohoTreeEvent>();
/**
* This event is fired when a node is selected, the SohoTreeNode
* selected is passed in the argument passed to the handler.
* */
@Output() selected = new EventEmitter<SohoTreeEvent>();
/**
* This event is fired when right clicking a node.
* */
// @todo fix the use of this native attribute
// eslint-disable-next-line @angular-eslint/no-output-native
@Output() contextmenu = new EventEmitter<SohoTreeEvent>();
/**
* This event is fired when a node is unselected, the SohoTreeNode
* unselected is passed in the argument passed to the handler.
* */
@Output() unselected = new EventEmitter<SohoTreeEvent>();
@Output() sortstart = new EventEmitter<SohoTreeEvent>();
@Output() sortend = new EventEmitter<SohoTreeEvent>();
/**
* This event is fired when context menu is selected, the SohoTreeNode
* selected is passed in the argument passed to the handler.
* */
@Output() menuselect = new EventEmitter<SohoTreeEvent>();
/**
* This event is fired on context menu opening, the SohoTreeNode
* selected is passed in the argument passed to the handler.
* */
@Output() menuopen = new EventEmitter<SohoTreeEvent>();
// -------------------------------------------
// Host Bindings
// -------------------------------------------
// Set the enable / disabled class (not working)
@HostBinding('class.is-disabled') isDisabled = false;
// Set the appropriate SoHo class for a tree.
@HostBinding('class.tree') treeClass = true;
// Set the role.
@HostBinding('attr.role') treeRole = 'tree';
// -------------------------------------------
// Private Member Data
// -------------------------------------------
/** Reference to the jQuery control. */
private jQueryElement?: JQuery;
/** Reference to the SoHo tree control api. */
private tree?: SohoTreeStatic | null;
/** The tree's type. */
private treeType?: SohoTreeType;
/** An internal options object that gets updated by using the component's Inputs(). */
options: SohoTreeOptions = {};
/**
* Constructor.
*
* @param elementRef - the element matching this directive.
* @param treeService - service for obtaining data (optional)
*/
constructor(
private elementRef: ElementRef,
@Optional() private treeService: SohoTreeService) {
}
// -------------------------------------------
// Public API
// -------------------------------------------
/**
* Resets the data display to the default provided by the service,
* that is by calling getRootNodes.
*
* The alternative is to set the dataset property, which
* has the same affect but allows the client to specify
* the nodes.
*
* This method is only applicable when the service is defined,
* but will not fail if one is not set.
*/
public reset() {
if (this.treeType !== SohoTreeComponent.CONTENT_ONLY && this.treeService) {
this.treeService.getRootTreeNodes()
.subscribe((dataset: SohoTreeNode[]) => this.dataset = dataset);
}
}
/** Enable the tree */
public enable(): void {
this.isDisabled = false;
if (this.tree) {
this.tree?.enable();
}
}
/** Disables the tree from reacting to events. */
public disable(): void {
this.isDisabled = true;
if (this.tree) {
this.tree?.disable();
}
}
public setFocus(node: SohoTreeNode) {
ArgumentHelper.checkNotNull('node', node);
this.tree?.setFocus(node);
}
public disableNode(node: SohoTreeNode) {
ArgumentHelper.checkNotNull('node', node);
node.disabled = true;
this.tree?.updateNode(node);
}
public enableNode(node: SohoTreeNode): void {
ArgumentHelper.checkNotNull('node', node);
node.disabled = false;
this.tree?.updateNode(node);
}
/**
* Updates the note with the information in the given SohoTreeNode.
*
* @parm node the tree node; must not be null.
*/
public updateNode(node: SohoTreeNode): void {
ArgumentHelper.checkNotNull('node', node);
this.tree?.updateNode(node);
}
/**
* Expands all the loaded tree nodes.
*
* Note: this does not load additional nodes.
*/
public expandAll() {
if (this.tree) {
this.tree?.expandAll();
}
}
/**
* Collapse all the tree nodes.
*/
public collapseAll() {
if (this.tree) {
this.tree?.collapseAll();
}
}
/**
* Remove the given node.
*/
public removeNode(node: SohoTreeNode) {
if (this.tree) {
this.tree?.removeNode(node);
}
}
/**
* Preserves all nodes' enablement states in the Tree component
*/
public preserveEnablementState() {
if (this.tree) {
return this.tree?.preserveEnablementState();
}
}
/**
* Restores all nodes' original enablement states in the Tree component
*/
public restoreEnablementState() {
if (this.tree) {
this.tree?.restoreEnablementState();
}
}
/**
* Set the selected note based in the id of the node. If the node
* does not exist an exception is thrown.
*/
public selectNode(id: string, focus = true) {
ArgumentHelper.checkNotEmpty('id', id);
const treeNode: undefined | SohoTreeNode = this.tree?.findById(id);
if (treeNode && treeNode.node) {
this.tree?.selectNode(treeNode.node, focus);
} else {
throw Error(`Node ${id} does not exist`);
}
}
/**
* Set the selected note based in the id of the node. If the node
* does not exist an exception is thrown.
*/
public unSelectedNode(id: string, focus = false) {
ArgumentHelper.checkNotEmpty('id', id);
const treeNode: SohoTreeNode = (this.tree as any).findById(id);
if (treeNode && treeNode.node) {
(this.tree as any).unSelectedNode(treeNode.node, focus);
} else {
throw Error(`Node ${id} does not exist`);
}
}
/**
* Returns a list of selected tree nodes, or an
* empty array if the tree has not been initialised
* yet.
*/
public getSelectedNodes(): SohoTreeNode[] {
const result: SohoTreeNode[] = [];
if (this.tree) {
// It would be good if the tree widget had a method that returned
// tree nodes rather then an intermediate wrapper, but to clean up
// the api we dispose of the extra information here.
this.tree?.getSelectedNodes().forEach(
(n) => {
result.push(n.data);
}
);
}
return result;
}
/**
* Adds a node to the tree.
*/
public addNode(treeNode: SohoTreeNode, location: any = 'bottom', isBeforeOrAfter = '') {
ArgumentHelper.checkNotNull('treeNode', treeNode);
this.tree?.addNode(treeNode, location, isBeforeOrAfter);
}
/**
* Find the tree node for the given identifier (id).
*/
public findById(id: string): SohoTreeNode {
ArgumentHelper.checkNotEmpty('id', id);
return (this.tree as any).findById(id);
}
/**
* Toggles open/closed state of the given tree node.
*/
public toggleNode(node: SohoTreeNode) {
ArgumentHelper.checkNotNull('node', node);
ArgumentHelper.checkNotNull('node.node', node.node);
this.tree?.toggleNode((node.node as any));
}
// -------------------------------------------
// Event Handlers
// -------------------------------------------
/**
* Handle a request to load the children of the specified node.
*
* event - the tree event used to determine which node to load
* response - function used to return the children
*/
private onDataRequest(event: SohoTreeEvent, response: SohoTreeResponseFunction) {
const node = event.data;
this.treeService.getTreeNodes(node)
.subscribe((children: SohoTreeNode[]) => {
response(children);
});
}
// ------------------------------------------
// Lifecycle Events
// ------------------------------------------
ngOnInit() {
}
ngAfterViewInit() {
// Wrap the "unordered list" element in a jQuery selector.
this.jQueryElement = jQuery(this.elementRef.nativeElement);
// Ensure the source is set when a service is defined.
if (!this.options.dataset && !this.options.source && this.treeService) {
this.options.source =
(args: SohoTreeEvent, response: SohoTreeResponseFunction) => this.onDataRequest(args, response);
}
// Initialise the Soho control.
this.jQueryElement.tree(this.options);
// Once the control is initialised, extract the control
// plug-in from the element. The element name is
// defined by the plug-in, but in this case it is 'tree'.
this.tree = this.jQueryElement.data('tree');
// Preload from the service if specified (unless data already provided).
if (this.treeType !== SohoTreeComponent.CONTENT_ONLY && !this.options.dataset && this.treeService) {
// ... bootstrap the root nodes ...
this.treeService.getRootTreeNodes()
.subscribe((dataset: SohoTreeNode[]) => this.dataset = dataset);
}
// Initialize any event handlers.
this.jQueryElement
.on('contextmenu', (_e: JQuery.TriggeredEvent, args: SohoTreeEvent) => this.contextmenu?.next(args))
.on('selected', (_e: JQuery.TriggeredEvent, args: SohoTreeEvent) => this.selected.next(args))
.on('unselected', (_e: JQuery.TriggeredEvent, args: SohoTreeEvent) => this.unselected.next(args))
.on('expand', (_e: JQuery.TriggeredEvent, args: SohoTreeEvent) => this.expand.next(args))
.on('collapse', (_e: JQuery.TriggeredEvent, args: SohoTreeEvent) => this.collapse.next(args))
.on('sortstart', (_e: JQuery.TriggeredEvent, args: SohoTreeEvent) => this.sortstart.next(args))
.on('sortend', (_e: JQuery.TriggeredEvent, args: SohoTreeEvent) => this.sortend.next(args))
.on('menuselect', (_e: JQuery.Event, args: SohoTreeEvent) => this.menuselect.next(args))
.on('menuopen', (_e: JQuery.Event, args: SohoTreeEvent) => this.menuopen.next(args));
}
ngOnDestroy() {
if (this.tree) {
this.tree?.destroy();
this.tree = null;
}
}
} | the_stack |
import { TimeService } from '@core/services/time.service';
import { deepClone, isDefined, isNumeric, isUndefined } from '@app/core/utils';
import * as moment_ from 'moment';
import * as momentTz from 'moment-timezone';
const moment = moment_;
export const SECOND = 1000;
export const MINUTE = 60 * SECOND;
export const HOUR = 60 * MINUTE;
export const DAY = 24 * HOUR;
export const WEEK = 7 * DAY;
export const YEAR = DAY * 365;
export type ComparisonDuration = moment_.unitOfTime.DurationConstructor | 'previousInterval' | 'customInterval';
export enum TimewindowType {
REALTIME,
HISTORY
}
export enum RealtimeWindowType {
LAST_INTERVAL,
INTERVAL
}
export enum HistoryWindowType {
LAST_INTERVAL,
FIXED,
INTERVAL
}
export interface IntervalWindow {
interval?: number;
timewindowMs?: number;
quickInterval?: QuickTimeInterval;
}
export interface RealtimeWindow extends IntervalWindow{
realtimeType?: RealtimeWindowType;
}
export interface FixedWindow {
startTimeMs: number;
endTimeMs: number;
}
export interface HistoryWindow extends IntervalWindow {
historyType?: HistoryWindowType;
fixedTimewindow?: FixedWindow;
}
export enum AggregationType {
MIN = 'MIN',
MAX = 'MAX',
AVG = 'AVG',
SUM = 'SUM',
COUNT = 'COUNT',
NONE = 'NONE'
}
export const aggregationTranslations = new Map<AggregationType, string>(
[
[AggregationType.MIN, 'aggregation.min'],
[AggregationType.MAX, 'aggregation.max'],
[AggregationType.AVG, 'aggregation.avg'],
[AggregationType.SUM, 'aggregation.sum'],
[AggregationType.COUNT, 'aggregation.count'],
[AggregationType.NONE, 'aggregation.none'],
]
);
export interface Aggregation {
interval?: number;
type: AggregationType;
limit: number;
}
export interface Timewindow {
displayValue?: string;
displayTimezoneAbbr?: string;
hideInterval?: boolean;
hideAggregation?: boolean;
hideAggInterval?: boolean;
hideTimezone?: boolean;
selectedTab?: TimewindowType;
realtime?: RealtimeWindow;
history?: HistoryWindow;
aggregation?: Aggregation;
timezone?: string;
}
export interface SubscriptionAggregation extends Aggregation {
interval?: number;
timeWindow?: number;
stateData?: boolean;
}
export interface SubscriptionTimewindow {
startTs?: number;
quickInterval?: QuickTimeInterval;
timezone?: string;
tsOffset?: number;
realtimeWindowMs?: number;
fixedWindow?: FixedWindow;
aggregation?: SubscriptionAggregation;
timeForComparison?: ComparisonDuration;
}
export interface WidgetTimewindow {
minTime?: number;
maxTime?: number;
interval?: number;
timezone?: string;
stDiff?: number;
}
export enum QuickTimeInterval {
YESTERDAY = 'YESTERDAY',
DAY_BEFORE_YESTERDAY = 'DAY_BEFORE_YESTERDAY',
THIS_DAY_LAST_WEEK = 'THIS_DAY_LAST_WEEK',
PREVIOUS_WEEK = 'PREVIOUS_WEEK',
PREVIOUS_WEEK_ISO = 'PREVIOUS_WEEK_ISO',
PREVIOUS_MONTH = 'PREVIOUS_MONTH',
PREVIOUS_YEAR = 'PREVIOUS_YEAR',
CURRENT_HOUR = 'CURRENT_HOUR',
CURRENT_DAY = 'CURRENT_DAY',
CURRENT_DAY_SO_FAR = 'CURRENT_DAY_SO_FAR',
CURRENT_WEEK = 'CURRENT_WEEK',
CURRENT_WEEK_ISO = 'CURRENT_WEEK_ISO',
CURRENT_WEEK_SO_FAR = 'CURRENT_WEEK_SO_FAR',
CURRENT_WEEK_ISO_SO_FAR = 'CURRENT_WEEK_ISO_SO_FAR',
CURRENT_MONTH = 'CURRENT_MONTH',
CURRENT_MONTH_SO_FAR = 'CURRENT_MONTH_SO_FAR',
CURRENT_YEAR = 'CURRENT_YEAR',
CURRENT_YEAR_SO_FAR = 'CURRENT_YEAR_SO_FAR'
}
export const QuickTimeIntervalTranslationMap = new Map<QuickTimeInterval, string>([
[QuickTimeInterval.YESTERDAY, 'timeinterval.predefined.yesterday'],
[QuickTimeInterval.DAY_BEFORE_YESTERDAY, 'timeinterval.predefined.day-before-yesterday'],
[QuickTimeInterval.THIS_DAY_LAST_WEEK, 'timeinterval.predefined.this-day-last-week'],
[QuickTimeInterval.PREVIOUS_WEEK, 'timeinterval.predefined.previous-week'],
[QuickTimeInterval.PREVIOUS_WEEK_ISO, 'timeinterval.predefined.previous-week-iso'],
[QuickTimeInterval.PREVIOUS_MONTH, 'timeinterval.predefined.previous-month'],
[QuickTimeInterval.PREVIOUS_YEAR, 'timeinterval.predefined.previous-year'],
[QuickTimeInterval.CURRENT_HOUR, 'timeinterval.predefined.current-hour'],
[QuickTimeInterval.CURRENT_DAY, 'timeinterval.predefined.current-day'],
[QuickTimeInterval.CURRENT_DAY_SO_FAR, 'timeinterval.predefined.current-day-so-far'],
[QuickTimeInterval.CURRENT_WEEK, 'timeinterval.predefined.current-week'],
[QuickTimeInterval.CURRENT_WEEK_ISO, 'timeinterval.predefined.current-week-iso'],
[QuickTimeInterval.CURRENT_WEEK_SO_FAR, 'timeinterval.predefined.current-week-so-far'],
[QuickTimeInterval.CURRENT_WEEK_ISO_SO_FAR, 'timeinterval.predefined.current-week-iso-so-far'],
[QuickTimeInterval.CURRENT_MONTH, 'timeinterval.predefined.current-month'],
[QuickTimeInterval.CURRENT_MONTH_SO_FAR, 'timeinterval.predefined.current-month-so-far'],
[QuickTimeInterval.CURRENT_YEAR, 'timeinterval.predefined.current-year'],
[QuickTimeInterval.CURRENT_YEAR_SO_FAR, 'timeinterval.predefined.current-year-so-far']
]);
export function historyInterval(timewindowMs: number): Timewindow {
return {
selectedTab: TimewindowType.HISTORY,
history: {
historyType: HistoryWindowType.LAST_INTERVAL,
timewindowMs
}
};
}
export function defaultTimewindow(timeService: TimeService): Timewindow {
const currentTime = moment().valueOf();
return {
displayValue: '',
hideInterval: false,
hideAggregation: false,
hideAggInterval: false,
hideTimezone: false,
selectedTab: TimewindowType.REALTIME,
realtime: {
realtimeType: RealtimeWindowType.LAST_INTERVAL,
interval: SECOND,
timewindowMs: MINUTE,
quickInterval: QuickTimeInterval.CURRENT_DAY
},
history: {
historyType: HistoryWindowType.LAST_INTERVAL,
interval: SECOND,
timewindowMs: MINUTE,
fixedTimewindow: {
startTimeMs: currentTime - DAY,
endTimeMs: currentTime
},
quickInterval: QuickTimeInterval.CURRENT_DAY
},
aggregation: {
type: AggregationType.AVG,
limit: Math.floor(timeService.getMaxDatapointsLimit() / 2)
}
};
}
function getTimewindowType(timewindow: Timewindow): TimewindowType {
if (isUndefined(timewindow.selectedTab)) {
return isDefined(timewindow.realtime) ? TimewindowType.REALTIME : TimewindowType.HISTORY;
} else {
return timewindow.selectedTab;
}
}
export function initModelFromDefaultTimewindow(value: Timewindow, timeService: TimeService): Timewindow {
const model = defaultTimewindow(timeService);
if (value) {
model.hideInterval = value.hideInterval;
model.hideAggregation = value.hideAggregation;
model.hideAggInterval = value.hideAggInterval;
model.hideTimezone = value.hideTimezone;
model.selectedTab = getTimewindowType(value);
if (model.selectedTab === TimewindowType.REALTIME) {
if (isDefined(value.realtime.interval)) {
model.realtime.interval = value.realtime.interval;
}
if (isUndefined(value.realtime.realtimeType)) {
if (isDefined(value.realtime.quickInterval)) {
model.realtime.realtimeType = RealtimeWindowType.INTERVAL;
} else {
model.realtime.realtimeType = RealtimeWindowType.LAST_INTERVAL;
}
} else {
model.realtime.realtimeType = value.realtime.realtimeType;
}
if (model.realtime.realtimeType === RealtimeWindowType.INTERVAL) {
model.realtime.quickInterval = value.realtime.quickInterval;
} else {
model.realtime.timewindowMs = value.realtime.timewindowMs;
}
} else {
if (isDefined(value.history.interval)) {
model.history.interval = value.history.interval;
}
if (isUndefined(value.history.historyType)) {
if (isDefined(value.history.timewindowMs)) {
model.history.historyType = HistoryWindowType.LAST_INTERVAL;
} else if (isDefined(value.history.quickInterval)) {
model.history.historyType = HistoryWindowType.INTERVAL;
} else {
model.history.historyType = HistoryWindowType.FIXED;
}
} else {
model.history.historyType = value.history.historyType;
}
if (model.history.historyType === HistoryWindowType.LAST_INTERVAL) {
model.history.timewindowMs = value.history.timewindowMs;
} else if (model.history.historyType === HistoryWindowType.INTERVAL) {
model.history.quickInterval = value.history.quickInterval;
} else {
model.history.fixedTimewindow.startTimeMs = value.history.fixedTimewindow.startTimeMs;
model.history.fixedTimewindow.endTimeMs = value.history.fixedTimewindow.endTimeMs;
}
}
if (value.aggregation) {
if (value.aggregation.type) {
model.aggregation.type = value.aggregation.type;
}
model.aggregation.limit = value.aggregation.limit || Math.floor(timeService.getMaxDatapointsLimit() / 2);
}
model.timezone = value.timezone;
}
return model;
}
export function toHistoryTimewindow(timewindow: Timewindow, startTimeMs: number, endTimeMs: number,
interval: number, timeService: TimeService): Timewindow {
if (timewindow.history) {
interval = isDefined(interval) ? interval : timewindow.history.interval;
} else if (timewindow.realtime) {
interval = timewindow.realtime.interval;
} else {
interval = 0;
}
let aggType: AggregationType;
let limit: number;
if (timewindow.aggregation) {
aggType = timewindow.aggregation.type || AggregationType.AVG;
limit = timewindow.aggregation.limit || timeService.getMaxDatapointsLimit();
} else {
aggType = AggregationType.AVG;
limit = timeService.getMaxDatapointsLimit();
}
return {
hideInterval: timewindow.hideInterval || false,
hideAggregation: timewindow.hideAggregation || false,
hideAggInterval: timewindow.hideAggInterval || false,
hideTimezone: timewindow.hideTimezone || false,
selectedTab: TimewindowType.HISTORY,
history: {
historyType: HistoryWindowType.FIXED,
fixedTimewindow: {
startTimeMs,
endTimeMs
},
interval: timeService.boundIntervalToTimewindow(endTimeMs - startTimeMs, interval, AggregationType.AVG)
},
aggregation: {
type: aggType,
limit
},
timezone: timewindow.timezone
};
}
export function timewindowTypeChanged(newTimewindow: Timewindow, oldTimewindow: Timewindow): boolean {
if (!newTimewindow || !oldTimewindow) {
return false;
}
const newType = getTimewindowType(newTimewindow);
const oldType = getTimewindowType(oldTimewindow);
return newType !== oldType;
}
export function calculateTsOffset(timezone?: string): number {
if (timezone) {
const tz = getTimezone(timezone);
const localOffset = moment().utcOffset();
return (tz.utcOffset() - localOffset) * 60 * 1000;
} else {
return 0;
}
}
export function isHistoryTypeTimewindow(timewindow: Timewindow): boolean {
return getTimewindowType(timewindow) === TimewindowType.HISTORY;
}
export function createSubscriptionTimewindow(timewindow: Timewindow, stDiff: number, stateData: boolean,
timeService: TimeService): SubscriptionTimewindow {
const subscriptionTimewindow: SubscriptionTimewindow = {
fixedWindow: null,
realtimeWindowMs: null,
aggregation: {
interval: SECOND,
limit: timeService.getMaxDatapointsLimit(),
type: AggregationType.AVG
},
timezone: timewindow.timezone,
tsOffset: calculateTsOffset(timewindow.timezone)
};
let aggTimewindow;
if (stateData) {
subscriptionTimewindow.aggregation.type = AggregationType.NONE;
subscriptionTimewindow.aggregation.stateData = true;
}
if (isDefined(timewindow.aggregation) && !stateData) {
subscriptionTimewindow.aggregation = {
type: timewindow.aggregation.type || AggregationType.AVG,
limit: timewindow.aggregation.limit || timeService.getMaxDatapointsLimit()
};
}
const selectedTab = getTimewindowType(timewindow);
if (selectedTab === TimewindowType.REALTIME) {
let realtimeType = timewindow.realtime.realtimeType;
if (isUndefined(realtimeType)) {
if (isDefined(timewindow.realtime.quickInterval)) {
realtimeType = RealtimeWindowType.INTERVAL;
} else {
realtimeType = RealtimeWindowType.LAST_INTERVAL;
}
}
if (realtimeType === RealtimeWindowType.INTERVAL) {
subscriptionTimewindow.realtimeWindowMs =
getSubscriptionRealtimeWindowFromTimeInterval(timewindow.realtime.quickInterval, timewindow.timezone);
subscriptionTimewindow.quickInterval = timewindow.realtime.quickInterval;
const currentDate = getCurrentTime(timewindow.timezone);
subscriptionTimewindow.startTs = calculateIntervalStartTime(timewindow.realtime.quickInterval, currentDate).valueOf();
} else {
subscriptionTimewindow.realtimeWindowMs = timewindow.realtime.timewindowMs;
const currentDate = getCurrentTime(timewindow.timezone);
subscriptionTimewindow.startTs = currentDate.valueOf() + stDiff - subscriptionTimewindow.realtimeWindowMs;
}
subscriptionTimewindow.aggregation.interval =
timeService.boundIntervalToTimewindow(subscriptionTimewindow.realtimeWindowMs, timewindow.realtime.interval,
subscriptionTimewindow.aggregation.type);
aggTimewindow = subscriptionTimewindow.realtimeWindowMs;
if (realtimeType !== RealtimeWindowType.INTERVAL) {
const startDiff = subscriptionTimewindow.startTs % subscriptionTimewindow.aggregation.interval;
if (startDiff) {
subscriptionTimewindow.startTs -= startDiff;
aggTimewindow += subscriptionTimewindow.aggregation.interval;
}
}
} else {
let historyType = timewindow.history.historyType;
if (isUndefined(historyType)) {
if (isDefined(timewindow.history.timewindowMs)) {
historyType = HistoryWindowType.LAST_INTERVAL;
} else if (isDefined(timewindow.history.quickInterval)) {
historyType = HistoryWindowType.INTERVAL;
} else {
historyType = HistoryWindowType.FIXED;
}
}
if (historyType === HistoryWindowType.LAST_INTERVAL) {
const currentDate = getCurrentTime(timewindow.timezone);
const currentTime = currentDate.valueOf();
subscriptionTimewindow.fixedWindow = {
startTimeMs: currentTime - timewindow.history.timewindowMs,
endTimeMs: currentTime
};
aggTimewindow = timewindow.history.timewindowMs;
} else if (historyType === HistoryWindowType.INTERVAL) {
const startEndTime = calculateIntervalStartEndTime(timewindow.history.quickInterval, timewindow.timezone);
subscriptionTimewindow.fixedWindow = {
startTimeMs: startEndTime[0],
endTimeMs: startEndTime[1]
};
aggTimewindow = subscriptionTimewindow.fixedWindow.endTimeMs - subscriptionTimewindow.fixedWindow.startTimeMs;
subscriptionTimewindow.quickInterval = timewindow.history.quickInterval;
} else {
subscriptionTimewindow.fixedWindow = {
startTimeMs: timewindow.history.fixedTimewindow.startTimeMs - subscriptionTimewindow.tsOffset,
endTimeMs: timewindow.history.fixedTimewindow.endTimeMs - subscriptionTimewindow.tsOffset
};
aggTimewindow = subscriptionTimewindow.fixedWindow.endTimeMs - subscriptionTimewindow.fixedWindow.startTimeMs;
}
subscriptionTimewindow.startTs = subscriptionTimewindow.fixedWindow.startTimeMs;
subscriptionTimewindow.aggregation.interval =
timeService.boundIntervalToTimewindow(aggTimewindow, timewindow.history.interval, subscriptionTimewindow.aggregation.type);
}
const aggregation = subscriptionTimewindow.aggregation;
aggregation.timeWindow = aggTimewindow;
if (aggregation.type !== AggregationType.NONE) {
aggregation.limit = Math.ceil(aggTimewindow / subscriptionTimewindow.aggregation.interval);
}
return subscriptionTimewindow;
}
function getSubscriptionRealtimeWindowFromTimeInterval(interval: QuickTimeInterval, tz?: string): number {
let currentDate;
switch (interval) {
case QuickTimeInterval.CURRENT_HOUR:
return HOUR;
case QuickTimeInterval.CURRENT_DAY:
case QuickTimeInterval.CURRENT_DAY_SO_FAR:
return DAY;
case QuickTimeInterval.CURRENT_WEEK:
case QuickTimeInterval.CURRENT_WEEK_ISO:
case QuickTimeInterval.CURRENT_WEEK_SO_FAR:
case QuickTimeInterval.CURRENT_WEEK_ISO_SO_FAR:
return WEEK;
case QuickTimeInterval.CURRENT_MONTH:
case QuickTimeInterval.CURRENT_MONTH_SO_FAR:
currentDate = getCurrentTime(tz);
return currentDate.endOf('month').diff(currentDate.clone().startOf('month'));
case QuickTimeInterval.CURRENT_YEAR:
case QuickTimeInterval.CURRENT_YEAR_SO_FAR:
currentDate = getCurrentTime(tz);
return currentDate.endOf('year').diff(currentDate.clone().startOf('year'));
}
}
export function calculateIntervalStartEndTime(interval: QuickTimeInterval, tz?: string): [number, number] {
const startEndTs: [number, number] = [0, 0];
const currentDate = getCurrentTime(tz);
const startDate = calculateIntervalStartTime(interval, currentDate);
startEndTs[0] = startDate.valueOf();
const endDate = calculateIntervalEndTime(interval, startDate, tz);
startEndTs[1] = endDate.valueOf();
return startEndTs;
}
export function calculateIntervalStartTime(interval: QuickTimeInterval, currentDate: moment_.Moment): moment_.Moment {
switch (interval) {
case QuickTimeInterval.YESTERDAY:
currentDate.subtract(1, 'days');
return currentDate.startOf('day');
case QuickTimeInterval.DAY_BEFORE_YESTERDAY:
currentDate.subtract(2, 'days');
return currentDate.startOf('day');
case QuickTimeInterval.THIS_DAY_LAST_WEEK:
currentDate.subtract(1, 'weeks');
return currentDate.startOf('day');
case QuickTimeInterval.PREVIOUS_WEEK:
currentDate.subtract(1, 'weeks');
return currentDate.startOf('week');
case QuickTimeInterval.PREVIOUS_WEEK_ISO:
currentDate.subtract(1, 'weeks');
return currentDate.startOf('isoWeek');
case QuickTimeInterval.PREVIOUS_MONTH:
currentDate.subtract(1, 'months');
return currentDate.startOf('month');
case QuickTimeInterval.PREVIOUS_YEAR:
currentDate.subtract(1, 'years');
return currentDate.startOf('year');
case QuickTimeInterval.CURRENT_HOUR:
return currentDate.startOf('hour');
case QuickTimeInterval.CURRENT_DAY:
case QuickTimeInterval.CURRENT_DAY_SO_FAR:
return currentDate.startOf('day');
case QuickTimeInterval.CURRENT_WEEK:
case QuickTimeInterval.CURRENT_WEEK_SO_FAR:
return currentDate.startOf('week');
case QuickTimeInterval.CURRENT_WEEK_ISO:
case QuickTimeInterval.CURRENT_WEEK_ISO_SO_FAR:
return currentDate.startOf('isoWeek');
case QuickTimeInterval.CURRENT_MONTH:
case QuickTimeInterval.CURRENT_MONTH_SO_FAR:
return currentDate.startOf('month');
case QuickTimeInterval.CURRENT_YEAR:
case QuickTimeInterval.CURRENT_YEAR_SO_FAR:
return currentDate.startOf('year');
}
}
export function calculateIntervalEndTime(interval: QuickTimeInterval, startDate: moment_.Moment, tz?: string): number {
switch (interval) {
case QuickTimeInterval.YESTERDAY:
case QuickTimeInterval.DAY_BEFORE_YESTERDAY:
case QuickTimeInterval.THIS_DAY_LAST_WEEK:
case QuickTimeInterval.CURRENT_DAY:
return startDate.add(1, 'day').valueOf();
case QuickTimeInterval.PREVIOUS_WEEK:
case QuickTimeInterval.PREVIOUS_WEEK_ISO:
case QuickTimeInterval.CURRENT_WEEK:
case QuickTimeInterval.CURRENT_WEEK_ISO:
return startDate.add(1, 'week').valueOf();
case QuickTimeInterval.PREVIOUS_MONTH:
case QuickTimeInterval.CURRENT_MONTH:
return startDate.add(1, 'month').valueOf();
case QuickTimeInterval.PREVIOUS_YEAR:
case QuickTimeInterval.CURRENT_YEAR:
return startDate.add(1, 'year').valueOf();
case QuickTimeInterval.CURRENT_HOUR:
return startDate.add(1, 'hour').valueOf();
case QuickTimeInterval.CURRENT_DAY_SO_FAR:
case QuickTimeInterval.CURRENT_WEEK_SO_FAR:
case QuickTimeInterval.CURRENT_WEEK_ISO_SO_FAR:
case QuickTimeInterval.CURRENT_MONTH_SO_FAR:
case QuickTimeInterval.CURRENT_YEAR_SO_FAR:
return getCurrentTime(tz).valueOf();
}
}
export function quickTimeIntervalPeriod(interval: QuickTimeInterval): number {
switch (interval) {
case QuickTimeInterval.CURRENT_HOUR:
return HOUR;
case QuickTimeInterval.YESTERDAY:
case QuickTimeInterval.DAY_BEFORE_YESTERDAY:
case QuickTimeInterval.THIS_DAY_LAST_WEEK:
case QuickTimeInterval.CURRENT_DAY:
case QuickTimeInterval.CURRENT_DAY_SO_FAR:
return DAY;
case QuickTimeInterval.PREVIOUS_WEEK:
case QuickTimeInterval.PREVIOUS_WEEK_ISO:
case QuickTimeInterval.CURRENT_WEEK:
case QuickTimeInterval.CURRENT_WEEK_ISO:
case QuickTimeInterval.CURRENT_WEEK_SO_FAR:
case QuickTimeInterval.CURRENT_WEEK_ISO_SO_FAR:
return WEEK;
case QuickTimeInterval.PREVIOUS_MONTH:
case QuickTimeInterval.CURRENT_MONTH:
case QuickTimeInterval.CURRENT_MONTH_SO_FAR:
return DAY * 30;
case QuickTimeInterval.PREVIOUS_YEAR:
case QuickTimeInterval.CURRENT_YEAR:
case QuickTimeInterval.CURRENT_YEAR_SO_FAR:
return YEAR;
}
}
export function calculateIntervalComparisonStartTime(interval: QuickTimeInterval,
startDate: moment_.Moment): moment_.Moment {
switch (interval) {
case QuickTimeInterval.YESTERDAY:
case QuickTimeInterval.DAY_BEFORE_YESTERDAY:
case QuickTimeInterval.CURRENT_DAY:
case QuickTimeInterval.CURRENT_DAY_SO_FAR:
startDate.subtract(1, 'days');
return startDate.startOf('day');
case QuickTimeInterval.THIS_DAY_LAST_WEEK:
startDate.subtract(1, 'weeks');
return startDate.startOf('day');
case QuickTimeInterval.PREVIOUS_WEEK:
case QuickTimeInterval.CURRENT_WEEK:
case QuickTimeInterval.CURRENT_WEEK_SO_FAR:
startDate.subtract(1, 'weeks');
return startDate.startOf('week');
case QuickTimeInterval.PREVIOUS_WEEK_ISO:
case QuickTimeInterval.CURRENT_WEEK_ISO:
case QuickTimeInterval.CURRENT_WEEK_ISO_SO_FAR:
startDate.subtract(1, 'weeks');
return startDate.startOf('isoWeek');
case QuickTimeInterval.PREVIOUS_MONTH:
case QuickTimeInterval.CURRENT_MONTH:
case QuickTimeInterval.CURRENT_MONTH_SO_FAR:
startDate.subtract(1, 'months');
return startDate.startOf('month');
case QuickTimeInterval.PREVIOUS_YEAR:
case QuickTimeInterval.CURRENT_YEAR:
case QuickTimeInterval.CURRENT_YEAR_SO_FAR:
startDate.subtract(1, 'years');
return startDate.startOf('year');
case QuickTimeInterval.CURRENT_HOUR:
startDate.subtract(1, 'hour');
return startDate.startOf('hour');
}
}
export function calculateIntervalComparisonEndTime(interval: QuickTimeInterval,
comparisonStartDate: moment_.Moment,
endDate: moment_.Moment): number {
switch (interval) {
case QuickTimeInterval.CURRENT_DAY_SO_FAR:
return endDate.subtract(1, 'days').valueOf();
case QuickTimeInterval.CURRENT_WEEK_SO_FAR:
case QuickTimeInterval.CURRENT_WEEK_ISO_SO_FAR:
return endDate.subtract(1, 'week').valueOf();
case QuickTimeInterval.CURRENT_MONTH_SO_FAR:
return endDate.subtract(1, 'month').valueOf();
case QuickTimeInterval.CURRENT_YEAR_SO_FAR:
return endDate.subtract(1, 'year').valueOf();
default:
return calculateIntervalEndTime(interval, comparisonStartDate);
}
}
export function createTimewindowForComparison(subscriptionTimewindow: SubscriptionTimewindow,
timeUnit: ComparisonDuration, customIntervalValue: number): SubscriptionTimewindow {
const timewindowForComparison: SubscriptionTimewindow = {
fixedWindow: null,
realtimeWindowMs: null,
aggregation: subscriptionTimewindow.aggregation,
tsOffset: subscriptionTimewindow.tsOffset
};
if (subscriptionTimewindow.fixedWindow) {
let startTimeMs;
let endTimeMs;
if (timeUnit === 'previousInterval') {
if (subscriptionTimewindow.quickInterval) {
const startDate = moment(subscriptionTimewindow.fixedWindow.startTimeMs);
const endDate = moment(subscriptionTimewindow.fixedWindow.endTimeMs);
if (subscriptionTimewindow.timezone) {
startDate.tz(subscriptionTimewindow.timezone);
endDate.tz(subscriptionTimewindow.timezone);
}
const comparisonStartDate = calculateIntervalComparisonStartTime(subscriptionTimewindow.quickInterval, startDate);
startTimeMs = comparisonStartDate.valueOf();
endTimeMs = calculateIntervalComparisonEndTime(subscriptionTimewindow.quickInterval, comparisonStartDate, endDate);
} else {
const timeInterval = subscriptionTimewindow.fixedWindow.endTimeMs - subscriptionTimewindow.fixedWindow.startTimeMs;
endTimeMs = subscriptionTimewindow.fixedWindow.startTimeMs;
startTimeMs = endTimeMs - timeInterval;
}
} else if (timeUnit === 'customInterval') {
if (isNumeric(customIntervalValue) && isFinite(customIntervalValue) && customIntervalValue > 0) {
const timeInterval = subscriptionTimewindow.fixedWindow.endTimeMs - subscriptionTimewindow.fixedWindow.startTimeMs;
endTimeMs = subscriptionTimewindow.fixedWindow.endTimeMs - Math.round(customIntervalValue);
startTimeMs = endTimeMs - timeInterval;
} else {
endTimeMs = subscriptionTimewindow.fixedWindow.endTimeMs;
startTimeMs = subscriptionTimewindow.fixedWindow.startTimeMs;
}
} else {
const timeInterval = subscriptionTimewindow.fixedWindow.endTimeMs - subscriptionTimewindow.fixedWindow.startTimeMs;
endTimeMs = moment(subscriptionTimewindow.fixedWindow.endTimeMs).subtract(1, timeUnit).valueOf();
startTimeMs = endTimeMs - timeInterval;
}
timewindowForComparison.startTs = startTimeMs;
timewindowForComparison.fixedWindow = {
startTimeMs: timewindowForComparison.startTs,
endTimeMs
};
}
return timewindowForComparison;
}
export function cloneSelectedTimewindow(timewindow: Timewindow): Timewindow {
const cloned: Timewindow = {};
cloned.hideInterval = timewindow.hideInterval || false;
cloned.hideAggregation = timewindow.hideAggregation || false;
cloned.hideAggInterval = timewindow.hideAggInterval || false;
cloned.hideTimezone = timewindow.hideTimezone || false;
if (isDefined(timewindow.selectedTab)) {
cloned.selectedTab = timewindow.selectedTab;
if (timewindow.selectedTab === TimewindowType.REALTIME) {
cloned.realtime = deepClone(timewindow.realtime);
} else if (timewindow.selectedTab === TimewindowType.HISTORY) {
cloned.history = deepClone(timewindow.history);
}
}
cloned.aggregation = deepClone(timewindow.aggregation);
cloned.timezone = timewindow.timezone;
return cloned;
}
export interface TimeInterval {
name: string;
translateParams: {[key: string]: any};
value: number;
}
export const defaultTimeIntervals = new Array<TimeInterval>(
{
name: 'timeinterval.seconds-interval',
translateParams: {seconds: 1},
value: SECOND
},
{
name: 'timeinterval.seconds-interval',
translateParams: {seconds: 5},
value: 5 * SECOND
},
{
name: 'timeinterval.seconds-interval',
translateParams: {seconds: 10},
value: 10 * SECOND
},
{
name: 'timeinterval.seconds-interval',
translateParams: {seconds: 15},
value: 15 * SECOND
},
{
name: 'timeinterval.seconds-interval',
translateParams: {seconds: 30},
value: 30 * SECOND
},
{
name: 'timeinterval.minutes-interval',
translateParams: {minutes: 1},
value: MINUTE
},
{
name: 'timeinterval.minutes-interval',
translateParams: {minutes: 2},
value: 2 * MINUTE
},
{
name: 'timeinterval.minutes-interval',
translateParams: {minutes: 5},
value: 5 * MINUTE
},
{
name: 'timeinterval.minutes-interval',
translateParams: {minutes: 10},
value: 10 * MINUTE
},
{
name: 'timeinterval.minutes-interval',
translateParams: {minutes: 15},
value: 15 * MINUTE
},
{
name: 'timeinterval.minutes-interval',
translateParams: {minutes: 30},
value: 30 * MINUTE
},
{
name: 'timeinterval.hours-interval',
translateParams: {hours: 1},
value: HOUR
},
{
name: 'timeinterval.hours-interval',
translateParams: {hours: 2},
value: 2 * HOUR
},
{
name: 'timeinterval.hours-interval',
translateParams: {hours: 5},
value: 5 * HOUR
},
{
name: 'timeinterval.hours-interval',
translateParams: {hours: 10},
value: 10 * HOUR
},
{
name: 'timeinterval.hours-interval',
translateParams: {hours: 12},
value: 12 * HOUR
},
{
name: 'timeinterval.days-interval',
translateParams: {days: 1},
value: DAY
},
{
name: 'timeinterval.days-interval',
translateParams: {days: 7},
value: 7 * DAY
},
{
name: 'timeinterval.days-interval',
translateParams: {days: 30},
value: 30 * DAY
}
);
export enum TimeUnit {
SECONDS = 'SECONDS',
MINUTES = 'MINUTES',
HOURS = 'HOURS',
DAYS = 'DAYS'
}
export enum TimeUnitMilli {
MILLISECONDS = 'MILLISECONDS'
}
export type FullTimeUnit = TimeUnit | TimeUnitMilli;
export const timeUnitTranslationMap = new Map<FullTimeUnit, string>(
[
[TimeUnitMilli.MILLISECONDS, 'timeunit.milliseconds'],
[TimeUnit.SECONDS, 'timeunit.seconds'],
[TimeUnit.MINUTES, 'timeunit.minutes'],
[TimeUnit.HOURS, 'timeunit.hours'],
[TimeUnit.DAYS, 'timeunit.days']
]
);
export interface TimezoneInfo {
id: string;
name: string;
offset: string;
nOffset: number;
abbr: string;
}
let timezones: TimezoneInfo[] = null;
let defaultTimezone: string = null;
export function getTimezones(): TimezoneInfo[] {
if (!timezones) {
timezones = momentTz.tz.names().map((zoneName) => {
const tz = momentTz.tz(zoneName);
return {
id: zoneName,
name: zoneName.replace(/_/g, ' '),
offset: `UTC${tz.format('Z')}`,
nOffset: tz.utcOffset(),
abbr: tz.zoneAbbr()
};
});
}
return timezones;
}
export function getTimezoneInfo(timezoneId: string, defaultTimezoneId?: string, userTimezoneByDefault?: boolean): TimezoneInfo {
const timezoneList = getTimezones();
let foundTimezone = timezoneId ? timezoneList.find(timezoneInfo => timezoneInfo.id === timezoneId) : null;
if (!foundTimezone) {
if (userTimezoneByDefault) {
const userTimezone = getDefaultTimezone();
foundTimezone = timezoneList.find(timezoneInfo => timezoneInfo.id === userTimezone);
} else if (defaultTimezoneId) {
foundTimezone = timezoneList.find(timezoneInfo => timezoneInfo.id === defaultTimezoneId);
}
}
return foundTimezone;
}
export function getDefaultTimezoneInfo(): TimezoneInfo {
const userTimezone = getDefaultTimezone();
return getTimezoneInfo(userTimezone);
}
export function getDefaultTimezone(): string {
if (!defaultTimezone) {
defaultTimezone = momentTz.tz.guess();
}
return defaultTimezone;
}
export function getCurrentTime(tz?: string): moment_.Moment {
if (tz) {
return moment().tz(tz);
} else {
return moment();
}
}
export function getTime(ts: number, tz?: string): moment_.Moment {
if (tz) {
return moment(ts).tz(tz);
} else {
return moment(ts);
}
}
export function getTimezone(tz: string): moment_.Moment {
return moment.tz(tz);
}
export function getCurrentTimeForComparison(timeForComparison: moment_.unitOfTime.DurationConstructor, tz?: string): moment_.Moment {
return getCurrentTime(tz).subtract(1, timeForComparison);
} | the_stack |
import { BigNumber } from "bignumber.js";
import {
sortByMarketcap,
listTokens,
listCryptoCurrencies,
getCryptoCurrencyById,
getFiatCurrencyByTicker,
formatCurrencyUnit,
parseCurrencyUnit,
chopCurrencyUnitDecimals,
formatShort,
decodeURIScheme,
encodeURIScheme,
sanitizeValueString,
} from "../currencies";
import { byContractAddressAndChainId } from "@ledgerhq/hw-app-eth/erc20";
import { CryptoCurrency, TokenCurrency } from "@ledgerhq/cryptoassets";
test("erc20 are all consistent with those on ledgerjs side", () => {
const normalList = listTokens();
const delistedList = listTokens({
withDelisted: true,
});
expect(delistedList.length).toBeGreaterThan(normalList.length);
for (const token of delistedList) {
if (token.delisted) {
expect(normalList.find((o) => o.id === token.id)).toBeUndefined();
}
if (token.tokenType === "erc20") {
const tokenData = byContractAddressAndChainId(
token.contractAddress,
token.parentCurrency.ethereumLikeInfo?.chainId || 0
);
if (!tokenData) {
throw new Error(token.name + " not available in ledgerjs data");
}
expect(token.ticker.toLowerCase()).toBe(tokenData.ticker.toLowerCase());
expect(token.contractAddress.toLowerCase()).toBe(
tokenData.contractAddress.toLowerCase()
);
expect(token.units[0].magnitude).toBe(tokenData.decimals);
}
}
});
test("sort by marketcap", () => {
const tokens = listTokens().filter(
(t) => t.ticker === "XST" || t.ticker === "ZRX" || t.ticker === "HOT"
);
const currencies: (CryptoCurrency | TokenCurrency)[] =
listCryptoCurrencies().filter(
(c) => c.ticker === "BTC" || c.ticker === "XST" || c.ticker === "ETH"
);
expect(
sortByMarketcap(currencies.concat(tokens), [
"BTC",
"ETH",
"ZRX",
"HOT",
"XST",
]).map((c) => c.id)
).toMatchObject([
"bitcoin",
"ethereum",
"ethereum/erc20/0x_project",
"ethereum/erc20/holotoken",
"stealthcoin",
"ethereum/erc20/hydro_protocol",
"ethereum/erc20/xensor",
"ethereum/erc20/xstable.protocol",
]);
});
test("can format a currency unit", () => {
const btc = getCryptoCurrencyById("bitcoin").units[0];
expect(formatCurrencyUnit(btc, new BigNumber(100000000))).toBe("1");
expect(
formatCurrencyUnit(btc, new BigNumber(1000000), {
showCode: true,
})
).toBe("0.01 BTC");
expect(
formatCurrencyUnit(btc, new BigNumber(100000000), {
showCode: true,
})
).toBe("1 BTC");
expect(
formatCurrencyUnit(btc, new BigNumber(100000000), {
showCode: true,
showAllDigits: true,
})
).toBe("1.00000000 BTC");
expect(
formatCurrencyUnit(btc, new BigNumber(100000000), {
showCode: true,
showAllDigits: true,
alwaysShowSign: true,
})
).toBe("+1.00000000 BTC");
});
test("do not consider 'showAllDigits: undefined' as false", () => {
expect(
formatCurrencyUnit(
getFiatCurrencyByTicker("USD").units[0],
new BigNumber(-1234500),
{
showCode: true,
showAllDigits: undefined,
}
)
).toBe("-$12,345.00");
});
test("can enable discreet mode", () => {
const btc = getCryptoCurrencyById("bitcoin").units[0];
expect(
formatCurrencyUnit(btc, new BigNumber(100000000), {
discreet: true,
})
).toBe("***");
expect(
formatCurrencyUnit(btc, new BigNumber(1000000), {
discreet: true,
showCode: true,
})
).toBe("*** BTC");
expect(
formatCurrencyUnit(btc, new BigNumber(100000000), {
discreet: true,
showCode: true,
})
).toBe("*** BTC");
expect(
formatCurrencyUnit(btc, new BigNumber(100000000), {
discreet: true,
showCode: true,
showAllDigits: true,
})
).toBe("*** BTC");
expect(
formatCurrencyUnit(btc, new BigNumber(100000000), {
discreet: true,
showCode: true,
showAllDigits: true,
alwaysShowSign: true,
})
).toBe("+*** BTC");
});
test("formatter will floor values by default", () => {
expect(
formatCurrencyUnit(
getCryptoCurrencyById("bitcoin").units[0],
new BigNumber(1000001),
{}
)
).toBe("0.01");
expect(
formatCurrencyUnit(
getCryptoCurrencyById("bitcoin").units[0],
new BigNumber(1000010)
)
).toBe("0.01");
expect(
formatCurrencyUnit(
getCryptoCurrencyById("bitcoin").units[0],
new BigNumber(1000100)
)
).toBe("0.010001");
expect(
formatCurrencyUnit(
getCryptoCurrencyById("bitcoin").units[0],
new BigNumber("999999999999")
)
).toBe("9,999");
});
test("formatter rounding can be disabled", () => {
expect(
formatCurrencyUnit(
getCryptoCurrencyById("bitcoin").units[0],
new BigNumber("999999999999"),
{
disableRounding: true,
}
)
).toBe("9,999.99999999");
});
test("sub magnitude", () => {
expect(
formatCurrencyUnit(
getFiatCurrencyByTicker("USD").units[0],
new BigNumber(0.04),
{
subMagnitude: 2,
}
)
).toBe("0.0004");
// digits will be round after subMagnitude
expect(
formatCurrencyUnit(
getFiatCurrencyByTicker("USD").units[0],
new BigNumber(0.03987654),
{
subMagnitude: 2,
showCode: true,
}
)
).toBe("$0.0003");
expect(
formatCurrencyUnit(
getFiatCurrencyByTicker("USD").units[0],
new BigNumber(0.03987654),
{
subMagnitude: 2,
disableRounding: true,
}
)
).toBe("0.0003");
expect(
formatCurrencyUnit(
getFiatCurrencyByTicker("USD").units[0],
new BigNumber(0.03987654),
{
subMagnitude: 5,
disableRounding: true,
}
)
).toBe("0.0003987");
// even tho the USD unit showAllDigits, it does not force the sub magnitude digits to show
expect(
formatCurrencyUnit(
getFiatCurrencyByTicker("USD").units[0],
new BigNumber(0.03),
{
subMagnitude: 5,
disableRounding: true,
}
)
).toBe("0.0003");
expect(
formatCurrencyUnit(
getCryptoCurrencyById("bitcoin").units[0],
new BigNumber(9.123456),
{
subMagnitude: 2,
disableRounding: true,
}
)
).toBe("0.0000000912");
expect(
formatCurrencyUnit(
getCryptoCurrencyById("bitcoin").units[0],
new BigNumber("999999999999.123456"),
{
disableRounding: true,
subMagnitude: 2,
}
)
).toBe("9,999.9999999912");
expect(
formatCurrencyUnit(
getCryptoCurrencyById("bitcoin").units[0],
new BigNumber("999999999999.123456"),
{
subMagnitude: 2,
}
)
).toBe("9,999");
});
test("parseCurrencyUnit", () => {
expect(
parseCurrencyUnit(
getCryptoCurrencyById("bitcoin").units[0],
"9999.99999999"
).toNumber()
).toBe(999999999999);
expect(
parseCurrencyUnit(
getCryptoCurrencyById("bitcoin").units[0],
".987654"
).toNumber()
).toBe(98765400);
expect(
parseCurrencyUnit(
getCryptoCurrencyById("bitcoin").units[0],
"9999"
).toNumber()
).toBe(999900000000);
expect(
parseCurrencyUnit(getCryptoCurrencyById("bitcoin").units[0], "1").toNumber()
).toBe(100000000);
/*expect(
parseCurrencyUnit(getCryptoCurrencyById("bitcoin").units[0], "0x1").toNumber()
).toBe(0);*/
expect(
parseCurrencyUnit(
getCryptoCurrencyById("bitcoin").units[0],
"NOPE"
).toNumber()
).toBe(0);
});
test("formatter works with fiats", () => {
expect(
formatCurrencyUnit(
getFiatCurrencyByTicker("EUR").units[0],
new BigNumber(12345),
{
showCode: true,
}
)
).toBe("€123.45");
// by default, fiats always show the digits
expect(
formatCurrencyUnit(
getFiatCurrencyByTicker("EUR").units[0],
new BigNumber(12300)
)
).toBe("123.00");
});
test("formatter useGrouping", () => {
expect(
formatCurrencyUnit(
getFiatCurrencyByTicker("EUR").units[0],
new BigNumber(1234500),
{
useGrouping: true,
}
)
).toBe("12,345.00");
expect(
formatCurrencyUnit(
getFiatCurrencyByTicker("EUR").units[0],
new BigNumber(1234500),
{
useGrouping: false,
}
)
).toBe("12345.00");
});
test("formatter can change locale", () => {
expect(
formatCurrencyUnit(
getFiatCurrencyByTicker("USD").units[0],
new BigNumber(-1234567),
{
showCode: true,
}
)
).toBe("-$12,345.67");
});
test("formatter does not show very small value in rounding mode", () => {
expect(
formatCurrencyUnit(
getCryptoCurrencyById("ethereum").units[0],
new BigNumber(1)
)
).toBe("0");
expect(
formatCurrencyUnit(
getCryptoCurrencyById("ethereum").units[0],
new BigNumber(1000)
)
).toBe("0");
});
test("formatShort", () => {
expect(
formatShort(
getFiatCurrencyByTicker("EUR").units[0],
new BigNumber(123456789)
)
).toBe("1.2m");
expect(
formatShort(getFiatCurrencyByTicker("EUR").units[0], new BigNumber(123456))
).toBe("1.2k");
expect(
formatShort(
getCryptoCurrencyById("ethereum").units[0],
new BigNumber(600000)
)
).toBe("0");
});
test("chopCurrencyUnitDecimals", () => {
expect(
chopCurrencyUnitDecimals(getFiatCurrencyByTicker("EUR").units[0], "1")
).toBe("1");
expect(
chopCurrencyUnitDecimals(getFiatCurrencyByTicker("EUR").units[0], "1234")
).toBe("1234");
expect(
chopCurrencyUnitDecimals(getFiatCurrencyByTicker("EUR").units[0], "1234.56")
).toBe("1234.56");
expect(
chopCurrencyUnitDecimals(
getFiatCurrencyByTicker("EUR").units[0],
"1234.5678"
)
).toBe("1234.56");
expect(
chopCurrencyUnitDecimals(
getFiatCurrencyByTicker("EUR").units[0],
"1234.5678 EUR"
)
).toBe("1234.56 EUR");
});
test("encodeURIScheme", () => {
expect(
encodeURIScheme({
currency: getCryptoCurrencyById("bitcoin"),
address: "1gre1noAY9HiK2qxoW8FzSdjdFBcoZ5fV",
})
).toBe("bitcoin:1gre1noAY9HiK2qxoW8FzSdjdFBcoZ5fV");
expect(
encodeURIScheme({
currency: getCryptoCurrencyById("bitcoin"),
address: "1gre1noAY9HiK2qxoW8FzSdjdFBcoZ5fV",
amount: new BigNumber("1234567000000"),
})
).toBe("bitcoin:1gre1noAY9HiK2qxoW8FzSdjdFBcoZ5fV?amount=12345.67");
});
test("decodeURIScheme", () => {
expect(
decodeURIScheme("bitcoin:1gre1noAY9HiK2qxoW8FzSdjdFBcoZ5fV")
).toMatchObject({
currency: getCryptoCurrencyById("bitcoin"),
address: "1gre1noAY9HiK2qxoW8FzSdjdFBcoZ5fV",
});
expect(
decodeURIScheme("bitcoin:1gre1noAY9HiK2qxoW8FzSdjdFBcoZ5fV?amount=12345.67")
).toMatchObject({
currency: getCryptoCurrencyById("bitcoin"),
address: "1gre1noAY9HiK2qxoW8FzSdjdFBcoZ5fV",
amount: new BigNumber("1234567000000"),
});
expect(
decodeURIScheme(
"ethereum:0x931d387731bbbc988b312206c74f77d004d6b84b?gas=100&gasPrice=200&value=" +
10 ** 18
)
).toMatchObject({
currency: getCryptoCurrencyById("ethereum"),
address: "0x931d387731bbbc988b312206c74f77d004d6b84b",
amount: new BigNumber(10 ** 18),
userGasLimit: new BigNumber(100),
gasPrice: new BigNumber(200),
});
expect(
decodeURIScheme(
"ethereum:0x931d387731bbbc988b312206c74f77d004d6b84b?gas=-1&gasPrice=-1&value=-1"
)
).toMatchObject({
currency: getCryptoCurrencyById("ethereum"),
address: "0x931d387731bbbc988b312206c74f77d004d6b84b",
amount: new BigNumber(0),
userGasLimit: new BigNumber(0),
gasPrice: new BigNumber(0),
});
expect(
decodeURIScheme(
"ethereum:0x072b04a9b047C3c7a2A455FFF5264D785e6E55C9?amount=0.0647&gasPrice=77000000000"
)
).toMatchObject({
currency: getCryptoCurrencyById("ethereum"),
address: "0x072b04a9b047C3c7a2A455FFF5264D785e6E55C9",
amount: new BigNumber(0.0647).times(10 ** 18),
gasPrice: new BigNumber(77000000000),
});
});
test("sanitizeValueString", () => {
const bitcoin = getCryptoCurrencyById("bitcoin");
const btcUnit = bitcoin.units[0];
const satUnit = bitcoin.units[bitcoin.units.length - 1];
expect(sanitizeValueString(btcUnit, "")).toMatchObject({
display: "",
});
expect(sanitizeValueString(btcUnit, "123456")).toMatchObject({
display: "123456",
value: "12345600000000",
});
expect(sanitizeValueString(btcUnit, "1")).toMatchObject({
display: "1",
value: "100000000",
});
expect(sanitizeValueString(btcUnit, "1.00")).toMatchObject({
display: "1.00",
value: "100000000",
});
expect(sanitizeValueString(btcUnit, ".00")).toMatchObject({
display: "0.00",
});
expect(sanitizeValueString(btcUnit, ".1")).toMatchObject({
display: "0.1",
});
expect(sanitizeValueString(btcUnit, ".123456789")).toMatchObject({
display: "0.12345678",
});
expect(sanitizeValueString(btcUnit, "1ab")).toMatchObject({
display: "1",
});
expect(sanitizeValueString(btcUnit, "1,3")).toMatchObject({
display: "1.3",
});
expect(sanitizeValueString(btcUnit, "1 300")).toMatchObject({
display: "1300",
});
expect(sanitizeValueString(btcUnit, "13.")).toMatchObject({
display: "13.",
value: "1300000000",
});
expect(sanitizeValueString(satUnit, "13.")).toMatchObject({
display: "13",
value: "13",
});
expect(sanitizeValueString(btcUnit, "000.12345678")).toMatchObject({
display: "0.12345678",
value: "12345678",
});
expect(sanitizeValueString(btcUnit, "001.23456789")).toMatchObject({
display: "1.23456789",
value: "123456789",
});
}); | the_stack |
import { assert, assertionError } from '@firebase/util';
import { AckUserWrite } from '../operation/AckUserWrite';
import { Merge } from '../operation/Merge';
import { Operation, OperationType } from '../operation/Operation';
import { Overwrite } from '../operation/Overwrite';
import { ChildrenNode } from '../snap/ChildrenNode';
import { KEY_INDEX } from '../snap/indexes/KeyIndex';
import { Node } from '../snap/Node';
import { ImmutableTree } from '../util/ImmutableTree';
import {
newEmptyPath,
Path,
pathChild,
pathGetBack,
pathGetFront,
pathGetLength,
pathIsEmpty,
pathParent,
pathPopFront
} from '../util/Path';
import {
WriteTreeRef,
writeTreeRefCalcCompleteChild,
writeTreeRefCalcCompleteEventCache,
writeTreeRefCalcCompleteEventChildren,
writeTreeRefCalcEventCacheAfterServerOverwrite,
writeTreeRefShadowingWrite
} from '../WriteTree';
import { Change, changeValue } from './Change';
import { ChildChangeAccumulator } from './ChildChangeAccumulator';
import {
CompleteChildSource,
NO_COMPLETE_CHILD_SOURCE,
WriteTreeCompleteChildSource
} from './CompleteChildSource';
import { NodeFilter } from './filter/NodeFilter';
import {
ViewCache,
viewCacheGetCompleteEventSnap,
viewCacheGetCompleteServerSnap,
viewCacheUpdateEventSnap,
viewCacheUpdateServerSnap
} from './ViewCache';
export interface ProcessorResult {
readonly viewCache: ViewCache;
readonly changes: Change[];
}
export interface ViewProcessor {
readonly filter: NodeFilter;
}
export function newViewProcessor(filter: NodeFilter): ViewProcessor {
return { filter };
}
export function viewProcessorAssertIndexed(
viewProcessor: ViewProcessor,
viewCache: ViewCache
): void {
assert(
viewCache.eventCache.getNode().isIndexed(viewProcessor.filter.getIndex()),
'Event snap not indexed'
);
assert(
viewCache.serverCache.getNode().isIndexed(viewProcessor.filter.getIndex()),
'Server snap not indexed'
);
}
export function viewProcessorApplyOperation(
viewProcessor: ViewProcessor,
oldViewCache: ViewCache,
operation: Operation,
writesCache: WriteTreeRef,
completeCache: Node | null
): ProcessorResult {
const accumulator = new ChildChangeAccumulator();
let newViewCache, filterServerNode;
if (operation.type === OperationType.OVERWRITE) {
const overwrite = operation as Overwrite;
if (overwrite.source.fromUser) {
newViewCache = viewProcessorApplyUserOverwrite(
viewProcessor,
oldViewCache,
overwrite.path,
overwrite.snap,
writesCache,
completeCache,
accumulator
);
} else {
assert(overwrite.source.fromServer, 'Unknown source.');
// We filter the node if it's a tagged update or the node has been previously filtered and the
// update is not at the root in which case it is ok (and necessary) to mark the node unfiltered
// again
filterServerNode =
overwrite.source.tagged ||
(oldViewCache.serverCache.isFiltered() && !pathIsEmpty(overwrite.path));
newViewCache = viewProcessorApplyServerOverwrite(
viewProcessor,
oldViewCache,
overwrite.path,
overwrite.snap,
writesCache,
completeCache,
filterServerNode,
accumulator
);
}
} else if (operation.type === OperationType.MERGE) {
const merge = operation as Merge;
if (merge.source.fromUser) {
newViewCache = viewProcessorApplyUserMerge(
viewProcessor,
oldViewCache,
merge.path,
merge.children,
writesCache,
completeCache,
accumulator
);
} else {
assert(merge.source.fromServer, 'Unknown source.');
// We filter the node if it's a tagged update or the node has been previously filtered
filterServerNode =
merge.source.tagged || oldViewCache.serverCache.isFiltered();
newViewCache = viewProcessorApplyServerMerge(
viewProcessor,
oldViewCache,
merge.path,
merge.children,
writesCache,
completeCache,
filterServerNode,
accumulator
);
}
} else if (operation.type === OperationType.ACK_USER_WRITE) {
const ackUserWrite = operation as AckUserWrite;
if (!ackUserWrite.revert) {
newViewCache = viewProcessorAckUserWrite(
viewProcessor,
oldViewCache,
ackUserWrite.path,
ackUserWrite.affectedTree,
writesCache,
completeCache,
accumulator
);
} else {
newViewCache = viewProcessorRevertUserWrite(
viewProcessor,
oldViewCache,
ackUserWrite.path,
writesCache,
completeCache,
accumulator
);
}
} else if (operation.type === OperationType.LISTEN_COMPLETE) {
newViewCache = viewProcessorListenComplete(
viewProcessor,
oldViewCache,
operation.path,
writesCache,
accumulator
);
} else {
throw assertionError('Unknown operation type: ' + operation.type);
}
const changes = accumulator.getChanges();
viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, changes);
return { viewCache: newViewCache, changes };
}
function viewProcessorMaybeAddValueEvent(
oldViewCache: ViewCache,
newViewCache: ViewCache,
accumulator: Change[]
): void {
const eventSnap = newViewCache.eventCache;
if (eventSnap.isFullyInitialized()) {
const isLeafOrEmpty =
eventSnap.getNode().isLeafNode() || eventSnap.getNode().isEmpty();
const oldCompleteSnap = viewCacheGetCompleteEventSnap(oldViewCache);
if (
accumulator.length > 0 ||
!oldViewCache.eventCache.isFullyInitialized() ||
(isLeafOrEmpty && !eventSnap.getNode().equals(oldCompleteSnap)) ||
!eventSnap.getNode().getPriority().equals(oldCompleteSnap.getPriority())
) {
accumulator.push(
changeValue(viewCacheGetCompleteEventSnap(newViewCache))
);
}
}
}
function viewProcessorGenerateEventCacheAfterServerEvent(
viewProcessor: ViewProcessor,
viewCache: ViewCache,
changePath: Path,
writesCache: WriteTreeRef,
source: CompleteChildSource,
accumulator: ChildChangeAccumulator
): ViewCache {
const oldEventSnap = viewCache.eventCache;
if (writeTreeRefShadowingWrite(writesCache, changePath) != null) {
// we have a shadowing write, ignore changes
return viewCache;
} else {
let newEventCache, serverNode;
if (pathIsEmpty(changePath)) {
// TODO: figure out how this plays with "sliding ack windows"
assert(
viewCache.serverCache.isFullyInitialized(),
'If change path is empty, we must have complete server data'
);
if (viewCache.serverCache.isFiltered()) {
// We need to special case this, because we need to only apply writes to complete children, or
// we might end up raising events for incomplete children. If the server data is filtered deep
// writes cannot be guaranteed to be complete
const serverCache = viewCacheGetCompleteServerSnap(viewCache);
const completeChildren =
serverCache instanceof ChildrenNode
? serverCache
: ChildrenNode.EMPTY_NODE;
const completeEventChildren = writeTreeRefCalcCompleteEventChildren(
writesCache,
completeChildren
);
newEventCache = viewProcessor.filter.updateFullNode(
viewCache.eventCache.getNode(),
completeEventChildren,
accumulator
);
} else {
const completeNode = writeTreeRefCalcCompleteEventCache(
writesCache,
viewCacheGetCompleteServerSnap(viewCache)
);
newEventCache = viewProcessor.filter.updateFullNode(
viewCache.eventCache.getNode(),
completeNode,
accumulator
);
}
} else {
const childKey = pathGetFront(changePath);
if (childKey === '.priority') {
assert(
pathGetLength(changePath) === 1,
"Can't have a priority with additional path components"
);
const oldEventNode = oldEventSnap.getNode();
serverNode = viewCache.serverCache.getNode();
// we might have overwrites for this priority
const updatedPriority = writeTreeRefCalcEventCacheAfterServerOverwrite(
writesCache,
changePath,
oldEventNode,
serverNode
);
if (updatedPriority != null) {
newEventCache = viewProcessor.filter.updatePriority(
oldEventNode,
updatedPriority
);
} else {
// priority didn't change, keep old node
newEventCache = oldEventSnap.getNode();
}
} else {
const childChangePath = pathPopFront(changePath);
// update child
let newEventChild;
if (oldEventSnap.isCompleteForChild(childKey)) {
serverNode = viewCache.serverCache.getNode();
const eventChildUpdate =
writeTreeRefCalcEventCacheAfterServerOverwrite(
writesCache,
changePath,
oldEventSnap.getNode(),
serverNode
);
if (eventChildUpdate != null) {
newEventChild = oldEventSnap
.getNode()
.getImmediateChild(childKey)
.updateChild(childChangePath, eventChildUpdate);
} else {
// Nothing changed, just keep the old child
newEventChild = oldEventSnap.getNode().getImmediateChild(childKey);
}
} else {
newEventChild = writeTreeRefCalcCompleteChild(
writesCache,
childKey,
viewCache.serverCache
);
}
if (newEventChild != null) {
newEventCache = viewProcessor.filter.updateChild(
oldEventSnap.getNode(),
childKey,
newEventChild,
childChangePath,
source,
accumulator
);
} else {
// no complete child available or no change
newEventCache = oldEventSnap.getNode();
}
}
}
return viewCacheUpdateEventSnap(
viewCache,
newEventCache,
oldEventSnap.isFullyInitialized() || pathIsEmpty(changePath),
viewProcessor.filter.filtersNodes()
);
}
}
function viewProcessorApplyServerOverwrite(
viewProcessor: ViewProcessor,
oldViewCache: ViewCache,
changePath: Path,
changedSnap: Node,
writesCache: WriteTreeRef,
completeCache: Node | null,
filterServerNode: boolean,
accumulator: ChildChangeAccumulator
): ViewCache {
const oldServerSnap = oldViewCache.serverCache;
let newServerCache;
const serverFilter = filterServerNode
? viewProcessor.filter
: viewProcessor.filter.getIndexedFilter();
if (pathIsEmpty(changePath)) {
newServerCache = serverFilter.updateFullNode(
oldServerSnap.getNode(),
changedSnap,
null
);
} else if (serverFilter.filtersNodes() && !oldServerSnap.isFiltered()) {
// we want to filter the server node, but we didn't filter the server node yet, so simulate a full update
const newServerNode = oldServerSnap
.getNode()
.updateChild(changePath, changedSnap);
newServerCache = serverFilter.updateFullNode(
oldServerSnap.getNode(),
newServerNode,
null
);
} else {
const childKey = pathGetFront(changePath);
if (
!oldServerSnap.isCompleteForPath(changePath) &&
pathGetLength(changePath) > 1
) {
// We don't update incomplete nodes with updates intended for other listeners
return oldViewCache;
}
const childChangePath = pathPopFront(changePath);
const childNode = oldServerSnap.getNode().getImmediateChild(childKey);
const newChildNode = childNode.updateChild(childChangePath, changedSnap);
if (childKey === '.priority') {
newServerCache = serverFilter.updatePriority(
oldServerSnap.getNode(),
newChildNode
);
} else {
newServerCache = serverFilter.updateChild(
oldServerSnap.getNode(),
childKey,
newChildNode,
childChangePath,
NO_COMPLETE_CHILD_SOURCE,
null
);
}
}
const newViewCache = viewCacheUpdateServerSnap(
oldViewCache,
newServerCache,
oldServerSnap.isFullyInitialized() || pathIsEmpty(changePath),
serverFilter.filtersNodes()
);
const source = new WriteTreeCompleteChildSource(
writesCache,
newViewCache,
completeCache
);
return viewProcessorGenerateEventCacheAfterServerEvent(
viewProcessor,
newViewCache,
changePath,
writesCache,
source,
accumulator
);
}
function viewProcessorApplyUserOverwrite(
viewProcessor: ViewProcessor,
oldViewCache: ViewCache,
changePath: Path,
changedSnap: Node,
writesCache: WriteTreeRef,
completeCache: Node | null,
accumulator: ChildChangeAccumulator
): ViewCache {
const oldEventSnap = oldViewCache.eventCache;
let newViewCache, newEventCache;
const source = new WriteTreeCompleteChildSource(
writesCache,
oldViewCache,
completeCache
);
if (pathIsEmpty(changePath)) {
newEventCache = viewProcessor.filter.updateFullNode(
oldViewCache.eventCache.getNode(),
changedSnap,
accumulator
);
newViewCache = viewCacheUpdateEventSnap(
oldViewCache,
newEventCache,
true,
viewProcessor.filter.filtersNodes()
);
} else {
const childKey = pathGetFront(changePath);
if (childKey === '.priority') {
newEventCache = viewProcessor.filter.updatePriority(
oldViewCache.eventCache.getNode(),
changedSnap
);
newViewCache = viewCacheUpdateEventSnap(
oldViewCache,
newEventCache,
oldEventSnap.isFullyInitialized(),
oldEventSnap.isFiltered()
);
} else {
const childChangePath = pathPopFront(changePath);
const oldChild = oldEventSnap.getNode().getImmediateChild(childKey);
let newChild;
if (pathIsEmpty(childChangePath)) {
// Child overwrite, we can replace the child
newChild = changedSnap;
} else {
const childNode = source.getCompleteChild(childKey);
if (childNode != null) {
if (
pathGetBack(childChangePath) === '.priority' &&
childNode.getChild(pathParent(childChangePath)).isEmpty()
) {
// This is a priority update on an empty node. If this node exists on the server, the
// server will send down the priority in the update, so ignore for now
newChild = childNode;
} else {
newChild = childNode.updateChild(childChangePath, changedSnap);
}
} else {
// There is no complete child node available
newChild = ChildrenNode.EMPTY_NODE;
}
}
if (!oldChild.equals(newChild)) {
const newEventSnap = viewProcessor.filter.updateChild(
oldEventSnap.getNode(),
childKey,
newChild,
childChangePath,
source,
accumulator
);
newViewCache = viewCacheUpdateEventSnap(
oldViewCache,
newEventSnap,
oldEventSnap.isFullyInitialized(),
viewProcessor.filter.filtersNodes()
);
} else {
newViewCache = oldViewCache;
}
}
}
return newViewCache;
}
function viewProcessorCacheHasChild(
viewCache: ViewCache,
childKey: string
): boolean {
return viewCache.eventCache.isCompleteForChild(childKey);
}
function viewProcessorApplyUserMerge(
viewProcessor: ViewProcessor,
viewCache: ViewCache,
path: Path,
changedChildren: ImmutableTree<Node>,
writesCache: WriteTreeRef,
serverCache: Node | null,
accumulator: ChildChangeAccumulator
): ViewCache {
// HACK: In the case of a limit query, there may be some changes that bump things out of the
// window leaving room for new items. It's important we process these changes first, so we
// iterate the changes twice, first processing any that affect items currently in view.
// TODO: I consider an item "in view" if cacheHasChild is true, which checks both the server
// and event snap. I'm not sure if this will result in edge cases when a child is in one but
// not the other.
let curViewCache = viewCache;
changedChildren.foreach((relativePath, childNode) => {
const writePath = pathChild(path, relativePath);
if (viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {
curViewCache = viewProcessorApplyUserOverwrite(
viewProcessor,
curViewCache,
writePath,
childNode,
writesCache,
serverCache,
accumulator
);
}
});
changedChildren.foreach((relativePath, childNode) => {
const writePath = pathChild(path, relativePath);
if (!viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {
curViewCache = viewProcessorApplyUserOverwrite(
viewProcessor,
curViewCache,
writePath,
childNode,
writesCache,
serverCache,
accumulator
);
}
});
return curViewCache;
}
function viewProcessorApplyMerge(
viewProcessor: ViewProcessor,
node: Node,
merge: ImmutableTree<Node>
): Node {
merge.foreach((relativePath, childNode) => {
node = node.updateChild(relativePath, childNode);
});
return node;
}
function viewProcessorApplyServerMerge(
viewProcessor: ViewProcessor,
viewCache: ViewCache,
path: Path,
changedChildren: ImmutableTree<Node>,
writesCache: WriteTreeRef,
serverCache: Node | null,
filterServerNode: boolean,
accumulator: ChildChangeAccumulator
): ViewCache {
// If we don't have a cache yet, this merge was intended for a previously listen in the same location. Ignore it and
// wait for the complete data update coming soon.
if (
viewCache.serverCache.getNode().isEmpty() &&
!viewCache.serverCache.isFullyInitialized()
) {
return viewCache;
}
// HACK: In the case of a limit query, there may be some changes that bump things out of the
// window leaving room for new items. It's important we process these changes first, so we
// iterate the changes twice, first processing any that affect items currently in view.
// TODO: I consider an item "in view" if cacheHasChild is true, which checks both the server
// and event snap. I'm not sure if this will result in edge cases when a child is in one but
// not the other.
let curViewCache = viewCache;
let viewMergeTree;
if (pathIsEmpty(path)) {
viewMergeTree = changedChildren;
} else {
viewMergeTree = new ImmutableTree<Node>(null).setTree(
path,
changedChildren
);
}
const serverNode = viewCache.serverCache.getNode();
viewMergeTree.children.inorderTraversal((childKey, childTree) => {
if (serverNode.hasChild(childKey)) {
const serverChild = viewCache.serverCache
.getNode()
.getImmediateChild(childKey);
const newChild = viewProcessorApplyMerge(
viewProcessor,
serverChild,
childTree
);
curViewCache = viewProcessorApplyServerOverwrite(
viewProcessor,
curViewCache,
new Path(childKey),
newChild,
writesCache,
serverCache,
filterServerNode,
accumulator
);
}
});
viewMergeTree.children.inorderTraversal((childKey, childMergeTree) => {
const isUnknownDeepMerge =
!viewCache.serverCache.isCompleteForChild(childKey) &&
childMergeTree.value === undefined;
if (!serverNode.hasChild(childKey) && !isUnknownDeepMerge) {
const serverChild = viewCache.serverCache
.getNode()
.getImmediateChild(childKey);
const newChild = viewProcessorApplyMerge(
viewProcessor,
serverChild,
childMergeTree
);
curViewCache = viewProcessorApplyServerOverwrite(
viewProcessor,
curViewCache,
new Path(childKey),
newChild,
writesCache,
serverCache,
filterServerNode,
accumulator
);
}
});
return curViewCache;
}
function viewProcessorAckUserWrite(
viewProcessor: ViewProcessor,
viewCache: ViewCache,
ackPath: Path,
affectedTree: ImmutableTree<boolean>,
writesCache: WriteTreeRef,
completeCache: Node | null,
accumulator: ChildChangeAccumulator
): ViewCache {
if (writeTreeRefShadowingWrite(writesCache, ackPath) != null) {
return viewCache;
}
// Only filter server node if it is currently filtered
const filterServerNode = viewCache.serverCache.isFiltered();
// Essentially we'll just get our existing server cache for the affected paths and re-apply it as a server update
// now that it won't be shadowed.
const serverCache = viewCache.serverCache;
if (affectedTree.value != null) {
// This is an overwrite.
if (
(pathIsEmpty(ackPath) && serverCache.isFullyInitialized()) ||
serverCache.isCompleteForPath(ackPath)
) {
return viewProcessorApplyServerOverwrite(
viewProcessor,
viewCache,
ackPath,
serverCache.getNode().getChild(ackPath),
writesCache,
completeCache,
filterServerNode,
accumulator
);
} else if (pathIsEmpty(ackPath)) {
// This is a goofy edge case where we are acking data at this location but don't have full data. We
// should just re-apply whatever we have in our cache as a merge.
let changedChildren = new ImmutableTree<Node>(null);
serverCache.getNode().forEachChild(KEY_INDEX, (name, node) => {
changedChildren = changedChildren.set(new Path(name), node);
});
return viewProcessorApplyServerMerge(
viewProcessor,
viewCache,
ackPath,
changedChildren,
writesCache,
completeCache,
filterServerNode,
accumulator
);
} else {
return viewCache;
}
} else {
// This is a merge.
let changedChildren = new ImmutableTree<Node>(null);
affectedTree.foreach((mergePath, value) => {
const serverCachePath = pathChild(ackPath, mergePath);
if (serverCache.isCompleteForPath(serverCachePath)) {
changedChildren = changedChildren.set(
mergePath,
serverCache.getNode().getChild(serverCachePath)
);
}
});
return viewProcessorApplyServerMerge(
viewProcessor,
viewCache,
ackPath,
changedChildren,
writesCache,
completeCache,
filterServerNode,
accumulator
);
}
}
function viewProcessorListenComplete(
viewProcessor: ViewProcessor,
viewCache: ViewCache,
path: Path,
writesCache: WriteTreeRef,
accumulator: ChildChangeAccumulator
): ViewCache {
const oldServerNode = viewCache.serverCache;
const newViewCache = viewCacheUpdateServerSnap(
viewCache,
oldServerNode.getNode(),
oldServerNode.isFullyInitialized() || pathIsEmpty(path),
oldServerNode.isFiltered()
);
return viewProcessorGenerateEventCacheAfterServerEvent(
viewProcessor,
newViewCache,
path,
writesCache,
NO_COMPLETE_CHILD_SOURCE,
accumulator
);
}
function viewProcessorRevertUserWrite(
viewProcessor: ViewProcessor,
viewCache: ViewCache,
path: Path,
writesCache: WriteTreeRef,
completeServerCache: Node | null,
accumulator: ChildChangeAccumulator
): ViewCache {
let complete;
if (writeTreeRefShadowingWrite(writesCache, path) != null) {
return viewCache;
} else {
const source = new WriteTreeCompleteChildSource(
writesCache,
viewCache,
completeServerCache
);
const oldEventCache = viewCache.eventCache.getNode();
let newEventCache;
if (pathIsEmpty(path) || pathGetFront(path) === '.priority') {
let newNode;
if (viewCache.serverCache.isFullyInitialized()) {
newNode = writeTreeRefCalcCompleteEventCache(
writesCache,
viewCacheGetCompleteServerSnap(viewCache)
);
} else {
const serverChildren = viewCache.serverCache.getNode();
assert(
serverChildren instanceof ChildrenNode,
'serverChildren would be complete if leaf node'
);
newNode = writeTreeRefCalcCompleteEventChildren(
writesCache,
serverChildren as ChildrenNode
);
}
newNode = newNode as Node;
newEventCache = viewProcessor.filter.updateFullNode(
oldEventCache,
newNode,
accumulator
);
} else {
const childKey = pathGetFront(path);
let newChild = writeTreeRefCalcCompleteChild(
writesCache,
childKey,
viewCache.serverCache
);
if (
newChild == null &&
viewCache.serverCache.isCompleteForChild(childKey)
) {
newChild = oldEventCache.getImmediateChild(childKey);
}
if (newChild != null) {
newEventCache = viewProcessor.filter.updateChild(
oldEventCache,
childKey,
newChild,
pathPopFront(path),
source,
accumulator
);
} else if (viewCache.eventCache.getNode().hasChild(childKey)) {
// No complete child available, delete the existing one, if any
newEventCache = viewProcessor.filter.updateChild(
oldEventCache,
childKey,
ChildrenNode.EMPTY_NODE,
pathPopFront(path),
source,
accumulator
);
} else {
newEventCache = oldEventCache;
}
if (
newEventCache.isEmpty() &&
viewCache.serverCache.isFullyInitialized()
) {
// We might have reverted all child writes. Maybe the old event was a leaf node
complete = writeTreeRefCalcCompleteEventCache(
writesCache,
viewCacheGetCompleteServerSnap(viewCache)
);
if (complete.isLeafNode()) {
newEventCache = viewProcessor.filter.updateFullNode(
newEventCache,
complete,
accumulator
);
}
}
}
complete =
viewCache.serverCache.isFullyInitialized() ||
writeTreeRefShadowingWrite(writesCache, newEmptyPath()) != null;
return viewCacheUpdateEventSnap(
viewCache,
newEventCache,
complete,
viewProcessor.filter.filtersNodes()
);
}
} | the_stack |
* @module Workspace
*/
import * as fs from "fs-extra";
import { parse } from "json5";
import { BeEvent, JSONSchemaType } from "@itwin/core-bentley";
import { LocalFileName } from "@itwin/core-common";
/** The type of a Setting, according to its schema
* @beta
*/
export type SettingType = JSONSchemaType;
/**
* The name of a Setting. SettingNames must be valid JavaScript property names, defined in a [[SettingSpec]].
* @see [SettingName]($docs/learning/backend/Workspace#settingnames)
* @beta
*/
export type SettingName = string;
/** The name of a [[SettingDictionary]]. `SettingDictionary`s are stored in [[Settings]] and may be removed by DictionaryName.
* DictionaryNames must be valid JavaScript property names.
* @beta
*/
export type DictionaryName = string;
/**
* A function called by [[Settings.resolveSetting]] for every SettingDictionary with a Setting that matches a name. The
* SettingDictionaries are sorted by priority and this function is called in priority order with the highest priority first.
* When this function returns a non-undefined value, the iteration is stopped and that value is returned. In this way,
* applications can "combine" the prioritized Setting values as appropriate. The default implementation of this function
* used by [[Settings.getSetting]] merely returns a clone of the value the first time it is called, so the highest priority
* value is returned.
* @beta
*/
export type SettingResolver<T> = (val: T, dict: DictionaryName, priority: SettingsPriority) => T | undefined;
/** An entry in the array returned by [[Settings.inspectSetting]]
* @beta
*
*/
export interface SettingInspector<T> { value: T, dictionary: DictionaryName, priority: number }
/** An object with string-named members (as opposed to an array object).
* @beta
*/
export interface SettingObject {
[name: string]: SettingType;
}
/**
* An object with Settings as its members. A SettingDictionary also has a name and generally comes from a parsed JSON file, but
* may also be created in memory by applications
* @beta
*/
export type SettingDictionary = SettingObject;
/**
* Values for SettingsPriority determine the sort order for Settings. Higher values take precedence over lower values.
* @beta
*/
export enum SettingsPriority {
/** values supplied default-settings files */
defaults = 100,
/** values supplied by applications at runtime */
application = 200,
/** values that apply to all iTwins for an organization. */
organization = 300,
/** values that apply to all iModels in an iTwin. */
iTwin = 400,
/** values that apply to a single iModel. */
iModel = 500,
}
/** The current set of Settings for a Workspace.
* @beta
*/
export interface Settings {
/** @internal */
close(): void;
/** Event raised whenever a SettingsDictionary is added or removed. */
readonly onSettingsChanged: BeEvent<() => void>;
/** Add a SettingDictionary from a local settings file. The file should be in [JSON5](https://json5.org/) format. It is read
* and parsed and the fileName is used as the DictionaryName.
* @param fileName the name of a local settings file of the SettingDictionary. This becomes the DictionaryName.
* @param priority the SettingsPriority for the SettingDictionary
* @note If the SettingDictionary was previously added, the new content overrides the old content.
*/
addFile(fileName: LocalFileName, priority: SettingsPriority): void;
/** Add a SettingDictionary from a JSON5 stringified string. The string is parsed and the resultant object is added as a SettingDictionary.
* @param dictionaryName the name of the SettingDictionary
* @param priority the SettingsPriority for the SettingDictionary
* @param settingsJson the JSON5 stringified string to be parsed.
* @note If the SettingDictionary was previously added, the new content overrides the old content.
*/
addJson(dictionaryName: DictionaryName, priority: SettingsPriority, settingsJson: string): void;
/** Add a SettingDictionary object.
* @param dictionaryName the name of the SettingDictionary
* @param priority the SettingsPriority for the SettingDictionary
* @param settings the SettingDictionary object to be added.
* @note If the SettingDictionary was previously added, the new content overrides the old content.
*/
addDictionary(dictionaryName: DictionaryName, priority: SettingsPriority, settings: SettingDictionary): void;
/** Remove a SettingDictionary by name. */
dropDictionary(dictionaryName: DictionaryName): void;
/**
* Resolve a setting, by name, using a SettingResolver.
* @param settingName The name of the setting to resolve
* @param resolver function to be called for each SettingDictionary with a matching Setting. Iteration stops when it returns a non-undefined value.
* @param defaultValue value returned if settingName is not present in any SettingDictionary or resolver never returned a value.
* @returns the resolved setting value.
*/
resolveSetting<T extends SettingType>(settingName: SettingName, resolver: SettingResolver<T>, defaultValue?: T): T | undefined;
resolveSetting<T extends SettingType>(settingName: SettingName, resolver: SettingResolver<T>, defaultValue: T): T;
/** Get the highest priority setting for a SettingName.
* @param settingName The name of the setting
* @param defaultValue value returned if settingName is not present in any SettingDictionary.
* @note This method is generic on SettingType, but no type checking is actually performed at run time. So, if you
* use this method to get a setting with an expected type, but its value is a different type, the return type of this method will be wrong.
* You must always type check the result. Use the non-generic "get" methods (e.g. [[getString]]) if you only want the value
* if its type is correct.
*/
getSetting<T extends SettingType>(settingName: SettingName, defaultValue?: T): T | undefined;
/** Get a string setting by SettingName.
* @param settingName The name of the setting
* @param defaultValue value returned if settingName is not present in any SettingDictionary, or if the highest priority setting is not a string.
*/
getString(settingName: SettingName, defaultValue: string): string;
getString(settingName: SettingName, defaultValue?: string): string | undefined;
/** Get a boolean setting by SettingName.
* @param settingName The name of the setting
* @param defaultValue value returned if settingName is not present in any SettingDictionary, or if the highest priority setting is not a boolean.
*/
getBoolean(settingName: SettingName, defaultValue: boolean): boolean;
getBoolean(settingName: SettingName, defaultValue?: boolean): boolean | undefined;
/** Get a number setting by SettingName.
* @param settingName The name of the setting
* @param defaultValue value returned if settingName is not present in any SettingDictionary, or if the highest priority setting is not a number.
*/
getNumber(settingName: SettingName, defaultValue: number): number;
getNumber(settingName: SettingName): number | undefined;
/** Get an object setting by SettingName.
* @param settingName The name of the setting
* @param defaultValue value returned if settingName is not present in any SettingDictionary, or if the highest priority setting is not an object.
*/
getObject<T extends object>(settingName: SettingName, defaultValue: T): T;
getObject<T extends object>(settingName: SettingName): T | undefined;
/** Get an array setting by SettingName.
* @param settingName The name of the setting
* @param defaultValue value returned if settingName is not present in any SettingDictionary, or if the highest priority setting is not an array.
*/
getArray<T extends SettingType>(settingName: SettingName, defaultValue: Array<T>): Array<T>;
getArray<T extends SettingType>(settingName: SettingName): Array<T> | undefined;
/** Get an array of [[SettingInspector] objects, sorted in priority order, for all Settings that match a SettingName.
* @note this method is mainly for debugging and diagnostics.
*/
inspectSetting<T extends SettingType>(name: SettingName): SettingInspector<T>[];
}
/** @internal */
function deepClone<T extends SettingType>(obj: any): T {
if (!obj || typeof obj !== "object")
return obj;
const result = Array.isArray(obj) ? [] : {} as any;
Object.keys(obj).forEach((key: string) => {
const val = obj[key];
if (val && typeof val === "object") {
result[key] = deepClone(val);
} else {
result[key] = val;
}
});
return result;
}
class SettingsDictionary {
public constructor(public readonly name: string, public readonly priority: SettingsPriority, public readonly settings: SettingDictionary) { }
public getSetting<T extends SettingType>(settingName: string): SettingType | undefined {
return this.settings[settingName] as T | undefined;
}
}
/**
* Internal implementation of Settings interface.
* @internal
*/
export class BaseSettings implements Settings {
private _dictionaries: SettingsDictionary[] = [];
protected verifyPriority(_priority: SettingsPriority) { }
public close() { }
public readonly onSettingsChanged = new BeEvent<() => void>();
public addFile(fileName: LocalFileName, priority: SettingsPriority) {
this.addJson(fileName, priority, fs.readFileSync(fileName, "utf-8"));
}
public addJson(dictionaryName: string, priority: SettingsPriority, settingsJson: string) {
this.addDictionary(dictionaryName, priority, parse(settingsJson));
}
public addDictionary(dictionaryName: string, priority: SettingsPriority, settings: SettingDictionary) {
this.verifyPriority(priority);
this.dropDictionary(dictionaryName, false); // make sure we don't have the same dictionary twice
const file = new SettingsDictionary(dictionaryName, priority, settings);
const doAdd = () => {
for (let i = 0; i < this._dictionaries.length; ++i) {
if (this._dictionaries[i].priority <= file.priority) {
this._dictionaries.splice(i, 0, file);
return;
}
}
this._dictionaries.push(file);
};
doAdd();
this.onSettingsChanged.raiseEvent();
}
public dropDictionary(dictionaryName: DictionaryName, raiseEvent = true) {
for (let i = 0; i < this._dictionaries.length; ++i) {
if (this._dictionaries[i].name === dictionaryName) {
this._dictionaries.splice(i, 1);
if (raiseEvent)
this.onSettingsChanged.raiseEvent();
return true;
}
}
return false;
}
public resolveSetting<T extends SettingType>(name: SettingName, resolver: SettingResolver<T>, defaultValue?: T): T | undefined {
for (const dict of this._dictionaries) {
const val = dict.getSetting(name) as T | undefined;
const resolved = val && resolver(val, dict.name, dict.priority);
if (undefined !== resolved)
return resolved;
}
return defaultValue;
}
public getSetting<T extends SettingType>(name: SettingName, defaultValue?: T): T | undefined {
return this.resolveSetting(name, (val) => deepClone<T>(val)) ?? defaultValue;
}
/** for debugging. Returns an array of all values for a setting, sorted by priority.
* @note values are not cloned. Do not modify objects or arrays.
*/
public inspectSetting<T extends SettingType>(name: SettingName): SettingInspector<T>[] {
const all: SettingInspector<T>[] = [];
this.resolveSetting<T>(name, (value, dictionary, priority) => { all.push({ value, dictionary, priority }); return undefined; });
return all;
}
public getString(name: SettingName, defaultValue: string): string;
public getString(name: SettingName): string | undefined;
public getString(name: SettingName, defaultValue?: string): string | undefined {
const out = this.getSetting<string>(name);
return typeof out === "string" ? out : defaultValue;
}
public getBoolean(name: SettingName, defaultValue: boolean): boolean;
public getBoolean(name: SettingName): boolean | undefined;
public getBoolean(name: SettingName, defaultValue?: boolean): boolean | undefined {
const out = this.getSetting<boolean>(name);
return typeof out === "boolean" ? out : defaultValue;
}
public getNumber(name: SettingName, defaultValue: number): number;
public getNumber(name: SettingName): number | undefined;
public getNumber(name: SettingName, defaultValue?: number): number | undefined {
const out = this.getSetting<number>(name);
return typeof out === "number" ? out : defaultValue;
}
public getObject<T extends object>(name: SettingName, defaultValue: T): T;
public getObject<T extends object>(name: SettingName): T | undefined;
public getObject<T extends object>(name: SettingName, defaultValue?: T): T | undefined {
const out = this.getSetting<SettingObject>(name);
return typeof out === "object" ? out as T : defaultValue;
}
public getArray<T extends SettingType>(name: SettingName, defaultValue: Array<T>): Array<T>;
public getArray<T extends SettingType>(name: SettingName): Array<T> | undefined;
public getArray<T extends SettingType>(name: SettingName, defaultValue?: Array<T>): Array<T> | undefined {
const out = this.getSetting<Array<T>>(name);
return Array.isArray(out) ? out : defaultValue;
}
} | the_stack |
import {ReadBuffer} from "../buffer";
import LRU from "../lru";
import {ICodec, uuid, ScalarCodec} from "./ifaces";
import {NULL_CODEC, SCALAR_CODECS} from "./codecs";
import {NULL_CODEC_ID, KNOWN_TYPES, KNOWN_TYPENAMES} from "./consts";
import {EMPTY_TUPLE_CODEC, EMPTY_TUPLE_CODEC_ID, TupleCodec} from "./tuple";
import * as numerics from "./numerics";
import * as numbers from "./numbers";
import * as datecodecs from "./datetime";
import {ArrayCodec} from "./array";
import {NamedTupleCodec} from "./namedtuple";
import {EnumCodec} from "./enum";
import {ObjectCodec} from "./object";
import {SetCodec} from "./set";
import {ProtocolVersion} from "../ifaces";
import {versionGreaterThanOrEqual} from "../utils";
const CODECS_CACHE_SIZE = 1000;
const CODECS_BUILD_CACHE_SIZE = 200;
const CTYPE_SET = 0;
const CTYPE_SHAPE = 1;
const CTYPE_BASE_SCALAR = 2;
const CTYPE_SCALAR = 3;
const CTYPE_TUPLE = 4;
const CTYPE_NAMEDTUPLE = 5;
const CTYPE_ARRAY = 6;
const CTYPE_ENUM = 7;
interface StringCodecSpec {
decimal?: boolean;
bigint?: boolean;
int64?: boolean;
datetime?: boolean;
local_datetime?: boolean;
}
const DECIMAL_TYPEID = KNOWN_TYPENAMES.get("std::decimal")!;
const BIGINT_TYPEID = KNOWN_TYPENAMES.get("std::bigint")!;
const INT64_TYPEID = KNOWN_TYPENAMES.get("std::int64")!;
const DATETIME_TYPEID = KNOWN_TYPENAMES.get("std::datetime")!;
const LOCAL_DATETIME_TYPEID = KNOWN_TYPENAMES.get("cal::local_datetime")!;
export class CodecsRegistry {
private codecsBuildCache: LRU<uuid, ICodec>;
private codecs: LRU<uuid, ICodec>;
private customScalarCodecs: Map<uuid, ICodec>;
constructor() {
this.codecs = new LRU({capacity: CODECS_CACHE_SIZE});
this.codecsBuildCache = new LRU({capacity: CODECS_BUILD_CACHE_SIZE});
this.customScalarCodecs = new Map();
}
setStringCodecs({
decimal,
bigint,
int64,
datetime,
local_datetime,
}: StringCodecSpec = {}): void {
// This is a private API and it will change in the future.
if (decimal) {
this.customScalarCodecs.set(
DECIMAL_TYPEID,
new numerics.DecimalStringCodec(DECIMAL_TYPEID)
);
} else {
this.customScalarCodecs.delete(DECIMAL_TYPEID);
}
if (bigint) {
this.customScalarCodecs.set(
BIGINT_TYPEID,
new numerics.BigIntStringCodec(BIGINT_TYPEID)
);
} else {
this.customScalarCodecs.delete(BIGINT_TYPEID);
}
if (int64) {
this.customScalarCodecs.set(
INT64_TYPEID,
new numbers.Int64StringCodec(INT64_TYPEID)
);
} else {
this.customScalarCodecs.delete(INT64_TYPEID);
}
if (datetime) {
this.customScalarCodecs.set(
DATETIME_TYPEID,
new datecodecs.EdgeDBDateTimeCodec(DATETIME_TYPEID)
);
} else {
this.customScalarCodecs.delete(DATETIME_TYPEID);
}
if (local_datetime) {
this.customScalarCodecs.set(
LOCAL_DATETIME_TYPEID,
new datecodecs.EdgeDBDateTimeCodec(LOCAL_DATETIME_TYPEID)
);
} else {
this.customScalarCodecs.delete(LOCAL_DATETIME_TYPEID);
}
}
hasCodec(typeId: uuid): boolean {
if (this.codecs.has(typeId)) {
return true;
}
return typeId === NULL_CODEC_ID || typeId === EMPTY_TUPLE_CODEC_ID;
}
getCodec(typeId: uuid): ICodec | null {
const codec = this.codecs.get(typeId);
if (codec != null) {
return codec;
}
if (typeId === EMPTY_TUPLE_CODEC_ID) {
return EMPTY_TUPLE_CODEC;
}
if (typeId === NULL_CODEC_ID) {
return NULL_CODEC;
}
return null;
}
buildCodec(spec: Buffer, protocolVersion: ProtocolVersion): ICodec {
const frb = new ReadBuffer(spec);
const codecsList: ICodec[] = [];
let codec: ICodec | null = null;
while (frb.length) {
codec = this._buildCodec(frb, codecsList, protocolVersion);
if (codec == null) {
// An annotation; ignore.
continue;
}
codecsList.push(codec);
this.codecs.set(codec.tid, codec);
}
if (!codecsList.length) {
throw new Error("could not build a codec");
}
return codecsList[codecsList.length - 1];
}
private _buildCodec(
frb: ReadBuffer,
cl: ICodec[],
protocolVersion: ProtocolVersion
): ICodec | null {
const t = frb.readUInt8();
const tid = frb.readUUID();
let res = this.codecs.get(tid);
if (res == null) {
res = this.codecsBuildCache.get(tid);
}
if (res != null) {
// We have a codec for this "tid"; advance the buffer
// so that we can process the next codec.
switch (t) {
case CTYPE_SET: {
frb.discard(2);
break;
}
case CTYPE_SHAPE: {
const els = frb.readUInt16();
for (let i = 0; i < els; i++) {
if (versionGreaterThanOrEqual(protocolVersion, [0, 11])) {
frb.discard(5); // 4 (flags) + 1 (cardinality)
} else {
frb.discard(1); // flags
}
const elm_length = frb.readUInt32();
frb.discard(elm_length + 2);
}
break;
}
case CTYPE_BASE_SCALAR: {
break;
}
case CTYPE_SCALAR: {
frb.discard(2);
break;
}
case CTYPE_TUPLE: {
const els = frb.readUInt16();
frb.discard(2 * els);
break;
}
case CTYPE_NAMEDTUPLE: {
const els = frb.readUInt16();
for (let i = 0; i < els; i++) {
const elm_length = frb.readUInt32();
frb.discard(elm_length + 2);
}
break;
}
case CTYPE_ARRAY: {
frb.discard(2);
const els = frb.readUInt16();
if (els !== 1) {
throw new Error(
"cannot handle arrays with more than one dimension"
);
}
frb.discard(4);
break;
}
case CTYPE_ENUM: {
const els = frb.readUInt16();
for (let i = 0; i < els; i++) {
const elm_length = frb.readUInt32();
frb.discard(elm_length);
}
break;
}
default: {
if (t >= 0x7f && t <= 0xff) {
const ann_length = frb.readUInt32();
if (t === 0xff) {
const typeName = frb.readBuffer(ann_length).toString("utf8");
const codec =
this.codecs.get(tid) ?? this.codecsBuildCache.get(tid);
if (codec instanceof ScalarCodec) {
codec.setTypeName(typeName);
}
} else {
frb.discard(ann_length);
}
return null;
} else {
throw new Error(
`no codec implementation for EdgeDB data class ${t}`
);
}
}
}
return res;
}
switch (t) {
case CTYPE_BASE_SCALAR: {
res = this.customScalarCodecs.get(tid);
if (res != null) {
break;
}
res = SCALAR_CODECS.get(tid);
if (!res) {
if (KNOWN_TYPES.has(tid)) {
throw new Error(`no JS codec for ${KNOWN_TYPES.get(tid)}`);
}
throw new Error(`node JS codec for the type with ID ${tid}`);
}
if (!(res instanceof ScalarCodec)) {
throw new Error(
"could not build scalar codec: base scalar has a non-scalar codec"
);
}
break;
}
case CTYPE_SHAPE: {
const els = frb.readUInt16();
const codecs: ICodec[] = new Array(els);
const names: string[] = new Array(els);
const flags: number[] = new Array(els);
const cards: number[] = new Array(els);
for (let i = 0; i < els; i++) {
let flag: number;
let card: number;
if (versionGreaterThanOrEqual(protocolVersion, [0, 11])) {
flag = frb.readUInt32();
card = frb.readUInt8(); // cardinality
} else {
flag = frb.readUInt8();
card = 0;
}
const strLen = frb.readUInt32();
const name = frb.readBuffer(strLen).toString("utf8");
const pos = frb.readUInt16();
const subCodec = cl[pos];
if (subCodec == null) {
throw new Error("could not build object codec: missing subcodec");
}
codecs[i] = subCodec;
names[i] = name;
flags[i] = flag;
cards[i] = card;
}
res = new ObjectCodec(tid, codecs, names, flags, cards);
break;
}
case CTYPE_SET: {
const pos = frb.readUInt16();
const subCodec = cl[pos];
if (subCodec == null) {
throw new Error("could not build set codec: missing subcodec");
}
res = new SetCodec(tid, subCodec);
break;
}
case CTYPE_SCALAR: {
const pos = frb.readUInt16();
res = cl[pos];
if (res == null) {
throw new Error(
"could not build scalar codec: missing a codec for base scalar"
);
}
if (!(res instanceof ScalarCodec)) {
throw new Error(
"could not build scalar codec: base scalar has a non-scalar codec"
);
}
res = <ICodec>res.derive(tid);
break;
}
case CTYPE_ARRAY: {
const pos = frb.readUInt16();
const els = frb.readUInt16();
if (els !== 1) {
throw new Error("cannot handle arrays with more than one dimension");
}
const dimLen = frb.readInt32();
const subCodec = cl[pos];
if (subCodec == null) {
throw new Error("could not build array codec: missing subcodec");
}
res = new ArrayCodec(tid, subCodec, dimLen);
break;
}
case CTYPE_TUPLE: {
const els = frb.readUInt16();
if (els === 0) {
res = EMPTY_TUPLE_CODEC;
} else {
const codecs = new Array(els);
for (let i = 0; i < els; i++) {
const pos = frb.readUInt16();
const subCodec = cl[pos];
if (subCodec == null) {
throw new Error("could not build tuple codec: missing subcodec");
}
codecs[i] = subCodec;
}
res = new TupleCodec(tid, codecs);
}
break;
}
case CTYPE_NAMEDTUPLE: {
const els = frb.readUInt16();
const codecs = new Array(els);
const names = new Array(els);
for (let i = 0; i < els; i++) {
const strLen = frb.readUInt32();
names[i] = frb.readBuffer(strLen).toString("utf8");
const pos = frb.readUInt16();
const subCodec = cl[pos];
if (subCodec == null) {
throw new Error(
"could not build namedtuple codec: missing subcodec"
);
}
codecs[i] = subCodec;
}
res = new NamedTupleCodec(tid, codecs, names);
break;
}
case CTYPE_ENUM: {
/* There's no way to customize ordering in JS, so we
simply ignore that information and unpack enums into
simple strings.
*/
const els = frb.readUInt16();
for (let i = 0; i < els; i++) {
frb.discard(frb.readUInt32());
}
res = new EnumCodec(tid);
break;
}
}
if (res == null) {
if (KNOWN_TYPES.has(tid)) {
throw new Error(
`could not build a codec for ${KNOWN_TYPES.get(tid)} type`
);
} else {
throw new Error(`could not build a codec for ${tid} type`);
}
}
this.codecsBuildCache.set(tid, res);
return res;
}
} | the_stack |
import { promisify } from 'util';
import test from 'ava';
import { simpleParser, ParsedMail, AddressObject } from 'mailparser';
import { SMTPServer } from 'smtp-server';
import {
DEFAULT_TIMEOUT,
SMTPClient,
Message,
MessageHeaders,
isRFC2822Date,
} from '../email';
const parseMap = new Map<string, ParsedMail>();
const port = 3000;
let greylistPort = 4000;
const client = new SMTPClient({
port,
user: 'pooh',
password: 'honey',
ssl: true,
});
const server = new SMTPServer({
secure: true,
onAuth(auth, _session, callback) {
if (auth.username === 'pooh' && auth.password === 'honey') {
callback(null, { user: 'pooh' });
} else {
return callback(new Error('invalid user / pass'));
}
},
async onData(stream, _session, callback: () => void) {
const mail = await simpleParser(stream, {
skipHtmlToText: true,
skipTextToHtml: true,
skipImageLinks: true,
} as Record<string, unknown>);
parseMap.set(mail.subject as string, mail);
callback();
},
});
async function send(headers: Partial<MessageHeaders>) {
return new Promise<ParsedMail>((resolve, reject) => {
client.send(new Message(headers), (err) => {
if (err) {
reject(err);
} else {
resolve(parseMap.get(headers.subject as string) as ParsedMail);
}
});
});
}
test.before(async (t) => {
server.listen(port, t.pass);
});
test.after(async (t) => {
server.close(t.pass);
});
test('client invokes callback exactly once for invalid connection', async (t) => {
const msg = {
from: 'foo@bar.baz',
to: 'foo@bar.baz',
subject: 'hello world',
text: 'hello world',
};
await t.notThrowsAsync(
new Promise<void>((resolve, reject) => {
let counter = 0;
const invalidClient = new SMTPClient({ host: 'bar.baz' });
const incrementCounter = () => {
if (counter > 0) {
reject();
} else {
counter++;
}
};
invalidClient.send(new Message(msg), (err) => {
if (err == null) {
reject();
} else {
incrementCounter();
}
});
// @ts-expect-error the error event is only accessible from the protected socket property
invalidClient.smtp.sock.once('error', () => {
if (counter === 1) {
resolve();
} else {
reject();
}
});
})
);
});
test('client has a default connection timeout', async (t) => {
const connectionOptions = {
user: 'username',
password: 'password',
host: '127.0.0.1',
port: 1234,
timeout: undefined as number | null | undefined,
};
t.is(new SMTPClient(connectionOptions).smtp.timeout, DEFAULT_TIMEOUT);
connectionOptions.timeout = null;
t.is(new SMTPClient(connectionOptions).smtp.timeout, DEFAULT_TIMEOUT);
connectionOptions.timeout = undefined;
t.is(new SMTPClient(connectionOptions).smtp.timeout, DEFAULT_TIMEOUT);
});
test('client deduplicates recipients', async (t) => {
const msg = {
from: 'zelda@gmail.com',
to: 'gannon@gmail.com',
cc: 'gannon@gmail.com',
bcc: 'gannon@gmail.com',
};
const stack = client.createMessageStack(new Message(msg));
t.true(stack.to.length === 1);
t.is(stack.to[0].address, 'gannon@gmail.com');
});
test('client accepts array recipients', async (t) => {
const msg = new Message({
from: 'zelda@gmail.com',
to: ['gannon1@gmail.com'],
cc: ['gannon2@gmail.com'],
bcc: ['gannon3@gmail.com'],
});
msg.header.to = [msg.header.to as string];
msg.header.cc = [msg.header.cc as string];
msg.header.bcc = [msg.header.bcc as string];
const { isValid } = msg.checkValidity();
const stack = client.createMessageStack(msg);
t.true(isValid);
t.is(stack.to.length, 3);
t.deepEqual(
stack.to.map((x) => x.address),
['gannon1@gmail.com', 'gannon2@gmail.com', 'gannon3@gmail.com']
);
});
test('client accepts array sender', async (t) => {
const msg = new Message({
from: ['zelda@gmail.com'],
to: ['gannon1@gmail.com'],
});
msg.header.from = [msg.header.from as string];
const { isValid } = msg.checkValidity();
t.true(isValid);
});
test('client rejects message without `from` header', async (t) => {
const { message: error } = await t.throwsAsync(
send({
subject: 'this is a test TEXT message from emailjs',
text: "It is hard to be brave when you're only a Very Small Animal.",
})
);
t.is(error, 'Message must have a `from` header');
});
test('client rejects message without `to`, `cc`, or `bcc` header', async (t) => {
const { message: error } = await t.throwsAsync(
send({
subject: 'this is a test TEXT message from emailjs',
from: 'piglet@gmail.com',
text: "It is hard to be brave when you're only a Very Small Animal.",
})
);
t.is(error, 'Message must have at least one `to`, `cc`, or `bcc` header');
});
test('client allows message with only `cc` recipient header', async (t) => {
const msg = {
subject: 'this is a test TEXT message from emailjs',
from: 'piglet@gmail.com',
cc: 'pooh@gmail.com',
text: "It is hard to be brave when you're only a Very Small Animal.",
};
const mail = await send(msg);
t.is(mail.text, msg.text + '\n\n\n');
t.is(mail.subject, msg.subject);
t.is(mail.from?.text, msg.from);
t.is((mail.cc as AddressObject).text, msg.cc);
});
test('client allows message with only `bcc` recipient header', async (t) => {
const msg = {
subject: 'this is a test TEXT message from emailjs',
from: 'piglet@gmail.com',
bcc: 'pooh@gmail.com',
text: "It is hard to be brave when you're only a Very Small Animal.",
};
const mail = await send(msg);
t.is(mail.text, msg.text + '\n\n\n');
t.is(mail.subject, msg.subject);
t.is(mail.from?.text, msg.from);
t.is(mail.bcc, undefined);
});
test('client constructor throws if `password` supplied without `user`', async (t) => {
t.notThrows(() => new SMTPClient({ user: 'anything', password: 'anything' }));
t.throws(() => new SMTPClient({ password: 'anything' }));
t.throws(
() =>
new SMTPClient({ username: 'anything', password: 'anything' } as Record<
string,
unknown
>)
);
});
test('client supports greylisting', async (t) => {
t.plan(3);
const msg = {
subject: 'this is a test TEXT message from emailjs',
from: 'piglet@gmail.com',
bcc: 'pooh@gmail.com',
text: "It is hard to be brave when you're only a Very Small Animal.",
};
const greylistServer = new SMTPServer({
secure: true,
onRcptTo(_address, _session, callback) {
t.pass();
callback();
},
onAuth(auth, _session, callback) {
if (auth.username === 'pooh' && auth.password === 'honey') {
callback(null, { user: 'pooh' });
} else {
return callback(new Error('invalid user / pass'));
}
},
});
const { onRcptTo } = greylistServer;
greylistServer.onRcptTo = (_address, _session, callback) => {
greylistServer.onRcptTo = (a, s, cb) => {
t.pass();
const err = new Error('greylist');
(err as never as { responseCode: number }).responseCode = 450;
greylistServer.onRcptTo = onRcptTo;
onRcptTo(a, s, cb);
};
const err = new Error('greylist');
(err as never as { responseCode: number }).responseCode = 450;
callback(err);
};
const p = greylistPort++;
await t.notThrowsAsync(
new Promise<void>((resolve, reject) => {
greylistServer.listen(p, () => {
new SMTPClient({
port: p,
user: 'pooh',
password: 'honey',
ssl: true,
}).send(new Message(msg), (err) => {
greylistServer.close();
if (err) {
reject(err);
} else {
resolve();
}
});
});
})
);
});
test('client only responds once to greylisting', async (t) => {
t.plan(4);
const msg = {
subject: 'this is a test TEXT message from emailjs',
from: 'piglet@gmail.com',
bcc: 'pooh@gmail.com',
text: "It is hard to be brave when you're only a Very Small Animal.",
};
const greylistServer = new SMTPServer({
secure: true,
onRcptTo(_address, _session, callback) {
t.pass();
const err = new Error('greylist');
(err as never as { responseCode: number }).responseCode = 450;
callback(err);
},
onAuth(auth, _session, callback) {
if (auth.username === 'pooh' && auth.password === 'honey') {
callback(null, { user: 'pooh' });
} else {
return callback(new Error('invalid user / pass'));
}
},
});
const p = greylistPort++;
const { message: error } = await t.throwsAsync(
new Promise<void>((resolve, reject) => {
greylistServer.listen(p, () => {
new SMTPClient({
port: p,
user: 'pooh',
password: 'honey',
ssl: true,
}).send(new Message(msg), (err) => {
greylistServer.close();
if (err) {
reject(err);
} else {
resolve();
}
});
});
})
);
t.is(error, "bad response on command 'RCPT': greylist");
});
test('client send can have result awaited when promisified', async (t) => {
// bind necessary to retain internal access to client prototype
const sendAsync = promisify(client.send.bind(client));
const msg = {
subject: 'this is a test TEXT message from emailjs',
from: 'piglet@gmail.com',
bcc: 'pooh@gmail.com',
text: "It is hard to be brave when you're only a Very Small Animal.",
};
try {
const message = await sendAsync(new Message(msg));
t.true(message instanceof Message);
t.like(message, {
alternative: null,
content: 'text/plain; charset=utf-8',
text: "It is hard to be brave when you're only a Very Small Animal.",
header: {
bcc: 'pooh@gmail.com',
from: 'piglet@gmail.com',
subject: '=?UTF-8?Q?this_is_a_test_TEXT_message_from_emailjs?=',
},
});
t.deepEqual(message.attachments, []);
t.true(isRFC2822Date(message.header.date as string));
t.regex(message.header['message-id'] as string, /^<.*[@]{1}.*>$/);
} catch (err) {
if (err instanceof Error) {
t.fail(err.message);
} else if (typeof err === 'string') {
t.fail(err);
} else {
t.fail();
}
}
});
test('client sendAsync can have result awaited', async (t) => {
const msg = {
subject: 'this is a test TEXT message from emailjs',
from: 'piglet@gmail.com',
bcc: 'pooh@gmail.com',
text: "It is hard to be brave when you're only a Very Small Animal.",
};
try {
const message = await client.sendAsync(new Message(msg));
t.true(message instanceof Message);
t.like(message, {
alternative: null,
content: 'text/plain; charset=utf-8',
text: "It is hard to be brave when you're only a Very Small Animal.",
header: {
bcc: 'pooh@gmail.com',
from: 'piglet@gmail.com',
subject: '=?UTF-8?Q?this_is_a_test_TEXT_message_from_emailjs?=',
},
});
t.deepEqual(message.attachments, []);
t.true(isRFC2822Date(message.header.date as string));
t.regex(message.header['message-id'] as string, /^<.*[@]{1}.*>$/);
} catch (err) {
if (err instanceof Error) {
t.fail(err.message);
} else if (typeof err === 'string') {
t.fail(err);
} else {
t.fail();
}
}
});
test('client sendAsync can have error caught when awaited', async (t) => {
const msg = {
subject: 'this is a test TEXT message from emailjs',
from: 'piglet@gmail.com',
bcc: 'pooh@gmail.com',
text: "It is hard to be brave when you're only a Very Small Animal.",
};
try {
const invalidClient = new SMTPClient({ host: 'bar.baz' });
const message = await invalidClient.sendAsync(new Message(msg));
t.true(message instanceof Message);
t.fail();
} catch (err) {
t.true(err instanceof Error);
t.pass();
}
}); | the_stack |
import { Ref } from 'vue'
import { storeToRefs } from 'pinia'
import { useMainStore, useSlidesStore } from '@/store'
import { PPTElement } from '@/types/slides'
import { AlignmentLineProps } from '@/types/edit'
import { VIEWPORT_SIZE } from '@/configs/canvas'
import { getRectRotatedRange, AlignLine, uniqAlignLines } from '@/utils/element'
import useHistorySnapshot from '@/hooks/useHistorySnapshot'
export default (
elementList: Ref<PPTElement[]>,
alignmentLines: Ref<AlignmentLineProps[]>,
) => {
const slidesStore = useSlidesStore()
const { activeElementIdList, activeGroupElementId, canvasScale } = storeToRefs(useMainStore())
const { viewportRatio } = storeToRefs(slidesStore)
const { addHistorySnapshot } = useHistorySnapshot()
const dragElement = (e: MouseEvent, element: PPTElement) => {
if (!activeElementIdList.value.includes(element.id)) return
let isMouseDown = true
const edgeWidth = VIEWPORT_SIZE
const edgeHeight = VIEWPORT_SIZE * viewportRatio.value
const sorptionRange = 5
const originElementList: PPTElement[] = JSON.parse(JSON.stringify(elementList.value))
const originActiveElementList = originElementList.filter(el => activeElementIdList.value.includes(el.id))
const elOriginLeft = element.left
const elOriginTop = element.top
const elOriginWidth = element.width
const elOriginHeight = ('height' in element && element.height) ? element.height : 0
const elOriginRotate = ('rotate' in element && element.rotate) ? element.rotate : 0
const startPageX = e.pageX
const startPageY = e.pageY
let isMisoperation: boolean | null = null
const isActiveGroupElement = element.id === activeGroupElementId.value
// 收集对齐对齐吸附线
// 包括页面内除目标元素外的其他元素在画布中的各个可吸附对齐位置:上下左右四边,水平中心、垂直中心
// 其中线条和被旋转过的元素需要重新计算他们在画布中的中心点位置的范围
let horizontalLines: AlignLine[] = []
let verticalLines: AlignLine[] = []
for (const el of elementList.value) {
if (el.type === 'line') continue
if (isActiveGroupElement && el.id === element.id) continue
if (!isActiveGroupElement && activeElementIdList.value.includes(el.id)) continue
let left, top, width, height
if ('rotate' in el && el.rotate) {
const { xRange, yRange } = getRectRotatedRange({
left: el.left,
top: el.top,
width: el.width,
height: el.height,
rotate: el.rotate,
})
left = xRange[0]
top = yRange[0]
width = xRange[1] - xRange[0]
height = yRange[1] - yRange[0]
}
else {
left = el.left
top = el.top
width = el.width
height = el.height
}
const right = left + width
const bottom = top + height
const centerX = top + height / 2
const centerY = left + width / 2
const topLine: AlignLine = { value: top, range: [left, right] }
const bottomLine: AlignLine = { value: bottom, range: [left, right] }
const horizontalCenterLine: AlignLine = { value: centerX, range: [left, right] }
const leftLine: AlignLine = { value: left, range: [top, bottom] }
const rightLine: AlignLine = { value: right, range: [top, bottom] }
const verticalCenterLine: AlignLine = { value: centerY, range: [top, bottom] }
horizontalLines.push(topLine, bottomLine, horizontalCenterLine)
verticalLines.push(leftLine, rightLine, verticalCenterLine)
}
// 画布可视区域的四个边界、水平中心、垂直中心
const edgeTopLine: AlignLine = { value: 0, range: [0, edgeWidth] }
const edgeBottomLine: AlignLine = { value: edgeHeight, range: [0, edgeWidth] }
const edgeHorizontalCenterLine: AlignLine = { value: edgeHeight / 2, range: [0, edgeWidth] }
const edgeLeftLine: AlignLine = { value: 0, range: [0, edgeHeight] }
const edgeRightLine: AlignLine = { value: edgeWidth, range: [0, edgeHeight] }
const edgeVerticalCenterLine: AlignLine = { value: edgeWidth / 2, range: [0, edgeHeight] }
horizontalLines.push(edgeTopLine, edgeBottomLine, edgeHorizontalCenterLine)
verticalLines.push(edgeLeftLine, edgeRightLine, edgeVerticalCenterLine)
// 对齐吸附线去重
horizontalLines = uniqAlignLines(horizontalLines)
verticalLines = uniqAlignLines(verticalLines)
// 开始移动
document.onmousemove = e => {
const currentPageX = e.pageX
const currentPageY = e.pageY
// 如果鼠标滑动距离过小,则将操作判定为误操作:
// 如果误操作标记为null,表示是第一次触发移动,需要计算当前是否是误操作
// 如果误操作标记为true,表示当前还处在误操作范围内,但仍然需要继续计算检查后续操作是否还处于误操作
// 如果误操作标记为false,表示已经脱离了误操作范围,不需要再次计算
if (isMisoperation !== false) {
isMisoperation = Math.abs(startPageX - currentPageX) < sorptionRange &&
Math.abs(startPageY - currentPageY) < sorptionRange
}
if (!isMouseDown || isMisoperation) return
const moveX = (currentPageX - startPageX) / canvasScale.value
const moveY = (currentPageY - startPageY) / canvasScale.value
// 基础目标位置
let targetLeft = elOriginLeft + moveX
let targetTop = elOriginTop + moveY
// 计算目标元素在画布中的位置范围,用于吸附对齐
// 需要区分单选和多选两种情况,其中多选状态下需要计算多选元素的整体范围;单选状态下需要继续区分线条、普通元素、旋转后的普通元素三种情况
let targetMinX: number, targetMaxX: number, targetMinY: number, targetMaxY: number
if (activeElementIdList.value.length === 1 || isActiveGroupElement) {
if (elOriginRotate) {
const { xRange, yRange } = getRectRotatedRange({
left: targetLeft,
top: targetTop,
width: elOriginWidth,
height: elOriginHeight,
rotate: elOriginRotate,
})
targetMinX = xRange[0]
targetMaxX = xRange[1]
targetMinY = yRange[0]
targetMaxY = yRange[1]
}
else if (element.type === 'line') {
targetMinX = targetLeft
targetMaxX = targetLeft + Math.max(element.start[0], element.end[0])
targetMinY = targetTop
targetMaxY = targetTop + Math.max(element.start[1], element.end[1])
}
else {
targetMinX = targetLeft
targetMaxX = targetLeft + elOriginWidth
targetMinY = targetTop
targetMaxY = targetTop + elOriginHeight
}
}
else {
const leftValues = []
const topValues = []
const rightValues = []
const bottomValues = []
for (let i = 0; i < originActiveElementList.length; i++) {
const element = originActiveElementList[i]
const left = element.left + moveX
const top = element.top + moveY
const width = element.width
const height = ('height' in element && element.height) ? element.height : 0
const rotate = ('rotate' in element && element.rotate) ? element.rotate : 0
if ('rotate' in element && element.rotate) {
const { xRange, yRange } = getRectRotatedRange({ left, top, width, height, rotate })
leftValues.push(xRange[0])
topValues.push(yRange[0])
rightValues.push(xRange[1])
bottomValues.push(yRange[1])
}
else if (element.type === 'line') {
leftValues.push(left)
topValues.push(top)
rightValues.push(left + Math.max(element.start[0], element.end[0]))
bottomValues.push(top + Math.max(element.start[1], element.end[1]))
}
else {
leftValues.push(left)
topValues.push(top)
rightValues.push(left + width)
bottomValues.push(top + height)
}
}
targetMinX = Math.min(...leftValues)
targetMaxX = Math.max(...rightValues)
targetMinY = Math.min(...topValues)
targetMaxY = Math.max(...bottomValues)
}
const targetCenterX = targetMinX + (targetMaxX - targetMinX) / 2
const targetCenterY = targetMinY + (targetMaxY - targetMinY) / 2
// 将收集到的对齐吸附线与计算的目标元素位置范围做对比,二者的差小于设定的值时执行自动对齐校正
// 水平和垂直两个方向需要分开计算
const _alignmentLines: AlignmentLineProps[] = []
let isVerticalAdsorbed = false
let isHorizontalAdsorbed = false
for (let i = 0; i < horizontalLines.length; i++) {
const { value, range } = horizontalLines[i]
const min = Math.min(...range, targetMinX, targetMaxX)
const max = Math.max(...range, targetMinX, targetMaxX)
if (Math.abs(targetMinY - value) < sorptionRange && !isHorizontalAdsorbed) {
targetTop = targetTop - (targetMinY - value)
isHorizontalAdsorbed = true
_alignmentLines.push({type: 'horizontal', axis: {x: min - 50, y: value}, length: max - min + 100})
}
if (Math.abs(targetMaxY - value) < sorptionRange && !isHorizontalAdsorbed) {
targetTop = targetTop - (targetMaxY - value)
isHorizontalAdsorbed = true
_alignmentLines.push({type: 'horizontal', axis: {x: min - 50, y: value}, length: max - min + 100})
}
if (Math.abs(targetCenterY - value) < sorptionRange && !isHorizontalAdsorbed) {
targetTop = targetTop - (targetCenterY - value)
isHorizontalAdsorbed = true
_alignmentLines.push({type: 'horizontal', axis: {x: min - 50, y: value}, length: max - min + 100})
}
}
for (let i = 0; i < verticalLines.length; i++) {
const { value, range } = verticalLines[i]
const min = Math.min(...range, targetMinY, targetMaxY)
const max = Math.max(...range, targetMinY, targetMaxY)
if (Math.abs(targetMinX - value) < sorptionRange && !isVerticalAdsorbed) {
targetLeft = targetLeft - (targetMinX - value)
isVerticalAdsorbed = true
_alignmentLines.push({type: 'vertical', axis: {x: value, y: min - 50}, length: max - min + 100})
}
if (Math.abs(targetMaxX - value) < sorptionRange && !isVerticalAdsorbed) {
targetLeft = targetLeft - (targetMaxX - value)
isVerticalAdsorbed = true
_alignmentLines.push({type: 'vertical', axis: {x: value, y: min - 50}, length: max - min + 100})
}
if (Math.abs(targetCenterX - value) < sorptionRange && !isVerticalAdsorbed) {
targetLeft = targetLeft - (targetCenterX - value)
isVerticalAdsorbed = true
_alignmentLines.push({type: 'vertical', axis: {x: value, y: min - 50}, length: max - min + 100})
}
}
alignmentLines.value = _alignmentLines
// 单选状态下,或者当前选中的多个元素中存在正在操作的元素时,仅修改正在操作的元素的位置
if (activeElementIdList.value.length === 1 || isActiveGroupElement) {
elementList.value = elementList.value.map(el => {
return el.id === element.id ? { ...el, left: targetLeft, top: targetTop } : el
})
}
// 多选状态下,除了修改正在操作的元素的位置,其他被选中的元素也需要修改位置信息
// 其他被选中的元素的位置信息通过正在操作的元素的移动偏移量来进行计算
else {
const handleElement = elementList.value.find(el => el.id === element.id)
if (!handleElement) return
elementList.value = elementList.value.map(el => {
if (activeElementIdList.value.includes(el.id)) {
if (el.id === element.id) {
return {
...el,
left: targetLeft,
top: targetTop,
}
}
return {
...el,
left: el.left + (targetLeft - handleElement.left),
top: el.top + (targetTop - handleElement.top),
}
}
return el
})
}
}
document.onmouseup = e => {
isMouseDown = false
document.onmousemove = null
document.onmouseup = null
alignmentLines.value = []
const currentPageX = e.pageX
const currentPageY = e.pageY
if (startPageX === currentPageX && startPageY === currentPageY) return
slidesStore.updateSlide({ elements: elementList.value })
addHistorySnapshot()
}
}
return {
dragElement,
}
} | the_stack |
import { Spreadsheet } from '../base/index';
import { ICellRenderer, CellRenderEventArgs, inView, CellRenderArgs, renderFilterCell } from '../common/index';
import { createHyperlinkElement, checkPrevMerge, createImageElement, IRenderer, getDPRValue } from '../common/index';
import { removeAllChildren } from '../common/index';
import { getColumnHeaderText, CellStyleModel, CellFormatArgs, getRangeIndexes, getRangeAddress } from '../../workbook/common/index';
import { CellStyleExtendedModel, setChart, refreshChart, getCellAddress, ValidationModel, MergeArgs } from '../../workbook/common/index';
import { CellModel, SheetModel, skipDefaultValue, isHiddenRow, RangeModel, isHiddenCol} from '../../workbook/base/index';
import { getRowHeight, setRowHeight, getCell, getColumnWidth, getSheet, setCell } from '../../workbook/base/index';
import { addClass, attributes, getNumberDependable, extend, compile, isNullOrUndefined, detach } from '@syncfusion/ej2-base';
import { getFormattedCellObject, applyCellFormat, workbookFormulaOperation, wrapEvent, cFRender } from '../../workbook/common/index';
import { getTypeFromFormat, activeCellMergedRange, addHighlight, getCellIndexes, updateView } from '../../workbook/index';
import { checkIsFormula, checkConditionalFormat } from '../../workbook/common/index';
/**
* CellRenderer class which responsible for building cell content.
*
* @hidden
*/
export class CellRenderer implements ICellRenderer {
private parent: Spreadsheet;
private element: HTMLTableCellElement;
private th: HTMLTableHeaderCellElement;
private tableRow: HTMLElement;
constructor(parent?: Spreadsheet) {
this.parent = parent;
this.element = this.parent.createElement('td') as HTMLTableCellElement;
this.th = this.parent.createElement('th', { className: 'e-header-cell' }) as HTMLTableHeaderCellElement;
this.tableRow = parent.createElement('tr', { className: 'e-row' });
this.parent.on(updateView, this.updateView, this);
this.parent.on('calculateFormula', this.calculateFormula, this);
}
public renderColHeader(index: number, row: Element, refChild?: Element): void {
const headerCell: Element = this.th.cloneNode() as Element;
attributes(headerCell, { 'role': 'columnheader', 'aria-colindex': (index + 1).toString(), 'tabindex': '-1' });
const headerText: string = getColumnHeaderText(index + 1);
headerCell.innerHTML = headerText;
const sheet: SheetModel = this.parent.getActiveSheet();
if (isHiddenCol(sheet, index + 1)) { headerCell.classList.add('e-hide-start'); }
if (index !== 0 && isHiddenCol(sheet, index - 1)) { headerCell.classList.add('e-hide-end'); }
refChild ? row.insertBefore(headerCell, refChild) : row.appendChild(headerCell);
this.parent.trigger(
'beforeCellRender', <CellRenderEventArgs>{ cell: null, element: headerCell, address: headerText, colIndex: index });
}
public renderRowHeader(index: number, row: Element, refChild?: Element): void {
const headerCell: Element = this.element.cloneNode() as Element;
addClass([headerCell], 'e-header-cell');
attributes(headerCell, { 'role': 'rowheader', 'tabindex': '-1' });
headerCell.innerHTML = (index + 1).toString();
refChild ? row.insertBefore(headerCell, refChild) : row.appendChild(headerCell);
this.parent.trigger(
'beforeCellRender', <CellRenderEventArgs>{ cell: null, element: headerCell, address: `${index + 1}`, rowIndex: index });
}
public render(args: CellRenderArgs): Element {
const sheet: SheetModel = this.parent.getActiveSheet();
args.td = this.element.cloneNode() as HTMLTableCellElement;
args.td.className = 'e-cell';
attributes(args.td, { 'role': 'gridcell', 'aria-colindex': (args.colIdx + 1).toString(), 'tabindex': '-1' });
if (this.checkMerged(args)) {
args.refChild ? args.row.insertBefore(args.td, args.refChild) : args.row.appendChild(args.td);
return args.td;
}
args.isRefresh = false;
this.update(args);
if (args.cell && Object.keys(args.cell).length && args.td) {
if (sheet.conditionalFormats && sheet.conditionalFormats.length) {
this.parent.notify(
cFRender, { rowIdx: args.rowIdx, colIdx: args.colIdx, cell: args.cell, td: args.td, isChecked: false });
}
if (args.td.childElementCount && args.td.children[0].className === 'e-cf-databar') {
if (args.cell.style && args.cell.style.fontSize) {
(args.td.children[0].querySelector('.e-databar-value') as HTMLElement).style.fontSize = args.cell.style.fontSize;
}
(args.td.children[0] as HTMLElement).style.height = '100%';
(args.td.children[0].firstElementChild.nextElementSibling as HTMLElement).style.height = '100%';
}
}
if (!args.td.classList.contains('e-cell-template')) {
this.parent.notify(renderFilterCell, { td: args.td, rowIndex: args.rowIdx, colIndex: args.colIdx });
}
args.refChild ? args.row.insertBefore(args.td, args.refChild) : args.row.appendChild(args.td);
const evtArgs: CellRenderEventArgs = { cell: args.cell, element: args.td, address: args.address, rowIndex: args.rowIdx, colIndex:
args.colIdx, needHeightCheck: false, row: args.row };
this.parent.trigger('beforeCellRender', evtArgs);
if (!sheet.rows[args.rowIdx] || !sheet.rows[args.rowIdx].customHeight) {
if ((evtArgs.element && evtArgs.element.children.length) || evtArgs.needHeightCheck) {
const clonedCell: HTMLElement = evtArgs.element.cloneNode(true) as HTMLElement;
clonedCell.style.width = getColumnWidth(sheet, args.colIdx, true) + 'px';
this.tableRow.appendChild(clonedCell);
}
if ((args.lastCell && this.tableRow.childElementCount) || evtArgs.needHeightCheck) {
const tableRow: HTMLElement = args.row || this.parent.getRow(args.rowIdx);
const previouseHeight: number = getRowHeight(sheet, args.rowIdx);
const rowHeight: number = this.getRowHeightOnInit();
if (rowHeight > previouseHeight) {
const dprHgt: number = getDPRValue(rowHeight);
tableRow.style.height = `${dprHgt}px`;
(args.hRow || this.parent.getRow(args.rowIdx, this.parent.getRowHeaderTable())).style.height = `${dprHgt}px`;
setRowHeight(sheet, args.rowIdx, rowHeight);
}
this.tableRow.innerHTML = '';
}
}
this.setWrapByValue(sheet, args);
return evtArgs.element;
}
private setWrapByValue(sheet: SheetModel, args: CellRenderArgs): void {
if (args.cell && !args.cell.wrap && args.cell.value && args.cell.value.toString().includes('\n')) {
setCell(args.rowIdx, args.colIdx, sheet, { wrap: true }, true);
this.parent.notify(
wrapEvent, { range: [args.rowIdx, args.colIdx, args.rowIdx, args.colIdx], wrap: true, initial: true, sheet: sheet,
td: args.td, row: args.row, hRow: args.hRow });
}
}
private update(args: CellRenderArgs): void {
const sheet: SheetModel = this.parent.getActiveSheet();
const compiledTemplate: string = this.processTemplates(args.cell, args.rowIdx, args.colIdx);
if (compiledTemplate) {
if (typeof compiledTemplate === 'string') {
args.td.innerHTML = compiledTemplate;
} else {
removeAllChildren(args.td);
args.td.appendChild(compiledTemplate);
}
args.td.classList.add('e-cell-template');
}
if (args.isRefresh) {
if (args.td.rowSpan) {
this.mergeFreezeRow(sheet, args.rowIdx, args.colIdx, args.td.rowSpan, args.row, true);
args.td.removeAttribute('rowSpan');
}
if (args.td.colSpan) {
this.mergeFreezeCol(sheet, args.rowIdx, args.colIdx, args.td.colSpan, true);
args.td.removeAttribute('colSpan');
}
if (this.checkMerged(args)) { return; }
if (args.cell && !args.cell.hyperlink) {
const hyperlink: Element = args.td.querySelector('.e-hyperlink');
if (hyperlink) {
detach(hyperlink);
}
}
}
if (args.cell && args.cell.formula) {
this.calculateFormula(args);
}
const formatArgs: { [key: string]: string | boolean | number | CellModel } = {
type: args.cell && getTypeFromFormat(args.cell.format),
value: args.cell && args.cell.value, format: args.cell && args.cell.format ? args.cell.format : 'General',
formattedText: args.cell && args.cell.value, onLoad: true, isRightAlign: false, cell: args.cell,
rowIndex: args.rowIdx, colIndex: args.colIdx, isRowFill: false };
if (args.cell) { this.parent.notify(getFormattedCellObject, formatArgs); }
this.parent.refreshNode(
args.td, { type: formatArgs.type as string, result: formatArgs.formattedText as string, curSymbol:
getNumberDependable(this.parent.locale, 'USD'), isRightAlign: formatArgs.isRightAlign as boolean,
value: <string>formatArgs.value || '', isRowFill: <boolean>formatArgs.isRowFill });
let style: CellStyleModel = {};
if (args.cell) {
if (args.cell.style) {
if ((args.cell.style as CellStyleExtendedModel).properties) {
style = skipDefaultValue(args.cell.style, true);
} else { style = args.cell.style; }
}
if (args.cell.chart && args.cell.chart.length > 0) {
this.parent.notify(setChart, { chart : args.cell.chart, isInitCell: true, range: getCellAddress(args.rowIdx, args.colIdx), isUndoRedo: false});
}
if (args.cell.hyperlink) {
this.parent.notify(createHyperlinkElement, { cell: args.cell, td: args.td, rowIdx: args.rowIdx, colIdx: args.colIdx });
}
if (args.cell.rowSpan > 1) {
const rowSpan: number = args.cell.rowSpan - this.parent.hiddenCount(args.rowIdx, args.rowIdx + (args.cell.rowSpan - 1));
if (rowSpan > 1) {
args.td.rowSpan = rowSpan; this.mergeFreezeRow(sheet, args.rowIdx, args.colIdx, rowSpan, args.row);
}
}
if (args.cell.colSpan > 1) {
const colSpan: number = args.cell.colSpan -
this.parent.hiddenCount(args.colIdx, args.colIdx + (args.cell.colSpan - 1), 'columns');
if (colSpan > 1) {
args.td.colSpan = colSpan;
this.mergeFreezeCol(sheet, args.rowIdx, args.colIdx, colSpan);
}
}
if (args.cell.image) {
for (let i: number = 0; i < args.cell.image.length; i++) {
if (args.cell.image[i]) {
this.parent.notify(createImageElement, {
options: {
src: args.cell.image[i].src, imageId: args.cell.image[i].id,
height: args.cell.image[i].height, width: args.cell.image[i].width,
top: args.cell.image[i].top, left: args.cell.image[i].left
},
range: getRangeAddress([args.rowIdx, args.colIdx, args.rowIdx, args.colIdx]), isPublic: false
});
}
}
}
}
if (args.isRefresh) { this.removeStyle(args.td, args.rowIdx, args.colIdx); }
if (args.lastCell && this.parent.chartColl && this.parent.chartColl.length) {
this.parent.notify(refreshChart, {
cell: args.cell, rIdx: args.rowIdx, cIdx: args.colIdx, sheetIdx: this.parent.activeSheetIndex
});
}
this.applyStyle(args, style);
if ((args.checkCf || (args.lastCell && args.isRefresh)) && sheet.conditionalFormats && sheet.conditionalFormats.length) {
this.parent.notify(checkConditionalFormat, { rowIdx: args.rowIdx, colIdx: args.colIdx, cell: args.cell, td: args.td });
}
if (args.checkNextBorder === 'Row') {
const borderTop: string = this.parent.getCellStyleValue(
['borderTop'], [Number(this.parent.getContentTable().rows[0].getAttribute('aria-rowindex')) - 1, args.colIdx]).borderTop;
if (borderTop !== '' && (!args.cell || !args.cell.style || !(args.cell.style as CellStyleExtendedModel).bottomPriority)) {
this.parent.notify(applyCellFormat, { style: { borderBottom: borderTop }, rowIdx: args.rowIdx,
colIdx: args.colIdx, cell: args.td });
}
}
if (args.checkNextBorder === 'Column') {
const borderLeft: string = this.parent.getCellStyleValue(['borderLeft'], [args.rowIdx, args.colIdx + 1]).borderLeft;
if (borderLeft !== '' && (!args.cell || !args.cell.style || (!args.cell.style.borderRight && !args.cell.style.border))) {
this.parent.notify(applyCellFormat, { style: { borderRight: borderLeft }, rowIdx: args.rowIdx, colIdx: args.colIdx,
cell: args.td });
}
}
if (args.cell) {
if (args.cell.hyperlink && !args.td.classList.contains('e-cell-template')) {
let address: string; if (typeof (args.cell.hyperlink) === 'string') {
address = args.cell.hyperlink;
if (address.indexOf('http://') !== 0 && address.indexOf('https://') !== 0 && address.indexOf('ftp://') !== 0) {
args.cell.hyperlink = address.toLowerCase().indexOf('www.') === 0 ? 'http://' + address : address;
}
} else {
address = args.cell.hyperlink.address;
if (address.indexOf('http://') !== 0 && address.indexOf('https://') !== 0 && address.indexOf('ftp://') !== 0) {
args.cell.hyperlink.address = address.toLowerCase().indexOf('www.') === 0 ? 'http://' + address : address;
}
}
this.parent.notify(createHyperlinkElement, { cell: args.cell, td: args.td, rowIdx: args.rowIdx, colIdx: args.colIdx });
}
if (args.cell.wrap) {
this.parent.notify(wrapEvent, {
range: [args.rowIdx, args.colIdx, args.rowIdx, args.colIdx], wrap: true, sheet:
sheet, initial: true, td: args.td, row: args.row, hRow: args.hRow, isCustomHgt: !args.isRefresh &&
getRowHeight(sheet, args.rowIdx) > 20
});
}
}
const validation: ValidationModel = (args.cell && args.cell.validation) || (sheet.columns && sheet.columns[args.colIdx] &&
sheet.columns[args.colIdx].validation);
if (validation && validation.isHighlighted) {
this.parent.notify(addHighlight, { range: getRangeAddress([args.rowIdx, args.colIdx]), td: args.td });
}
if (args.cell && args.cell.validation && args.cell.validation.isHighlighted) {
this.parent.notify(addHighlight, { range: getRangeAddress([args.rowIdx, args.colIdx]), td: args.td });
}
}
private applyStyle(args: CellRenderArgs, style: CellStyleModel): void {
if (Object.keys(style).length || Object.keys(this.parent.commonCellStyle).length || args.lastCell) {
this.parent.notify(applyCellFormat, <CellFormatArgs>{
style: extend({}, this.parent.commonCellStyle, style), rowIdx: args.rowIdx, colIdx: args.colIdx, cell: args.td,
first: args.first, row: args.row, lastCell: args.lastCell, hRow: args.hRow, pRow: args.pRow, isHeightCheckNeeded:
args.isHeightCheckNeeded, manualUpdate: args.manualUpdate, onActionUpdate: args.onActionUpdate });
}
}
private calculateFormula(args: CellRenderArgs): void {
if (args.cell.value !== undefined && args.cell.value !== null) {
const eventArgs: { [key: string]: string | number | boolean } = { action: 'checkFormulaAdded', added: true, address:
args.address, sheetId: (args.sheetIndex === undefined ? this.parent.getActiveSheet() :
getSheet(this.parent, args.sheetIndex)).id.toString() };
this.parent.notify(workbookFormulaOperation, eventArgs);
if (eventArgs.added) {
return;
}
} else if (args.formulaRefresh) {
args.cell.value = '';
}
const isFormula: boolean = checkIsFormula(args.cell.formula);
const eventArgs: { [key: string]: string | number | boolean } = { action: 'refreshCalculate', value: args.cell.formula, rowIndex:
args.rowIdx, colIndex: args.colIdx, isFormula: isFormula, sheetIndex: args.sheetIndex, isRefreshing: args.isRefreshing };
this.parent.notify(workbookFormulaOperation, eventArgs);
args.cell.value = getCell(
args.rowIdx, args.colIdx, isNullOrUndefined(args.sheetIndex) ? this.parent.getActiveSheet() :
getSheet(this.parent, args.sheetIndex)).value;
}
private checkMerged(args: CellRenderArgs): boolean {
if (args.cell && (args.cell.colSpan < 0 || args.cell.rowSpan < 0)) {
const sheet: SheetModel = this.parent.getActiveSheet();
if (sheet.frozenRows || sheet.frozenColumns) {
const mergeArgs: MergeArgs = { range: [args.rowIdx, args.colIdx, args.rowIdx, args.colIdx] };
this.parent.notify(activeCellMergedRange, mergeArgs);
const frozenRow: number = this.parent.frozenRowCount(sheet); const frozenCol: number = this.parent.frozenColCount(sheet);
let setDisplay: boolean;
if (sheet.frozenRows && sheet.frozenColumns) {
if (mergeArgs.range[0] < frozenRow && mergeArgs.range[1] < frozenCol) {
setDisplay = args.rowIdx < frozenRow && args.colIdx < frozenCol;
} else if (mergeArgs.range[0] < frozenRow) {
setDisplay = args.rowIdx < frozenRow;
} else if (mergeArgs.range[1] < frozenCol) {
setDisplay = args.colIdx < frozenCol;
} else {
setDisplay = true;
}
} else {
setDisplay = frozenRow ? (mergeArgs.range[0] >= frozenRow || args.rowIdx < frozenRow) : (mergeArgs.range[1] >= frozenCol
|| args.colIdx < frozenCol);
}
if (setDisplay) { args.td.style.display = 'none'; }
} else {
args.td.style.display = 'none';
}
if (args.cell.colSpan < 0) {
this.parent.notify(checkPrevMerge, args);
if (args.cell.style && args.cell.style.borderTop) { this.applyStyle(args, { borderTop: args.cell.style.borderTop }); }
}
if (args.cell.rowSpan < 0) {
args.isRow = true; this.parent.notify(checkPrevMerge, args);
if (args.cell.style && args.cell.style.borderLeft) { this.applyStyle(args, { borderLeft: args.cell.style.borderLeft }); }
}
return true;
}
return false;
}
private mergeFreezeRow(sheet: SheetModel, rowIdx: number, colIdx: number, rowSpan: number, tr: Element, unMerge?: boolean): void {
const frozenRow: number = this.parent.frozenRowCount(sheet);
if (frozenRow && rowIdx < frozenRow && rowIdx + (rowSpan - 1) >= frozenRow) {
let rowEle: HTMLElement; let spanRowTop: number = 0; let height: number;
const frozenCol: number = this.parent.frozenColCount(sheet);
const row: HTMLTableRowElement = tr as HTMLTableRowElement || this.parent.getRow(rowIdx, null, colIdx);
const emptyRows: Element[] = [].slice.call(row.parentElement.querySelectorAll('.e-empty'));
if (unMerge) {
const curEmptyLength: number = rowIdx + rowSpan - frozenRow;
if (curEmptyLength < emptyRows.length) {
return;
} else {
let curSpan: number = 0;
if (curEmptyLength === emptyRows.length) {
let curCell: CellModel; let i: number; let len: number;
if (frozenCol && colIdx < frozenCol) {
i = getCellIndexes(sheet.topLeftCell)[1]; len = frozenCol;
} else {
i = this.parent.viewport.leftIndex + frozenCol; len = this.parent.viewport.rightIndex;
}
for (i; i < len; i++) {
if (i === colIdx) { continue; }
curCell = getCell(rowIdx, i, sheet, false, true);
if (curCell.rowSpan && rowIdx + curCell.rowSpan - frozenRow > curSpan) {
curSpan = rowIdx + curCell.rowSpan - frozenRow;
}
}
if (curSpan === curEmptyLength) { return; }
} else {
curSpan = curEmptyLength;
}
let lastRowIdx: number = rowIdx + (rowSpan - 1);
for (let i: number = curSpan, len: number = emptyRows.length; i < len; i++) {
spanRowTop += getRowHeight(sheet, lastRowIdx);
lastRowIdx--; detach(emptyRows.pop());
}
this.updateSpanTop(colIdx, frozenCol, spanRowTop, true);
if (!emptyRows.length) { this.updateColZIndex(colIdx, frozenCol, true); }
return;
}
}
this.updateColZIndex(colIdx, frozenCol);
for (let i: number = frozenRow, len: number = rowIdx + (rowSpan - 1); i <= len; i++) {
height = getRowHeight(sheet, i); spanRowTop += -height;
if (frozenRow + emptyRows.length > i) { continue; }
rowEle = row.cloneNode() as HTMLElement;
rowEle.classList.add('e-empty'); rowEle.style.visibility = 'hidden';
rowEle.style.height = height + 'px';
row.parentElement.appendChild(rowEle);
}
this.updateSpanTop(colIdx, frozenCol, spanRowTop);
}
}
private updateSpanTop(colIdx: number, frozenCol: number, top: number, update?: boolean): void {
const mainPanel: HTMLElement = this.parent.serviceLocator.getService<IRenderer>('sheet').contentPanel;
if (update) {
if (!parseInt(mainPanel.style.top, 10)) { return; }
top = parseInt(mainPanel.style.top, 10) + top;
}
if (frozenCol && colIdx < frozenCol && (update || !parseInt(mainPanel.style.top, 10) || top <
parseInt(mainPanel.style.top, 10))) {
mainPanel.style.top = top + 'px';
const scroll: HTMLElement = mainPanel.nextElementSibling as HTMLElement;
if (scroll) { scroll.style.top = top + 'px'; }
}
}
private mergeFreezeCol(sheet: SheetModel, rowIdx: number, colIdx: number, colSpan: number, unMerge?: boolean): void {
const frozenCol: number = this.parent.frozenColCount(sheet);
if (frozenCol && colIdx < frozenCol && colIdx + (colSpan - 1) >= frozenCol) {
let col: HTMLElement; let width: number; const frozenRow: number = this.parent.frozenRowCount(sheet);
const colGrp: Element = (rowIdx < frozenRow ? this.parent.getSelectAllContent() : this.parent.getRowHeaderContent()).querySelector('colgroup');
const emptyCols: Element[] = [].slice.call(colGrp.querySelectorAll('.e-empty'));
if (unMerge) {
const curEmptyLength: number = colIdx + colSpan - frozenCol;
if (curEmptyLength < emptyCols.length) {
return;
} else {
let curSpan: number = 0;
if (curEmptyLength === emptyCols.length) {
let curCell: CellModel; let len: number; let i: number;
if (frozenRow && rowIdx < frozenCol) {
len = frozenRow; i = getCellIndexes(sheet.topLeftCell)[0];
} else {
len = this.parent.viewport.bottomIndex; i = this.parent.viewport.topIndex + frozenRow;
}
for (i; i < len; i++) {
if (i === rowIdx) { continue; }
curCell = getCell(i, colIdx, sheet, false, true);
if (curCell.colSpan && colIdx + curCell.colSpan - frozenCol > curSpan) {
curSpan = colIdx + curCell.colSpan - frozenCol;
}
}
if (curSpan === curEmptyLength) { return; }
} else {
curSpan = curEmptyLength;
}
for (let i: number = curSpan, len: number = emptyCols.length; i < len; i++) { detach(emptyCols.pop()); }
this.parent.serviceLocator.getService<IRenderer>('sheet').setPanelWidth(sheet, this.parent.getRowHeaderContent());
if (!emptyCols.length) { this.updateRowZIndex(rowIdx, frozenRow, true); }
return;
}
}
this.updateRowZIndex(rowIdx, frozenRow);
for (let i: number = frozenCol, len: number = colIdx + (colSpan - 1); i <= len; i++) {
if (frozenCol + emptyCols.length > i) { continue; }
col = colGrp.childNodes[0].cloneNode() as HTMLElement;
col.classList.add('e-empty'); col.style.visibility = 'hidden';
width = getColumnWidth(sheet, i, null, true); col.style.width = width + 'px';
colGrp.appendChild(col);
if (i === len) {
this.parent.serviceLocator.getService<IRenderer>('sheet').setPanelWidth(
sheet, this.parent.getRowHeaderContent());
}
}
}
}
private updateColZIndex(colIdx: number, frozenCol: number, remove?: boolean): void {
if (colIdx < frozenCol) {
this.updateSelectAllZIndex(remove);
} else {
this.parent.getColumnHeaderContent().style.zIndex = remove ? '' : '2';
this.updatedHeaderZIndex(remove);
}
}
private updateSelectAllZIndex(remove: boolean): void {
const frozenRowEle: HTMLElement = this.parent.element.querySelector('.e-frozen-row');
const frozenColEle: HTMLElement = this.parent.element.querySelector('.e-frozen-column');
if (remove) {
this.parent.getSelectAllContent().style.zIndex = '';
if (frozenRowEle) { frozenRowEle.style.zIndex = ''; }
if (frozenColEle) { frozenColEle.style.zIndex = ''; }
} else {
if (this.parent.getRowHeaderContent().style.zIndex || this.parent.getColumnHeaderContent().style.zIndex) {
this.parent.getSelectAllContent().style.zIndex = '3';
if (frozenRowEle) { frozenRowEle.style.zIndex = '4'; }
if (frozenColEle) { frozenColEle.style.zIndex = '4'; }
} else {
this.parent.getSelectAllContent().style.zIndex = '2';
}
}
}
private updatedHeaderZIndex(remove: boolean): void {
if (!remove && this.parent.getSelectAllContent().style.zIndex === '2') {
this.parent.getSelectAllContent().style.zIndex = '3';
const frozenRowEle: HTMLElement = this.parent.element.querySelector('.e-frozen-row');
const frozenColEle: HTMLElement = this.parent.element.querySelector('.e-frozen-column');
if (frozenColEle) { frozenColEle.style.zIndex = '4'; }
if (frozenRowEle) { frozenRowEle.style.zIndex = '4'; }
}
}
private updateRowZIndex(rowIdx: number, frozenRow: number, remove?: boolean): void {
if (rowIdx < frozenRow) {
this.updateSelectAllZIndex(remove);
} else {
this.parent.getRowHeaderContent().style.zIndex = remove ? '' : '2';
this.updatedHeaderZIndex(remove);
}
}
private processTemplates(cell: CellModel, rowIdx: number, colIdx: number): string {
const sheet: SheetModel = this.parent.getActiveSheet();
const ranges: RangeModel[] = sheet.ranges;
let range: number[];
for (let j: number = 0, len: number = ranges.length; j < len; j++) {
if (ranges[j].template) {
range = getRangeIndexes(ranges[j].address.length ? ranges[j].address : ranges[j].startCell);
if (range[0] <= rowIdx && range[1] <= colIdx && range[2] >= rowIdx && range[3] >= colIdx) {
if (cell) {
return this.compileCellTemplate(ranges[j].template, cell);
} else {
if (!getCell(rowIdx, colIdx, sheet, true)) {
return this.compileCellTemplate(ranges[j].template, getCell(rowIdx, colIdx, sheet, null, true));
}
}
}
}
}
return '';
}
private compileCellTemplate(template: string, cell: CellModel): string {
let compiledStr: Function;
if (typeof template === 'string') {
let templateString: string;
if (template.trim().indexOf('#') === 0) {
templateString = document.querySelector(template).innerHTML.trim();
} else {
templateString = template;
}
compiledStr = compile(templateString);
if (!(this.parent as { isVue?: boolean }).isVue || document.querySelector(template)) {
return (compiledStr(cell, this.parent, 'ranges', '', true)[0] as HTMLElement).outerHTML;
} else {
return compiledStr(cell, this.parent, 'ranges', '')[0];
}
} else {
compiledStr = compile(template);
return compiledStr(cell, this.parent, 'ranges', '')[0];
}
}
private getRowHeightOnInit(): number {
const tTable: HTMLElement = this.parent.createElement('table', { className: 'e-table e-test-table' });
const tBody: HTMLElement = tTable.appendChild(this.parent.createElement('tbody'));
tBody.appendChild(this.tableRow);
this.parent.element.appendChild(tTable);
const height: number = Math.round(this.tableRow.getBoundingClientRect().height);
this.parent.element.removeChild(tTable);
return height < 20 ? 20 : height;
}
private removeStyle(element: HTMLElement, rowIdx: number, colIdx: number): void {
let cellStyle: CellStyleModel;
if (element.style.length) {
cellStyle = this.parent.getCellStyleValue(['borderLeft', 'border'], [rowIdx, colIdx + 1]);
const rightBorder: string = cellStyle.borderLeft || cellStyle.border;
cellStyle = this.parent.getCellStyleValue(['borderTop', 'border'], [rowIdx + 1, colIdx]);
const bottomBorder: string = cellStyle.borderTop || cellStyle.border;
if (rightBorder || bottomBorder) {
[].slice.call(element.style).forEach((style: string) => {
if (rightBorder && bottomBorder) {
if (!style.includes('border-right') && !style.includes('border-bottom')) {
element.style.removeProperty(style);
}
} else if ((rightBorder && !(style.indexOf('border-right') > -1) && (!bottomBorder || bottomBorder === 'none')) ||
(bottomBorder && !(style.indexOf('border-bottom') > -1) && (!rightBorder || rightBorder === 'none'))) {
element.style.removeProperty(style);
}
});
} else {
element.removeAttribute('style');
}
}
const prevRowCell: HTMLElement = this.parent.getCell(rowIdx - 1, colIdx);
if (prevRowCell && prevRowCell.style.borderBottom) {
const prevRowIdx: number = Number(prevRowCell.parentElement.getAttribute('aria-rowindex')) - 1;
cellStyle = this.parent.getCellStyleValue(['borderBottom', 'border'], [prevRowIdx, colIdx]);
if (!(cellStyle.borderBottom || cellStyle.border)) { prevRowCell.style.borderBottom = ''; }
}
const prevColCell: HTMLElement = <HTMLElement>element.previousElementSibling;
if (prevColCell && prevColCell.style.borderRight) {
colIdx = Number(prevColCell.getAttribute('aria-colindex')) - 1;
cellStyle = this.parent.getCellStyleValue(['borderRight', 'border'], [rowIdx, colIdx]);
if (!(cellStyle.borderRight || cellStyle.border)) { prevColCell.style.borderRight = ''; }
}
}
/**
* @hidden
* @param {number[]} range - Specifies the range.
* @param {boolean} refreshing - Specifies the refresh.
* @param {boolean} checkWrap - Specifies the range.
* @param {boolean} checkHeight - Specifies the checkHeight.
* @param {boolean} checkCf - Specifies the check for conditional format.
* @returns {void}
*/
public refreshRange(range: number[], refreshing?: boolean, checkWrap?: boolean, checkHeight?: boolean, checkCf?: boolean): void {
const sheet: SheetModel = this.parent.getActiveSheet();
const cRange: number[] = range.slice(); let args: CellRenderArgs; let cell: HTMLTableCellElement;
if (inView(this.parent, cRange, true)) {
for (let i: number = cRange[0]; i <= cRange[2]; i++) {
if (isHiddenRow(sheet, i)) { continue; }
for (let j: number = cRange[1]; j <= cRange[3]; j++) {
if (isHiddenCol(sheet, j)) { continue; }
cell = this.parent.getCell(i, j) as HTMLTableCellElement;
if (cell) {
args = { rowIdx: i, colIdx: j, td: cell, cell: getCell(i, j, sheet), isRefreshing: refreshing, lastCell: j ===
cRange[3], isRefresh: true, isHeightCheckNeeded: true, manualUpdate: true, first: '', onActionUpdate:
checkHeight, checkCf: checkCf };
this.update(args);
this.parent.notify(renderFilterCell, { td: cell, rowIndex: i, colIndex: j });
if (checkWrap) { this.setWrapByValue(sheet, args); }
}
}
}
}
}
public refresh(rowIdx: number, colIdx: number, lastCell?: boolean, element?: Element, checkCf?: boolean, checkWrap?: boolean): void {
const sheet: SheetModel = this.parent.getActiveSheet();
if (!element && (isHiddenRow(sheet, rowIdx) || isHiddenCol(sheet, colIdx))) { return; }
if (element || !this.parent.scrollSettings.enableVirtualization || this.parent.insideViewport(rowIdx, colIdx)) {
const cell: HTMLTableCellElement = <HTMLTableCellElement>(element || this.parent.getCell(rowIdx, colIdx));
if (!cell) { return; }
const args: CellRenderArgs = { rowIdx: rowIdx, colIdx: colIdx, td: cell, cell: getCell(rowIdx, colIdx, sheet), isRefresh: true,
lastCell: lastCell, isHeightCheckNeeded: true, manualUpdate: true, first: '', checkCf: checkCf };
this.update(args);
this.parent.notify(renderFilterCell, { td: cell, rowIndex: rowIdx, colIndex: colIdx });
if (checkWrap) {
this.setWrapByValue(sheet, args);
}
}
}
private updateView(
args: { indexes: number[], sheetIndex?: number, refreshing?: boolean, checkWrap?: boolean, checkCf?: boolean }): void {
if (isNullOrUndefined(args.sheetIndex) || (args.sheetIndex === this.parent.activeSheetIndex)) {
this.refreshRange(args.indexes, args.refreshing, args.checkWrap, false, args.checkCf);
} else if (args.refreshing) {
this.calculateFormula(
{ cell: getCell(args.indexes[0], args.indexes[1], getSheet(this.parent, args.sheetIndex), true, true),
rowIdx: args.indexes[0], colIdx: args.indexes[1], sheetIndex: args.sheetIndex });
}
}
} | the_stack |
import * as protos from '../../protos/operations';
import * as assert from 'assert';
import * as sinon from 'sinon';
import {SinonStub} from 'sinon';
import {describe, it} from 'mocha';
import {OperationsClientBuilder} from '../../src/operationsClient';
import * as protobuf from 'protobufjs';
import {GrpcClient} from '../../src/grpc';
import {PassThrough} from 'stream';
import {ResultTuple} from '../../src/apitypes';
function generateSampleMessage<T extends object>(instance: T) {
const filledObject = (
instance.constructor as typeof protobuf.Message
).toObject(instance as protobuf.Message<T>, {defaults: true});
return (instance.constructor as typeof protobuf.Message).fromObject(
filledObject
) as T;
}
function stubSimpleCall<ResponseType>(response?: ResponseType, error?: Error) {
return error
? sinon.stub().rejects(error)
: sinon.stub().resolves([response]);
}
function stubSimpleCallWithCallback<ResponseType>(
response?: ResponseType,
error?: Error
) {
return error
? sinon.stub().callsArgWith(2, error)
: sinon.stub().callsArgWith(2, null, response);
}
function stubPageStreamingCall<ResponseType>(
responses?: ResponseType[],
error?: Error
) {
const pagingStub = sinon.stub();
if (responses) {
for (let i = 0; i < responses.length; ++i) {
pagingStub.onCall(i).callsArgWith(2, null, responses[i]);
}
}
const transformStub = error
? sinon.stub().callsArgWith(2, error)
: pagingStub;
const mockStream = new PassThrough({
objectMode: true,
transform: transformStub,
});
// trigger as many responses as needed
if (responses) {
for (let i = 0; i < responses.length; ++i) {
setImmediate(() => {
mockStream.write({});
});
}
setImmediate(() => {
mockStream.end();
});
} else {
setImmediate(() => {
mockStream.write({});
});
setImmediate(() => {
mockStream.end();
});
}
return sinon.stub().returns(mockStream);
}
function stubAsyncIterationCall<ResponseType>(
responses?: ResponseType[],
error?: Error
) {
let counter = 0;
const asyncIterable = {
[Symbol.asyncIterator]() {
return {
async next() {
if (error) {
return Promise.reject(error);
}
if (counter >= responses!.length) {
return Promise.resolve({done: true, value: undefined});
}
return Promise.resolve({done: false, value: responses![counter++]});
},
};
},
};
return sinon.stub().returns(asyncIterable);
}
describe('operation client', () => {
describe('getOperation ', () => {
it('invokes getOperation without error', async () => {
const grpcClient = new GrpcClient();
const clientOptions = {
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
};
const client = new OperationsClientBuilder(grpcClient).operationsClient(
clientOptions
);
const request = generateSampleMessage(
new protos.google.longrunning.GetOperationRequest()
);
const expectedResponse = generateSampleMessage(
new protos.google.longrunning.Operation()
);
client.innerApiCalls.getOperation = stubSimpleCall(expectedResponse);
const response = await client.getOperation(request);
assert.deepStrictEqual(response, [expectedResponse]);
assert(
(client.innerApiCalls.getOperation as SinonStub)
.getCall(0)
.calledWith(request)
);
});
it('invokes getOperation without error using callback', async () => {
const grpcClient = new GrpcClient();
const clientOptions = {
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
};
const client = new OperationsClientBuilder(grpcClient).operationsClient(
clientOptions
);
const request = generateSampleMessage(
new protos.google.longrunning.GetOperationRequest()
);
const expectedResponse = generateSampleMessage(
new protos.google.longrunning.Operation()
);
client.innerApiCalls.getOperation =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.getOperation(
request,
undefined,
(
err?: Error | null,
result?: protos.google.longrunning.Operation | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.getOperation as SinonStub)
.getCall(0)
.calledWith(request /* callback function above */)
);
});
it('invokes getOperation with error', async () => {
const grpcClient = new GrpcClient();
const clientOptions = {
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
};
const client = new OperationsClientBuilder(grpcClient).operationsClient(
clientOptions
);
const request = generateSampleMessage(
new protos.google.longrunning.GetOperationRequest()
);
const expectedError = new Error('expected');
client.innerApiCalls.getOperation = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(async () => {
await client.getOperation(request);
}, expectedError);
assert(
(client.innerApiCalls.getOperation as SinonStub)
.getCall(0)
.calledWith(request)
);
});
});
describe('getOperationInternal ', () => {
it('invokes getOperationInternal without error', async () => {
const grpcClient = new GrpcClient();
const clientOptions = {
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
};
const client = new OperationsClientBuilder(grpcClient).operationsClient(
clientOptions
);
const request = generateSampleMessage(
new protos.google.longrunning.GetOperationRequest()
);
const expectedResponse: ResultTuple = [
new protos.google.longrunning.Operation(),
null,
new protos.google.longrunning.Operation(),
];
client.innerApiCalls.getOperation = stubSimpleCall(expectedResponse);
const response = await client.getOperationInternal(request);
assert.deepStrictEqual(response, [expectedResponse]);
assert(
(client.innerApiCalls.getOperation as SinonStub)
.getCall(0)
.calledWith(request)
);
});
it('invokes getOperationInternal without error using callback', async () => {
const grpcClient = new GrpcClient();
const clientOptions = {
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
};
const client = new OperationsClientBuilder(grpcClient).operationsClient(
clientOptions
);
const request = generateSampleMessage(
new protos.google.longrunning.GetOperationRequest()
);
const expectedResponse: ResultTuple = [
new protos.google.longrunning.Operation(),
null,
new protos.google.longrunning.Operation(),
];
client.innerApiCalls.getOperation =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.getOperationInternal(
request,
undefined,
(
err?: Error | null,
result?: protos.google.longrunning.Operation | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.getOperation as SinonStub)
.getCall(0)
.calledWith(request /* callback function above */)
);
});
it('invokes getOperationInternal with error', async () => {
const grpcClient = new GrpcClient();
const clientOptions = {
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
};
const client = new OperationsClientBuilder(grpcClient).operationsClient(
clientOptions
);
const request = generateSampleMessage(
new protos.google.longrunning.GetOperationRequest()
);
const expectedError = new Error('expected');
client.innerApiCalls.getOperation = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(async () => {
await client.getOperationInternal(request);
}, expectedError);
assert(
(client.innerApiCalls.getOperation as SinonStub)
.getCall(0)
.calledWith(request)
);
});
});
describe('listOperations ', () => {
it('invokes listOperations without error', async () => {
const grpcClient = new GrpcClient();
const clientOptions = {
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
};
const client = new OperationsClientBuilder(grpcClient).operationsClient(
clientOptions
);
const request = generateSampleMessage(
new protos.google.longrunning.ListOperationsRequest()
);
const expectedResponse = generateSampleMessage(
new protos.google.longrunning.ListOperationsResponse()
);
client.innerApiCalls.listOperations = stubSimpleCall(expectedResponse);
const response = await client.listOperations(request);
assert.deepStrictEqual(response, [expectedResponse]);
assert(
(client.innerApiCalls.listOperations as SinonStub)
.getCall(0)
.calledWith(request)
);
});
it('invokes listOperations without error using callback', async () => {
const grpcClient = new GrpcClient();
const clientOptions = {
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
};
const client = new OperationsClientBuilder(grpcClient).operationsClient(
clientOptions
);
const request = generateSampleMessage(
new protos.google.longrunning.ListOperationsRequest()
);
const expectedResponse = generateSampleMessage(
new protos.google.longrunning.ListOperationsResponse()
);
client.innerApiCalls.listOperations =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.listOperations(
request,
undefined,
(
err?: Error | null,
result?: protos.google.longrunning.ListOperationsResponse | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.listOperations as SinonStub)
.getCall(0)
.calledWith(request /* callback function above */)
);
});
it('invokes listOperations with error', async () => {
const grpcClient = new GrpcClient();
const clientOptions = {
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
};
const client = new OperationsClientBuilder(grpcClient).operationsClient(
clientOptions
);
const request = generateSampleMessage(
new protos.google.longrunning.ListOperationsRequest()
);
const expectedError = new Error('expected');
client.innerApiCalls.listOperations = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(async () => {
await client.listOperations(request);
}, expectedError);
assert(
(client.innerApiCalls.listOperations as SinonStub)
.getCall(0)
.calledWith(request)
);
});
it('invokes listOperationsStream without error', async () => {
const grpcClient = new GrpcClient();
const clientOptions = {
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
};
const client = new OperationsClientBuilder(grpcClient).operationsClient(
clientOptions
);
const request = generateSampleMessage(
new protos.google.longrunning.ListOperationsRequest()
);
const expectedResponse = [
generateSampleMessage(new protos.google.longrunning.Operation()),
generateSampleMessage(new protos.google.longrunning.Operation()),
generateSampleMessage(new protos.google.longrunning.Operation()),
];
client.descriptor.listOperations.createStream =
stubPageStreamingCall(expectedResponse);
const stream = client.listOperationsStream(request);
const promise = new Promise((resolve, reject) => {
const responses: protos.google.longrunning.Operation[] = [];
stream.on('data', (response: protos.google.longrunning.Operation) => {
responses.push(response);
});
stream.on('end', () => {
resolve(responses);
});
stream.on('error', (err: Error) => {
reject(err);
});
});
const responses = await promise;
assert.deepStrictEqual(responses, expectedResponse);
assert(
(client.descriptor.listOperations.createStream as SinonStub)
.getCall(0)
.calledWith(client.innerApiCalls.listOperations, request)
);
});
it('invokes listOperationsStream with error', async () => {
const grpcClient = new GrpcClient();
const clientOptions = {
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
};
const client = new OperationsClientBuilder(grpcClient).operationsClient(
clientOptions
);
const request = generateSampleMessage(
new protos.google.longrunning.ListOperationsRequest()
);
const expectedError = new Error('expected');
client.descriptor.listOperations.createStream = stubPageStreamingCall(
undefined,
expectedError
);
const stream = client.listOperationsStream(request);
const promise = new Promise((resolve, reject) => {
const responses: protos.google.longrunning.Operation[] = [];
stream.on('data', (response: protos.google.longrunning.Operation) => {
responses.push(response);
});
stream.on('end', () => {
resolve(responses);
});
stream.on('error', (err: Error) => {
reject(err);
});
});
await assert.rejects(async () => {
await promise;
}, expectedError);
assert(
(client.descriptor.listOperations.createStream as SinonStub)
.getCall(0)
.calledWith(client.innerApiCalls.listOperations, request)
);
});
it('uses async iteration with listOperation without error', async () => {
const grpcClient = new GrpcClient();
const clientOptions = {
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
};
const client = new OperationsClientBuilder(grpcClient).operationsClient(
clientOptions
);
const request = generateSampleMessage(
new protos.google.longrunning.ListOperationsRequest()
);
const expectedResponse = [
generateSampleMessage(
new protos.google.longrunning.ListOperationsResponse()
),
generateSampleMessage(
new protos.google.longrunning.ListOperationsResponse()
),
generateSampleMessage(
new protos.google.longrunning.ListOperationsResponse()
),
];
client.descriptor.listOperations.asyncIterate =
stubAsyncIterationCall(expectedResponse);
const responses: protos.google.longrunning.ListOperationsResponse[] = [];
const iterable = client.listOperationsAsync(request);
for await (const resource of iterable) {
responses.push(resource!);
}
assert.deepStrictEqual(responses, expectedResponse);
assert.deepStrictEqual(
(client.descriptor.listOperations.asyncIterate as SinonStub).getCall(0)
.args[1],
request
);
});
it('uses async iteration with listOperation with error', async () => {
const grpcClient = new GrpcClient();
const clientOptions = {
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
};
const client = new OperationsClientBuilder(grpcClient).operationsClient(
clientOptions
);
const request = generateSampleMessage(
new protos.google.longrunning.ListOperationsRequest()
);
const expectedError = new Error('expected');
client.descriptor.listOperations.asyncIterate = stubAsyncIterationCall(
undefined,
expectedError
);
const iterable = client.listOperationsAsync(request);
await assert.rejects(async () => {
const responses: protos.google.longrunning.ListOperationsResponse[] =
[];
for await (const resource of iterable) {
responses.push(resource!);
}
});
assert.deepStrictEqual(
(client.descriptor.listOperations.asyncIterate as SinonStub).args[0][1],
request
);
});
});
describe('cancelOperation ', () => {
it('invokes cancelOperation without error', async () => {
const grpcClient = new GrpcClient();
const clientOptions = {
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
};
const client = new OperationsClientBuilder(grpcClient).operationsClient(
clientOptions
);
const request = generateSampleMessage(
new protos.google.longrunning.CancelOperationRequest()
);
const expectedResponse = generateSampleMessage(
new protos.google.protobuf.Empty()
);
client.innerApiCalls.cancelOperation = stubSimpleCall(expectedResponse);
const response = await client.cancelOperation(request);
assert.deepStrictEqual(response, [expectedResponse]);
assert(
(client.innerApiCalls.cancelOperation as SinonStub)
.getCall(0)
.calledWith(request)
);
});
it('invokes cancelOperation without error using callback', async () => {
const grpcClient = new GrpcClient();
const clientOptions = {
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
};
const client = new OperationsClientBuilder(grpcClient).operationsClient(
clientOptions
);
const request = generateSampleMessage(
new protos.google.longrunning.CancelOperationRequest()
);
const expectedResponse = generateSampleMessage(
new protos.google.protobuf.Empty()
);
client.innerApiCalls.cancelOperation =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.cancelOperation(
request,
undefined,
(
err?: Error | null,
result?: protos.google.protobuf.Empty | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.cancelOperation as SinonStub)
.getCall(0)
.calledWith(request /* callback function above */)
);
});
it('invokes cancelOperation with error', async () => {
const grpcClient = new GrpcClient();
const clientOptions = {
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
};
const client = new OperationsClientBuilder(grpcClient).operationsClient(
clientOptions
);
const request = generateSampleMessage(
new protos.google.longrunning.CancelOperationRequest()
);
const expectedError = new Error('expected');
client.innerApiCalls.cancelOperation = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(async () => {
await client.cancelOperation(request);
}, expectedError);
assert(
(client.innerApiCalls.cancelOperation as SinonStub)
.getCall(0)
.calledWith(request)
);
});
});
describe('deleteOperation ', () => {
it('invokes deleteOperation without error', async () => {
const grpcClient = new GrpcClient();
const clientOptions = {
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
};
const client = new OperationsClientBuilder(grpcClient).operationsClient(
clientOptions
);
const request = generateSampleMessage(
new protos.google.longrunning.DeleteOperationRequest()
);
const expectedResponse = generateSampleMessage(
new protos.google.protobuf.Empty()
);
client.innerApiCalls.deleteOperation = stubSimpleCall(expectedResponse);
const response = await client.deleteOperation(request);
assert.deepStrictEqual(response, [expectedResponse]);
assert(
(client.innerApiCalls.deleteOperation as SinonStub)
.getCall(0)
.calledWith(request)
);
});
it('invokes deleteOperation without error using callback', async () => {
const grpcClient = new GrpcClient();
const clientOptions = {
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
};
const client = new OperationsClientBuilder(grpcClient).operationsClient(
clientOptions
);
const request = generateSampleMessage(
new protos.google.longrunning.DeleteOperationRequest()
);
const expectedResponse = generateSampleMessage(
new protos.google.protobuf.Empty()
);
client.innerApiCalls.deleteOperation =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.deleteOperation(
request,
undefined,
(
err?: Error | null,
result?: protos.google.protobuf.Empty | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.deleteOperation as SinonStub)
.getCall(0)
.calledWith(request /* callback function above */)
);
});
it('invokes deleteOperation with error', async () => {
const grpcClient = new GrpcClient();
const clientOptions = {
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
};
const client = new OperationsClientBuilder(grpcClient).operationsClient(
clientOptions
);
const request = generateSampleMessage(
new protos.google.longrunning.DeleteOperationRequest()
);
const expectedError = new Error('expected');
client.innerApiCalls.deleteOperation = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(async () => {
await client.deleteOperation(request);
}, expectedError);
assert(
(client.innerApiCalls.deleteOperation as SinonStub)
.getCall(0)
.calledWith(request)
);
});
});
}); | the_stack |
import MiniCssExtractPlugin from "mini-css-extract-plugin";
import svgToTinyDataUri from "mini-svg-data-uri";
import type Config from "webpack-chain";
import merge from "deepmerge";
import yaml from "js-yaml";
import { getDefaultESBuildTarget, getIncompatibleConfig } from "../utils";
import type { INormalizedOpts } from "../types";
const addAssetsRule = (config: Config) => {
config.module
.rule("assets")
// load source as raw if specified `raw` in resourceQuery. e.g., `import myModule from 'my-module?raw';`
.oneOf("raw")
.resourceQuery(/raw/)
.set("type", "asset/source") // TODO: replace after webpack-chain support webpack5
.end() // end of oneOf
// load source as inline if specified `inline` in resourceQuery. e.g., `import myModule from 'my-module?inline';`
.oneOf("inline")
.resourceQuery(/inline/)
.set("type", "asset/inline") // TODO: replace after webpack-chain support webpack5
.end() // end of oneOf
// load images as inline if it's size is smaller then 10000 byte
.oneOf("images")
.test(/\.(png|jpe?g|gif|webp|ico|bmp)(\?.*)?$/)
.set("type", "asset") // TODO: replace after webpack-chain support webpack5
.parser({ dataUrlCondition: { maxSize: 10000 } })
.end() // end of oneOf
// load svg as inline by custom data URI generator if it's size is smaller then 10000 byte
.oneOf("svg")
.test(/\.svg(\?.*)?$/)
.set("type", "asset") // TODO: replace after webpack-chain support webpack5
.parser({ dataUrlCondition: { maxSize: 10000 } })
.set("generator", {
dataUrl: content => {
if (typeof content !== "string") {
content = content.toString();
}
return svgToTinyDataUri(content);
},
}) // TODO: replace after webpack-chain support webpack5
.end() // end of oneOf
// load fonts as resource
.oneOf("fonts")
.test(/\.(eot|woff|woff2|ttf)(\?.*)?$/)
.set("type", "asset/resource") // TODO: replace after webpack-chain support webpack5
.end() // end of oneOf
// load plaintext as raw
.oneOf("plaintext")
.test(/\.(txt|text|md)(\?.*)?$/)
.set("type", "asset/source") // TODO: replace after webpack-chain support webpack5
.end() // end of oneOf
.oneOf("yaml")
.test(/\.(yml|yaml)$/)
.type("json")
.parser({ parse: yaml.load })
.end() // end of oneOf
.end();
};
const addESBuildLoader = (config: Config, options: INormalizedOpts) => {
const target = getDefaultESBuildTarget(options);
config.module
.rule("esbuild")
.oneOf("js")
.test(/\.(js|mjs|jsx)$/)
.use("esbuild-loader")
.loader(require.resolve("esbuild-loader"))
.options({
loader: "jsx",
target,
...(typeof options.esbuild.loader === "object" ? options.esbuild.loader : {}),
})
.end() // end of use
.end() // end of oneOf
.oneOf("ts")
.test(/\.ts$/)
.use("esbuild-loader")
.loader(require.resolve("esbuild-loader"))
.options({
loader: "ts",
target,
...(typeof options.esbuild.loader === "object" ? options.esbuild.loader : {}),
})
.end() // end of use
.end() // end of oneOf
.oneOf("tsx")
.test(/\.tsx$/)
.use("esbuild-loader")
.loader(require.resolve("esbuild-loader"))
.options({
loader: "tsx",
target,
...(typeof options.esbuild.loader === "object" ? options.esbuild.loader : {}),
})
.end() // end of use
.end() // end of oneOf
.end();
};
const hasJsxRuntime = () => {
try {
require.resolve("react/jsx-runtime");
return true;
} catch (e) {
return false;
}
};
const getSWCOptions = (
options: INormalizedOpts,
{ typescripit = true, react = true }: { typescripit?: boolean; react?: boolean } = {},
) => {
const defaultOptions = {
env: {
coreJs: "3",
},
jsc: {
parser: {
syntax: typescripit ? "typescript" : "ecmascript",
decorators: true,
dynamicImport: true,
...(typescripit
? { tsx: react }
: {
jsx: react,
privateMethod: true,
functionBind: true,
classPrivateProperty: true,
exportDefaultFrom: true,
exportNamespaceFrom: true,
importMeta: true,
}),
},
transform: {
react: {
development: options.env === "development",
runtime: hasJsxRuntime() ? "automatic" : "classic",
},
legacyDecorator: true,
decoratorMetadata: true,
},
},
};
return typeof options.swc === "object" ? merge(defaultOptions, options.swc) : defaultOptions;
};
const addSWCLoader = (config: Config, options: INormalizedOpts) => {
config.module
.rule("swc")
// Transform all `jsx` files
.oneOf("js")
.test(/\.(mjs|js|jsx)$/)
.use("swc-loader")
.loader(require.resolve("swc-loader"))
.options(getSWCOptions(options, { typescripit: false }))
.end() // end of use
.end() // end of oneOf
.oneOf("ts")
.test(/\.ts$/)
.use("swc-loader")
.loader(require.resolve("swc-loader"))
.options(getSWCOptions(options, { react: false }))
.end() // end of use
.end() // end of oneOf
.oneOf("tsx")
.test(/\.tsx$/)
.use("swc-loader")
.loader(require.resolve("swc-loader"))
.options(getSWCOptions(options))
.end() // end of use
.end() // end of oneOf
.end();
};
const getBabelOpts = (
options: INormalizedOpts,
{ typescript = true, react = true }: { typescript?: boolean; react?: boolean } = {},
) => {
return {
presets: [
[
require.resolve("@dawnjs/babel-preset-dawn"),
{
typescript,
react: react
? {
development: options.env === "development",
runtime: options.babel?.jsxRuntime && hasJsxRuntime() ? "automatic" : "classic",
pragma: options.babel?.pragma,
pragmaFrag: options.babel?.pragmaFrag,
}
: false,
reactRequire:
react &&
!(options.babel?.disableAutoReactRequire === true || (options.babel?.jsxRuntime && hasJsxRuntime())),
transformRuntime: options.babel?.runtimeHelpers
? {
corejs: options.babel?.corejs,
...(typeof options.babel?.runtimeHelpers === "string"
? { version: options.babel?.runtimeHelpers }
: {}),
}
: undefined,
},
],
...(options.babel?.extraBabelPresets ?? []),
].filter(Boolean),
plugins: [
options.server && options.serverOpts.hot && require.resolve("react-refresh/babel"),
...(options.babel?.extraBabelPlugins ?? []),
].filter(Boolean),
cacheDirectory: process.env.BABEL_CACHE !== "none",
cacheCompression: false,
};
};
const pkgsRegList = getIncompatibleConfig();
const addBabelRule = (config: Config, options: INormalizedOpts) => {
config.module
.rule("babel")
// Transform all `jsx` files
.oneOf("jsx")
.test(/\.jsx$/)
.use("babel-loader")
.loader(require.resolve("babel-loader"))
.options(getBabelOpts(options, { typescript: false }))
.end() // end of use
.end() // end of oneOf
// Transform all `js` and `mjs` files except files in node_modules
.oneOf("app-js")
.test(/\.(js|mjs)$/)
.exclude.add(/node_modules/)
.end() // end of exclude
.use("babel-loader")
.loader(require.resolve("babel-loader"))
.options(getBabelOpts(options, { typescript: false }))
.end() // end of use
.end() // end of oneOf
// Transform extra `js` and `mjs` files with user config
.when(!!options.babel?.extraBabelIncludes?.length, rule => {
rule
.oneOf("extra-js")
.test(/\.(js|mjs)$/)
.include.merge(options.babel.extraBabelIncludes)
.end() // end of include
.use("babel-loader")
.loader(require.resolve("babel-loader"))
.options(getBabelOpts(options, { typescript: false }));
})
// compile whatever you need in ie11
// make ie11 incompatible alone, developer can also use extraBabelIncludes
.when(!!options.babel?.ie11Incompatible, rule => {
rule
.oneOf("ie11-incompatible")
.include.merge(pkgsRegList)
.end()
.use("babel-loader")
.loader(require.resolve("babel-loader"))
.options(getBabelOpts(options, { typescript: false }))
.end();
})
// Transform all `ts` files with react off
.oneOf("ts")
.test(/\.ts$/)
.use("babel-loader")
.loader(require.resolve("babel-loader"))
.options(getBabelOpts(options, { react: false }))
.end() // end of use
.end() // end of oneOf
// Transform all `tsx` files
.oneOf("tsx")
.test(/\.tsx$/)
.use("babel-loader")
.loader(require.resolve("babel-loader"))
.options(getBabelOpts(options))
.end() // end of use
.end() // end of oneOf
.end();
};
const addWorkerRule = (config: Config, options: INormalizedOpts) => {
config.module
.rule("worker")
.test(/\.worker\.(js|mjs|ts)/)
.use("worker-loader")
.loader(require.resolve("worker-loader"))
.options({
inline: "fallback",
...options.workerLoader,
});
};
const addStyleRule = (
config: Config,
options: INormalizedOpts,
{
name,
test,
preProcessors,
}: {
name: string;
test: any;
importLoaders?: number;
preProcessors?: Array<{ loader: string; options?: object }>;
},
) => {
config.module
.rule(name)
.test(test)
// use style-loader for injectCSS, or extract css by mini-css-extract-plugin otherwise
.when(
options.injectCSS,
rule => {
rule.use("style-loader").loader(require.resolve("style-loader")).options(options.styleLoader);
},
rule => {
rule.use("extract-css-loader").loader(MiniCssExtractPlugin.loader).options(options.styleLoader);
},
)
// use css-loader, enable css modules for .modules.* by default
.use("css-loader")
.loader(require.resolve("css-loader"))
.options({
importLoaders: preProcessors?.length ?? 0 + 1,
...options.cssLoader,
})
.end()
// use postcss-loader before css-loader, but after any pre-processor loader
.use("postcss-loader")
.loader(require.resolve("postcss-loader"))
.options({
implementation: require.resolve("postcss"),
...options.postcssLoader,
postcssOptions: (loaderContext: any) => {
let customOptions = options.postcssLoader?.postcssOptions;
if (typeof customOptions === "function") {
customOptions = customOptions(loaderContext);
}
return {
plugins: [
[require.resolve("postcss-preset-env"), { stage: 0, ...options.postcssPresetEnv }],
...(options.extraPostCSSPlugins ?? []),
],
...customOptions,
};
},
})
.end()
.when(!!preProcessors?.length, rule => {
preProcessors.forEach(preProcessor => {
rule.use(preProcessor.loader).loader(require.resolve(preProcessor.loader)).options(preProcessor.options);
});
});
};
export default async (config: Config, options: INormalizedOpts) => {
addAssetsRule(config);
if (options.esbuild?.loader) {
addESBuildLoader(config, options);
} else if (options.swc) {
addSWCLoader(config, options);
} else {
addBabelRule(config, options);
}
addWorkerRule(config, options); // MUST AFTER BABEL RULE !!!
addStyleRule(config, options, { name: "css", test: /\.css(\?.*)?$/, importLoaders: 1 });
addStyleRule(config, options, {
name: "less",
test: /\.less(\?.*)?$/,
preProcessors: [
{
loader: "less-loader",
options: {
implementation: require.resolve("less"),
...options.lessLoader,
lessOptions: (loaderContext: any) => {
let customOptions = options.lessLoader?.lessOptions;
if (typeof customOptions === "function") {
customOptions = customOptions(loaderContext);
}
return { rewriteUrls: "all", javascriptEnabled: true, ...customOptions };
},
},
},
],
});
addStyleRule(config, options, {
name: "sass",
test: /\.s(a|c)ss(\?.*)?$/,
preProcessors: [
{ loader: "resolve-url-loader", options: { ...options.resolveUrlLoader } },
{
loader: "sass-loader",
options: {
implementation: require.resolve("sass"),
...options.sassLoader,
sourceMap: true, // required by `resolve-url-loader`, see https://github.com/bholloway/resolve-url-loader/blob/master/packages/resolve-url-loader/README.md#configure-webpack
sassOptions: (loaderContext: any) => {
let customOptions = options.sassLoader?.sassOptions;
if (typeof customOptions === "function") {
customOptions = customOptions(loaderContext);
}
return { quietDeps: true, ...customOptions };
},
},
},
],
});
}; | the_stack |
import { applyArtifacts, computeAllStats, createProxiedStats } from "../TestUtils"
import formula from "./data"
let setupStats
// Discord ID: 822256929929822248
describe("Testing Jean's Formulas (sohum#5921)", () => {
beforeEach(() => {
setupStats = createProxiedStats({
characterHP: 9533, characterATK: 155, characterDEF: 499,
characterEle: "anemo", characterLevel: 60,
weaponType: "sword", weaponATK: 347,
heal_: 11.1, enerRech_: 100 + 50.5,
enemyLevel: 85, physical_enemyRes_: 70, // Ruin Guard
tlvl: Object.freeze({ auto: 1 - 1, skill: 1 - 1, burst: 1 - 1 }),
})
})
describe("with artifacts", () => {
beforeEach(() => applyArtifacts(setupStats, [
{ hp: 3967, atk_: 9.3, atk: 16, critDMG_: 13.2, hp_: 10.5, }, // Flower of Life
{ atk: 258, critDMG_: 7, def: 81, critRate_: 3.9, hp: 239, }, // Plume of Death
{ enerRech_: 29.8, critDMG_: 6.2, hp: 209, eleMas: 19, atk: 16 }, // Sands of Eon
{ anemo_dmg_: 30.8, hp: 448, eleMas: 40, critRate_: 3.9, def: 21 }, // Goblet of Eonothem
{ critRate_: 25.8, hp: 478, critDMG_: 7, atk_: 13.4, atk: 35, }, // Circlet of Logos
{ eleMas: 80 }, // 2 Wanderer's Troupe
]))
test("heal", () => {
const stats = computeAllStats(setupStats)
expect(formula.burst.regen(stats)[0](stats)).toApproximate(433)
expect(formula.passive1.dmg(stats)[0](stats)).toApproximate(156)
})
describe("no crit", () => {
beforeEach(() => setupStats.hitMode = "hit")
test("hit", () => {
const stats = computeAllStats(setupStats)
expect(formula.normal[0](stats)[0](stats)).toApproximate(63)
expect(formula.normal[1](stats)[0](stats)).toApproximate(59)
expect(formula.normal[2](stats)[0](stats)).toApproximate(78)
expect(formula.normal[3](stats)[0](stats)).toApproximate(86)
expect(formula.normal[4](stats)[0](stats)).toApproximate(103)
expect(formula.charged.dmg(stats)[0](stats)).toApproximate(211)
expect(formula.skill.dmg(stats)[0](stats)).toApproximate(1498)
expect(formula.burst.skill(stats)[0](stats)).toApproximate(2180)
expect(formula.burst.field_dmg(stats)[0](stats)).toApproximate(402)
})
})
describe("crit", () => {
beforeEach(() => setupStats.hitMode = "critHit")
test("hit", () => {
const stats = computeAllStats(setupStats)
expect(formula.normal[0](stats)[0](stats)).toApproximate(115)
expect(formula.normal[1](stats)[0](stats)).toApproximate(109)
expect(formula.normal[2](stats)[0](stats)).toApproximate(144)
expect(formula.normal[4](stats)[0](stats)).toApproximate(189)
expect(formula.skill.dmg(stats)[0](stats)).toApproximate(2748)
expect(formula.burst.skill(stats)[0](stats)).toApproximate(3998)
expect(formula.burst.field_dmg(stats)[0](stats)).toApproximate(737)
})
})
})
})
// Discord ID: 754914627246358610
describe("Testing Jean's Formulas (Saber#9529)", () => {
beforeEach(() => {
setupStats = createProxiedStats({
characterHP: 14695, characterATK: 239, characterDEF: 769,
characterEle: "anemo", characterLevel: 90,
weaponType: "sword", weaponATK: 674,
heal_: 22.2,
atk_: 20, physical_dmg_: 41.3, // Weapon
tlvl: Object.freeze({ auto: 9 - 1, skill: 8 - 1, burst: 6 - 1 }),
})
})
describe("with artifacts", () => {
beforeEach(() => applyArtifacts(setupStats, [
{ hp: 4780, critDMG_: 12.4, critRate_: 9.7, hp_: 4.1, def: 58 }, // Flower of Life
{ atk: 311, critRate_: 10.5, def: 19, critDMG_: 19.4, hp_: 4.7 }, // Plume of Death
{ atk_: 46.6, def_: 12.4, critDMG_: 22.5, hp: 478, enerRech_: 10.4 }, // Sands of Eon
{ atk_: 46.6, critDMG_: 27.2, def_: 5.8, eleMas: 23, critRate_: 6.6 }, // Goblet of Eonothem
{ critRate_: 31.1, enerRech_: 13, hp_: 14, hp: 299, eleMas: 56 }, // Circlet of Logos
{ atk_: 18, physical_dmg_: 25 }, // Gladiators 2set + Bloodstained 2set
]))
test("overall stats", () => {
const stats = computeAllStats(setupStats)
expect(stats.finalHP).toApproximate(14695 + 8897)
expect(stats.finalATK).toApproximate(914 + 1510)
expect(stats.finalDEF).toApproximate(769 + 216)
expect(stats.eleMas).toApproximate(79)
expect(stats.critRate_).toApproximate(62.9)
expect(stats.critDMG_).toApproximate(131.6)
expect(stats.enerRech_).toApproximate(123.3)
expect(stats.anemo_dmg_).toApproximate(0)
expect(stats.physical_dmg_).toApproximate(66.3)
})
test("healing", () => {
const stats = computeAllStats(setupStats)
expect(formula.burst.heal(stats)[0](stats)).toApproximate(13388)
expect(formula.burst.regen(stats)[0](stats)).toApproximate(1338)
expect(formula.passive1.dmg(stats)[0](stats)).toApproximate(443)
})
describe("no crit", () => {
beforeEach(() => setupStats.hitMode = "hit")
describe("Ruin Guard lvl 85", () => {
beforeEach(() => {
setupStats.enemyLevel = 85
setupStats.physical_enemyRes_ = 70
})
test("hits", () => {
const stats = computeAllStats(setupStats)
expect(formula.normal[0](stats)[0](stats)).toApproximate(544)
expect(formula.normal[1](stats)[0](stats)).toApproximate(513)
expect(formula.normal[2](stats)[0](stats)).toApproximate(678)
expect(formula.normal[3](stats)[0](stats)).toApproximate(741)
expect(formula.normal[4](stats)[0](stats)).toApproximate(891)
expect(formula.charged.dmg(stats)[0](stats)).toApproximate(1823)
expect(formula.plunging.dmg(stats)[0](stats)).toApproximate(719)
expect(formula.plunging.low(stats)[0](stats)).toApproximate(1438)
expect(formula.plunging.high(stats)[0](stats)).toApproximate(1797)
expect(formula.skill.dmg(stats)[0](stats)).toApproximate(5162)
expect(formula.skill.dmg_hold(stats)[0](stats)).toApproximate(7226)
})
})
})
describe("crit", () => {
beforeEach(() => setupStats.hitMode = "critHit")
describe("Ruin Guard lvl 85", () => {
beforeEach(() => {
setupStats.enemyLevel = 85
setupStats.physical_enemyRes_ = 70
})
test("hits", () => {
const stats = computeAllStats(setupStats)
expect(formula.normal[0](stats)[0](stats)).toApproximate(1259)
expect(formula.normal[1](stats)[0](stats)).toApproximate(1188)
expect(formula.normal[2](stats)[0](stats)).toApproximate(1571)
expect(formula.normal[3](stats)[0](stats)).toApproximate(1717)
expect(formula.normal[4](stats)[0](stats)).toApproximate(2064)
expect(formula.charged.dmg(stats)[0](stats)).toApproximate(4223)
expect(formula.plunging.dmg(stats)[0](stats)).toApproximate(1666)
expect(formula.plunging.low(stats)[0](stats)).toApproximate(3332)
expect(formula.plunging.high(stats)[0](stats)).toApproximate(4162)
expect(formula.skill.dmg(stats)[0](stats)).toApproximate(11954)
expect(formula.skill.dmg_hold(stats)[0](stats)).toApproximate(16736)
expect(formula.burst.skill(stats)[0](stats)).toApproximate(15217)
expect(formula.burst.field_dmg(stats)[0](stats)).toApproximate(2808)
})
})
})
})
describe("C1 with Anemo DMG Bonus", () => {
beforeEach(() => {
// Ruin Guard
setupStats.enemyLevel = 86
setupStats.physical_enemyRes_ = 70
})
describe("Setup 1", () => {
beforeEach(() => {
// Weapon
delete setupStats.atk_
delete setupStats.physical_dmg_
setupStats.weaponATK = 914 - setupStats.characterATK
setupStats.hp = 7542
setupStats.atk = 1487
setupStats.def = 218
setupStats.critRate_ = 39.1
setupStats.critDMG_ = 110.0
setupStats.heal_ = 22.2
setupStats.enerRech_ = 114.9
})
describe("no crit", () => {
beforeEach(() => setupStats.hitMode = "hit")
test("with Anemo DMG Bonus 46.6%", () => {
setupStats.anemo_dmg_ = 46.6
const stats = computeAllStats(setupStats)
expect(formula.skill.dmg(stats)[0](stats)).toApproximate(7477)
expect(formula.skill.dmg_hold(stats)[0](stats)).toApproximate(9517)
})
test("with Anemo DMG Bonus 71.6%", () => {
setupStats.anemo_dmg_ = 71.6
const stats = computeAllStats(setupStats)
expect(formula.skill.dmg(stats)[0](stats)).toApproximate(8752)
expect(formula.skill.dmg_hold(stats)[0](stats)).toApproximate(10792)
})
})
describe("crit", () => {
beforeEach(() => setupStats.hitMode = "critHit")
test("with Anemo DMG Bonus 46.6%", () => {
setupStats.anemo_dmg_ = 46.6
const stats = computeAllStats(setupStats)
expect(formula.skill.dmg(stats)[0](stats)).toApproximate(15700)
expect(formula.skill.dmg_hold(stats)[0](stats)).toApproximate(19984)
})
test("with Anemo DMG Bonus 71.6%", () => {
setupStats.anemo_dmg_ = 71.6
const stats = computeAllStats(setupStats)
expect(formula.skill.dmg(stats)[0](stats)).toApproximate(18378)
expect(formula.skill.dmg_hold(stats)[0](stats)).toApproximate(22662)
})
})
})
describe("Setup 2", () => {
beforeEach(() => {
// Weapon
delete setupStats.atk_
delete setupStats.physical_dmg_
setupStats.weaponATK = 914 - setupStats.characterATK
setupStats.hp = 7574
setupStats.atk = 1487
setupStats.def = 218
setupStats.critRate_ = 38.4
setupStats.critDMG_ = 90.6
setupStats.heal_ = 22.2
setupStats.enerRech_ = 120.7
})
describe("no crit", () => {
beforeEach(() => setupStats.hitMode = "hit")
test("with Anemo DMG Bonus 61.6%", () => {
setupStats.anemo_dmg_ = 61.6
const stats = computeAllStats(setupStats)
expect(formula.skill.dmg(stats)[0](stats)).toApproximate(8242)
expect(formula.skill.dmg_hold(stats)[0](stats)).toApproximate(10282)
})
test("with Anemo DMG Bonus 86.6%", () => {
setupStats.anemo_dmg_ = 86.6
const stats = computeAllStats(setupStats)
expect(formula.skill.dmg(stats)[0](stats)).toApproximate(9517)
expect(formula.skill.dmg_hold(stats)[0](stats)).toApproximate(11557)
})
})
describe("crit", () => {
beforeEach(() => setupStats.hitMode = "critHit")
test("with Anemo DMG Bonus 61.6%", () => {
setupStats.anemo_dmg_ = 61.6
const stats = computeAllStats(setupStats)
expect(formula.skill.dmg(stats)[0](stats)).toApproximate(15706)
expect(formula.skill.dmg_hold(stats)[0](stats)).toApproximate(19594)
})
test("with Anemo DMG Bonus 86.6%", () => {
setupStats.anemo_dmg_ = 86.6
const stats = computeAllStats(setupStats)
expect(formula.skill.dmg(stats)[0](stats)).toApproximate(18136)
expect(formula.skill.dmg_hold(stats)[0](stats)).toApproximate(22024)
})
})
})
describe("Setup 3", () => {
beforeEach(() => {
// Weapon
delete setupStats.atk_
delete setupStats.physical_dmg_
setupStats.weaponATK = 914 - setupStats.characterATK
setupStats.hp = 7574
setupStats.atk = 1237
setupStats.def = 228
setupStats.critRate_ = 32.5
setupStats.critDMG_ = 90.6
setupStats.heal_ = 22.2
setupStats.enerRech_ = 116.2
})
describe("no crit", () => {
beforeEach(() => setupStats.hitMode = "hit")
test("with Anemo DMG Bonus 22.0%", () => {
setupStats.anemo_dmg_ = 22.0
const stats = computeAllStats(setupStats)
expect(formula.skill.dmg(stats)[0](stats)).toApproximate(5575)
expect(formula.skill.dmg_hold(stats)[0](stats)).toApproximate(7403)
})
test("with Anemo DMG Bonus 47.0%", () => {
setupStats.anemo_dmg_ = 47.0
const stats = computeAllStats(setupStats)
expect(formula.skill.dmg(stats)[0](stats)).toApproximate(6717)
expect(formula.skill.dmg_hold(stats)[0](stats)).toApproximate(8545)
})
})
describe("crit", () => {
beforeEach(() => setupStats.hitMode = "critHit")
test("with Anemo DMG Bonus 22.0%", () => {
setupStats.anemo_dmg_ = 22.0
const stats = computeAllStats(setupStats)
expect(formula.skill.dmg(stats)[0](stats)).toApproximate(10624)
expect(formula.skill.dmg_hold(stats)[0](stats)).toApproximate(14107)
})
test("with Anemo DMG Bonus 47.0%", () => {
setupStats.anemo_dmg_ = 47.0
const stats = computeAllStats(setupStats)
expect(formula.skill.dmg(stats)[0](stats)).toApproximate(12801)
})
})
})
describe("Setup 4", () => {
beforeEach(() => {
// Weapon
delete setupStats.atk_
delete setupStats.physical_dmg_
setupStats.weaponATK = 914 - setupStats.characterATK
setupStats.skill_dmg_ = 16
setupStats.hp = 7574
setupStats.atk = 921
setupStats.def = 228
setupStats.critRate_ = 32.5
setupStats.critDMG_ = 90.6
setupStats.heal_ = 22.2
setupStats.enerRech_ = 162.1
})
describe("no crit", () => {
beforeEach(() => setupStats.hitMode = "hit")
test("with Anemo DMG Bonus 22.0%", () => {
setupStats.anemo_dmg_ = 22.0
const stats = computeAllStats(setupStats)
expect(formula.skill.dmg(stats)[0](stats)).toApproximate(5462)
expect(formula.skill.dmg_hold(stats)[0](stats)).toApproximate(6880)
})
test("with Anemo DMG Bonus 47.0%", () => {
setupStats.anemo_dmg_ = 47.0
const stats = computeAllStats(setupStats)
expect(formula.skill.dmg(stats)[0](stats)).toApproximate(6348)
expect(formula.skill.dmg_hold(stats)[0](stats)).toApproximate(7767)
})
})
describe("crit", () => {
beforeEach(() => setupStats.hitMode = "critHit")
test("with Anemo DMG Bonus 22.0%", () => {
setupStats.anemo_dmg_ = 22.0
const stats = computeAllStats(setupStats)
expect(formula.skill.dmg(stats)[0](stats)).toApproximate(10408)
expect(formula.skill.dmg_hold(stats)[0](stats)).toApproximate(13112)
})
test("with Anemo DMG Bonus 47.0%", () => {
setupStats.anemo_dmg_ = 47.0
const stats = computeAllStats(setupStats)
expect(formula.skill.dmg(stats)[0](stats)).toApproximate(12098)
expect(formula.skill.dmg_hold(stats)[0](stats)).toApproximate(14801)
})
})
})
})
})
// Discord ID: 822256929929822248
describe("Testing Jean's Formulas (sohum#5921)", () => {
beforeEach(() => {
setupStats = createProxiedStats({
characterHP: 9533, characterATK: 155, characterDEF: 499,
characterEle: "anemo", characterLevel: 60,
weaponType: "sword", weaponATK: 347,
heal_: 11.1, enerRech_: 100 + 50.5,
enemyLevel: 85, physical_enemyRes_: 70, // Ruin Guard
tlvl: Object.freeze({ auto: 1 - 1, skill: 1 - 1, burst: 1 - 1 }),
})
})
describe("with artifacts", () => {
beforeEach(() => applyArtifacts(setupStats, [
{ hp: 3967, atk_: 9.3, atk: 16, critDMG_: 13.2, hp_: 10.5, }, // Flower of Life
{ atk: 258, critDMG_: 7, def: 81, critRate_: 3.9, hp: 239, }, // Plume of Death
{ enerRech_: 29.8, critDMG_: 6.2, hp: 209, eleMas: 19, atk: 16 }, // Sands of Eon
{ anemo_dmg_: 30.8, hp: 448, eleMas: 40, critRate_: 3.9, def: 21 }, // Goblet of Eonothem
{ critRate_: 25.8, hp: 478, critDMG_: 7, atk_: 13.4, atk: 35, }, // Circlet of Logos
{ eleMas: 80 }, // 2 Wanderer's Troupe
]))
test("heal", () => {
const stats = computeAllStats(setupStats)
expect(formula.burst.regen(stats)[0](stats)).toApproximate(433)
expect(formula.passive1.dmg(stats)[0](stats)).toApproximate(156)
})
describe("no crit", () => {
beforeEach(() => setupStats.hitMode = "hit")
test("hit", () => {
const stats = computeAllStats(setupStats)
expect(formula.normal[0](stats)[0](stats)).toApproximate(63)
expect(formula.normal[1](stats)[0](stats)).toApproximate(59)
expect(formula.normal[2](stats)[0](stats)).toApproximate(78)
expect(formula.normal[3](stats)[0](stats)).toApproximate(86)
expect(formula.normal[4](stats)[0](stats)).toApproximate(103)
expect(formula.charged.dmg(stats)[0](stats)).toApproximate(211)
expect(formula.skill.dmg(stats)[0](stats)).toApproximate(1498)
expect(formula.burst.skill(stats)[0](stats)).toApproximate(2180)
expect(formula.burst.field_dmg(stats)[0](stats)).toApproximate(402)
})
})
describe("crit", () => {
beforeEach(() => setupStats.hitMode = "critHit")
test("hit", () => {
const stats = computeAllStats(setupStats)
expect(formula.normal[0](stats)[0](stats)).toApproximate(115)
expect(formula.normal[1](stats)[0](stats)).toApproximate(109)
expect(formula.normal[2](stats)[0](stats)).toApproximate(144)
expect(formula.normal[4](stats)[0](stats)).toApproximate(189)
expect(formula.skill.dmg(stats)[0](stats)).toApproximate(2748)
expect(formula.burst.skill(stats)[0](stats)).toApproximate(3998)
expect(formula.burst.field_dmg(stats)[0](stats)).toApproximate(737)
})
})
})
}) | the_stack |
import m from 'mithril';
import _ from 'underscore';
import h from '../h';
import projectVM from '../vms/project-vm';
import rewardVM from '../vms/reward-vm';
import faqBox from '../c/faq-box';
import { getCurrentUserCached } from '../shared/services/user/get-current-user-cached';
import { isLoggedIn } from '../shared/services/user/is-logged-in';
import { RewardDetails } from '../entities';
const projectsReward = {
oninit: function(vnode: m.Vnode<any>) {
const vm = rewardVM,
selectedReward = vm.selectedReward,
selectReward = vm.selectReward,
rewards = vm.rewards(),
mode = projectVM.currentProject().mode,
faq = window.I18n.translations[window.I18n.currentLocale()].projects.faq[mode];
// TODO unify projectsReward and project-reward-list reward submission. fix routing issue.
const submitContribution = () => {
const valueFloat = h.monetaryToFloat(vm.contributionValue);
if (valueFloat < vm.selectedReward().minimum_value) {
vm.error(`O valor de apoio para essa recompensa deve ser de no mínimo R$${vm.selectedReward().minimum_value}`);
} else if (!isLoggedIn(getCurrentUserCached())) {
const storeKey = 'selectedReward';
h.storeObject(storeKey, { value: valueFloat, reward: vm.selectedReward() });
return h.navigateToDevise(`/${projectVM.currentProject().permalink}`);
} else {
vm.error('');
vm.contributionValue(valueFloat);
m.route.set(`/projects/${projectVM.currentProject().project_id}/payment`, {
project_user_id: projectVM.currentProject().user_id
});
}
return false;
};
const isSelected = (reward: RewardDetails) => reward.id === selectedReward().id;
if (_.first(rewards).id !== vm.noReward.id) {
rewards.unshift(vm.noReward);
}
vnode.state = {
rewards,
project: projectVM.currentProject,
contributionValue: vm.contributionValue,
submitContribution,
applyMask: vm.applyMask,
error: vm.error,
isSelected,
selectedReward,
selectReward,
faq
};
},
view: function({state, attrs}) {
const project = state.project;
return m('#project-rewards', [
m('.w-section.page-header.u-text-center', [
m('.w-container', [
m('h1.fontsize-larger.fontweight-semibold.project-name[itemprop="name"]', h.selfOrEmpty(project().name || project().project_name)),
m('h2.fontsize-base.lineheight-looser[itemprop="author"]', [
'por ',
project().user ? project().user.name : project().owner_name ? project().owner_name : ''
])
])
]),
m('.w-section.header-cont-new',
m('.w-container',
m('.fontweight-semibold.lineheight-tight.text-success.fontsize-large.u-text-center-small-only', [
'Escolha a recompensa e o valor do apoio',
m.trust(' '),
m('span.fontsize-small.badge.badge-success', '(parcele em até 6x)')
])
)
),
m('.section[id=\'new-contribution\']',
m('.w-container',
m('.w-row',
[
m('.w-col.w-col-8',
m('.w-form.back-reward-form',
m('form.simple_form.new_contribution', {
onsubmit: state.submitContribution
}, _.map(state.rewards, (reward, index) => {
const isSelected = state.isSelected(reward),
monetaryMinimum = h.applyMonetaryMask(reward.minimum_value);
return m('span.radio.w-radio.w-clearfix.back-reward-radio-reward', {
class: isSelected ? 'selected' : '',
onclick: state.selectReward(reward),
key: index
}, m(`label[for='contribution_reward_id_${reward.id}']`,
[
m(`input.radio_buttons.optional.w-input.text-field.w-radio-input.back-reward-radio-button[id='contribution_reward_id_${reward.id}'][name='contribution[reward_id]'][type='radio'][value='${reward.id}']`, {
checked: !!isSelected,
}),
m(`label.w-form-label.fontsize-base.fontweight-semibold.u-marginbottom-10[for='contribution_reward_${reward.id}']`,
reward.id === -1 ? 'Não quero recompensa' : `R$ ${reward.minimum_value} ou mais`
),
isSelected ? m('.w-row.back-reward-money',
[
m('.w-col.w-col-8.w-col-small-8.w-col-tiny-8.w-sub-col-middle.w-clearfix',
[
m('.w-row',
[
m('.w-col.w-col-3.w-col-small-3.w-col-tiny-3',
m('.back-reward-input-reward.placeholder',
'R$'
)
),
m('.w-col.w-col-9.w-col-small-9.w-col-tiny-9',
m('input.user-reward-value.back-reward-input-reward[autocomplete=\'off\'][type=\'tel\']', {
class: state.error() ? 'error' : '',
min: monetaryMinimum,
placeholder: monetaryMinimum,
onkeyup: m.withAttr('value', state.applyMask),
value: state.contributionValue()
}
)
)
]
),
state.error().length > 0 ? m('.text-error', [
m('br'),
m('span.fa.fa-exclamation-triangle'),
` ${state.error()}`
]) : ''
]
),
m('.submit-form.w-col.w-col-4.w-col-small-4.w-col-tiny-4',
m('button.btn.btn-large', [
'Continuar ',
m('span.fa.fa-chevron-right')
])
)
]
) : '',
m('.back-reward-reward-description',
[
m('.fontsize-smaller.u-marginbottom-10', reward.description),
reward.deliver_at ? m('.fontsize-smallest.fontcolor-secondary', `Estimativa de entrega: ${h.momentify(reward.deliver_at, 'MMM/YYYY')}`) : ''
]
)
]
)
); // End map return
})
)
)
),
m('.w-col.w-col-4', m(faqBox, { mode: state.project().mode, faq: state.faq }))
]
)
)
)
]);
}
};
export default projectsReward; | the_stack |
import {
AfterViewInit,
ChangeDetectorRef,
ContentChildren,
Directive,
ElementRef,
EventEmitter,
Host,
Input,
OnDestroy,
OnInit,
Optional,
Output,
QueryList,
Self,
SkipSelf,
TemplateRef,
ViewChild
} from '@angular/core';
import { NgControl, NgForm } from '@angular/forms';
import { ENTER } from '@angular/cdk/keycodes';
import { fromEvent, Observable, Subject, Subscription } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { PopoverFillMode } from '@fundamental-ngx/core/shared';
import { MobileModeConfig } from '@fundamental-ngx/core/mobile-mode';
import { ListComponent } from '@fundamental-ngx/core/list';
import {
ContentDensity,
ContentDensityService,
FocusEscapeDirection,
KeyUtil,
TemplateDirective
} from '@fundamental-ngx/core/utils';
import {
CollectionBaseInput,
FormField,
FormFieldControl,
isJsObject,
isOptionItem,
isString,
OptionItem
} from '@fundamental-ngx/platform/shared';
import { SelectComponent } from '../select/select.component';
import { SelectConfig } from '../select.config';
import { TextAlignment } from '../../combobox';
export type FdpSelectData<T> = OptionItem[] | Observable<T[]> | T[];
export class FdpSelectionChangeEvent {
constructor(
public source: SelectComponent,
public payload: any // Contains selected item
) {}
}
@Directive()
export abstract class BaseSelect extends CollectionBaseInput implements OnInit, AfterViewInit, OnDestroy {
/** Provides maximum default height for the optionPanel */
@Input()
maxHeight = '250px';
/** Whether the select should be built on mobile mode */
@Input()
mobile = false;
/** Tells the select if we need to group items */
@Input()
group = false;
/** A field name to use to group data by (support dotted notation) */
@Input()
groupKey?: string;
/** The field to show data in secondary column */
@Input()
secondaryKey?: string;
/** Show the second column (Applicable for two columns layout) */
@Input()
showSecondaryText = false;
/** Glyph to add icon in the select component. */
@Input()
glyph = 'slim-arrow-down';
/** The element to which the popover should be appended. */
@Input()
appendTo: ElementRef;
@Input()
triggerValue: String;
@Input()
fillControlMode: PopoverFillMode = 'at-least';
/** Horizontally align text inside the second column (Applicable for two columns layout) */
@Input()
secondaryTextAlignment: TextAlignment = 'right';
/**
* Max width of list container
* */
@Input()
width: string;
/** Whether the select component is readonly. */
@Input()
readonly = false;
/** Placeholder for the select. Appears in the
* triggerbox if no option is selected. */
@Input()
placeholder: string;
/** Whether the select is in compact mode. */
@Input()
compact = false;
/** Whether close the popover on outside click. */
@Input()
closeOnOutsideClick = true;
/** Custom template used to build control body. */
@Input()
controlTemplate: TemplateRef<any>;
/** Binds to control aria-labelledBy attribute */
@Input()
ariaLabelledBy = null;
/** Sets control aria-label attribute value */
@Input()
ariaLabel = null;
/** Select Input Mobile Configuration */
@Input()
mobileConfig: MobileModeConfig = { hasCloseButton: true };
/**
* String rendered as first value in the popup which let the user to make 'no selection' from
* available list of values. When this option is active and use make this selection we save a
* NULL value
*/
@Input()
noValueLabel: string;
@Input()
noWrapText = false;
/** Turns on/off Adjustable Width feature */
@Input()
autoResize = false;
/** First Column ratio */
@Input()
firstColumnRatio: number;
/** Secoond Column ratio */
@Input()
secondColumnRatio: number;
/**
* Min width of list container
*
* */
@Input()
minWidth?: number;
/**
* Max width of list container
* */
@Input()
maxWidth?: number;
/**
* content Density of element. 'cozy' | 'compact'
*/
@Input()
set contentDensity(contentDensity: ContentDensity) {
this._contentDensity = contentDensity;
this._isCompact = this.contentDensity !== 'cozy';
}
/** Data for suggestion list */
get list(): any {
return this._optionItems;
}
set list(value: any) {
if (value) {
this._optionItems = this._convertToOptionItems(value);
}
}
get canClose(): boolean {
return !(this.mobile && this.mobileConfig.approveButtonText);
}
/** Event emitted when item is selected. */
@Output()
selectionChange = new EventEmitter<FdpSelectionChangeEvent>();
/** @hidden */
@ViewChild(ListComponent)
listComponent: ListComponent;
/** @hidden */
@ContentChildren(TemplateDirective)
customTemplates: QueryList<TemplateDirective>;
/** Custom Option item Template
* * @hidden
* */
_optionItemTemplate: TemplateRef<any>;
/**
* Custom Secondary item Template
* @hidden
* */
_secondaryItemTemplate: TemplateRef<any>;
/**
* Custom Selected option item Template
* @hidden
* */
_selectedItemTemplate: TemplateRef<any>;
/** @hidden */
_contentDensityService: ContentDensityService;
/**
* @hidden
* Whether "contentDensity" is "compact"
*/
_isCompact: boolean;
/**
* List of option items
* @hidden
* */
_optionItems: OptionItem[];
/** @hidden */
_subscriptions = new Subscription();
/** @hidden */
private _searchInputElement: ElementRef;
/** Whether the select is opened. */
private _isOpen = false;
/**
* Need for opening mobile version
*
* @hidden
*/
private _openChange = new Subject<boolean>();
/** @hidden */
private _dsSubscription?: Subscription;
/** @hidden */
private _element: HTMLElement = this.elementRef.nativeElement;
constructor(
readonly cd: ChangeDetectorRef,
protected readonly elementRef: ElementRef,
@Optional() @Self() readonly ngControl: NgControl,
@Optional() @Self() readonly ngForm: NgForm,
protected selectConfig: SelectConfig,
@Optional() @SkipSelf() @Host() formField: FormField,
@Optional() @SkipSelf() @Host() formControl: FormFieldControl<any>
) {
super(cd, ngControl, ngForm, formField, formControl);
}
/** @hidden
* extended by super class
*/
ngOnInit(): void {
if (this.contentDensity === undefined && this._contentDensityService) {
this._subscriptions.add(
this._contentDensityService._contentDensityListener.subscribe((density) => {
this._isCompact = density !== 'cozy';
this.cd.markForCheck();
})
);
}
}
/** @hidden */
ngAfterViewInit(): void {
this._initWindowResize();
this._assignCustomTemplates();
super.ngAfterViewInit();
}
/** @hidden */
ngOnDestroy(): void {
super.ngOnDestroy();
this._subscriptions.unsubscribe();
if (this._dsSubscription) {
this._dsSubscription.unsubscribe();
}
}
/**
* Method to emit change event
* @hidden
*/
abstract _emitChangeEvent<K>(value: K): void;
/**
* Define is this item selected
* @hidden
*/
abstract _isSelectedOptionItem(selectedItem: OptionItem): boolean;
/**
* Emit select OptionItem
* @hidden
* */
abstract _selectOptionItem(item: OptionItem): void;
/**
* Define value as selected
* @hidden
* */
abstract _setAsSelected(item: OptionItem[]): void;
/** Is empty search field */
get isEmptyValue(): boolean {
return this.value.trim().length === 0;
}
/** write value for ControlValueAccessor */
writeValue(value: any): void {
if (!value) {
return;
}
const selectedItems = Array.isArray(value) ? value : [value];
this._setAsSelected(this._convertToOptionItems(selectedItems));
super.writeValue(value);
}
/** @hidden
* Close list * */
close(event: MouseEvent = null, forceClose: boolean = false): void {
if (event) {
const target = event.target as HTMLInputElement;
if (target && target.id === this.id) {
return;
}
}
if (this._isOpen && (forceClose || this.canClose)) {
this._isOpen = false;
this._openChange.next(this._isOpen);
this.cd.markForCheck();
this.onTouched();
}
}
/** @hidden */
showList(isOpen: boolean): void {
if (this._isOpen !== isOpen) {
this._isOpen = isOpen;
this.onTouched();
this._openChange.next(isOpen);
}
this.cd.detectChanges();
}
/** @hidden */
handleOptionItem(value: OptionItem): void {
if (value) {
this._selectOptionItem(value);
}
}
/** @hidden */
handlePressEnter(event: KeyboardEvent, value: OptionItem): void {
if (!KeyUtil.isKeyCode(event, ENTER)) {
return;
}
this.handleOptionItem(value);
}
/** Method passed to list component */
handleListFocusEscape(direction: FocusEscapeDirection): void {
if (direction === 'up') {
this._searchInputElement.nativeElement.focus();
}
}
/** @hidden */
private _initWindowResize(): void {
this._getOptionsListWidth();
if (!this.autoResize) {
return;
}
fromEvent(window, 'resize')
.pipe(takeUntil(this._destroyed))
.subscribe(() => this._getOptionsListWidth());
}
/** @hidden */
private _getOptionsListWidth(): void {
const body = document.body;
const rect = this._element.getBoundingClientRect();
const scrollBarWidth = body.offsetWidth - body.clientWidth;
this.maxWidth = window.innerWidth - scrollBarWidth - rect.left;
this.minWidth = rect.width - 2;
}
/**
* Convert original data to OptionItems Interface
* @hidden
*/
private _convertToOptionItems(items: any[]): OptionItem[] {
const item = items[0];
const elementTypeIsOptionItem = isOptionItem(item);
if (elementTypeIsOptionItem) {
return items as OptionItem[];
}
const elementTypeIsObject = isJsObject(item);
if (elementTypeIsObject) {
return this._convertObjectsToOptionItems(items);
}
const elementTypeIsString = isString(item);
if (elementTypeIsString) {
return this._convertPrimitiveToOptionItems(items);
}
return [];
}
/**
* Convert data to OptionItems Interface
* @hidden
*/
private _convertObjectsToOptionItems(items: any[]): OptionItem[] {
if (this.showSecondaryText && this.secondaryKey) {
return this._convertObjectsToSecondaryOptionItems(items);
} else {
return this._convertObjectsToDefaultOptionItems(items);
}
}
/**
* Convert object[] data to Secondary OptionItems Interface
* @hidden
*/
private _convertObjectsToSecondaryOptionItems<K>(items: K[]): OptionItem[] {
const selectItems: OptionItem[] = [];
for (let i = 0; i < items.length; i++) {
const value = items[i];
selectItems.push({
label: this.displayValue(value),
secondaryText: this.objectGet(value, this.secondaryKey),
value: value
});
}
return selectItems;
}
/**
* Convert Primitive data(Boolean, String, Number) to OptionItems Interface
* @hidden
*/
private _convertPrimitiveToOptionItems(items: any[]): OptionItem[] {
const selectItems: OptionItem[] = [];
for (let i = 0; i < items.length; i++) {
const value = items[i];
selectItems.push({ label: value, value: value });
}
return selectItems;
}
/**
* Convert object[] to OptionItems Interface (Default)
* @hidden
*/
private _convertObjectsToDefaultOptionItems(items: any[]): OptionItem[] {
const selectItems: OptionItem[] = [];
for (let i = 0; i < items.length; i++) {
const value = items[i];
selectItems.push({
label: this.displayValue(value),
value: value
});
}
return selectItems;
}
/** @hidden
* Assign custom templates
* */
private _assignCustomTemplates(): void {
this.customTemplates.forEach((template) => {
switch (template.getName()) {
case '_optionItemTemplate':
this._optionItemTemplate = template.templateRef;
break;
case '_secondaryItemTemplate':
this._secondaryItemTemplate = template.templateRef;
break;
case '_selectedItemTemplate':
this._selectedItemTemplate = template.templateRef;
break;
}
});
}
} | the_stack |
import { expect } from "chai";
import { IModelConnection, SnapshotConnection } from "@itwin/core-frontend";
import {
ChildNodeSpecificationTypes, InstanceLabelOverrideValueSpecificationType, Ruleset, RuleTypes, VariableValueTypes,
} from "@itwin/presentation-common";
import { Presentation } from "@itwin/presentation-frontend";
import { initialize, terminate } from "../../IntegrationTests";
import { printRuleset } from "../Utils";
describe("Learning Snippets", () => {
let imodel: IModelConnection;
beforeEach(async () => {
await initialize();
imodel = await SnapshotConnection.openFile("assets/datasets/Properties_60InstancesWithUrl2.ibim");
});
afterEach(async () => {
await imodel.close();
await terminate();
});
describe("Customization Rules", () => {
describe("DisabledSortingRule", () => {
it("uses `priority` attribute", async () => {
// __PUBLISH_EXTRACT_START__ Presentation.DisabledSortingRule.Priority.Ruleset
// The ruleset has root node rule that returns `bis.SpatialViewDefinition` instances with labels
// consisting of `Roll` and `Pitch` property values. Also there are two customization rules to sort
// instances by `Roll` property and to disable `bis.SpatialViewDefinition` instances sorting.
// The disabled sorting rule has higher priority and it is handled first.
const ruleset: Ruleset = {
id: "example",
rules: [{
ruleType: RuleTypes.RootNodes,
specifications: [{
specType: ChildNodeSpecificationTypes.InstanceNodesOfSpecificClasses,
classes: { schemaName: "BisCore", classNames: ["SpatialViewDefinition"] },
groupByClass: false,
groupByLabel: false,
}],
}, {
ruleType: RuleTypes.InstanceLabelOverride,
class: { schemaName: "BisCore", className: "SpatialViewDefinition" },
values: [{
specType: InstanceLabelOverrideValueSpecificationType.Composite,
separator: " x ",
parts: [
{ spec: { specType: InstanceLabelOverrideValueSpecificationType.Property, propertyName: "Roll" } },
{ spec: { specType: InstanceLabelOverrideValueSpecificationType.Property, propertyName: "Pitch" } },
],
}],
}, {
ruleType: RuleTypes.PropertySorting,
priority: 1,
class: { schemaName: "BisCore", className: "SpatialViewDefinition" },
propertyName: "Pitch",
}, {
ruleType: RuleTypes.DisabledSorting,
priority: 2,
class: { schemaName: "BisCore", className: "SpatialViewDefinition" },
}],
};
// __PUBLISH_EXTRACT_END__
printRuleset(ruleset);
// verify that nodes are not sorted by `Pitch` property
const nodes = await Presentation.presentation.getNodes({
imodel,
rulesetOrId: ruleset,
});
expect(nodes).to.be.lengthOf(4);
expect(nodes[0]).to.containSubset({ label: { displayValue: "-107.42 x -160.99" } });
expect(nodes[1]).to.containSubset({ label: { displayValue: "-45.00 x -35.26" } });
expect(nodes[2]).to.containSubset({ label: { displayValue: "-90.00 x 0.00" } });
expect(nodes[3]).to.containSubset({ label: { displayValue: "0.00 x 90.00" } });
});
it("uses `condition` attribute", async () => {
// __PUBLISH_EXTRACT_START__ Presentation.DisabledSortingRule.Condition.Ruleset
// The ruleset has root node rule that returns `bis.ViewDefinition` instances with labels
// consisting of `CodeValue` property value. Also there are customization rule to disable
// instances sorting.
const ruleset: Ruleset = {
id: "example",
rules: [{
ruleType: RuleTypes.RootNodes,
specifications: [{
specType: ChildNodeSpecificationTypes.InstanceNodesOfSpecificClasses,
classes: { schemaName: "BisCore", classNames: ["ViewDefinition"], arePolymorphic: true },
groupByClass: false,
groupByLabel: false,
}],
}, {
ruleType: RuleTypes.InstanceLabelOverride,
class: { schemaName: "BisCore", className: "ViewDefinition" },
values: [{
specType: InstanceLabelOverrideValueSpecificationType.Property,
propertyName: "CodeValue",
}],
}, {
ruleType: RuleTypes.DisabledSorting,
condition: "TRUE",
}],
};
// __PUBLISH_EXTRACT_END__
printRuleset(ruleset);
// verify that nodes are not sorted by `Pitch` property
const nodes = await Presentation.presentation.getNodes({
imodel,
rulesetOrId: ruleset,
rulesetVariables: [{ id: "SORT_INSTANCES", type: VariableValueTypes.Bool, value: true }],
});
expect(nodes).to.be.lengthOf(4);
expect(nodes[0]).to.containSubset({ label: { displayValue: "Default - View 1" } });
expect(nodes[1]).to.containSubset({ label: { displayValue: "Default - View 2" } });
expect(nodes[2]).to.containSubset({ label: { displayValue: "Default - View 3" } });
expect(nodes[3]).to.containSubset({ label: { displayValue: "Default - View 4" } });
});
it("uses `class` attribute", async () => {
// __PUBLISH_EXTRACT_START__ Presentation.DisabledSortingRule.Class.Ruleset
// The ruleset has root node rule that returns `bis.ViewDefinition` instances with labels
// consisting of class name and `CodeValue` property value. Also there two are customization rules to sort
// instances by `CodeValue` property and to disable `bis.SpatialViewDefinition` instances sorting.
const ruleset: Ruleset = {
id: "example",
rules: [{
ruleType: RuleTypes.RootNodes,
specifications: [{
specType: ChildNodeSpecificationTypes.InstanceNodesOfSpecificClasses,
classes: { schemaName: "BisCore", classNames: ["ViewDefinition"], arePolymorphic: true },
groupByClass: false,
groupByLabel: false,
}],
}, {
ruleType: RuleTypes.InstanceLabelOverride,
class: { schemaName: "BisCore", className: "ViewDefinition" },
values: [{
specType: InstanceLabelOverrideValueSpecificationType.Composite,
separator: " - ",
parts: [
{ spec: { specType: InstanceLabelOverrideValueSpecificationType.ClassName } },
{ spec: { specType: InstanceLabelOverrideValueSpecificationType.Property, propertyName: "CodeValue" } },
],
}],
}, {
ruleType: RuleTypes.PropertySorting,
priority: 1,
class: { schemaName: "BisCore", className: "ViewDefinition" },
propertyName: "CodeValue",
isPolymorphic: true,
}, {
ruleType: RuleTypes.DisabledSorting,
priority: 2,
class: { schemaName: "BisCore", className: "SpatialViewDefinition" },
}],
};
// __PUBLISH_EXTRACT_END__
printRuleset(ruleset);
const nodes = await Presentation.presentation.getNodes({
imodel,
rulesetOrId: ruleset,
});
expect(nodes).to.be.lengthOf(4);
expect(nodes[0]).to.containSubset({ label: { displayValue: "SpatialViewDefinition - Default - View 1" } });
expect(nodes[1]).to.containSubset({ label: { displayValue: "SpatialViewDefinition - Default - View 2" } });
expect(nodes[2]).to.containSubset({ label: { displayValue: "SpatialViewDefinition - Default - View 3" } });
expect(nodes[3]).to.containSubset({ label: { displayValue: "SpatialViewDefinition - Default - View 4" } });
});
it("uses `isPolymorphic` attribute", async () => {
// __PUBLISH_EXTRACT_START__ Presentation.DisabledSortingRule.IsPolymorphic.Ruleset
// The ruleset has root node rule that returns `bis.ViewDefinition` instances with labels
// consisting of class name and `CodeValue` property value. Also there are two customization rules to sort
// instances by `CodeValue` property and to disable `bis.ViewDefinition2d` instances sorting polymorphically.
const ruleset: Ruleset = {
id: "example",
rules: [{
ruleType: RuleTypes.RootNodes,
specifications: [{
specType: ChildNodeSpecificationTypes.InstanceNodesOfSpecificClasses,
classes: { schemaName: "BisCore", classNames: ["ViewDefinition"], arePolymorphic: true },
groupByClass: false,
groupByLabel: false,
}],
}, {
ruleType: RuleTypes.InstanceLabelOverride,
class: { schemaName: "BisCore", className: "ViewDefinition" },
values: [{
specType: InstanceLabelOverrideValueSpecificationType.Composite,
separator: " - ",
parts: [
{ spec: { specType: InstanceLabelOverrideValueSpecificationType.ClassName } },
{ spec: { specType: InstanceLabelOverrideValueSpecificationType.Property, propertyName: "CodeValue" } },
],
}],
}, {
ruleType: RuleTypes.PropertySorting,
priority: 1,
class: { schemaName: "BisCore", className: "ViewDefinition" },
propertyName: "CodeValue",
isPolymorphic: true,
}, {
ruleType: RuleTypes.DisabledSorting,
priority: 2,
class: { schemaName: "BisCore", className: "ViewDefinition2d" },
isPolymorphic: true,
}],
};
// __PUBLISH_EXTRACT_END__
printRuleset(ruleset);
const nodes = await Presentation.presentation.getNodes({
imodel,
rulesetOrId: ruleset,
});
expect(nodes).to.be.lengthOf(4);
expect(nodes[0]).to.containSubset({ label: { displayValue: "SpatialViewDefinition - Default - View 1" } });
expect(nodes[1]).to.containSubset({ label: { displayValue: "SpatialViewDefinition - Default - View 2" } });
expect(nodes[2]).to.containSubset({ label: { displayValue: "SpatialViewDefinition - Default - View 3" } });
expect(nodes[3]).to.containSubset({ label: { displayValue: "SpatialViewDefinition - Default - View 4" } });
});
});
});
}); | the_stack |
import quinary = require( './index' );
/**
* Returns the sum.
*
* @param x - input value
* @param y - input value
* @param z - input value
* @param w - input value
* @param u - input value
* @returns sum
*/
function add( x: number, y: number, z: number, w: number, u: number ): number {
return x + y + z + w + u;
}
// TESTS //
// The function returns `undefined`...
{
const x = new Float64Array( 10 );
const y = new Float64Array( 10 );
const z = new Float64Array( 10 );
const w = new Float64Array( 10 );
const u = new Float64Array( 10 );
const v = new Float64Array( 10 );
const arrays = [ x, y, z, w, u, v ];
const shape = [ 10 ];
const strides = [ 1, 1, 1, 1, 1, 1 ];
quinary( arrays, shape, strides, add ); // $ExpectType void
}
// The compiler throws an error if the function is provided a first argument which is not an array-like object containing array-like objects...
{
const shape = [ 10 ];
const strides = [ 1, 1, 1, 1, 1, 1 ];
quinary( 5, shape, strides, add ); // $ExpectError
quinary( true, shape, strides, add ); // $ExpectError
quinary( false, shape, strides, add ); // $ExpectError
quinary( null, shape, strides, add ); // $ExpectError
quinary( undefined, shape, strides, add ); // $ExpectError
quinary( {}, shape, strides, add ); // $ExpectError
quinary( [ 1 ], shape, strides, add ); // $ExpectError
quinary( ( x: number ): number => x, shape, strides, add ); // $ExpectError
}
// The compiler throws an error if the function is provided a second argument which is not an array-like object containing numbers...
{
const x = new Float64Array( 10 );
const y = new Float64Array( 10 );
const z = new Float64Array( 10 );
const w = new Float64Array( 10 );
const u = new Float64Array( 10 );
const v = new Float64Array( 10 );
const arrays = [ x, y, z, w, u, v ];
const strides = [ 1, 1, 1, 1, 1, 1 ];
quinary( arrays, '10', strides, add ); // $ExpectError
quinary( arrays, 10, strides, add ); // $ExpectError
quinary( arrays, true, strides, add ); // $ExpectError
quinary( arrays, false, strides, add ); // $ExpectError
quinary( arrays, null, strides, add ); // $ExpectError
quinary( arrays, undefined, strides, add ); // $ExpectError
quinary( arrays, [ '1' ], strides, add ); // $ExpectError
quinary( arrays, {}, strides, add ); // $ExpectError
quinary( arrays, ( x: number ): number => x, strides, add ); // $ExpectError
}
// The compiler throws an error if the function is provided a third argument which is not an array-like object containing numbers...
{
const x = new Float64Array( 10 );
const y = new Float64Array( 10 );
const z = new Float64Array( 10 );
const w = new Float64Array( 10 );
const u = new Float64Array( 10 );
const v = new Float64Array( 10 );
const arrays = [ x, y, z, w, u, v ];
const shape = [ 10 ];
quinary( arrays, shape, '10', add ); // $ExpectError
quinary( arrays, shape, 5, add ); // $ExpectError
quinary( arrays, shape, true, add ); // $ExpectError
quinary( arrays, shape, false, add ); // $ExpectError
quinary( arrays, shape, null, add ); // $ExpectError
quinary( arrays, shape, undefined, add ); // $ExpectError
quinary( arrays, shape, [ '1' ], add ); // $ExpectError
quinary( arrays, shape, {}, add ); // $ExpectError
quinary( arrays, shape, ( x: number ): number => x, add ); // $ExpectError
}
// The compiler throws an error if the function is provided a fourth argument which is not a quinary function...
{
const x = new Float64Array( 10 );
const y = new Float64Array( 10 );
const z = new Float64Array( 10 );
const w = new Float64Array( 10 );
const u = new Float64Array( 10 );
const v = new Float64Array( 10 );
const arrays = [ x, y, z, w, u, v ];
const shape = [ 10 ];
const strides = [ 1, 1, 1, 1, 1, 1 ];
quinary( arrays, shape, strides, '10' ); // $ExpectError
quinary( arrays, shape, strides, 5 ); // $ExpectError
quinary( arrays, shape, strides, true ); // $ExpectError
quinary( arrays, shape, strides, false ); // $ExpectError
quinary( arrays, shape, strides, null ); // $ExpectError
quinary( arrays, shape, strides, undefined ); // $ExpectError
quinary( arrays, shape, strides, [] ); // $ExpectError
quinary( arrays, shape, strides, {} ); // $ExpectError
}
// The compiler throws an error if the function is provided an unsupported number of arguments...
{
const x = new Float64Array( 10 );
const y = new Float64Array( 10 );
const z = new Float64Array( 10 );
const w = new Float64Array( 10 );
const u = new Float64Array( 10 );
const v = new Float64Array( 10 );
const arrays = [ x, y, z, w, u, v ];
const shape = [ 10 ];
const strides = [ 1, 1, 1, 1, 1, 1 ];
quinary(); // $ExpectError
quinary( arrays ); // $ExpectError
quinary( arrays, shape ); // $ExpectError
quinary( arrays, shape, strides ); // $ExpectError
quinary( arrays, shape, strides, add, 10 ); // $ExpectError
}
// Attached to main export is an `ndarray` method which returns `undefined`...
{
const x = new Float64Array( 10 );
const y = new Float64Array( 10 );
const z = new Float64Array( 10 );
const w = new Float64Array( 10 );
const u = new Float64Array( 10 );
const v = new Float64Array( 10 );
const arrays = [ x, y, z, w, u, v ];
const shape = [ 10 ];
const strides = [ 1, 1, 1, 1, 1, 1 ];
const offsets = [ 0, 0, 0, 0, 0, 0 ];
quinary.ndarray( arrays, shape, strides, offsets, add ); // $ExpectType void
}
// The compiler throws an error if the `ndarray` method is provided a first argument which is not an array-like object containing array-like objects...
{
const shape = [ 10 ];
const strides = [ 1, 1, 1, 1, 1, 1 ];
const offsets = [ 0, 0, 0, 0, 0, 0 ];
quinary.ndarray( 5, shape, strides, offsets, add ); // $ExpectError
quinary.ndarray( true, shape, strides, offsets, add ); // $ExpectError
quinary.ndarray( false, shape, strides, offsets, add ); // $ExpectError
quinary.ndarray( null, shape, strides, offsets, add ); // $ExpectError
quinary.ndarray( undefined, shape, strides, offsets, add ); // $ExpectError
quinary.ndarray( [ 1 ], shape, strides, offsets, add ); // $ExpectError
quinary.ndarray( {}, shape, strides, offsets, add ); // $ExpectError
quinary.ndarray( ( x: number ): number => x, shape, strides, offsets, add ); // $ExpectError
}
// The compiler throws an error if the `ndarray` method is provided a second argument which is not an array-like object containing numbers...
{
const x = new Float64Array( 10 );
const y = new Float64Array( 10 );
const z = new Float64Array( 10 );
const w = new Float64Array( 10 );
const u = new Float64Array( 10 );
const v = new Float64Array( 10 );
const arrays = [ x, y, z, w, u, v ];
const strides = [ 1, 1, 1, 1, 1, 1 ];
const offsets = [ 0, 0, 0, 0, 0, 0 ];
quinary.ndarray( arrays, '10', strides, offsets, add ); // $ExpectError
quinary.ndarray( arrays, 10, strides, offsets, add ); // $ExpectError
quinary.ndarray( arrays, true, strides, offsets, add ); // $ExpectError
quinary.ndarray( arrays, false, strides, offsets, add ); // $ExpectError
quinary.ndarray( arrays, null, strides, offsets, add ); // $ExpectError
quinary.ndarray( arrays, undefined, strides, offsets, add ); // $ExpectError
quinary.ndarray( arrays, [ '1' ], strides, offsets, add ); // $ExpectError
quinary.ndarray( arrays, {}, strides, offsets, add ); // $ExpectError
quinary.ndarray( arrays, ( x: number ): number => x, strides, offsets, add ); // $ExpectError
}
// The compiler throws an error if the `ndarray` method is provided a third argument which is not an array-like object containing numbers...
{
const x = new Float64Array( 10 );
const y = new Float64Array( 10 );
const z = new Float64Array( 10 );
const w = new Float64Array( 10 );
const u = new Float64Array( 10 );
const v = new Float64Array( 10 );
const arrays = [ x, y, z, w, u, v ];
const shape = [ 10 ];
const offsets = [ 0, 0, 0, 0, 0, 0 ];
quinary.ndarray( arrays, shape, '10', offsets, add ); // $ExpectError
quinary.ndarray( arrays, shape, 5, offsets, add ); // $ExpectError
quinary.ndarray( arrays, shape, true, offsets, add ); // $ExpectError
quinary.ndarray( arrays, shape, false, offsets, add ); // $ExpectError
quinary.ndarray( arrays, shape, null, offsets, add ); // $ExpectError
quinary.ndarray( arrays, shape, undefined, offsets, add ); // $ExpectError
quinary.ndarray( arrays, shape, [ '1' ], offsets, add ); // $ExpectError
quinary.ndarray( arrays, shape, {}, offsets, add ); // $ExpectError
quinary.ndarray( arrays, shape, ( x: number ): number => x, offsets, add ); // $ExpectError
}
// The compiler throws an error if the `ndarray` method is provided a fourth argument which is not an array-like object containing numbers...
{
const x = new Float64Array( 10 );
const y = new Float64Array( 10 );
const z = new Float64Array( 10 );
const w = new Float64Array( 10 );
const u = new Float64Array( 10 );
const v = new Float64Array( 10 );
const arrays = [ x, y, z, w, u, v ];
const shape = [ 10 ];
const strides = [ 1, 1, 1, 1, 1, 1 ];
quinary.ndarray( arrays, shape, strides, '10', add ); // $ExpectError
quinary.ndarray( arrays, shape, strides, 5, add ); // $ExpectError
quinary.ndarray( arrays, shape, strides, true, add ); // $ExpectError
quinary.ndarray( arrays, shape, strides, false, add ); // $ExpectError
quinary.ndarray( arrays, shape, strides, null, add ); // $ExpectError
quinary.ndarray( arrays, shape, strides, undefined, add ); // $ExpectError
quinary.ndarray( arrays, shape, strides, [ '1' ], add ); // $ExpectError
quinary.ndarray( arrays, shape, strides, {}, add ); // $ExpectError
quinary.ndarray( arrays, shape, strides, ( x: number ): number => x, add ); // $ExpectError
}
// The compiler throws an error if the `ndarray` method is provided a fifth argument which is not a quinary function...
{
const x = new Float64Array( 10 );
const y = new Float64Array( 10 );
const z = new Float64Array( 10 );
const w = new Float64Array( 10 );
const u = new Float64Array( 10 );
const v = new Float64Array( 10 );
const arrays = [ x, y, z, w, u, v ];
const shape = [ 10 ];
const strides = [ 1, 1, 1, 1, 1, 1 ];
const offsets = [ 0, 0, 0, 0, 0, 0 ];
quinary.ndarray( arrays, shape, strides, offsets, '10' ); // $ExpectError
quinary.ndarray( arrays, shape, strides, offsets, 5 ); // $ExpectError
quinary.ndarray( arrays, shape, strides, offsets, true ); // $ExpectError
quinary.ndarray( arrays, shape, strides, offsets, false ); // $ExpectError
quinary.ndarray( arrays, shape, strides, offsets, null ); // $ExpectError
quinary.ndarray( arrays, shape, strides, offsets, undefined ); // $ExpectError
quinary.ndarray( arrays, shape, strides, offsets, [] ); // $ExpectError
quinary.ndarray( arrays, shape, strides, offsets, {} ); // $ExpectError
}
// The compiler throws an error if the `ndarray` method is provided an unsupported number of arguments...
{
const x = new Float64Array( 10 );
const y = new Float64Array( 10 );
const z = new Float64Array( 10 );
const w = new Float64Array( 10 );
const u = new Float64Array( 10 );
const v = new Float64Array( 10 );
const arrays = [ x, y, z, w, u, v ];
const shape = [ 10 ];
const strides = [ 1, 1, 1, 1, 1, 1 ];
const offsets = [ 0, 0, 0, 0, 0, 0 ];
quinary.ndarray(); // $ExpectError
quinary.ndarray( arrays ); // $ExpectError
quinary.ndarray( arrays, shape ); // $ExpectError
quinary.ndarray( arrays, shape, strides ); // $ExpectError
quinary.ndarray( arrays, shape, strides, offsets ); // $ExpectError
quinary.ndarray( arrays, shape, strides, offsets, add, 10 ); // $ExpectError
} | the_stack |
import { useHistory, withRouter } from 'react-router-dom'
import Inventory2Icon from '@mui/icons-material/Inventory2'
import AccountTreeIcon from '@mui/icons-material/AccountTree'
import TuneIcon from '@mui/icons-material/Tune'
import { DockLayout, DockMode, LayoutData } from 'rc-dock'
import 'rc-dock/dist/rc-dock.css'
import React, { useEffect, useRef, useState } from 'react'
import { DndProvider } from 'react-dnd'
import { HTML5Backend } from 'react-dnd-html5-backend'
import { useTranslation } from 'react-i18next'
import Modal from 'react-modal'
import styled from 'styled-components'
import { getScene, saveScene } from '../functions/sceneFunctions'
import AssetsPanel from './assets/AssetsPanel'
import ConfirmDialog from './dialogs/ConfirmDialog'
import ErrorDialog from './dialogs/ErrorDialog'
import ExportProjectDialog from './dialogs/ExportProjectDialog'
import { ProgressDialog } from './dialogs/ProgressDialog'
import DragLayer from './dnd/DragLayer'
import HierarchyPanelContainer from './hierarchy/HierarchyPanelContainer'
import { PanelDragContainer, PanelIcon, PanelTitle } from './layout/Panel'
import PropertiesPanelContainer from './properties/PropertiesPanelContainer'
import ToolBar from './toolbar/ToolBar'
import ViewportPanelContainer from './viewport/ViewportPanelContainer'
import ProjectBrowserPanel from './assets/ProjectBrowserPanel'
import { cmdOrCtrlString } from '../functions/utils'
import { CommandManager } from '../managers/CommandManager'
import EditorEvents from '../constants/EditorEvents'
import { DefaultExportOptionsType, SceneManager } from '../managers/SceneManager'
import { CacheManager } from '../managers/CacheManager'
import { ProjectManager } from '../managers/ProjectManager'
import ScenesPanel from './assets/ScenesPanel'
import SaveNewProjectDialog from './dialogs/SaveNewProjectDialog'
import { DialogContext } from './hooks/useDialog'
import { saveProject } from '../functions/projectFunctions'
import { EditorAction, useEditorState } from '../services/EditorServices'
import { useDispatch } from '@xrengine/client-core/src/store'
import { Engine } from '@xrengine/engine/src/ecs/classes/Engine'
/**
* StyledEditorContainer component is used as root element of new project page.
* On this page we have an editor to create a new or modifing an existing project.
*
* @author Robert Long
* @type {Styled component}
*/
const StyledEditorContainer = (styled as any).div`
display: flex;
flex: 1;
flex-direction: column;
height: 100%;
width: 100%;
position: fixed;
`
/**
*Styled component used as workspace container.
*
* @author Robert Long
* @type {type}
*/
const WorkspaceContainer = (styled as any).div`
display: flex;
flex: 1;
overflow: hidden;
margin: 0px;
`
/**
*Styled component used as dock container.
*
* @author Hanzla Mateen
* @author Abhishek Pathak
* @type {type}
*/
export const DockContainer = (styled as any).div`
.dock-panel {
background: transparent;
pointer-events: auto;
opacity: 0.8;
border: none;
}
.dock-panel:first-child {
position: relative;
z-index: 99;
}
.dock-panel[data-dockid="+5"] {
visibility: hidden;
pointer-events: none;
}
.dock-divider {
pointer-events: auto;
background:rgba(1,1,1,${(props) => props.dividerAlpha});
}
.dock {
border-radius: 4px;
background: #282C31;
}
.dock-top .dock-bar {
font-size: 12px;
border-bottom: 1px solid rgba(0,0,0,0.2);
background: #282C31;
}
.dock-tab {
background: #282C31;
border-bottom: none;
}
.dock-tab:hover, .dock-tab-active, .dock-tab-active:hover {
color: #ffffff;
}
.dock-ink-bar {
background-color: #ffffff;
}
`
/**
* @author Abhishek Pathak
*/
DockContainer.defaultProps = {
dividerAlpha: 0
}
type EditorContainerProps = {
projectName: string
sceneName: string
}
/**
* EditorContainer class used for creating container for Editor
*
* @author Robert Long
*/
const EditorContainer = (props) => {
const projectName = useEditorState().projectName.value
const sceneName = useEditorState().sceneName.value
const { t } = useTranslation()
const [editorReady, setEditorReady] = useState(false)
const [DialogComponent, setDialogComponent] = useState<JSX.Element | null>(null)
const [modified, setModified] = useState(false)
const [sceneLoaded, setSceneLoaded] = useState(false)
const [toggleRefetchScenes, setToggleRefetchScenes] = useState(false)
const dispatch = useDispatch()
const history = useHistory()
const dockPanelRef = useRef<DockLayout>(null)
const importScene = async (projectFile) => {
setDialogComponent(<ProgressDialog title={t('editor:loading')} message={t('editor:loadingMsg')} />)
dispatch(EditorAction.sceneLoaded(null))
setSceneLoaded(false)
try {
await ProjectManager.instance.loadProject(projectFile)
setSceneLoaded(true)
SceneManager.instance.sceneModified = true
updateModifiedState()
setDialogComponent(null)
} catch (error) {
console.error(error)
setDialogComponent(
<ErrorDialog
title={t('editor:loadingError')}
message={error.message || t('editor:loadingErrorMsg')}
error={error}
/>
)
}
}
useEffect(() => {
const locationSceneName = props?.match?.params?.sceneName
const locationProjectName = props?.match?.params?.projectName
if (projectName !== locationProjectName) {
locationProjectName && dispatch(EditorAction.projectLoaded(locationProjectName))
}
if (sceneName !== locationSceneName) {
locationSceneName && dispatch(EditorAction.sceneLoaded(locationSceneName))
}
if (!projectName && !locationProjectName && !sceneName) {
dispatch(EditorAction.projectLoaded(projectName))
history.push(`/editor/${projectName}`)
}
}, [])
useEffect(() => {
if (editorReady && !sceneLoaded && sceneName) {
console.log(`Loading scene ${sceneName} via given url`)
loadScene(sceneName)
}
}, [editorReady, sceneLoaded])
const reRouteToLoadScene = (sceneName) => {
projectName && sceneName && history.push(`/editor/${projectName}/${sceneName}`)
}
const loadScene = async (sceneName) => {
setDialogComponent(<ProgressDialog title={t('editor:loading')} message={t('editor:loadingMsg')} />)
dispatch(EditorAction.sceneLoaded(null))
setSceneLoaded(false)
try {
if (!projectName) return
const project = await getScene(projectName, sceneName, false)
if (!project.scene) return
await ProjectManager.instance.loadProject(project.scene)
setDialogComponent(null)
} catch (error) {
console.error(error)
setDialogComponent(
<ErrorDialog
title={t('editor:loadingError')}
message={error.message || t('editor:loadingErrorMsg')}
error={error}
/>
)
}
dispatch(EditorAction.sceneLoaded(sceneName))
setSceneLoaded(true)
}
const newScene = async () => {
setDialogComponent(<ProgressDialog title={t('editor:loading')} message={t('editor:loadingMsg')} />)
dispatch(EditorAction.sceneLoaded(null))
setSceneLoaded(false)
try {
// TODO: replace with better template functionality
const project = await getScene('default-project', 'empty', false)
if (!project.scene) return
await ProjectManager.instance.loadProject(project.scene)
setDialogComponent(null)
} catch (error) {
console.error(error)
setDialogComponent(
<ErrorDialog
title={t('editor:loadingError')}
message={error.message || t('editor:loadingErrorMsg')}
error={error}
/>
)
}
dispatch(EditorAction.sceneLoaded(sceneName))
SceneManager.instance.sceneModified = true
updateModifiedState()
setSceneLoaded(true)
}
const updateModifiedState = (then?) => {
const nextModified = SceneManager.instance.sceneModified
if (nextModified !== modified) {
setModified(nextModified)
then && then()
} else if (then) {
then()
}
}
const setDebuginfo = () => {
const gl = Engine.renderer.getContext()
const debugInfo = gl.getExtension('WEBGL_debug_renderer_info')
let webglVendor = 'Unknown'
let webglRenderer = 'Unknown'
if (debugInfo) {
webglVendor = gl.getParameter(debugInfo.UNMASKED_VENDOR_WEBGL)
webglRenderer = gl.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL)
}
CommandManager.instance.removeListener(EditorEvents.RENDERER_INITIALIZED.toString(), setDebuginfo)
}
/**
* Scene Event Handlers
*/
const onEditorError = (error) => {
console.log(error)
if (error['aborted']) {
setDialogComponent(null)
return
}
console.error(error)
setDialogComponent(
<ErrorDialog
title={error.title || t('editor:error')}
message={error.message || t('editor:errorMsg')}
error={error}
/>
)
}
const onProjectLoaded = () => {
updateModifiedState()
}
const onCloseProject = () => {
history.push('/editor')
dispatch(EditorAction.projectLoaded(null))
}
const onSaveAs = async () => {
const abortController = new AbortController()
try {
let saveProjectFlag = true
if (sceneName || modified) {
const blob = await SceneManager.instance.takeScreenshot(512, 320)
const result: { name: string } = (await new Promise((resolve) => {
setDialogComponent(
<SaveNewProjectDialog
thumbnailUrl={URL.createObjectURL(blob!)}
initialName={Engine.scene.name}
onConfirm={resolve}
onCancel={resolve}
/>
)
})) as any
if (result && projectName) {
await saveScene(projectName, result.name, blob, abortController.signal)
SceneManager.instance.sceneModified = false
} else {
saveProjectFlag = false
}
}
if (saveProjectFlag && projectName) {
await saveProject(projectName)
updateModifiedState()
}
setDialogComponent(null)
} catch (error) {
console.error(error)
setDialogComponent(
<ErrorDialog title={t('editor:savingError')} message={error.message || t('editor:savingErrorMsg')} />
)
}
setToggleRefetchScenes(!toggleRefetchScenes)
}
const onExportProject = async () => {
if (!sceneName) return
const options = await new Promise<DefaultExportOptionsType>((resolve) => {
setDialogComponent(
<ExportProjectDialog
defaultOptions={Object.assign({}, SceneManager.DefaultExportOptions)}
onConfirm={resolve}
onCancel={resolve}
/>
)
})
if (!options) {
setDialogComponent(null)
return
}
const abortController = new AbortController()
setDialogComponent(
<ProgressDialog
title={t('editor:exporting')}
message={t('editor:exportingMsg')}
cancelable={true}
onCancel={() => abortController.abort()}
/>
)
try {
const { glbBlob } = await SceneManager.instance.exportScene(options)
setDialogComponent(null)
const el = document.createElement('a')
el.download = Engine.scene.name + '.glb'
el.href = URL.createObjectURL(glbBlob)
document.body.appendChild(el)
el.click()
document.body.removeChild(el)
} catch (error) {
if (error['aborted']) {
setDialogComponent(null)
return
}
console.error(error)
setDialogComponent(
<ErrorDialog
title={t('editor:exportingError')}
message={error.message || t('editor:exportingErrorMsg')}
error={error}
/>
)
}
}
const onImportScene = async () => {
const confirm = await new Promise((resolve) => {
setDialogComponent(
<ConfirmDialog
title={t('editor:importLegacy')}
message={t('editor:importLegacyMsg')}
confirmLabel="Yes, Continue"
onConfirm={() => resolve(true)}
onCancel={() => resolve(false)}
/>
)
})
setDialogComponent(null)
if (!confirm) return
const el = document.createElement('input')
el.type = 'file'
el.accept = '.world'
el.style.display = 'none'
el.onchange = () => {
if (el.files && el.files.length > 0) {
const fileReader: any = new FileReader()
fileReader.onload = () => {
const json = JSON.parse((fileReader as any).result)
importScene(json)
}
fileReader.readAsText(el.files[0])
}
}
el.click()
}
const onExportScene = async () => {
const projectFile = await (Engine.scene as any).serialize(sceneName)
const projectJson = JSON.stringify(projectFile)
const projectBlob = new Blob([projectJson])
const el = document.createElement('a')
const fileName = Engine.scene.name.toLowerCase().replace(/\s+/g, '-')
el.download = fileName + '.world'
el.href = URL.createObjectURL(projectBlob)
document.body.appendChild(el)
el.click()
document.body.removeChild(el)
}
const onSaveScene = async () => {
if (!sceneName) {
if (modified) {
onSaveAs()
}
return
}
const abortController = new AbortController()
setDialogComponent(
<ProgressDialog
title={t('editor:saving')}
message={t('editor:savingMsg')}
cancelable={true}
onCancel={() => {
abortController.abort()
setDialogComponent(null)
}}
/>
)
// Wait for 5ms so that the ProgressDialog shows up.
await new Promise((resolve) => setTimeout(resolve, 5))
const blob = await SceneManager.instance.takeScreenshot(512, 320)
try {
if (projectName) {
await saveScene(projectName, sceneName, blob, abortController.signal)
await saveProject(projectName)
}
SceneManager.instance.sceneModified = false
updateModifiedState()
setDialogComponent(null)
} catch (error) {
console.error(error)
setDialogComponent(
<ErrorDialog title={t('editor:savingError')} message={error.message || t('editor:savingErrorMsg')} />
)
}
setToggleRefetchScenes(!toggleRefetchScenes)
}
useEffect(() => {
console.log('toggleRefetchScenes')
dockPanelRef.current &&
dockPanelRef.current.updateTab('scenePanel', {
id: 'scenePanel',
title: (
<PanelDragContainer>
<PanelIcon as={Inventory2Icon} size={12} />
<PanelTitle>Scenes</PanelTitle>
</PanelDragContainer>
),
content: (
<ScenesPanel
newScene={newScene}
toggleRefetchScenes={toggleRefetchScenes}
projectName={projectName}
loadScene={reRouteToLoadScene}
/>
)
})
}, [toggleRefetchScenes])
useEffect(() => {
CacheManager.init()
ProjectManager.instance.init().then(() => {
setEditorReady(true)
CommandManager.instance.addListener(EditorEvents.RENDERER_INITIALIZED.toString(), setDebuginfo)
CommandManager.instance.addListener(EditorEvents.PROJECT_LOADED.toString(), onProjectLoaded)
CommandManager.instance.addListener(EditorEvents.ERROR.toString(), onEditorError)
})
}, [])
useEffect(() => {
return () => {
CommandManager.instance.removeListener(EditorEvents.ERROR.toString(), onEditorError)
CommandManager.instance.removeListener(EditorEvents.PROJECT_LOADED.toString(), onProjectLoaded)
ProjectManager.instance.dispose()
}
}, [])
const generateToolbarMenu = () => {
return [
{
name: t('editor:menubar.newProject'),
action: newScene
},
{
name: t('editor:menubar.saveProject'),
hotkey: `${cmdOrCtrlString}+s`,
action: onSaveScene
},
{
name: t('editor:menubar.saveAs'),
action: onSaveAs
},
// {
// name: t('editor:menubar.exportGLB'), // TODO: Disabled temporarily till workers are working
// action: onExportProject
// },
{
name: t('editor:menubar.importProject'),
action: onImportScene
},
{
name: t('editor:menubar.exportProject'),
action: onExportScene
},
{
name: t('editor:menubar.quit'),
action: onCloseProject
}
]
}
const toolbarMenu = generateToolbarMenu()
if (!editorReady) return <></>
const defaultLayout: LayoutData = {
dockbox: {
mode: 'horizontal' as DockMode,
children: [
{
mode: 'vertical' as DockMode,
size: 2,
children: [
{
tabs: [
{
id: 'scenePanel',
title: (
<PanelDragContainer>
<PanelIcon as={Inventory2Icon} size={12} />
<PanelTitle>Scenes</PanelTitle>
</PanelDragContainer>
),
content: (
<ScenesPanel
newScene={newScene}
projectName={projectName}
toggleRefetchScenes={toggleRefetchScenes}
loadScene={reRouteToLoadScene}
/>
)
},
{
id: 'filesPanel',
title: (
<PanelDragContainer>
<PanelIcon as={Inventory2Icon} size={12} />
<PanelTitle>Files</PanelTitle>
</PanelDragContainer>
),
content: <ProjectBrowserPanel />
}
]
}
]
},
{
mode: 'vertical' as DockMode,
size: 8,
children: [
{
id: '+5',
tabs: [{ id: 'viewPanel', title: 'Viewport', content: <div /> }],
size: 1
}
]
},
{
mode: 'vertical' as DockMode,
size: 2,
children: [
{
tabs: [
{
id: 'hierarchyPanel',
title: (
<PanelDragContainer>
<PanelIcon as={AccountTreeIcon} size={12} />
<PanelTitle>Hierarchy</PanelTitle>
</PanelDragContainer>
),
content: <HierarchyPanelContainer />
}
]
},
{
tabs: [
{
id: 'propertiesPanel',
title: (
<PanelDragContainer>
<PanelIcon as={TuneIcon} size={12} />
<PanelTitle>Properties</PanelTitle>
</PanelDragContainer>
),
content: <PropertiesPanelContainer />
},
{
id: 'assetsPanel',
title: (
<PanelDragContainer>
<PanelTitle>Elements</PanelTitle>
</PanelDragContainer>
),
content: <AssetsPanel />
}
]
}
]
}
]
}
}
return (
<StyledEditorContainer style={{ pointerEvents: 'none' }} id="editor-container">
<DialogContext.Provider value={[DialogComponent, setDialogComponent]}>
<DndProvider backend={HTML5Backend}>
<DragLayer />
<ToolBar editorReady={editorReady} menu={toolbarMenu} />
<WorkspaceContainer>
<ViewportPanelContainer />
<DockContainer>
<DockLayout
ref={dockPanelRef}
defaultLayout={defaultLayout}
style={{ position: 'absolute', left: 5, top: 55, right: 5, bottom: 5 }}
/>
</DockContainer>
</WorkspaceContainer>
<Modal
ariaHideApp={false}
isOpen={!!DialogComponent}
onRequestClose={() => setDialogComponent(null)}
shouldCloseOnOverlayClick={true}
className="Modal"
overlayClassName="Overlay"
>
{DialogComponent}
</Modal>
</DndProvider>
</DialogContext.Provider>
</StyledEditorContainer>
)
}
export default withRouter(EditorContainer) | the_stack |
import {
DebugSession,
ErrorDestination,
OutputEvent,
InitializedEvent,
StackFrame,
Source,
Scope,
Thread
} from "vscode-debugadapter";
import { DebugProtocol } from "vscode-debugprotocol";
import {
ITraceCmds,
LaunchRequestArguments,
PrologDebugger
} from "./prologDebugger";
import * as path from "path";
import { spawn, SpawnOptions } from "process-promises";
export class PrologDebugSession extends DebugSession {
private static SCOPEREF = 1;
public static THREAD_ID = 100;
private _prologDebugger: PrologDebugger;
private _runtimeExecutable: string;
// private _runtimeArgs: string[];
private _startupQuery: string;
private _startFile: string;
private _cwd: string;
private _stopOnEntry: boolean;
private _traceCmds: ITraceCmds;
private _currentVariables: DebugProtocol.Variable[] = [];
private _stackFrames: DebugProtocol.StackFrame[] = [];
private _debugging: boolean;
public constructor() {
super();
this.setDebuggerColumnsStartAt1(true);
this.setDebuggerLinesStartAt1(true);
this.setDebuggerPathFormat("native");
}
protected initializeRequest(
response: DebugProtocol.InitializeResponse,
args: DebugProtocol.InitializeRequestArguments
): void {
response.body = {
supportsConfigurationDoneRequest: true,
supportTerminateDebuggee: true,
supportsConditionalBreakpoints: true,
supportsHitConditionalBreakpoints: true,
supportsFunctionBreakpoints: true,
supportsEvaluateForHovers: true,
supportsExceptionOptions: true,
supportsExceptionInfoRequest: true,
exceptionBreakpointFilters: [
{
filter: "Notice",
label: "Notices"
},
{
filter: "Warning",
label: "Warnings"
},
{
filter: "Error",
label: "Errors"
},
{
filter: "Exception",
label: "Exceptions"
},
{
filter: "*",
label: "Everything",
default: true
}
]
};
this.sendResponse(response);
}
protected attachRequest(
response: DebugProtocol.AttachResponse,
args: DebugProtocol.AttachRequestArguments
) {
this.sendErrorResponse(
response,
new Error("Attach requests are not supported")
);
this.shutdown();
}
public addStackFrame(frame: {
id: number;
level: number;
name: string;
file: string;
line: number;
column: number;
}) {
this._stackFrames.unshift(
new StackFrame(
frame.id,
`(${frame.level})${frame.name}`,
new Source(
path.basename(frame.file),
this.convertDebuggerPathToClient(frame.file)
),
this.convertDebuggerLineToClient(frame.line),
this.convertDebuggerColumnToClient(frame.column)
)
);
}
public setCurrentVariables(vars: DebugProtocol.Variable[]) {
this._currentVariables = [];
while (vars.length > 0) {
this._currentVariables.push(vars.pop());
}
}
protected async launchRequest(
response: DebugProtocol.LaunchResponse,
args: LaunchRequestArguments
) {
// window.showInformationMessage("hello");
this._startupQuery = args.startupQuery || "start";
this._startFile = path.resolve(args.program);
this._cwd = args.cwd;
this._runtimeExecutable = args.runtimeExecutable || "swipl";
// this._runtimeArgs = args.runtimeArgs || null;
this._stopOnEntry = typeof args.stopOnEntry ? args.stopOnEntry : true;
this._traceCmds = args.traceCmds;
this._prologDebugger = await new PrologDebugger(args, this);
this._prologDebugger.addListener(
"responseBreakpoints",
(bps: DebugProtocol.SetBreakpointsResponse) => {
this.sendResponse(bps);
}
);
this._prologDebugger.addListener(
"responseFunctionBreakpoints",
(fbps: DebugProtocol.SetFunctionBreakpointsResponse) => {
this.sendResponse(fbps);
}
);
this.sendResponse(response);
this.sendEvent(new InitializedEvent());
}
protected threadsRequest(response: DebugProtocol.ThreadsResponse): void {
response.body = {
threads: [new Thread(PrologDebugSession.THREAD_ID, "thread 1")]
};
this.sendResponse(response);
}
protected setBreakPointsRequest(
response: DebugProtocol.SetBreakpointsResponse,
args: DebugProtocol.SetBreakpointsArguments
) {
if (this._debugging) {
this.debugOutput(
"Breakpoints set during debugging would take effect in next debugging process."
);
return;
}
this._prologDebugger.setBreakpoints(args, response);
}
protected setExceptionBreakPointsRequest(
response: DebugProtocol.SetExceptionBreakpointsResponse,
args: DebugProtocol.SetExceptionBreakpointsArguments
): void {
this.sendResponse(response);
}
protected setFunctionBreakPointsRequest(
response: DebugProtocol.SetFunctionBreakpointsResponse,
args: DebugProtocol.SetFunctionBreakpointsArguments
): void {
this._prologDebugger.setFunctionBreakpoints(args, response);
}
protected configurationDoneRequest(
response: DebugProtocol.ConfigurationDoneResponse,
args: DebugProtocol.ConfigurationDoneArguments
): void {
this.sendResponse(response);
this._prologDebugger.startup(`${this._startupQuery}`);
if (!this._stopOnEntry) {
this._prologDebugger.query(`cmd:${this._traceCmds.continue[1]}\n`);
}
this._debugging = true;
}
private evaluateExpression(exp: string) {
const vars = this._currentVariables;
for (let i = 0; i < vars.length; i++) {
if (vars[i].name === exp) {
return vars[i].value;
}
}
return null;
}
protected evaluateRequest(
response: DebugProtocol.EvaluateResponse,
args: DebugProtocol.EvaluateArguments
): void {
let val = this.evaluateExpression(args.expression);
if (val) {
response.body = {
result: val,
variablesReference: 0
};
this.sendResponse(response);
return;
} else {
if (args.context === "repl") {
const vars = this._currentVariables;
let exp = args.expression.trim();
if (exp.startsWith(":")) {
//work around for input from stdin
let input = "input" + args.expression;
this._prologDebugger.query(input + "\n");
} else {
for (let i = 0; i < vars.length; i++) {
let re = new RegExp("\\b" + vars[i].name + "\\b", "g");
exp = exp.replace(re, vars[i].value);
}
this.debugOutput(args.expression);
this.evaluate(exp);
}
response.body = { result: "", variablesReference: 0 };
}
this.sendResponse(response);
return;
}
}
protected stackTraceRequest(
response: DebugProtocol.StackTraceResponse,
args: DebugProtocol.StackTraceArguments
): void {
response.body = {
stackFrames: this._stackFrames
};
this.sendResponse(response);
}
protected variablesRequest(
response: DebugProtocol.VariablesResponse,
args: DebugProtocol.VariablesArguments
): void {
const variables = new Array<DebugProtocol.Variable>();
for (let i = 0; i < this._currentVariables.length; i++) {
variables.push(this._currentVariables[i]);
}
response.body = {
variables: variables
};
this.sendResponse(response);
}
protected scopesRequest(
response: DebugProtocol.ScopesResponse,
args: DebugProtocol.ScopesArguments
): void {
const scopes = new Array<Scope>();
scopes.push(new Scope("Local", PrologDebugSession.SCOPEREF++, false));
response.body = {
scopes: scopes
};
this.sendResponse(response);
}
protected continueRequest(
response: DebugProtocol.ContinueResponse,
args: DebugProtocol.ContinueArguments
): void {
this._prologDebugger.query(`cmd:${this._traceCmds.continue[1]}\n`);
this.sendResponse(response);
}
protected nextRequest(
response: DebugProtocol.NextResponse,
args: DebugProtocol.NextArguments
): void {
this._prologDebugger.query(`cmd:${this._traceCmds.stepover[1]}\n`);
this.sendResponse(response);
}
protected stepInRequest(
response: DebugProtocol.StepInResponse,
args: DebugProtocol.StepInArguments
): void {
this._prologDebugger.query(`cmd:${this._traceCmds.stepinto[1]}\n`);
this.sendResponse(response);
}
protected stepOutRequest(
response: DebugProtocol.StepOutResponse,
args: DebugProtocol.StepOutArguments
): void {
this._prologDebugger.query(`cmd:${this._traceCmds.stepout[1]}\n`);
this.sendResponse(response);
}
protected disconnectRequest(
response: DebugProtocol.DisconnectResponse,
args: DebugProtocol.DisconnectArguments
): void {
this._debugging = false;
this._prologDebugger.dispose();
this.shutdown();
this.sendResponse(response);
}
protected restartRequest(
response: DebugProtocol.RestartResponse,
args: DebugProtocol.RestartArguments
): void {
this._debugging = false;
this._prologDebugger.dispose();
this.shutdown();
this.sendResponse(response);
}
protected sendErrorResponse(
response: DebugProtocol.Response,
error: Error,
dest?: ErrorDestination
): void;
protected sendErrorResponse(
response: DebugProtocol.Response,
codeOrMessage: number | DebugProtocol.Message,
format?: string,
variables?: any,
dest?: ErrorDestination
): void;
protected sendErrorResponse(response: DebugProtocol.Response) {
if (arguments[1] instanceof Error) {
const error = arguments[1] as Error & {
code?: number | string;
errno?: number;
};
const dest = arguments[2] as ErrorDestination;
let code: number;
if (typeof error.code === "number") {
code = error.code as number;
} else if (typeof error.errno === "number") {
code = error.errno;
} else {
code = 0;
}
super.sendErrorResponse(response, code, error.message, dest);
} else {
super.sendErrorResponse(
response,
arguments[1],
arguments[2],
arguments[3],
arguments[4]
);
}
}
public debugOutput(msg: string) {
this.sendEvent(new OutputEvent(msg));
}
private evaluate(expression: string) {
let exec = this._runtimeExecutable;
let args = ["-q", `${this._startFile}`];
let input = `
call((${expression})).
halt.
`;
let spawnOptions: SpawnOptions = {
cwd: this._cwd
};
spawn(exec, args, spawnOptions)
.on("process", proc => {
if (proc.pid) {
proc.stdin.write(input);
proc.stdin.end();
}
})
.on("stdout", data => {
this.debugOutput("\n" + data);
})
.on("stderr", err => {
this.debugOutput("\n" + err);
})
.catch(err => {
this.debugOutput(err.message);
});
}
}
DebugSession.run(PrologDebugSession); | the_stack |
import Chart from "chart.js/auto";
import * as helpers from "chart.js/helpers";
import * as _ from "lodash-es";
import { UnitEnum } from "@src/models";
import { formatter } from "@src/utils";
export const INTERVALS = [
10000,
30000,
60 * 1000,
2 * 60 * 1000,
5 * 60 * 1000,
10 * 60 * 1000,
15 * 60 * 1000,
30 * 60 * 1000,
];
function getVisibleInterval(times: any, interval: number, width: number) {
const ticksCount = times.length;
const perTickPX = width / (ticksCount - 1);
let ticksPerVisibleTick = parseInt(`${100 / perTickPX}`);
const t = ticksPerVisibleTick * interval;
let result = interval;
if (t < 60 * 60 * 1000) {
INTERVALS.forEach((item) => {
if (t / item < 0.6) {
return;
} else {
result = item;
}
});
} else {
result = t - (t % (60 * 60 * 1000));
}
return result;
}
// Chart.register({
// id: "lazy",
// afterUpdate: function (chart: any) {
// const xAxes = chart.scales["xAxes-bottom"];
// const tickOffset = _.get(xAxes, "options.ticks.tickOffset", null);
// const display = _.get(xAxes, "options.display", false);
// if (display && tickOffset) {
// const width = _.get(chart, "scales.xAxes-bottom.width", 0);
// const interval = _.get(chart, "config.options.interval", 0);
// const times = _.get(chart, "config.options.times", []);
// const visibleInterval = getVisibleInterval(times, interval, width);
// xAxes.draw = function () {
// const xScale = chart.scales["xAxes-bottom"];
// // const tickFontColor = helpers.getValueOrDefault(
// // xScale.options.ticks.fontColor,
// // Chart.defaults.defaultFontColor
// // );
// // const tickFontSize = helpers.getValueOrDefault(
// // xScale.options.ticks.fontSize,
// // ChartJS.defaults.global.defaultFontSize
// // );
// // const tickFontStyle = helpers.getValueOrDefault(
// // xScale.options.ticks.fontStyle,
// // ChartJS.defaults.global.defaultFontStyle
// // );
// // const tickFontFamily = helpers.getValueOrDefault(
// // xScale.options.ticks.fontFamily,
// // ChartJS.defaults.global.defaultFontFamily
// // );
// // const tickLabelFont = helpers.fontString(
// // tickFontSize,
// // tickFontStyle,
// // tickFontFamily
// // );
// const tl = xScale.options.gridLines.tickMarkLength;
// const isRotated = xScale.labelRotation !== 0;
// const yTickStart = xScale.top;
// const yTickEnd = xScale.top + tl;
// const chartArea = chart.chartArea;
// helpers.each(
// xScale.ticks,
// (label: any, index: any) => {
// if (times[index] % visibleInterval !== 0) {
// return;
// }
// // console.log("xxxxxx",index,times,visibleInterval)
// // copy of chart.js code
// let xLineValue = this.getPixelForTick(index);
// const xLabelValue = this.getPixelForTick(
// index,
// this.options.gridLines.offsetGridLines
// );
// if (this.options.gridLines.display) {
// this.ctx.lineWidth = this.options.gridLines.lineWidth;
// this.ctx.strokeStyle = this.options.gridLines.color;
// xLineValue += helpers.aliasPixel(this.ctx.lineWidth);
// // Draw the label area
// this.ctx.beginPath();
// if (this.options.gridLines.drawTicks) {
// this.ctx.moveTo(xLineValue, yTickStart);
// this.ctx.lineTo(xLineValue, yTickEnd);
// }
// // Draw the chart area
// if (this.options.gridLines.drawOnChartArea) {
// this.ctx.moveTo(xLineValue, chartArea.top);
// this.ctx.lineTo(xLineValue, chartArea.bottom);
// }
// // Need to stroke in the loop because we are potentially changing line widths & colours
// this.ctx.stroke();
// }
// if (this.options.ticks.display) {
// this.ctx.save();
// this.ctx.translate(
// xLabelValue + this.options.ticks.labelOffset,
// isRotated
// ? this.top + 12
// : this.options.position === "top"
// ? this.bottom - tl
// : this.top + tl
// );
// this.ctx.rotate(helpers.toRadians(this.labelRotation) * -1);
// // this.ctx.font = tickLabelFont;
// this.ctx.textAlign = isRotated ? "right" : "center";
// this.ctx.textBaseline = isRotated
// ? "middle"
// : this.options.position === "top"
// ? "bottom"
// : "top";
// // this.ctx.fillStyle = tickFontColor;
// this.ctx.fillText(label, 0, 0);
// this.ctx.restore();
// }
// },
// xScale
// );
// };
// }
// },
// afterDraw: function (chart: any) {
// // const status = _.get(chart, "options.status", null);
// // const ctx = chart.chart.ctx;
// // if (isNoData(status)) {
// // chart.clear();
// // const width = chart.chart.width;
// // const height = chart.chart.height;
// // let text = "";
// // let color = get(chart, "options.scales.yAxes[0].ticks.fontColor", null);
// // ctx.textAlign = "center";
// // ctx.textBaseline = "middle";
// // switch (status.status) {
// // case ChartStatusEnum.NoData:
// // text = "No data to display";
// // break;
// // case ChartStatusEnum.BadRequest:
// // text = "Invalid Configuration";
// // color = "#D27613";
// // break;
// // case ChartStatusEnum.LoadError:
// // color = "#F56C6C";
// // ctx.fillStyle = color;
// // ctx.fillText(status.msg, width / 2, height / 2 + 20);
// // text = "Internal Server Error";
// // break;
// // default:
// // break;
// // }
// // ctx.font = "13px Arial";
// // ctx.fillStyle = color;
// // ctx.fillText(text, width / 2, height / 2);
// // ctx.restore();
// // } else if (chart.options.isSeriesChart) {
// // const chartArea = chart.chartArea;
// // ctx.beginPath();
// // ctx.lineWidth = 1;
// // ctx.strokeStyle = _.get(
// // chart,
// // "options.scales.yAxes[0].gridLines.color",
// // null
// // );
// // ctx.moveTo(chartArea.left, chartArea.bottom);
// // ctx.lineTo(chartArea.right, chartArea.bottom);
// // ctx.stroke();
// // }
// },
// });
Chart.register({
id: "message",
beforeDraw: function (chart: any, _args: any, _options: any): boolean {
const datasets = _.get(chart, "config._config.data.datasets", []);
if (datasets.length <= 0) {
// display no data message
chart.clear();
const ctx = chart.ctx;
const width = chart.canvas.clientWidth;
const height = chart.canvas.clientHeight;
ctx.font = "14px Arial";
ctx.fillStyle = "rgba(249, 249, 249, 0.6)";
ctx.textAlign = "center";
ctx.fillText("No data in response", width / 2, height / 2);
ctx.restore();
return false;
}
return true;
},
});
export const DefaultChartConfig = {
type: undefined,
data: {},
plugins: {
message: {},
},
options: {
responsive: true,
maintainAspectRatio: false,
animation: false,
scales: {
x: {
type: "category",
grid: {
drawTicks: false,
lineWidth: 0.3,
// tickMarkLength: 2,
tickLength: 2,
// drawOnChartArea: false,
drawBorder: false,
color: "rgba(249, 249, 249, 0.35)",
},
ticks: {
font: {
size: 12,
},
// fontSize: 10,
maxRotation: 0, // angle in degrees
color: "rgb(249, 249, 249)",
callback: function (_value: any, index: number, _values: any) {
const times = _.get(this, "chart.config._config.data.times", []);
const labels = _.get(this, "chart.config._config.data.labels", []);
if (index == 0 || times[index] % (5 * 60 * 1000) == 0) {
return labels[index];
}
return null;
},
align: "start", // default: center, start/end
// tickOffset: 100,
// fontColor: undefined,
},
display: undefined,
stacked: undefined,
},
y: {
grid: {
drawTicks: false,
lineWidth: 0.3,
autoSkip: true,
tickLength: 0,
// zeroLineWidth: 0,
drawBorder: false,
// drawOnChartArea: false,
// borderDash: [1, 1],
color: "rgba(249, 249, 249, 0.35)",
},
ticks: {
mirror: true, // draw tick in chart area
display: true,
// min: 0,
font: { size: 12 },
color: "rgb(249, 249, 249)",
autoSkip: true,
callback: function (value: any, index: number, _values: any) {
if (index == 0) {
//ignore first tick
return null;
}
if (index % 3 == 0) {
return formatter(
value,
_.get(this, "chart.config._config.unit", UnitEnum.None)
);
}
return null;
},
// tickMarkLength: 0,
// maxTicksLimit: 6,
suggestedMin: 0,
},
// suggestedMax: 10,
},
},
plugins: {
legend: {
display: false,
},
tooltip: {
mode: "dataset",
enabled: false,
},
title: {
display: false,
},
},
elements: {
line: {
tension: 0, // disables bezier curve
borderWidth: 1,
fill: undefined,
},
point: {
radius: 1,
hoverRadius: 2,
pointStyle: undefined,
},
arc: {
borderWidth: 0,
},
},
hover: {
// animationDuration: 0, // duration of animations when hovering an item
mode: "index",
intersect: false,
// onHover: undefined,
},
},
}; | the_stack |
import { utilsTest, formats, TEST_TIMESTAMP } from "./test-utils";
describe("DateTime calculations", () => {
utilsTest("date", (date, utils) => {
// ISO string
expect(utils.isEqual(date, utils.date(TEST_TIMESTAMP))).toBeTruthy();
// native Date
expect(utils.isEqual(date, utils.date(new Date(TEST_TIMESTAMP)))).toBeTruthy();
// parse already date-specific object
expect(utils.isEqual(date, utils.date(utils.date(TEST_TIMESTAMP)))).toBeTruthy();
// parse null inputs
expect(utils.date(null)).toBeNull();
// undefined
expect(utils.date(undefined)).toBeTruthy();
});
utilsTest("isValid", (date, utils) => {
const invalidDate = utils.date("2018-42-30T11:60:00.000Z");
expect(utils.isValid(date)).toBeTruthy();
expect(utils.isValid(invalidDate)).toBeFalsy();
expect(utils.isValid(undefined)).toBeTruthy();
expect(utils.isValid(null)).toBeFalsy();
expect(utils.isValid("2018-42-30T11:60:00.000Z")).toBeFalsy();
});
utilsTest("addSeconds", (date, utils, lib) => {
expect(utils.format(utils.addSeconds(date, 65), "seconds")).toBe("05");
expect(utils.format(utils.addSeconds(date, -5), "seconds")).toBe("55");
});
utilsTest("addMinutes", (date, utils, lib) => {
expect(utils.format(utils.addMinutes(date, 65), "minutes")).toBe("49");
expect(utils.format(utils.addMinutes(date, -5), "minutes")).toBe("39");
});
utilsTest("addHours", (date, utils, lib) => {
expect(utils.format(utils.addHours(date, 65), "hours24h")).toBe("04");
expect(utils.format(utils.addHours(date, -5), "hours24h")).toBe("06");
});
utilsTest("addDays", (date, utils, lib) => {
expect(utils.format(utils.addDays(date, 1), "dayOfMonth")).toBe("31");
expect(utils.format(utils.addDays(date, -1), "dayOfMonth")).toBe("29");
});
utilsTest("addWeeks", (date, utils, lib) => {
expect(utils.getDiff(utils.addWeeks(date, 1), date, "weeks")).toBe(1);
expect(utils.getDiff(utils.addWeeks(date, -1), date, "weeks")).toBe(-1);
});
utilsTest("addMonths", (date, utils, lib) => {
expect(utils.format(utils.addMonths(date, 2), "monthAndYear")).toBe("December 2018");
expect(utils.format(utils.addMonths(date, -2), "monthAndYear")).toBe("August 2018");
});
utilsTest("startOfDay", (date, utils, lib) => {
expect(utils.formatByString(utils.startOfDay(date), formats.dateTime[lib])).toBe(
"2018-10-30 00:00"
);
});
utilsTest("endOfDay", (date, utils, lib) => {
expect(utils.formatByString(utils.endOfDay(date), formats.dateTime[lib])).toBe(
"2018-10-30 23:59"
);
});
utilsTest("startOfMonth", (date, utils, lib) => {
expect(utils.formatByString(utils.startOfMonth(date), formats.dateTime[lib])).toBe(
"2018-10-01 00:00"
);
});
utilsTest("endOfMonth", (date, utils, lib) => {
expect(utils.formatByString(utils.endOfMonth(date), formats.dateTime[lib])).toBe(
"2018-10-31 23:59"
);
});
utilsTest("startOfWeek", (date, utils, lib) => {
expect(utils.formatByString(utils.startOfWeek(date), formats.dateTime[lib])).toBe(
lib === "Luxon" ? "2018-10-29 00:00" : "2018-10-28 00:00"
);
});
utilsTest("endOfWeek", (date, utils, lib) => {
expect(utils.formatByString(utils.endOfWeek(date), formats.dateTime[lib])).toBe(
lib === "Luxon" ? "2018-11-04 23:59" : "2018-11-03 23:59"
);
});
utilsTest("startOfWeekNonISO", (date, utils, lib) => {
expect(utils.formatByString(utils.startOfWeek(utils.date("2018-10-28T00:00:00.000Z")), formats.dateTime[lib])).toBe(
lib === "Luxon" ? "2018-10-22 00:00" : "2018-10-28 00:00"
);
});
utilsTest("endOfWeekNonISO", (date, utils, lib) => {
expect(utils.formatByString(utils.endOfWeek(utils.date("2018-10-28T00:00:00.000Z")), formats.dateTime[lib])).toBe(
lib === "Luxon" ? "2018-10-28 23:59" : "2018-11-03 23:59"
);
});
utilsTest("getPreviousMonth", (date, utils, lib) => {
expect(
utils.formatByString(utils.getPreviousMonth(date), formats.dateTime[lib])
).toBe("2018-09-30 11:44");
});
utilsTest("getMonthArray", (date, utils, lib) => {
expect(
utils
.getMonthArray(date)
.map((date) => utils.formatByString(date, formats.dateTime[lib]))
).toEqual([
"2018-01-01 00:00",
"2018-02-01 00:00",
"2018-03-01 00:00",
"2018-04-01 00:00",
"2018-05-01 00:00",
"2018-06-01 00:00",
"2018-07-01 00:00",
"2018-08-01 00:00",
"2018-09-01 00:00",
"2018-10-01 00:00",
"2018-11-01 00:00",
"2018-12-01 00:00",
]);
});
utilsTest("getNextMonth", (date, utils, lib) => {
expect(utils.formatByString(utils.getNextMonth(date), formats.dateTime[lib])).toBe(
"2018-11-30 11:44"
);
});
utilsTest("getHours", (date, utils) => {
expect(utils.getHours(date)).toBe(new Date(TEST_TIMESTAMP).getHours());
});
utilsTest("getMinutes", (date, utils) => {
expect(utils.getMinutes(date)).toBe(44);
});
utilsTest("getSeconds", (date, utils) => {
expect(utils.getSeconds(date)).toBe(0);
});
utilsTest("getYear", (date, utils) => {
expect(utils.getYear(date)).toBe(2018);
});
utilsTest("getMonth", (date, utils) => {
expect(utils.getMonth(date)).toBe(9);
});
utilsTest("getDaysInMonth", (date, utils) => {
expect(utils.getDaysInMonth(date)).toBe(31);
});
utilsTest("setMonth", (date, utils, lib) => {
const updatedTime = utils.formatByString(
utils.setMonth(date, 4),
formats.dateTime[lib]
);
expect(updatedTime).toBe("2018-05-30 11:44");
});
utilsTest("setHours", (date, utils, lib) => {
const updatedTime = utils.formatByString(
utils.setHours(date, 0),
formats.dateTime[lib]
);
expect(updatedTime).toBe("2018-10-30 00:44");
});
utilsTest("setMinutes", (date, utils, lib) => {
const updatedTime = utils.formatByString(
utils.setMinutes(date, 12),
formats.dateTime[lib]
);
expect(updatedTime).toBe("2018-10-30 11:12");
});
utilsTest("setMinutes", (date, utils, lib) => {
const updatedTime = utils.formatByString(
utils.setMinutes(date, 12),
formats.dateTime[lib]
);
expect(updatedTime).toBe("2018-10-30 11:12");
});
utilsTest("setYear", (date, utils, lib) => {
const updatedTime = utils.formatByString(
utils.setYear(date, 2011),
formats.dateTime[lib]
);
expect(updatedTime).toBe("2011-10-30 11:44");
});
utilsTest("setSeconds", (date, utils) => {
expect(utils.setSeconds(date, 11)).toBeTruthy();
});
utilsTest("isAfter", (date, utils, lib) => {
expect(utils.isAfter(utils.date(), date)).toBeTruthy();
expect(utils.isAfter(date, utils.date())).toBeFalsy();
});
utilsTest("isBefore", (date, utils, lib) => {
expect(utils.isBefore(date, utils.date())).toBeTruthy();
expect(utils.isBefore(utils.date(), date)).toBeFalsy();
});
utilsTest("isAfterDay", (date, utils, lib) => {
const nextDay = utils.addDays(date, 1);
expect(utils.isAfterDay(nextDay, date)).toBeTruthy();
expect(utils.isAfterDay(date, nextDay)).toBeFalsy();
});
utilsTest("isBeforeDay", (date, utils, lib) => {
const previousDay = utils.addDays(date, -1);
expect(utils.isBeforeDay(date, previousDay)).toBeFalsy();
expect(utils.isBeforeDay(previousDay, date)).toBeTruthy();
});
utilsTest("isAfterYear", (date, utils, lib) => {
const nextYear = utils.setYear(date, 2019);
expect(utils.isAfterYear(nextYear, date)).toBeTruthy();
expect(utils.isAfterYear(date, nextYear)).toBeFalsy();
});
utilsTest("isBeforeYear", (date, utils, lib) => {
const previousYear = utils.setYear(date, 2017);
expect(utils.isBeforeYear(date, previousYear)).toBeFalsy();
expect(utils.isBeforeYear(previousYear, date)).toBeTruthy();
});
utilsTest("getWeekArray", (date, utils) => {
const weekArray = utils.getWeekArray(date);
expect(weekArray).toHaveLength(5);
for (const week of weekArray) {
expect(week).toHaveLength(7);
}
});
utilsTest("getYearRange", (date, utils) => {
const yearRange = utils.getYearRange(date, utils.setYear(date, 2124));
expect(yearRange).toHaveLength(107);
expect(utils.getYear(yearRange[yearRange.length - 1])).toBe(2124);
const emptyYearRange = utils.getYearRange(
date,
utils.setYear(date, utils.getYear(date) - 1)
);
expect(emptyYearRange).toHaveLength(0);
});
utilsTest("getDiff", (date, utils) => {
expect(utils.getDiff(date, utils.date("2018-10-29T11:44:00.000Z"))).toBe(86400000);
expect(utils.getDiff(date, utils.date("2018-10-31T11:44:00.000Z"))).toBe(-86400000);
expect(utils.getDiff(date, "2018-10-31T11:44:00.000Z")).toBe(-86400000);
});
utilsTest("getDiff with units", (date, utils) => {
expect(utils.getDiff(date, utils.date("2017-09-29T11:44:00.000Z"), "years")).toBe(1);
expect(utils.getDiff(date, utils.date("2018-08-29T11:44:00.000Z"), "months")).toBe(2);
expect(utils.getDiff(date, utils.date("2018-05-29T11:44:00.000Z"), "quarters")).toBe(
1
);
expect(utils.getDiff(date, utils.date("2018-09-29T11:44:00.000Z"), "days")).toBe(31);
expect(utils.getDiff(date, utils.date("2018-09-29T11:44:00.000Z"), "weeks")).toBe(4);
expect(utils.getDiff(date, utils.date("2018-09-29T11:44:00.000Z"), "hours")).toBe(
744
);
expect(utils.getDiff(date, utils.date("2018-09-29T11:44:00.000Z"), "minutes")).toBe(
44640
);
expect(utils.getDiff(date, utils.date("2018-10-30T10:44:00.000Z"), "seconds")).toBe(
3600
);
expect(
utils.getDiff(date, utils.date("2018-10-30T10:44:00.000Z"), "milliseconds")
).toBe(3600000);
});
utilsTest("mergeDateAndTime", (date, utils, lib) => {
const mergedDate = utils.mergeDateAndTime(
date,
utils.date("2018-01-01T14:15:16.000Z")
);
expect(utils.toJsDate(mergedDate).toISOString()).toBe("2018-10-30T14:15:16.000Z");
});
utilsTest("isEqual", (date, utils) => {
expect(utils.isEqual(utils.date(null), null)).toBeTruthy();
expect(utils.isEqual(date, utils.date(TEST_TIMESTAMP))).toBeTruthy();
expect(utils.isEqual(null, utils.date(TEST_TIMESTAMP))).toBeFalsy();
});
utilsTest("parseISO", (_date, utils, lib) => {
const parsedDate = utils.parseISO(TEST_TIMESTAMP);
const outputtedISO = utils.toISO(parsedDate);
if (lib === "DateFns") {
// date-fns never suppress useless milliseconds in the end
expect(outputtedISO).toEqual(TEST_TIMESTAMP.replace(".000Z", "Z"));
} else if (lib === "Luxon") {
// luxon does not shorthand +00:00 to Z, which is also valid ISO string
expect(outputtedISO).toEqual(TEST_TIMESTAMP.replace("Z", "+00:00"));
} else {
expect(outputtedISO).toEqual(TEST_TIMESTAMP);
}
});
utilsTest("parse", (date, utils, lib) => {
const parsedDate = utils.parse("2018-10-30 11:44", formats.dateTime[lib]);
expect(utils.isEqual(parsedDate, date)).toBeTruthy();
expect(utils.parse("", formats.dateTime[lib])).toBeNull();
});
utilsTest("parse invalid inputs", (date, utils, lib) => {
const parsedDate = utils.parse("99-99-9999", formats.dateTime[lib]);
// expect(utils.isValid(parsedDateMoreText)).toBe(false);
expect(utils.isValid(parsedDate)).toBe(false);
});
utilsTest("isNull", (date, utils, lib) => {
expect(utils.isNull(null)).toBeTruthy();
expect(utils.isNull(date)).toBeFalsy();
});
utilsTest("isSameDay", (date, utils, lib) => {
expect(utils.isSameDay(date, utils.date("2018-10-30T00:00:00.000Z"))).toBeTruthy();
expect(utils.isSameDay(date, utils.date("2019-10-30T00:00:00.000Z"))).toBeFalsy();
});
utilsTest("isSameMonth", (date, utils, lib) => {
expect(utils.isSameMonth(date, utils.date("2018-10-01T00:00:00.000Z"))).toBeTruthy();
expect(utils.isSameMonth(date, utils.date("2019-10-01T00:00:00.000Z"))).toBeFalsy();
});
utilsTest("isSameYear", (date, utils, lib) => {
expect(utils.isSameYear(date, utils.date("2018-10-01T00:00:00.000Z"))).toBeTruthy();
expect(utils.isSameYear(date, utils.date("2019-10-01T00:00:00.000Z"))).toBeFalsy();
});
utilsTest("isSameHour", (date, utils, lib) => {
expect(utils.isSameHour(date, utils.date(TEST_TIMESTAMP))).toBeTruthy();
expect(
utils.isSameHour(date, utils.addDays(utils.date(TEST_TIMESTAMP), 5))
).toBeFalsy();
});
utilsTest("getCurrentLocaleCode: returns default locale", (date, utils, lib) => {
expect(utils.getCurrentLocaleCode()).toMatch(/en/);
});
utilsTest("toJsDate: returns date object", (date, utils) => {
expect(utils.toJsDate(date)).toBeInstanceOf(Date);
});
utilsTest("isWithinRange: checks that dates isBetween 2 other dates", (date, utils) => {
expect(
utils.isWithinRange(utils.date("2019-10-01T00:00:00.000Z"), [
utils.date("2019-09-01T00:00:00.000Z"),
utils.date("2019-11-01T00:00:00.000Z"),
])
).toBeTruthy();
expect(
utils.isWithinRange(utils.date("2019-12-01T00:00:00.000Z"), [
utils.date("2019-09-01T00:00:00.000Z"),
utils.date("2019-11-01T00:00:00.000Z"),
])
).toBeFalsy();
});
utilsTest("isWithinRange: should use inclusivity of range", (date, utils) => {
expect(
utils.isWithinRange(utils.date("2019-09-01T00:00:00.000Z"), [
utils.date("2019-09-01T00:00:00.000Z"),
utils.date("2019-12-01T00:00:00.000Z"),
])
).toBeTruthy();
expect(
utils.isWithinRange(utils.date("2019-12-01T00:00:00.000Z"), [
utils.date("2019-09-01T00:00:00.000Z"),
utils.date("2019-12-01T00:00:00.000Z"),
])
).toBeTruthy();
});
}); | the_stack |
import {TestBed} from '@angular/core/testing';
import {provideMockActions} from '@ngrx/effects/testing';
import {Action, Store} from '@ngrx/store';
import {MockStore, provideMockStore} from '@ngrx/store/testing';
import * as coreActions from '../../core/actions';
import {DataLoadState} from '../../types/data';
import {of, ReplaySubject} from 'rxjs';
import {buildNavigatedAction} from '../../app_routing/testing';
import {State} from '../../app_state';
import {
getExperimentIdsFromRoute,
getRouteId,
getRuns,
getRunsLoadState,
} from '../../selectors';
import {Run} from '../data_source/runs_data_source_types';
import * as actions from '../actions';
import {HparamsAndMetadata} from '../data_source/runs_data_source_types';
import {
buildHparamsAndMetadata,
provideTestingRunsDataSource,
TestingRunsDataSource,
} from '../data_source/testing';
import {RunsEffects} from './index';
function createRun(override: Partial<Run> = {}) {
return {
id: '123',
name: 'foo',
startTime: 0,
...override,
};
}
describe('runs_effects', () => {
let runsDataSource: TestingRunsDataSource;
let effects: RunsEffects;
let store: MockStore<State>;
let action: ReplaySubject<Action>;
let fetchRunsSubjects: Array<ReplaySubject<Run[]>>;
let fetchHparamsMetadataSubjects: Array<ReplaySubject<HparamsAndMetadata>>;
let dispatchSpy: jasmine.Spy;
let actualActions: Action[];
let selectSpy: jasmine.Spy;
function flushFetchRuns(requestIndex: number, runs: Run[]) {
expect(fetchRunsSubjects.length).toBeGreaterThan(requestIndex);
fetchRunsSubjects[requestIndex].next(runs);
fetchRunsSubjects[requestIndex].complete();
}
function flushRunsError(requestIndex: number) {
expect(fetchRunsSubjects.length).toBeGreaterThan(requestIndex);
fetchRunsSubjects[requestIndex].error(new ErrorEvent('error'));
fetchRunsSubjects[requestIndex].complete();
}
function flushFetchHparamsMetadata(
requestIndex: number,
metadata: HparamsAndMetadata
) {
expect(fetchHparamsMetadataSubjects.length).toBeGreaterThan(requestIndex);
fetchHparamsMetadataSubjects[requestIndex].next(metadata);
fetchHparamsMetadataSubjects[requestIndex].complete();
}
beforeEach(async () => {
action = new ReplaySubject<Action>(1);
await TestBed.configureTestingModule({
providers: [
provideMockActions(action),
RunsEffects,
provideMockStore(),
provideTestingRunsDataSource(),
],
}).compileComponents();
store = TestBed.inject<Store<State>>(Store) as MockStore<State>;
selectSpy = spyOn(store, 'select').and.callThrough();
actualActions = [];
dispatchSpy = spyOn(store, 'dispatch').and.callFake((action: Action) => {
actualActions.push(action);
});
effects = TestBed.inject(RunsEffects);
runsDataSource = TestBed.inject(TestingRunsDataSource);
fetchRunsSubjects = [];
spyOn(runsDataSource, 'fetchRuns').and.callFake(() => {
const subject = new ReplaySubject<Run[]>(1);
fetchRunsSubjects.push(subject);
return subject;
});
fetchHparamsMetadataSubjects = [];
spyOn(runsDataSource, 'fetchHparamsMetadata').and.callFake(() => {
const subject = new ReplaySubject<HparamsAndMetadata>(1);
fetchHparamsMetadataSubjects.push(subject);
return subject;
});
store.overrideSelector(getRunsLoadState, {
state: DataLoadState.NOT_LOADED,
lastLoadedTimeInMs: 0,
});
store.overrideSelector(getExperimentIdsFromRoute, null);
store.overrideSelector(getRouteId, 'foo');
});
describe('loadRunsOnRunTableShown', () => {
beforeEach(() => {
// Subscribes to effects.loadRunsOnRunTableShown$ change. Must subscribe
// after settings the action payload before.
effects.loadRunsOnRunTableShown$.subscribe(() => {});
});
[
{
runLoadState: DataLoadState.NOT_LOADED,
},
{
runLoadState: DataLoadState.FAILED,
},
].forEach(({runLoadState}) => {
it(
'fetches runs and hparams when runLoadState is ' +
DataLoadState[runLoadState],
() => {
store.overrideSelector(getRunsLoadState, {
state: runLoadState,
lastLoadedTimeInMs: 0,
});
// Force store to emit change and make selector to fetch the latest
// data.
store.refreshState();
action.next(actions.runTableShown({experimentIds: ['a']}));
const createRuns = () => [
createRun({
id: 'a/runA',
name: 'runA',
}),
createRun({
id: 'a/runA/runB',
name: 'runA/runB',
}),
];
flushFetchRuns(0, createRuns());
flushFetchHparamsMetadata(
0,
buildHparamsAndMetadata({
runToHparamsAndMetrics: {
'a/runA': {hparams: [{name: 'param', value: 1}], metrics: []},
},
})
);
const expectedExperimentId = 'a';
expect(actualActions).toEqual([
actions.fetchRunsRequested({
experimentIds: [expectedExperimentId],
requestedExperimentIds: [expectedExperimentId],
}),
actions.fetchRunsSucceeded({
experimentIds: ['a'],
runsForAllExperiments: createRuns(),
newRunsAndMetadata: {
[expectedExperimentId]: {
runs: createRuns(),
metadata: buildHparamsAndMetadata({
runToHparamsAndMetrics: {
'a/runA': {
hparams: [{name: 'param', value: 1}],
metrics: [],
},
},
}),
},
},
}),
]);
}
);
});
[
{
runLoadState: DataLoadState.LOADED,
},
{
runLoadState: DataLoadState.LOADING,
},
].forEach(({runLoadState}) => {
it(`does not fetch runs when runLoadState is ${DataLoadState[runLoadState]}`, () => {
store.overrideSelector(getRunsLoadState, {
state: runLoadState,
lastLoadedTimeInMs: 0,
});
store.refreshState();
action.next(actions.runTableShown({experimentIds: ['a']}));
expect(fetchRunsSubjects.length).toBe(0);
expect(actualActions).toEqual([]);
});
});
it('fires FAILED action when failed to fetch runs', () => {
action.next(actions.runTableShown({experimentIds: ['a']}));
const expectedExperimentId = 'a';
expect(fetchRunsSubjects.length).toBe(1);
flushRunsError(0);
expect(actualActions).toEqual([
actions.fetchRunsRequested({
experimentIds: [expectedExperimentId],
requestedExperimentIds: [expectedExperimentId],
}),
actions.fetchRunsFailed({
experimentIds: [expectedExperimentId],
requestedExperimentIds: [expectedExperimentId],
}),
]);
});
it('fires FAILED action when failed to fetch hparams', () => {
action.next(actions.runTableShown({experimentIds: ['a']}));
const expectedExperimentId = 'a';
fetchHparamsMetadataSubjects[0].error(new ErrorEvent('error'));
fetchHparamsMetadataSubjects[0].complete();
expect(actualActions).toEqual([
actions.fetchRunsRequested({
experimentIds: [expectedExperimentId],
requestedExperimentIds: [expectedExperimentId],
}),
actions.fetchRunsFailed({
experimentIds: [expectedExperimentId],
requestedExperimentIds: [expectedExperimentId],
}),
]);
});
it('allows concurrent requests that arrive out of order', () => {
const firstExperimentId = 'a';
const secondExperimentId = 'b';
action.next(actions.runTableShown({experimentIds: [firstExperimentId]}));
action.next(actions.runTableShown({experimentIds: [secondExperimentId]}));
// fetchRuns are still pending.
expect(actualActions).toEqual([
actions.fetchRunsRequested({
experimentIds: [firstExperimentId],
requestedExperimentIds: [firstExperimentId],
}),
actions.fetchRunsRequested({
experimentIds: [secondExperimentId],
requestedExperimentIds: [secondExperimentId],
}),
]);
const RUN_A = createRun({id: '0', name: 'runA'});
const RUN_B = createRun({id: '1', name: 'runB'});
const RUN_B_1 = createRun({id: '2', name: 'runB/1'});
// fetchRuns arrived out of order.
expect(fetchRunsSubjects.length).toBe(2);
flushFetchRuns(1, [RUN_B, RUN_B_1]);
flushFetchHparamsMetadata(1, buildHparamsAndMetadata({}));
flushFetchRuns(0, [RUN_A]);
flushFetchHparamsMetadata(0, buildHparamsAndMetadata({}));
expect(actualActions).toEqual([
actions.fetchRunsRequested({
experimentIds: [firstExperimentId],
requestedExperimentIds: [firstExperimentId],
}),
actions.fetchRunsRequested({
experimentIds: [secondExperimentId],
requestedExperimentIds: [secondExperimentId],
}),
actions.fetchRunsSucceeded({
experimentIds: ['b'],
runsForAllExperiments: [RUN_B, RUN_B_1],
newRunsAndMetadata: {
[secondExperimentId]: {
runs: [RUN_B, RUN_B_1],
metadata: buildHparamsAndMetadata({}),
},
},
}),
actions.fetchRunsSucceeded({
experimentIds: ['a'],
runsForAllExperiments: [RUN_A],
newRunsAndMetadata: {
[firstExperimentId]: {
runs: [RUN_A],
metadata: buildHparamsAndMetadata({}),
},
},
}),
]);
});
});
describe('loadRunsOnNavigationOrReload', () => {
beforeEach(() => {
effects.loadRunsOnNavigationOrReload$.subscribe(() => {});
});
[
{specAction: buildNavigatedAction, specName: 'navigation'},
{specAction: coreActions.manualReload, specName: 'manual reload'},
{specAction: coreActions.reload, specName: 'auto reload'},
].forEach(({specAction, specName}) => {
describe(`on ${specName}`, () => {
it(`fetches runs and hparams based on expIds in the route`, () => {
store.overrideSelector(getRouteId, 'c,exp1:123,exp2:456');
store.overrideSelector(getExperimentIdsFromRoute, ['123', '456']);
const createFooRuns = () => [
createRun({
id: 'foo/runA',
name: 'runA',
}),
];
const createBarRuns = () => [
createRun({
id: 'bar/runB',
name: 'runB',
}),
];
store.refreshState();
action.next(specAction());
// Flush second request first to spice things up.
flushFetchRuns(1, createBarRuns());
flushFetchHparamsMetadata(1, buildHparamsAndMetadata({}));
flushFetchRuns(0, createFooRuns());
flushFetchHparamsMetadata(0, buildHparamsAndMetadata({}));
expect(actualActions).toEqual([
actions.fetchRunsRequested({
experimentIds: ['123', '456'],
requestedExperimentIds: ['123', '456'],
}),
actions.fetchRunsSucceeded({
experimentIds: ['123', '456'],
runsForAllExperiments: [...createFooRuns(), ...createBarRuns()],
newRunsAndMetadata: {
456: {
runs: createBarRuns(),
metadata: buildHparamsAndMetadata({}),
},
123: {
runs: createFooRuns(),
metadata: buildHparamsAndMetadata({}),
},
},
}),
]);
});
it('fetches only runs that are not loading', () => {
const createFooRuns = () => [
createRun({
id: 'foo/runA',
name: 'runA',
}),
];
const createBarRuns = () => [
createRun({
id: 'bar/runB',
name: 'runB',
}),
];
const get123LoadState = new ReplaySubject(1);
get123LoadState.next({
state: DataLoadState.LOADING,
lastLoadedTimeInMs: 0,
});
selectSpy
.withArgs(getRuns, {experimentId: '123'})
.and.returnValue(of(createFooRuns()));
selectSpy
.withArgs(getRuns, {experimentId: '456'})
.and.returnValue(of(createBarRuns()));
selectSpy
.withArgs(getRunsLoadState, {experimentId: '123'})
.and.returnValue(get123LoadState);
selectSpy
.withArgs(getRunsLoadState, {experimentId: '456'})
.and.returnValue(
of({
state: DataLoadState.NOT_LOADED,
lastLoadedTimeInMs: null,
})
);
store.overrideSelector(getRouteId, 'c,exp1:123,exp2:456');
store.overrideSelector(getExperimentIdsFromRoute, ['123', '456']);
store.refreshState();
action.next(specAction());
flushFetchRuns(0, createBarRuns());
flushFetchHparamsMetadata(0, buildHparamsAndMetadata({}));
expect(actualActions).toEqual([
actions.fetchRunsRequested({
experimentIds: ['123', '456'],
requestedExperimentIds: ['456'],
}),
]);
// Since the stream is waiting until the loading runs are
// resolved, we need to change the load state in order to get the
// `fetchRunsSucceeded`.
get123LoadState.next({
state: DataLoadState.LOADED,
lastLoadedTimeInMs: 123,
});
expect(actualActions).toEqual([
actions.fetchRunsRequested({
experimentIds: ['123', '456'],
requestedExperimentIds: ['456'],
}),
actions.fetchRunsSucceeded({
experimentIds: ['123', '456'],
runsForAllExperiments: [...createFooRuns(), ...createBarRuns()],
newRunsAndMetadata: {
456: {
runs: createBarRuns(),
metadata: buildHparamsAndMetadata({}),
},
},
}),
]);
});
});
});
describe('on navigation', () => {
it('fetches for runs if not loaded before', () => {
const createFooRuns = () => [
createRun({
id: 'foo/runA',
name: 'runA',
}),
];
const createBarRuns = () => [
createRun({
id: 'bar/runB',
name: 'runB',
}),
];
selectSpy
.withArgs(getRuns, {experimentId: '123'})
.and.returnValue(of(createFooRuns()));
selectSpy
.withArgs(getRuns, {experimentId: '456'})
.and.returnValue(of(createBarRuns()));
selectSpy
.withArgs(getRunsLoadState, {experimentId: '123'})
.and.returnValue(
of({
state: DataLoadState.LOADED,
lastLoadedTimeInMs: 0,
})
);
selectSpy
.withArgs(getRunsLoadState, {experimentId: '456'})
.and.returnValue(
of({
state: DataLoadState.NOT_LOADED,
lastLoadedTimeInMs: null,
})
);
store.overrideSelector(getRouteId, 'c,exp1:123,exp2:456');
store.overrideSelector(getExperimentIdsFromRoute, ['123', '456']);
store.refreshState();
action.next(buildNavigatedAction());
flushFetchRuns(0, createBarRuns());
flushFetchHparamsMetadata(0, buildHparamsAndMetadata({}));
expect(actualActions).toEqual([
actions.fetchRunsRequested({
experimentIds: ['123', '456'],
requestedExperimentIds: ['456'],
}),
actions.fetchRunsSucceeded({
experimentIds: ['123', '456'],
runsForAllExperiments: [...createFooRuns(), ...createBarRuns()],
newRunsAndMetadata: {
456: {
runs: createBarRuns(),
metadata: buildHparamsAndMetadata({}),
},
},
}),
]);
});
it('ignores a navigation to the same routeId (hash changes)', () => {
store.overrideSelector(getRouteId, 'e,123');
store.overrideSelector(getExperimentIdsFromRoute, ['123']);
const createFooRuns = () => [
createRun({
id: 'foo/runA',
name: 'runA',
}),
];
selectSpy
.withArgs(getRuns, {experimentId: '123'})
.and.returnValue(of(createFooRuns()));
store.overrideSelector(getRunsLoadState, {
state: DataLoadState.LOADED,
lastLoadedTimeInMs: 0,
});
store.refreshState();
// Only the first one goes through.
action.next(buildNavigatedAction());
expect(actualActions).toEqual([
actions.fetchRunsRequested({
experimentIds: ['123'],
requestedExperimentIds: [],
}),
actions.fetchRunsSucceeded({
experimentIds: ['123'],
runsForAllExperiments: [...createFooRuns()],
newRunsAndMetadata: {},
}),
]);
action.next(buildNavigatedAction());
action.next(buildNavigatedAction());
expect(actualActions.length).toBe(2);
});
it('dispatches fetchRunsSucceeded even if data is already loaded', () => {
const createFooRuns = () => [
createRun({
id: 'foo/runA',
name: 'runA',
}),
];
selectSpy
.withArgs(getRuns, {experimentId: 'foo'})
.and.returnValue(of(createFooRuns()));
selectSpy
.withArgs(getRunsLoadState, {experimentId: 'foo'})
.and.returnValue(
of({
state: DataLoadState.LOADED,
lastLoadedTimeInMs: 0,
})
);
store.overrideSelector(getExperimentIdsFromRoute, ['foo']);
store.refreshState();
action.next(buildNavigatedAction());
expect(actualActions).toEqual([
actions.fetchRunsRequested({
experimentIds: ['foo'],
requestedExperimentIds: [],
}),
actions.fetchRunsSucceeded({
experimentIds: ['foo'],
runsForAllExperiments: [...createFooRuns()],
newRunsAndMetadata: {},
}),
]);
});
});
it('does not hang because one run failed to fetch', () => {
store.overrideSelector(getRouteId, 'c,exp1:123,exp2:456');
store.overrideSelector(getExperimentIdsFromRoute, ['123', '456']);
store.refreshState();
action.next(buildNavigatedAction());
flushRunsError(0);
flushFetchRuns(1, [createRun({id: 'bar/runB', name: 'runB'})]);
flushFetchHparamsMetadata(0, buildHparamsAndMetadata({}));
flushFetchHparamsMetadata(1, buildHparamsAndMetadata({}));
expect(actualActions).toEqual([
actions.fetchRunsRequested({
experimentIds: ['123', '456'],
requestedExperimentIds: ['123', '456'],
}),
actions.fetchRunsFailed({
experimentIds: ['123', '456'],
requestedExperimentIds: ['123', '456'],
}),
]);
});
it('does not cancel request even if user navigates away', () => {
store.overrideSelector(getRouteId, 'e,123');
store.overrideSelector(getExperimentIdsFromRoute, ['123']);
const createFooRuns = () => [
createRun({
id: 'foo/runA',
name: 'runA',
}),
];
const createBarRuns = () => [
createRun({
id: 'bar/runB',
name: 'runB',
}),
];
store.refreshState();
action.next(buildNavigatedAction());
// Emulate navigation to a new experiment route.
store.overrideSelector(getRouteId, 'e,456');
store.overrideSelector(getExperimentIdsFromRoute, ['456']);
// Force selectors to re-evaluate with a change in store.
store.refreshState();
action.next(buildNavigatedAction());
flushFetchRuns(1, createBarRuns());
flushFetchHparamsMetadata(1, buildHparamsAndMetadata({}));
flushFetchRuns(0, createFooRuns());
flushFetchHparamsMetadata(0, buildHparamsAndMetadata({}));
expect(actualActions).toEqual([
actions.fetchRunsRequested({
experimentIds: ['123'],
requestedExperimentIds: ['123'],
}),
actions.fetchRunsRequested({
experimentIds: ['456'],
requestedExperimentIds: ['456'],
}),
actions.fetchRunsSucceeded({
experimentIds: ['456'],
runsForAllExperiments: createBarRuns(),
newRunsAndMetadata: {
456: {runs: createBarRuns(), metadata: buildHparamsAndMetadata({})},
},
}),
actions.fetchRunsSucceeded({
experimentIds: ['123'],
runsForAllExperiments: createFooRuns(),
newRunsAndMetadata: {
123: {runs: createFooRuns(), metadata: buildHparamsAndMetadata({})},
},
}),
]);
});
it('fires FAILED action when at least one runs fetch failed', () => {
store.overrideSelector(getRouteId, 'c,exp1:123,exp2:456');
store.overrideSelector(getExperimentIdsFromRoute, ['123', '456']);
store.refreshState();
action.next(buildNavigatedAction());
flushRunsError(0);
flushFetchHparamsMetadata(0, buildHparamsAndMetadata({}));
flushFetchRuns(1, []);
flushFetchHparamsMetadata(1, buildHparamsAndMetadata({}));
expect(actualActions).toEqual([
actions.fetchRunsRequested({
experimentIds: ['123', '456'],
requestedExperimentIds: ['123', '456'],
}),
actions.fetchRunsFailed({
experimentIds: ['123', '456'],
requestedExperimentIds: ['123', '456'],
}),
]);
});
it('fires FAILED action when at least one hparams fetch failed', () => {
store.overrideSelector(getRouteId, 'c,exp1:123,exp2:456');
store.overrideSelector(getExperimentIdsFromRoute, ['123', '456']);
store.refreshState();
action.next(buildNavigatedAction());
flushFetchRuns(0, [createRun({id: 'foo/runA', name: 'runA'})]);
fetchHparamsMetadataSubjects[0].error(new ErrorEvent('error'));
fetchHparamsMetadataSubjects[0].complete();
flushFetchRuns(1, []);
flushFetchHparamsMetadata(1, buildHparamsAndMetadata({}));
expect(actualActions).toEqual([
actions.fetchRunsRequested({
experimentIds: ['123', '456'],
requestedExperimentIds: ['123', '456'],
}),
actions.fetchRunsFailed({
experimentIds: ['123', '456'],
requestedExperimentIds: ['123', '456'],
}),
]);
});
describe('multiple actions', () => {
it('waits for already loading runs so actions do not fire out of order', () => {
// When actions are fired out of order, then the list of runs can be
// stale and lead to incorrect run selection.
const createFooBeforeRuns = () => [
createRun({
id: 'foo/runA',
name: 'runA',
}),
];
const createFooAfterRuns = () => [
createRun({
id: 'foo/runA',
name: 'runA',
}),
createRun({
id: 'foo/runB',
name: 'runB',
}),
];
const createBarRuns = () => [
createRun({
id: 'bar/runB',
name: 'runB',
}),
];
const runsSubject = new ReplaySubject(1);
runsSubject.next(createFooBeforeRuns());
const runsLoadStateSubject = new ReplaySubject(1);
runsLoadStateSubject.next({
state: DataLoadState.NOT_LOADED,
lastLoadedTimeInMs: 0,
});
store.overrideSelector(getExperimentIdsFromRoute, ['foo']);
selectSpy
.withArgs(getRuns, {experimentId: 'foo'})
.and.returnValue(runsSubject);
selectSpy
.withArgs(getRunsLoadState, {experimentId: 'foo'})
.and.returnValue(runsLoadStateSubject);
selectSpy
.withArgs(getRuns, {experimentId: 'bar'})
.and.returnValue(of(null));
selectSpy
.withArgs(getRunsLoadState, {experimentId: 'bar'})
.and.returnValue(
of({
state: DataLoadState.NOT_LOADED,
lastLoadedTimeInMs: 0,
})
);
store.refreshState();
// User triggered reload on `/experiment/foo/`
action.next(coreActions.manualReload());
// User navigates to `/compare/a:foo,b:bar/`
store.overrideSelector(getExperimentIdsFromRoute, ['foo', 'bar']);
runsLoadStateSubject.next({
state: DataLoadState.LOADING,
lastLoadedTimeInMs: 0,
});
store.refreshState();
action.next(buildNavigatedAction());
// Flush the request for `bar`'s runs.
flushFetchRuns(1, createBarRuns());
flushFetchHparamsMetadata(1, buildHparamsAndMetadata({}));
// Flush the request for `foo`'s runs.
flushFetchRuns(0, createFooAfterRuns());
flushFetchHparamsMetadata(0, buildHparamsAndMetadata({}));
runsSubject.next(createFooAfterRuns());
runsLoadStateSubject.next({
state: DataLoadState.LOADED,
lastLoadedTimeInMs: 123,
});
expect(actualActions).toEqual([
actions.fetchRunsRequested({
experimentIds: ['foo'],
requestedExperimentIds: ['foo'],
}),
actions.fetchRunsRequested({
experimentIds: ['foo', 'bar'],
requestedExperimentIds: ['bar'],
}),
actions.fetchRunsSucceeded({
experimentIds: ['foo'],
runsForAllExperiments: [...createFooAfterRuns()],
newRunsAndMetadata: {
foo: {
runs: createFooAfterRuns(),
metadata: buildHparamsAndMetadata({}),
},
},
}),
actions.fetchRunsSucceeded({
experimentIds: ['foo', 'bar'],
runsForAllExperiments: [
...createFooAfterRuns(),
...createBarRuns(),
],
newRunsAndMetadata: {
bar: {
runs: createBarRuns(),
metadata: buildHparamsAndMetadata({}),
},
},
}),
]);
});
it('dispatches action when an already loading run fails to load', () => {
const createFooRuns = () => [];
const runsSubject = new ReplaySubject(1);
runsSubject.next(createFooRuns());
const runsLoadStateSubject = new ReplaySubject(1);
runsLoadStateSubject.next({
state: DataLoadState.NOT_LOADED,
lastLoadedTimeInMs: 0,
});
store.overrideSelector(getExperimentIdsFromRoute, ['foo']);
selectSpy
.withArgs(getRuns, {experimentId: 'foo'})
.and.returnValue(runsSubject);
selectSpy
.withArgs(getRunsLoadState, {experimentId: 'foo'})
.and.returnValue(runsLoadStateSubject);
store.refreshState();
action.next(coreActions.reload());
runsLoadStateSubject.next({
state: DataLoadState.LOADING,
lastLoadedTimeInMs: 0,
});
store.refreshState();
action.next(coreActions.manualReload());
flushRunsError(0);
flushFetchHparamsMetadata(0, buildHparamsAndMetadata({}));
runsLoadStateSubject.next({
state: DataLoadState.FAILED,
lastLoadedTimeInMs: 0,
});
expect(actualActions).toEqual([
actions.fetchRunsRequested({
experimentIds: ['foo'],
requestedExperimentIds: ['foo'],
}),
actions.fetchRunsRequested({
experimentIds: ['foo'],
requestedExperimentIds: [],
}),
actions.fetchRunsFailed({
experimentIds: ['foo'],
requestedExperimentIds: ['foo'],
}),
actions.fetchRunsFailed({
experimentIds: ['foo'],
requestedExperimentIds: [],
}),
]);
});
});
});
}); | the_stack |
import { hash } from '../../../lisk-cryptography/dist-node';
import {
LAYER_INDEX_SIZE,
NODE_HASH_SIZE,
EMPTY_HASH,
LEAF_PREFIX,
BRANCH_PREFIX,
PREFIX_HASH_TO_VALUE,
PREFIX_LOC_TO_HASH,
NODE_INDEX_SIZE,
} from './constants';
import { InMemoryDB } from '../inmemory_db';
import { PrefixStore } from './prefix_store';
import { NodeData, NodeInfo, NodeType, Proof, Database } from './types';
import {
calculatePathNodes,
generateHash,
getBinaryString,
isLeaf,
getRightSiblingInfo,
toIndex,
isLeft,
isSameLayer,
areSiblings,
getLocation,
treeSortFn,
insertNewIndex,
ROOT_INDEX,
} from './utils';
export class MerkleTree {
private _root: Buffer;
private _size = 0;
private readonly _preHashedLeaf: boolean;
private readonly _db: Database;
private readonly _hashToValueMap: PrefixStore;
private readonly _locationToHashMap: PrefixStore;
public constructor(options?: { preHashedLeaf?: boolean; db?: Database }) {
this._db = options?.db ?? new InMemoryDB();
this._hashToValueMap = new PrefixStore(this._db, PREFIX_HASH_TO_VALUE);
this._locationToHashMap = new PrefixStore(this._db, PREFIX_LOC_TO_HASH);
this._preHashedLeaf = options?.preHashedLeaf ?? false;
this._root = EMPTY_HASH;
}
public async init(initValues: Buffer[]): Promise<void> {
if (initValues.length <= 1) {
const rootNode = initValues.length
? await this._generateLeaf(initValues[0], 0)
: { hash: EMPTY_HASH, value: Buffer.alloc(0) };
this._root = rootNode.hash;
await this._hashToValueMap.set(this._root, rootNode.value);
await this._locationToHashMap.set(getBinaryString(0, this._getHeight()), this._root);
this._size = initValues.length ? 1 : 0;
return;
}
this._root = await this._build(initValues);
}
public get root(): Buffer {
return this._root;
}
public get size(): number {
return this._size;
}
public async append(value: Buffer): Promise<Buffer> {
if (this._size === 0) {
const leaf = await this._generateLeaf(value, 0);
this._root = leaf.hash;
this._size += 1;
return this._root;
}
const appendPath = await this._getAppendPathNodes();
const appendData = await this._generateLeaf(value, this._size);
let currentNode = await this._getNode(appendData.hash);
for (let i = 0; i < appendPath.length; i += 1) {
const leftNodeInfo = appendPath[i];
const newBranchNode = await this._generateBranch(
leftNodeInfo.hash,
currentNode.hash,
leftNodeInfo.layerIndex + 1,
leftNodeInfo.nodeIndex + 1,
);
currentNode = await this._getNode(newBranchNode.hash);
}
this._root = currentNode.hash;
this._size += 1;
return this.root;
}
public async generateProof(queryData: ReadonlyArray<Buffer>): Promise<Proof> {
if (this._size === 0) {
return {
siblingHashes: [],
idxs: [],
size: 0,
};
}
const idxs = await this._getIndices(queryData);
const siblingHashes = await this._getSiblingHashes(idxs);
return {
size: this._size,
idxs,
siblingHashes,
};
}
// idx is the first element of right tree
public async generateRightWitness(idx: number): Promise<Buffer[]> {
if (idx < 0 || idx > this._size) {
throw new Error('index out of range');
}
if (this._size === idx) {
return [];
}
if (idx === 0) {
return this._getAppendPathHashes();
}
const height = this._getHeight();
const size = this._size;
const rightWitness: Buffer[] = [];
let incrementalIdx = idx;
for (let layerIndex = 0; layerIndex < height; layerIndex += 1) {
const digit = (incrementalIdx >>> layerIndex) & 1;
if (digit === 0) {
continue;
}
const leftTreeLastIdx = idx - 1;
const nodeIndex = leftTreeLastIdx >> layerIndex;
const siblingInfo = getRightSiblingInfo(nodeIndex, layerIndex, size);
if (!siblingInfo) {
break;
}
const nodeHash = await this._locationToHashMap.get(
getBinaryString(siblingInfo.nodeIndex, height - siblingInfo.layerIndex),
);
if (!nodeHash) {
throw new Error(
`Invalid tree state. Node at ${siblingInfo.nodeIndex} in layer ${siblingInfo.layerIndex} does not exist for size ${this.size}`,
);
}
rightWitness.push(nodeHash);
incrementalIdx += 1 << layerIndex;
}
return rightWitness;
}
public async update(idxs: number[], updateData: ReadonlyArray<Buffer>): Promise<Buffer> {
const updateHashes = [];
const height = this._getHeight();
for (const idx of idxs) {
if (idx.toString(2).length !== height + 1) {
throw new Error('Updating data must be the leaf.');
}
}
for (const data of updateData) {
const leafValueWithoutNodeIndex = Buffer.concat(
[LEAF_PREFIX, data],
LEAF_PREFIX.length + data.length,
);
const leafHash = hash(leafValueWithoutNodeIndex);
updateHashes.push(leafHash);
}
const siblingHashes = await this._getSiblingHashes(idxs);
const calculatedTree = calculatePathNodes(updateHashes, this._size, idxs, siblingHashes);
for (const [index, hashedValue] of calculatedTree.entries()) {
const loc = getLocation(index, height);
const nodeIndexBuffer = Buffer.alloc(NODE_INDEX_SIZE);
nodeIndexBuffer.writeInt32BE(loc.nodeIndex, 0);
const prefix = loc.layerIndex === 0 ? LEAF_PREFIX : BRANCH_PREFIX;
const value = Buffer.concat(
[prefix, nodeIndexBuffer, hashedValue],
prefix.length + nodeIndexBuffer.length + hashedValue.length,
);
await this._hashToValueMap.set(hashedValue, value);
await this._locationToHashMap.set(getBinaryString(loc.nodeIndex, height), hashedValue);
}
return calculatedTree.get(ROOT_INDEX) as Buffer;
}
public async toString(): Promise<string> {
if (this._size === 0) {
return this.root.toString('hex');
}
return this._printNode(this.root);
}
private async _getSiblingHashes(idxs: number[]): Promise<Buffer[]> {
let sortedIdxs: number[] = idxs.filter(idx => idx !== 0);
sortedIdxs.sort(treeSortFn);
const siblingHashes: Buffer[] = [];
const size = this._size;
const height = this._getHeight();
while (sortedIdxs.length > 0) {
const currentIndex = sortedIdxs[0];
// check for next index in case I can use it if: node is left AND there are other indices AND next index is at distance 1 AND it is on the same layer
// in that case remove it from the indices
if (
isLeft(currentIndex) &&
sortedIdxs.length > 1 &&
isSameLayer(currentIndex, sortedIdxs[1]) &&
areSiblings(currentIndex, sortedIdxs[1])
) {
sortedIdxs = sortedIdxs.slice(2);
const parentIndex = currentIndex >> 1;
insertNewIndex(sortedIdxs, parentIndex);
continue;
}
const currentNodeLoc = getLocation(currentIndex, height);
if (currentNodeLoc.layerIndex === height) {
return siblingHashes;
}
const siblingNode = getRightSiblingInfo(
currentNodeLoc.nodeIndex,
currentNodeLoc.layerIndex,
size,
);
if (siblingNode) {
const siblingIndex = toIndex(siblingNode.nodeIndex, siblingNode.layerIndex, height);
const inOriginal = idxs.findIndex(i => i === siblingIndex);
if (inOriginal > -1) {
sortedIdxs = sortedIdxs.filter(i => i !== currentIndex);
const parentIndex = currentIndex >> 1;
insertNewIndex(sortedIdxs, parentIndex);
continue;
}
const location = getBinaryString(siblingNode.nodeIndex, height - siblingNode.layerIndex);
const siblingHash = await this._locationToHashMap.get(location);
if (!siblingHash) {
throw new Error(
`Invalid tree state for ${siblingNode.nodeIndex} ${siblingNode.layerIndex}`,
);
}
siblingHashes.push(siblingHash);
}
sortedIdxs = sortedIdxs.filter(i => i !== currentIndex);
const parentIndex = currentIndex >> 1;
insertNewIndex(sortedIdxs, parentIndex);
}
return siblingHashes;
}
private _getHeight(): number {
return Math.ceil(Math.log2(this._size)) + 1;
}
private async _generateLeaf(value: Buffer, nodeIndex: number): Promise<NodeData> {
const nodeIndexBuffer = Buffer.alloc(NODE_INDEX_SIZE);
nodeIndexBuffer.writeInt32BE(nodeIndex, 0);
// As per protocol nodeIndex is not included in hash
const leafValueWithoutNodeIndex = Buffer.concat(
[LEAF_PREFIX, value],
LEAF_PREFIX.length + value.length,
);
const leafHash = this._preHashedLeaf ? value : hash(leafValueWithoutNodeIndex);
// We include nodeIndex into the value to allow for nodeIndex retrieval for leaf nodes
const leafValueWithNodeIndex = Buffer.concat(
[LEAF_PREFIX, nodeIndexBuffer, value],
LEAF_PREFIX.length + nodeIndexBuffer.length + value.length,
);
await this._hashToValueMap.set(leafHash, leafValueWithNodeIndex);
await this._locationToHashMap.set(getBinaryString(nodeIndex, this._getHeight()), leafHash);
return {
value: leafValueWithNodeIndex,
hash: leafHash,
};
}
private async _generateBranch(
leftHashBuffer: Buffer,
rightHashBuffer: Buffer,
layerIndex: number,
nodeIndex: number,
): Promise<NodeData> {
const layerIndexBuffer = Buffer.alloc(LAYER_INDEX_SIZE);
const nodeIndexBuffer = Buffer.alloc(NODE_INDEX_SIZE);
layerIndexBuffer.writeInt8(layerIndex, 0);
nodeIndexBuffer.writeInt32BE(nodeIndex, 0);
const branchValue = Buffer.concat(
[BRANCH_PREFIX, layerIndexBuffer, nodeIndexBuffer, leftHashBuffer, rightHashBuffer],
BRANCH_PREFIX.length +
layerIndexBuffer.length +
nodeIndexBuffer.length +
leftHashBuffer.length +
rightHashBuffer.length,
);
const branchHash = generateHash(BRANCH_PREFIX, leftHashBuffer, rightHashBuffer);
await this._hashToValueMap.set(branchHash, branchValue);
await this._locationToHashMap.set(
getBinaryString(nodeIndex, this._getHeight() - layerIndex),
branchHash,
);
return {
hash: branchHash,
value: branchValue,
};
}
private async _build(initValues: Buffer[]): Promise<Buffer> {
// Generate hash and buffer of leaves and store in memory
const leafHashes = [];
this._size = initValues.length;
for (let i = 0; i < initValues.length; i += 1) {
const leaf = await this._generateLeaf(initValues[i], i);
leafHashes.push(leaf.hash);
}
// Start from base layer
let currentLayerIndex = 0;
let currentLayerHashes = leafHashes;
let orphanNodeHashInPreviousLayer: Buffer | undefined;
// Loop through each layer as long as there are nodes or an orphan node from previous layer
while (currentLayerHashes.length > 1 || orphanNodeHashInPreviousLayer !== undefined) {
const pairsOfHashes: Array<[Buffer, Buffer]> = [];
// Make pairs from the current layer nodes
for (let i = 0; i < currentLayerHashes.length - 1; i += 2) {
pairsOfHashes.push([currentLayerHashes[i], currentLayerHashes[i + 1]]);
}
// If there is one node left from pairs
if (currentLayerHashes.length % 2 === 1) {
// If no orphan node left from previous layer, set the last node to new orphan node
if (orphanNodeHashInPreviousLayer === undefined) {
orphanNodeHashInPreviousLayer = currentLayerHashes[currentLayerHashes.length - 1];
// If one orphan node left from previous layer then pair with last node
} else {
pairsOfHashes.push([
currentLayerHashes[currentLayerHashes.length - 1],
orphanNodeHashInPreviousLayer,
]);
orphanNodeHashInPreviousLayer = undefined;
}
}
// Generate hash and buffer for the parent layer and store
const parentLayerHashes = [];
for (let i = 0; i < pairsOfHashes.length; i += 1) {
const leftHash = pairsOfHashes[i][0];
const rightHash = pairsOfHashes[i][1];
const node = await this._generateBranch(leftHash, rightHash, currentLayerIndex + 1, i);
parentLayerHashes.push(node.hash);
}
// Set current layer to parent layer
currentLayerHashes = parentLayerHashes;
currentLayerIndex += 1;
}
return currentLayerHashes[0];
}
private async _getAppendPathNodes(): Promise<NodeInfo[]> {
if (this._size === 0) {
return [];
}
// Create the appendPath
const appendPath: NodeInfo[] = [];
let currentNode = await this._getNode(this._root);
// If tree is fully balanced
if (this._size === 2 ** (this._getHeight() - 1)) {
appendPath.push(currentNode);
} else {
// We start from the root layer and traverse each layer down the tree on the right side
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, no-constant-condition
while (true) {
const currentLayer = currentNode.layerIndex;
let currentLayerSize = this._size >> currentLayer;
// if layer has odd nodes and current node is odd (hence index is even)
if (currentLayerSize % 2 === 1 && currentNode.nodeIndex % 2 === 0) {
appendPath.push(currentNode);
}
// if node is leaf, break
if (currentNode.type === NodeType.LEAF) {
break;
}
// if layer below is odd numbered, push left child
currentLayerSize = this._size >> (currentLayer - 1);
if (currentLayerSize % 2 === 1) {
const leftNode = await this._getNode(currentNode.leftHash);
appendPath.push(leftNode);
}
// go to right child
currentNode = await this._getNode(currentNode.rightHash);
}
}
// Append path should be from bottom
return appendPath.reverse();
}
private async _getIndices(queryHashes: ReadonlyArray<Buffer>): Promise<number[]> {
const idxs = [];
const height = this._getHeight();
for (const query of queryHashes) {
try {
const node = await this._getNode(query);
idxs.push(toIndex(node.nodeIndex, node.layerIndex, height));
} catch (error) {
idxs.push(0);
}
}
return idxs;
}
private async _getAppendPathHashes(): Promise<Buffer[]> {
const appendPathNodes = await this._getAppendPathNodes();
return appendPathNodes.map(p => p.hash);
}
private async _getNode(nodeHash: Buffer): Promise<NodeInfo> {
const value = await this._hashToValueMap.get(nodeHash);
if (!value) {
throw new Error(`Hash does not exist in merkle tree: ${nodeHash.toString('hex')}`);
}
const type = isLeaf(value) ? NodeType.LEAF : NodeType.BRANCH;
const layerIndex = type === NodeType.LEAF ? 0 : value.readInt8(BRANCH_PREFIX.length);
const nodeIndex =
type === NodeType.BRANCH
? value.readInt32BE(BRANCH_PREFIX.length + LAYER_INDEX_SIZE)
: value.readInt32BE(LEAF_PREFIX.length);
const rightHash = type === NodeType.BRANCH ? value.slice(-1 * NODE_HASH_SIZE) : Buffer.alloc(0);
const leftHash =
type === NodeType.BRANCH
? value.slice(-2 * NODE_HASH_SIZE, -1 * NODE_HASH_SIZE)
: Buffer.alloc(0);
return {
type,
hash: nodeHash,
value,
layerIndex,
nodeIndex,
rightHash,
leftHash,
};
}
private async _printNode(hashValue: Buffer, level = 1): Promise<string> {
const nodeValue = await this._hashToValueMap.get(hashValue);
if (nodeValue && isLeaf(nodeValue)) {
return hashValue.toString('hex');
}
const node = await this._getNode(hashValue);
const left = await this._printNode(node.leftHash, level + 1);
const right = await this._printNode(node.rightHash, level + 1);
return [
hashValue.toString('hex'),
`├${' ─ '.repeat(level)} ${left}`,
`├${' ─ '.repeat(level)} ${right}`,
].join('\n');
}
} | the_stack |
import './style.scss';
import React, { useState, useEffect } from 'react';
import { motion, useAnimation } from 'framer-motion';
import { useChat } from '../chat-context/ChatContext';
import { IOption } from '../../types';
export default function ChatBody() {
// Attributes
const { isOpen, closeChat, config, defaultOption } = useChat();
const apparitionAnimation = useAnimation();
const apparitionHeaderAnimation = useAnimation();
const apparitionBodyAnimation = useAnimation();
const apparitionFooterAnimation = useAnimation();
const [option, setOption] = useState<IOption>(defaultOption);
const [steps, setSteps] = useState<IOption[]>([]);
const [email, setEmail] = useState('');
const [message, setMessage] = useState('');
const [isDone, setIsDone] = useState(false);
// Effects
useEffect(() => {
if (!isOpen) {
outSequence();
} else {
inSequence();
}
}, [isOpen])
// Methods
async function inSequence() {
await apparitionAnimation.start({ scaleY: 0, opacity: 0, x: 0, transition: { duration: 0 } });
apparitionAnimation.start({ opacity: 1, scaleY: 1, transition: { duration: 0.2 } });
apparitionHeaderAnimation.start({ opacity: 1, y: 0, transition: { delay: 0.2 } });
apparitionBodyAnimation.start({ y: 0, opacity: 1, transition: { delay: 0.2 } });
apparitionFooterAnimation.start({ y: 0, opacity: 1, scale: 1, transition: { delay: 0.2, ease: "linear" } });
}
async function outSequence() {
await apparitionAnimation.start({ scaleY: 1, opacity: 0, x: 450, transition: { duration: 0.5 } });
apparitionHeaderAnimation.start({ opacity: 0, y: 10, transition: { duration: 0.3 } });
apparitionBodyAnimation.start({ y: -10, opacity: 0, transition: { duration: 0.3 } });
apparitionFooterAnimation.start({ y: 10, opacity: 0, transition: { duration: 0.3, ease: "linear" } });
}
function handleOptionClicked(option: IOption) {
setSteps((steps) => { steps.push(option); return steps; });
setOption(option);
}
function handleBackClicked() {
// Resets the current values
setMessage('');
setEmail('');
// Sets the current option to the previous one
if (steps.length >= 2) {
setOption(steps[steps.length - 2]);
}
else {
setOption(defaultOption);
}
// Removes the previous step
setSteps((steps) => {
steps.pop();
return steps;
});
}
async function handleSendClicked() {
if (isFormFilledIn()) {
await config.handleSendClicked({ email, message, steps, option });
setIsDone(true);
}
}
async function handleFinishClicked() {
await outSequence();
reset();
if (config.handleFinalButtonClicked) {
config.handleFinalButtonClicked();
}
}
/**
* Returns if the message and e-mail are filled in
*/
function isFormFilledIn() {
if (message && email) {
return true
}
return false;
}
/**
* Resets the entire state of the chat
*/
function reset() {
closeChat();
setOption(defaultOption);
setSteps([]);
setIsDone(false);
setEmail('');
setMessage('');
}
if (!isOpen) {
return (
<>
</>
)
}
// Render
if (isDone) {
return (
<motion.div initial={{ scaleY: 0, opacity: 0 }} animate={apparitionAnimation} className="chat-body-small-container">
<div className="chat-body-done-title">
{config.finalTitle}
</div>
<div className="chat-body-done-sub-title">
{config.finalSubTitle}
</div>
<motion.div onClick={handleFinishClicked} whileHover={{ scale: 1.05 }} whileTap={{ scale: 0.9 }} className="chat-body-done-button" style={{ background: config.finalButtonColor }}>
{config.finalButtonText}
</motion.div>
</motion.div>
);
}
return (
<motion.div initial={{ scaleY: 0, opacity: 0, x: 500 }} animate={apparitionAnimation} className="chat-body-container">
<div className="chat-body-header" style={{ background: config.mainColor }}>
<motion.div initial={{ opacity: 0, y: 10 }} animate={apparitionHeaderAnimation}>
{
option.subTitle ?
(
<div>
<div className="chat-body-header-title-container">
<div className="chat-body-header-title">
{option.title}
</div>
<div onClick={closeChat} className="chat-body-header-title-close-button">
<svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M1.04261 2.45673L5.58588 7L1.04261 11.5433C0.652462 11.9334 0.652463 12.5672 1.04261 12.9574C1.43276 13.3475 2.06658 13.3475 2.45673 12.9574L7 8.41412L11.5433 12.9574C11.9334 13.3475 12.5672 13.3475 12.9574 12.9574C13.3475 12.5672 13.3475 11.9334 12.9574 11.5433L8.41412 7L12.9574 2.45673C13.3475 2.06658 13.3475 1.43276 12.9574 1.04261C12.5672 0.652463 11.9334 0.652462 11.5433 1.04261L7 5.58588L2.45673 1.04261C2.06658 0.652463 1.43276 0.652463 1.04261 1.04261C0.652463 1.43276 0.652463 2.06658 1.04261 2.45673Z" fill="white" stroke="white" strokeWidth="0.5" />
</svg>
</div>
</div>
<div className="chat-body-header-body">
{option.subTitle}
</div>
</div>
)
:
(
<div className="chat-body-header-small">
<div className="chat-body-header-small-left">
<motion.div whileHover={{ x: -2 }} whileTap={{ scale: 0.9 }} onClick={handleBackClicked} className="chat-body-header-small-image">
<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M4.76036 10.388C4.76712 10.3955 4.77411 10.4028 4.78133 10.4101L9.88097 15.5188C10.0316 15.6697 10.0314 15.914 9.88049 16.0646C9.72963 16.2152 9.48525 16.215 9.33465 16.0641L4.23503 10.9554C4.0031 10.7231 3.87334 10.4275 3.84573 10.1242C3.83291 10.0858 3.82597 10.0447 3.82597 10.002C3.82597 9.95954 3.83282 9.91869 3.84548 9.88048C3.8726 9.57589 4.00275 9.27875 4.23591 9.04566L9.34254 3.93958C9.49327 3.78886 9.73765 3.78887 9.88837 3.93961C10.0391 4.09035 10.0391 4.33473 9.88834 4.48545L4.78169 9.59155C4.7737 9.59954 4.766 9.6077 4.75857 9.61602L17.3347 9.61602C17.5479 9.61602 17.7207 9.78883 17.7207 10.002C17.7207 10.2152 17.5479 10.388 17.3347 10.388L4.76036 10.388Z" fill="white" stroke="white" />
</svg>
</motion.div>
<div className="chat-body-header-small-title">
{option.title}
</div>
</div>
<div onClick={reset} className="chat-body-header-title-close-button">
<svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M1.04261 2.45673L5.58588 7L1.04261 11.5433C0.652462 11.9334 0.652463 12.5672 1.04261 12.9574C1.43276 13.3475 2.06658 13.3475 2.45673 12.9574L7 8.41412L11.5433 12.9574C11.9334 13.3475 12.5672 13.3475 12.9574 12.9574C13.3475 12.5672 13.3475 11.9334 12.9574 11.5433L8.41412 7L12.9574 2.45673C13.3475 2.06658 13.3475 1.43276 12.9574 1.04261C12.5672 0.652463 11.9334 0.652462 11.5433 1.04261L7 5.58588L2.45673 1.04261C2.06658 0.652463 1.43276 0.652463 1.04261 1.04261C0.652463 1.43276 0.652463 2.06658 1.04261 2.45673Z" fill="white" stroke="white" strokeWidth="0.5" />
</svg>
</div>
</div>
)
}
</motion.div>
</div>
<motion.div initial={{ opacity: 0, y: -10 }} animate={apparitionBodyAnimation} className="chat-body-content">
<div className="chat-body-content-message">
<img src={config.avatarIcon} className="chat-body-content-message-image" />
<div className="chat-body-content-message-body">
{option.message}
</div>
</div>
<div className="chat-body-content-options">
{option.options && option.options.map((option) => (
<motion.div key={option.name} whileHover={{ scale: 1.1 }} whileTap={{ scale: 0.9 }} onClick={() => handleOptionClicked(option)} className="chat-body-content-option" style={{ background: config.mainColor }}>
{option.name}
</motion.div>
))}
</div>
</motion.div>
{
option.options === undefined ?
(
<motion.div animate={apparitionFooterAnimation} className="chat-body-messenger">
<div className="chat-body-messenger-body">
<input autoFocus value={email} onChange={(event) => setEmail(event.target.value)} placeholder={config.emailPlaceholder} />
<textarea value={message} onChange={(event) => setMessage(event.target.value)} placeholder={config.messagePlaceholder} />
</div>
<div className="chat-body-messenger-footer">
<motion.div whileHover={{ x: isFormFilledIn() ? 2 : 0 }} whileTap={{ scale: 0.9 }} onClick={handleSendClicked} className="chat-body-messenger-footer-image" style={{ cursor: isFormFilledIn() ? 'pointer' : 'not-allowed' }}>
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M0.0275001 22.8866L2.05466 14.1079C2.13468 13.7344 2.45476 13.4409 2.85485 13.3875L14.1909 12.2135C14.511 12.1868 14.511 11.7065 14.1909 11.6531L2.85485 10.5591C2.45476 10.5324 2.13468 10.2389 2.05466 9.86538L0.0275001 1.11344C-0.159212 0.366318 0.640983 -0.247385 1.33448 0.0994905L23.4999 11.1995C24.1667 11.5464 24.1667 12.507 23.4999 12.8538L1.33448 23.9005C0.640983 24.2474 -0.159212 23.6337 0.0275001 22.8866Z" fill={isFormFilledIn() ? config.sendButtonColor : '#C4C4C4'} />
</svg>
</motion.div>
</div>
</motion.div>
)
:
(
<motion.div animate={apparitionFooterAnimation} className="chat-body-footer">
{config.footer}
</motion.div>
)
}
</motion.div >
)
} | the_stack |
import * as React from "react";
export function Hero() {
return (
<div className="pt-8 overflow-hidden sm:pt-12 lg:relative lg:py-48">
<div className="mx-auto max-w-md px-4 sm:max-w-3xl sm:px-6 lg:px-8 lg:max-w-7xl lg:grid lg:grid-cols-2 lg:gap-24">
<div>
<div>
<img
className="h-11 w-auto"
src="https://tailwindui.com/img/logos/workflow-mark.svg?color=indigo&shade=500"
alt="Codotype"
/>
</div>
<div className="mt-20">
<div>
<a href="#" className="inline-flex space-x-4">
<span className="rounded bg-indigo-50 px-2.5 py-1 text-xs font-semibold text-indigo-500 tracking-wide uppercase">
What's new
</span>
<span className="inline-flex items-center text-sm font-medium text-indigo-500 space-x-1">
<span>Just shipped version 0.1.0</span>
{/* <!-- Heroicon name: solid/chevron-right --> */}
<svg
className="h-5 w-5"
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 20 20"
fill="currentColor"
aria-hidden="true"
>
<path
fill-rule="evenodd"
d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z"
clip-rule="evenodd"
/>
</svg>
</span>
</a>
</div>
<div className="mt-6 sm:max-w-xl">
<h1 className="text-4xl font-extrabold text-gray-900 tracking-tight sm:text-5xl">
Issue management for growing teams
</h1>
<p className="mt-6 text-xl text-gray-500">
Anim aute id magna aliqua ad ad non deserunt
sunt. Qui irure qui lorem cupidatat commodo.
</p>
</div>
<form
action="#"
className="mt-12 sm:max-w-lg sm:w-full sm:flex"
>
<div className="min-w-0 flex-1">
<label className="sr-only">Email address</label>
<input
id="hero_email"
type="email"
className="block w-full border border-gray-300 rounded-md px-5 py-3 text-base text-gray-900 placeholder-gray-500 shadow-sm focus:border-indigo-500 focus:ring-indigo-500"
placeholder="Enter your email"
/>
</div>
<div className="mt-4 sm:mt-0 sm:ml-3">
<button
type="submit"
className="block w-full rounded-md border border-transparent px-5 py-3 bg-indigo-500 text-base font-medium text-white shadow hover:bg-indigo-600 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 sm:px-10"
>
Notify me
</button>
</div>
</form>
<div className="mt-6">
<div className="inline-flex items-center divide-x divide-gray-300">
<div className="flex-shrink-0 flex pr-5">
{/* <!-- Heroicon name: solid/star --> */}
<svg
className="h-5 w-5 text-yellow-400"
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 20 20"
fill="currentColor"
aria-hidden="true"
>
<path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" />
</svg>
{/* <!-- Heroicon name: solid/star --> */}
<svg
className="h-5 w-5 text-yellow-400"
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 20 20"
fill="currentColor"
aria-hidden="true"
>
<path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" />
</svg>
{/* <!-- Heroicon name: solid/star --> */}
<svg
className="h-5 w-5 text-yellow-400"
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 20 20"
fill="currentColor"
aria-hidden="true"
>
<path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" />
</svg>
{/* <!-- Heroicon name: solid/star --> */}
<svg
className="h-5 w-5 text-yellow-400"
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 20 20"
fill="currentColor"
aria-hidden="true"
>
<path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" />
</svg>
{/* <!-- Heroicon name: solid/star --> */}
<svg
className="h-5 w-5 text-yellow-400"
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 20 20"
fill="currentColor"
aria-hidden="true"
>
<path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" />
</svg>
</div>
<div className="min-w-0 flex-1 pl-5 py-1 text-sm text-gray-500 sm:py-3">
<span className="font-medium text-gray-900">
Rated 5 stars
</span>{" "}
by over{" "}
<span className="font-medium text-indigo-500">
500 beta users
</span>
</div>
</div>
</div>
</div>
</div>
</div>
<div className="sm:mx-auto sm:max-w-3xl sm:px-6">
<div className="py-12 sm:relative sm:mt-12 sm:py-16 lg:absolute lg:inset-y-0 lg:right-0 lg:w-1/2">
<div className="hidden sm:block">
<div className="absolute inset-y-0 left-1/2 w-screen bg-gray-50 rounded-l-3xl lg:left-80 lg:right-0 lg:w-full"></div>
<svg
className="absolute top-8 right-1/2 -mr-3 lg:m-0 lg:left-0"
width="404"
height="392"
fill="none"
viewBox="0 0 404 392"
>
<defs>
<pattern
id="837c3e70-6c3a-44e6-8854-cc48c737b659"
x="0"
y="0"
width="20"
height="20"
patternUnits="userSpaceOnUse"
>
<rect
x="0"
y="0"
width="4"
height="4"
className="text-gray-200"
fill="currentColor"
/>
</pattern>
</defs>
<rect
width="404"
height="392"
fill="url(#837c3e70-6c3a-44e6-8854-cc48c737b659)"
/>
</svg>
</div>
<div className="relative pl-4 -mr-40 sm:mx-auto sm:max-w-3xl sm:px-0 lg:max-w-none lg:h-full lg:pl-12">
<img
className="w-full rounded-md shadow-xl ring-1 ring-black ring-opacity-5 lg:h-full lg:w-auto lg:max-w-none"
src="https://tailwindui.com/img/component-images/task-app-rose.jpg"
alt=""
/>
</div>
</div>
</div>
</div>
);
} | the_stack |
export const adminPage = `import { useEffect } from "react";
import { useRouter } from "next/router";
import { useEditState } from "tinacms/dist/edit-state";
const GoToEditPage = () => {
const { setEdit } = useEditState();
const router = useRouter();
useEffect(() => {
setEdit(true);
router.back();
}, []);
return <div>Entering edit mode..</div>;
};
export default GoToEditPage;
`
export const exitAdminPage = `import { useEffect } from "react";
import { useRouter } from "next/router";
import { useEditState } from "tinacms/dist/edit-state";
const GoToEditPage = () => {
const { setEdit } = useEditState();
const router = useRouter();
useEffect(() => {
setEdit(false);
router.back();
}, []);
return <div>Exiting edit mode..</div>;;
};
export default GoToEditPage;
`
export const blogPost = `---
title: Vote For Pedro
---
# Welcome to the blog.
> To edit this site head over to the [\` /
admin\`](/admin) route. Then click the pencil icon in the bottom lefthand corner to start editing 🦙.
# Dixi gaude Arethusa
## Oscula mihi
Lorem markdownum numerabilis armentorum platanus, cultros coniunx sibi per
silvas, nostris clausit sequemur diverso scopulosque. Fecit tum alta sed non
falcato murmura, geminas donata Amyntore, quoque Nox. Invitam inquit, modo
nocte; ut ignis faciemque manes in imagine sinistra ut mucrone non ramos
sepulcro supplex. Crescentesque populos motura, fit cumque. Verumque est; retro
sibi tristia bracchia Aetola telae caruerunt et.
## Mutato fefellimus sit demisit aut alterius sollicito
Phaethonteos vestes quem involvite iuvenca; furiali anne: sati totumque,
**corpora** cum rapacibus nunc! Nervis repetatne, miserabile doleas, deprensum
hunc, fluctus Threicio, ad urbes, magicaeque, quid. Per credensque series adicis
poteram [quidem](#)! Iam uni mensas victrix
vittas ut flumina Satyri adulter; bellum iacet domitae repercusso truncis urnis
mille rigidi sub taurum.
`
export const nextPostPage =
() => `// THIS FILE HAS BEEN GENERATED WITH THE TINA CLI.
// This is a demo file once you have tina setup feel free to delete this file
import { staticRequest, gql, getStaticPropsForTina } from "tinacms";
import Head from "next/head";
import { createGlobalStyle } from "styled-components";
// Styles for markdown
const GlobalStyle = createGlobalStyle\`
h1,h2,h3,h4,h5 {
margin-bottom: 1.5rem;
margin-top: 1.5rem;
}
blockquote {
background-color: rgb(209,250,229);
}
h1 {
font-size: 45px;
}
h2 {
font-size: 35px;
}
h3 {
font-size: 25px;
}
h4 {
font-size: 22px;
}
ul {
padding-left: 0;
}
li {
list-style-type: none;
}
a {
font-weight: bold;
color: rgb(59,130,246);
text-decoration: underline;
}
\`;
const defaultMarked = (markdown) => markdown;
// Use the props returned by get static props (this can be deleted when the edit provider and tina-wrapper are moved to _app.js)
const BlogPage = (props) => {
return (
<>
<Head>
{/* Tailwind CDN */}
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/2.2.7/tailwind.min.css"
integrity="sha512-y6ZMKFUQrn+UUEVoqYe8ApScqbjuhjqzTuwUMEGMDuhS2niI8KA3vhH2LenreqJXQS+iIXVTRL2iaNfJbDNA1Q=="
crossOrigin="anonymous"
referrerPolicy="no-referrer"
/>
{/* Marked CDN */}
<script
type="text/javascript"
crossOrigin="anonymous"
src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"
/>
</Head>
<div>
<div
style={{
textAlign: "center",
}}
>
<h1 className="text-3xl m-8 text-center leading-8 font-extrabold tracking-tight text-gray-900 sm:text-4xl">
{props.data.getPostsDocument.data.title}
</h1>
{/* Convert markdown to html in the browser only */}
{typeof window !== "undefined" && (
<ContentSection
content={window.marked(props.data.getPostsDocument.data.body)}
></ContentSection>
)}
</div>
<div className="bg-green-100 text-center">
Lost and looking for a place to start?
<a
href="https://tina.io/guides/tina-cloud/getting-started/overview/"
className="text-blue-500 underline"
>
{" "}
Check out this guide
</a>{" "}
to see how add TinaCMS to an existing Next.js site.
</div>
</div>
</>
);
};
export const getStaticProps = async ({ params }) => {
const tinaProps = await getStaticPropsForTina({
query: gql\`
query BlogPostQuery($relativePath: String!) {
getPostsDocument(relativePath: $relativePath) {
data {
title
body
}
}
}
\`,
variables: { relativePath: \`\${params.filename}.md\` },
});
return {
props: {
...tinaProps,
},
};
};
export const getStaticPaths = async () => {
const postsListData = (await staticRequest({
query: gql\`
query GetPostsList {
getPostsList {
edges {
node {
sys {
filename
}
}
}
}
}
\`,
}));
return {
paths: postsListData.getPostsList.edges.map((post) => ({
params: { filename: post.node.sys.filename },
})),
fallback: false,
};
};
export default BlogPage;
const ContentSection = ({ content }) => {
return (
<div className="relative py-16 bg-white overflow-hidden">
<div className="hidden lg:block lg:absolute lg:inset-y-0 lg:h-full lg:w-full">
<div
className="relative h-full text-lg max-w-prose mx-auto"
aria-hidden="true"
>
<svg
className="absolute top-12 left-full transform translate-x-32"
width={404}
height={384}
fill="none"
viewBox="0 0 404 384"
>
<defs>
<pattern
id="74b3fd99-0a6f-4271-bef2-e80eeafdf357"
x={0}
y={0}
width={20}
height={20}
patternUnits="userSpaceOnUse"
>
<rect
x={0}
y={0}
width={4}
height={4}
className="text-gray-200"
fill="currentColor"
/>
</pattern>
</defs>
<rect
width={404}
height={384}
fill="url(#74b3fd99-0a6f-4271-bef2-e80eeafdf357)"
/>
</svg>
<svg
className="absolute top-1/2 right-full transform -translate-y-1/2 -translate-x-32"
width={404}
height={384}
fill="none"
viewBox="0 0 404 384"
>
<defs>
<pattern
id="f210dbf6-a58d-4871-961e-36d5016a0f49"
x={0}
y={0}
width={20}
height={20}
patternUnits="userSpaceOnUse"
>
<rect
x={0}
y={0}
width={4}
height={4}
className="text-gray-200"
fill="currentColor"
/>
</pattern>
</defs>
<rect
width={404}
height={384}
fill="url(#f210dbf6-a58d-4871-961e-36d5016a0f49)"
/>
</svg>
<svg
className="absolute bottom-12 left-full transform translate-x-32"
width={404}
height={384}
fill="none"
viewBox="0 0 404 384"
>
<defs>
<pattern
id="d3eb07ae-5182-43e6-857d-35c643af9034"
x={0}
y={0}
width={20}
height={20}
patternUnits="userSpaceOnUse"
>
<rect
x={0}
y={0}
width={4}
height={4}
className="text-gray-200"
fill="currentColor"
/>
</pattern>
</defs>
<rect
width={404}
height={384}
fill="url(#d3eb07ae-5182-43e6-857d-35c643af9034)"
/>
</svg>
</div>
</div>
<div className="relative px-4 sm:px-6 lg:px-8">
<div className="text-lg max-w-prose mx-auto">
<div dangerouslySetInnerHTML={{ __html: content }}></div>
<GlobalStyle />
</div>
</div>
</div>
);
};
`
export const AppJsContent = (
extraImports?: string
) => `import dynamic from 'next/dynamic'
import { TinaEditProvider } from 'tinacms/dist/edit-state'
const TinaCMS = dynamic(() => import('tinacms'), { ssr: false })
${extraImports || ''}
const App = ({ Component, pageProps }) => {
return (
<>
<TinaEditProvider
editMode={
<TinaCMS
clientId={process.env.NEXT_PUBLIC_TINA_CLIENT_ID}
branch={process.env.NEXT_PUBLIC_EDIT_BRANCH}
organization={process.env.NEXT_PUBLIC_ORGANIZATION_NAME}
isLocalClient={Boolean(
Number(process.env.NEXT_PUBLIC_USE_LOCAL_CLIENT ?? true)
)}
{...pageProps}
>
{(livePageProps) => <Component {...livePageProps} />}
</TinaCMS>
}
>
<Component {...pageProps} />
</TinaEditProvider>
</>
)
}
export default App
` | the_stack |
// Should refer to this part.
// https://github.com/draft-js-plugins/draft-js-plugins/blob/master/draft-js-mention-plugin/src/MentionSuggestions/index.js#L236
// You can see that name is used for substitued value.
// https://github.coam/draft-js-plugins/draft-js-plugins/bloba/mastera/draft-js-mention-plugin/src/modifiers/addMention.js
// Make user suggestion # instead of @ following the documenations above.
// Send the project.
import * as React from "react";
import { EditorContext } from "./EditorContext";
import {
Box,
Paper,
TextField,
InputAdornment,
IconButton,
Typography,
} from "@material-ui/core";
import { ToggleButtonGroup, ToggleButton } from "@material-ui/lab";
import {
AddAPhoto,
Link,
Check
} from "@material-ui/icons";
import {
Editor,
EditorState,
Modifier,
CompositeDecorator,
AtomicBlockUtils,
getVisibleSelectionRect,
convertToRaw, // JSON
ContentBlock
} from "draft-js";
import draftUtils from "draft-js-plugins-utils";
import createMentionPlugin, {
defaultSuggestionsFilter
} from "draft-js-mention-plugin";
import "draft-js-mention-plugin/lib/plugin.css";
import { Mentions, mentions } from "./mentions";
import { linkStrategy } from "./linkStrategy";
import { DecoratedLink } from "./DecoratedLink";
import { MediaComponent } from "./MediaComponent";
// interface IProps {
// variables: Array<{id: string, name: string}>
// state: EditorState
// onChange(state: EditorState): void
// }
// <Editor {...props } />
// Should modify <Editor></Editor> part below with them.
export default function Draft({
user,
author,
}) {
// 1. Focus
const editor = React.useRef<Editor>(null);
const focusEditor = React.useCallback(() => {
if (editor.current) {
editor.current.focus();
}
}, [editor]);
// 2. Menu(toggle bars)
const [toggleButtonGroupValue, setToggleButtonGroupValue] = React.useState<
string | null
>(null);
const handleToggleButtonGroup = (
event: React.MouseEvent<HTMLElement, MouseEvent>,
value: string
) => {
event.stopPropagation();
event.preventDefault();
setToggleButtonGroupValue(value);
switch (value) {
case "header-one":
setEditorState(
EditorState.push(
editorState,
Modifier.setBlockType(
editorState.getCurrentContent(),
editorState.getSelection(),
value
),
"change-block-type"
)
);
break;
case "header-two":
setEditorState(
EditorState.push(
editorState,
Modifier.setBlockType(
editorState.getCurrentContent(),
editorState.getSelection(),
value
),
"change-block-type"
)
);
break;
case "BOLD":
setEditorState(
EditorState.push(
editorState,
Modifier.applyInlineStyle(
editorState.getCurrentContent(),
editorState.getSelection(),
value
),
"change-inline-style"
)
);
break;
case "ITALIC":
setEditorState(
EditorState.push(
editorState,
Modifier.applyInlineStyle(
editorState.getCurrentContent(),
editorState.getSelection(),
value
),
"change-inline-style"
)
);
break;
case "insert-image":
//@ts-ignore
document.getElementById("fileInput").click();
setToggleButtonGroupValue("null"); // What is diffrent with null?
break;
case "insert-link":
break;
default:
setToggleButtonGroupValue(null); // // What is diffrent with "null"?
break;
}
};
// 3. Text editor
const [editorState, setEditorState] = React.useState<EditorState>(
EditorState.createEmpty(
new CompositeDecorator([
{
strategy: linkStrategy,
component: DecoratedLink
}
])
),
);
// 4. Rectangle menu
const [selectionRect, setSelectionRect] = React.useState<{
left: number;
width: number;
right: number;
top: number;
bottom: number;
height: number;
}>({ left: 0, width: 0, right: 0, top: 0, bottom: 0, height: 0 });
const renderBlock = (contentBlock: ContentBlock) => {
if (contentBlock.getType() === "atomic") {
const entityKey = contentBlock.getEntityAt(0);
const entityData = editorState
.getCurrentContent()
.getEntity(entityKey)
.getData();
return {
component: MediaComponent,
editable: false,
props: {
src: { file: entityData.src }
}
};
}
};
React.useEffect(() => {
if (getVisibleSelectionRect(window) !== null) {
setSelectionRect(getVisibleSelectionRect(window));
}
}, [editorState, setSelectionRect]);
// 5. anchorElUrl is this directly relevant to 4.?
const [anchorElUrl, setAnchorElUrl] = React.useState<string>("");
// 6.
const editorPlaceholder = `Hey ${user.name}, hope you are doing well. You can reach to us ${author.email}.`
// 7. Mention plugin
const mentionPlugin = createMentionPlugin({
mentions,
entityMutability: 'IMMUTABLE',
mentionPrefix: '#',
});
const [suggestions, setSugesstions] = React.useState<Mentions>(mentions);
const onSearchChange = ({ value }) => {
const newSugesstion = defaultSuggestionsFilter(value, mentions);
setSugesstions(newSugesstion);
};
const onAddMention = (mention) => {
console.log(mention);
};
const { MentionSuggestions } = mentionPlugin;
const plugins = [mentionPlugin];
return (
<Box>
<Box m={2}>
<Box mb={2}>
<Typography variant="h2" component="h2" gutterBottom>
Test draft-js with TypeScript
</Typography>
<ToggleButtonGroup
exclusive
onChange={handleToggleButtonGroup}
value={toggleButtonGroupValue}
>
<ToggleButton value="header-one">
H1
</ToggleButton>
<ToggleButton value="header-two">
H2
</ToggleButton>
<ToggleButton value="BOLD">
<strong>B</strong>
</ToggleButton>
<ToggleButton value="ITALIC">
<i>I</i>
</ToggleButton>
<ToggleButton value="insert-image">
<AddAPhoto />
</ToggleButton>
<ToggleButton
value="insert-link"
disabled={editorState.getSelection().isCollapsed()}
>
<Link />
</ToggleButton>
</ToggleButtonGroup>
</Box>
<Box>
<Paper style={{ minHeight: "144px" }}>
<Box onClick={focusEditor} p={4}>
<EditorContext.Provider value={editorState}>
<Editor
editorState={editorState}
onChange={setEditorState}
placeholder={editorPlaceholder}
blockRendererFn={renderBlock}
plugins={plugins}
ref={editor}
/>
</EditorContext.Provider>
<MentionSuggestions
onSearchChange={onSearchChange}
suggestions={suggestions}
onAddMention={onAddMention}
/>
</Box>
</Paper>
</Box>
</Box>
<Box
style={{
position: "absolute",
top: selectionRect.top,
left: selectionRect.right + 12,
background: "#FFF",
display: toggleButtonGroupValue === "insert-link" ? "block" : "none"
}}
>
<TextField
variant="outlined"
InputProps={{
endAdornment: (
<InputAdornment position="start">
<IconButton
onClick={() => {
setEditorState(
draftUtils.createLinkAtSelection(editorState, anchorElUrl)
);
setToggleButtonGroupValue(null);
}}
>
<Check />
</IconButton>
</InputAdornment>
)
}}
placeholder="https://"
value={anchorElUrl}
onChange={e => setAnchorElUrl(e.target.value)}
/>
</Box>
<Box ml={3}>
<pre>
{JSON.stringify(
convertToRaw(editorState.getCurrentContent()),
null,
2
)}
</pre>
</Box>
<input
id="fileInput"
style={{ display: "none" }}
type="file"
accept="image/png,image/jpeg,image/jpg,image/gif"
onChange={event => {
const reader = new FileReader();
reader.addEventListener(
"load",
function () {
const contentStateWithEntity = editorState
.getCurrentContent()
.createEntity("IMAGE", "IMMUTABLE", { src: reader.result });
setEditorState(
AtomicBlockUtils.insertAtomicBlock(
EditorState.set(editorState, {
currentContent: contentStateWithEntity
}),
contentStateWithEntity.getLastCreatedEntityKey(),
" "
)
);
},
false
);
if (event.target.files) {
reader.readAsDataURL(
Array.prototype.slice.call(event.target.files)[0]
);
}
}}
/>
</Box>
);
} | the_stack |
import { expect } from 'chai';
import { ICheckedSelectionState, makeCheckedSelectionStore } from '../makeCheckedSelectionStore';
const getStateRecord = (state: any) => {
return state.getIn(['test']) as ICheckedSelectionState;
};
const testMakeCheckedSelectionStore = makeCheckedSelectionStore(getStateRecord, { defaultSelectionState: false });
const testMakeCheckedSelectionStoreWithDefaultSelected = makeCheckedSelectionStore(getStateRecord, { defaultSelectionState: true });
const initialState = testMakeCheckedSelectionStore.initialState;
const initialStateDefaultSelected = testMakeCheckedSelectionStoreWithDefaultSelected.initialState;
describe('makeCheckedSelectionStore reducer with not selected by default', () => {
const reducer = testMakeCheckedSelectionStore.reducer;
it('should toggle all to be selected and their default selection state to be true', () => {
const testState = reducer(initialState, testMakeCheckedSelectionStore.toggleSelectAll());
expect(testState.defaultSelectionState).to.be.true;
expect(testState.areAllSelected).to.be.true;
expect(testState.overrides.size).to.equal(0);
});
it('should toggle all to be selected and their default selection state to be true and remove all overrides', () => {
const testOverrides = new Map([
['1', true],
['2', false],
]);
const testInitialState = {...initialState, overrides: testOverrides};
const testState = reducer(testInitialState, testMakeCheckedSelectionStore.toggleSelectAll());
expect(testState.defaultSelectionState).to.be.true;
expect(testState.areAllSelected).to.be.true;
expect(testState.overrides.size).to.equal(0);
});
it('should toggle all to be not selected and their default selection state to be false', () => {
const testInitialState = {...initialState, areAllSelected: true};
const testState = reducer(testInitialState, testMakeCheckedSelectionStore.toggleSelectAll());
expect(testState.defaultSelectionState).to.be.false;
expect(testState.areAllSelected).to.be.false;
expect(testState.overrides.size).to.equal(0);
});
it('should toggle all to be not selected and their default selection state to be false and remove all overrides', () => {
const testOverrides = new Map([
['1', true],
['2', false],
]);
const testInitialState = {...initialState, overrides: testOverrides, areAllSelected: true};
const testState = reducer(testInitialState, testMakeCheckedSelectionStore.toggleSelectAll());
expect(testState.defaultSelectionState).to.be.false;
expect(testState.areAllSelected).to.be.false;
expect(testState.overrides.size).to.equal(0);
});
it('should toggle a single item and leave all are selected set as false and create an override set to true at id 1', () => {
const testState = reducer(initialState, testMakeCheckedSelectionStore.toggleSingleItem({id: '1'}));
expect(testState.areAllSelected).to.be.false;
const overrides = testState.overrides;
expect(overrides.get('1')).to.be.true;
});
it('should toggle a single item and change all are selected from true to be false and create an override set to true at id 1', () => {
const testInitialState = {...initialState, areAllSelected: true};
const testState = reducer(testInitialState, testMakeCheckedSelectionStore.toggleSingleItem({id: '1'}));
expect(testState.areAllSelected).to.be.false;
const overrides = testState.overrides;
expect(overrides.get('1')).to.be.true;
});
it('should toggle a single item and change all are selected from true to be false and create an override set to true at id 1, then toggle back off again', () => {
const testInitialState = {...initialState, areAllSelected: true};
let testState = reducer(testInitialState, testMakeCheckedSelectionStore.toggleSingleItem({id: '1'}));
expect(testState.areAllSelected).to.be.false;
const overrides = testState.overrides;
expect(overrides.get('1')).to.be.true;
testState = reducer(testState, testMakeCheckedSelectionStore.toggleSingleItem({id: '1'}));
expect(testState.areAllSelected).to.be.false;
expect(testState.overrides.size).to.equal(0);
});
it('should toggle a single item and change all are selected to be false and remove the override at id 1', () => {
const testOverrides = new Map([['1', true]]);
const testInitialState = {...initialState, overrides: testOverrides};
const testState = reducer(testInitialState, testMakeCheckedSelectionStore.toggleSingleItem({id: '1'}));
expect(testState.areAllSelected).to.be.false;
expect(testState.overrides.size).to.equal(0);
});
it('should toggle a single item and change all are selected to be false and remove the override at id 1 and leave the override at 2', () => {
const testOverrides = new Map([
['1', true],
['2', false],
]);
const testInitialState = {...initialState, overrides: testOverrides};
const testState = reducer(testInitialState, testMakeCheckedSelectionStore.toggleSingleItem({id: '1'}));
expect(testState.areAllSelected).to.be.false;
expect(testState.overrides.size).to.equal(1);
const overrides = testState.overrides;
expect(overrides.get('2')).to.be.false;
});
it('should toggle a single item and change all are selected to be false and remove the override at id 1, then toggle again and add it back', () => {
const testOverrides = new Map([['1', true]]);
const testInitialState = {...initialState, overrides: testOverrides};
let testState = reducer(testInitialState, testMakeCheckedSelectionStore.toggleSingleItem({id: '1'}));
expect(testState.areAllSelected).to.be.false;
expect(testState.overrides.size).to.equal(0);
testState = reducer(testState, testMakeCheckedSelectionStore.toggleSingleItem({id: '1'}));
expect(testState.areAllSelected).to.be.false;
const overrides = testState.overrides;
expect(overrides.get('1')).to.be.true;
});
});
describe('makeCheckedSelectionStore reducer with selected by default set to true', () => {
const reducer = testMakeCheckedSelectionStoreWithDefaultSelected.reducer;
it('should toggle all to be selected as false and their default selection state to be false', () => {
const testState = reducer(initialStateDefaultSelected, testMakeCheckedSelectionStoreWithDefaultSelected.toggleSelectAll());
expect(testState.defaultSelectionState).to.be.false;
expect(testState.areAllSelected).to.be.false;
expect(testState.overrides.size).to.equal(0);
});
it('should toggle all to be selected and their default selection state to be true and remove all overrides', () => {
const testOverrides = new Map([
['1', true],
['2', false],
]);
const testInitialState = {...initialStateDefaultSelected, overrides: testOverrides};
const testState = reducer(testInitialState, testMakeCheckedSelectionStoreWithDefaultSelected.toggleSelectAll());
expect(testState.defaultSelectionState).to.be.false;
expect(testState.areAllSelected).to.be.false;
expect(testState.overrides.size).to.equal(0);
});
it('should toggle all to be not selected and their default selection state to be false', () => {
const testInitialState = {...initialStateDefaultSelected, areAllSelected: true};
const testState = reducer(testInitialState, testMakeCheckedSelectionStoreWithDefaultSelected.toggleSelectAll());
expect(testState.defaultSelectionState).to.be.false;
expect(testState.areAllSelected).to.be.false;
expect(testState.overrides.size).to.equal(0);
});
it('should toggle all to be not selected and their default selection state to be false and remove all overrides', () => {
const testOverrides = new Map([
['1', true],
['2', false],
]);
const testInitialState = {...initialStateDefaultSelected, overrides: testOverrides, areAllSelected: true};
const testState = reducer(testInitialState, testMakeCheckedSelectionStoreWithDefaultSelected.toggleSelectAll());
expect(testState.defaultSelectionState).to.be.false;
expect(testState.areAllSelected).to.be.false;
expect(testState.overrides.size).to.equal(0);
});
it('should toggle a single item and leave are selected to be set as false and create an override set to false at id 1 then toggle it again and remove the override', () => {
let testState = reducer(initialStateDefaultSelected, testMakeCheckedSelectionStoreWithDefaultSelected.toggleSingleItem({id: '1'}));
expect(testState.defaultSelectionState).to.be.true;
expect(testState.areAllSelected).to.be.false;
const overrides = testState.overrides;
expect(
overrides.get('1'),
).to.be.false;
testState = reducer(testState, testMakeCheckedSelectionStoreWithDefaultSelected.toggleSingleItem({id: '1'}));
expect(testState.defaultSelectionState).to.be.true;
expect(testState.areAllSelected).to.be.true;
expect(testState.overrides.size).to.equal(0);
});
it('should toggle a single item and change all are selected from true to be false and create an override set to false at id 1', () => {
const testInitialState = {...initialStateDefaultSelected, areAllSelected: true};
const testState = reducer(testInitialState, testMakeCheckedSelectionStoreWithDefaultSelected.toggleSingleItem({id: '1'}));
expect(testState.defaultSelectionState).to.be.true;
expect(testState.areAllSelected).to.be.false;
const overrides = testState.overrides;
expect(
overrides.get('1'),
).to.be.false;
});
it('should toggle a single item and change all are selected to be true and remove the override at id 1', () => {
const testOverrides = new Map([['1', true]]);
const testInitialState = {...initialStateDefaultSelected, overrides: testOverrides};
const testState = reducer(testInitialState, testMakeCheckedSelectionStoreWithDefaultSelected.toggleSingleItem({id: '1'}));
expect(testState.defaultSelectionState).to.be.true;
expect(testState.areAllSelected).to.be.true;
expect(testState.overrides.size).to.equal(0);
});
});
describe('makeCheckedSelectionStore getItemCheckedState', () => {
it('should return any overrides of a given id found in state', () => {
const testOverrides = new Map([
['1', true],
['2', false],
]);
const testItemCheckedState = testMakeCheckedSelectionStore.getItemCheckedState(testOverrides, '1', false);
expect(
testItemCheckedState,
).to.equal(
true,
);
});
it('should return false if no overrides matching a given id are found and isCheckedByDefault is false', () => {
const testOverrides = new Map([
['1', true],
['2', false],
]);
const testItemCheckedState = testMakeCheckedSelectionStore.getItemCheckedState(testOverrides, '3', false);
expect(
testItemCheckedState,
).to.equal(
false,
);
});
it('should return true if no overrides matching a given id are found and isCheckedByDefault is true', () => {
const testOverrides = new Map([
['1', true],
['2', false],
]);
const testItemCheckedState = testMakeCheckedSelectionStore.getItemCheckedState(testOverrides, '3', true);
expect(
testItemCheckedState,
).to.equal(
true,
);
});
it('should return false if no overrides are provided and isCheckedByDefault is false', () => {
const testItemCheckedState = testMakeCheckedSelectionStore.getItemCheckedState(undefined, '1', false);
expect(
testItemCheckedState,
).to.equal(
false,
);
});
it('should return true if no overrides are provided and isCheckedByDefault is true', () => {
const testItemCheckedState = testMakeCheckedSelectionStore.getItemCheckedState(undefined, '1', true);
expect(
testItemCheckedState,
).to.equal(
true,
);
});
}); | the_stack |
import NetRegexes from '../../../../../resources/netregexes';
import Outputs from '../../../../../resources/outputs';
import { callOverlayHandler } from '../../../../../resources/overlay_plugin_api';
import Util from '../../../../../resources/util';
import ZoneId from '../../../../../resources/zone_id';
import { RaidbossData } from '../../../../../types/data';
import { PluginCombatantState } from '../../../../../types/event';
import { TriggerSet } from '../../../../../types/trigger';
export interface Data extends RaidbossData {
converter: boolean;
diveCounter: number;
slamLevis: PluginCombatantState[];
}
// TODO: we could consider a timeline trigger for the Tidal Roar raidwide,
// but it barely does 25% health, has no startsUsing, and the timeline for
// this fight is not reliable enough to use.
// TODO: it'd be nice to call out the dives too, but there is no log line
// or combatant in the right place until ~4.5s after the nameplate toggles.
// This is about 1-2s after the splash appears, and so feels really late.
// Unfortunately the dives also have multiple combatants in plausible
// positions (+/-7, +/-20) and so more work would need to be done to tell
// them apart.
const triggerSet: TriggerSet<Data> = {
zoneId: ZoneId.TheWhorleaterExtreme,
timelineFile: 'levi-ex.txt',
initData: () => {
return {
converter: false,
diveCounter: 0,
slamLevis: [],
};
},
triggers: [
{
id: 'LeviEx Dive Counter Tidal Wave Reset',
type: 'Ability',
netRegex: NetRegexes.ability({ source: 'Leviathan', id: '82E', capture: false }),
netRegexDe: NetRegexes.ability({ source: 'Leviathan', id: '82E', capture: false }),
netRegexFr: NetRegexes.ability({ source: 'Léviathan', id: '82E', capture: false }),
netRegexJa: NetRegexes.ability({ source: 'リヴァイアサン', id: '82E', capture: false }),
netRegexCn: NetRegexes.ability({ source: '利维亚桑', id: '82E', capture: false }),
netRegexKo: NetRegexes.ability({ source: '리바이어선', id: '82E', capture: false }),
run: (data) => {
// There's always a slam after Tidal Wave.
data.diveCounter = 1;
// If you are running this unsynced and don't hit the button,
// then prevent "Hit the Button" calls on future dives.
data.converter = false;
},
},
{
id: 'LeviEx Dive Counter Body Slam Reset',
type: 'Ability',
netRegex: NetRegexes.ability({ source: 'Leviathan', id: '82A', capture: false }),
netRegexDe: NetRegexes.ability({ source: 'Leviathan', id: '82A', capture: false }),
netRegexFr: NetRegexes.ability({ source: 'Léviathan', id: '82A', capture: false }),
netRegexJa: NetRegexes.ability({ source: 'リヴァイアサン', id: '82A', capture: false }),
netRegexCn: NetRegexes.ability({ source: '利维亚桑', id: '82A', capture: false }),
netRegexKo: NetRegexes.ability({ source: '리바이어선', id: '82A', capture: false }),
// Redundant, but this will keep things on track if anything goes awry.
run: (data) => data.diveCounter = 1,
},
{
id: 'LeviEx Dive Counter Wave Spume Adjust',
type: 'AddedCombatant',
netRegex: NetRegexes.addedCombatant({ name: 'Wave Spume', capture: false }),
netRegexDe: NetRegexes.addedCombatant({ name: 'Gischtwelle', capture: false }),
netRegexFr: NetRegexes.addedCombatant({ name: 'Écume Ondulante', capture: false }),
netRegexJa: NetRegexes.addedCombatant({ name: 'ウェイブ・スピューム', capture: false }),
netRegexCn: NetRegexes.addedCombatant({ name: '巨浪泡沫', capture: false }),
netRegexKo: NetRegexes.addedCombatant({ name: '파도치는 물거품', capture: false }),
suppressSeconds: 5,
// Usually the pattern is slam / dive / dive / slam, but after wave spumes appear,
// there is a single dive then a slam. Adjust for this one-off case here.
run: (data) => data.diveCounter = 2,
},
{
id: 'LeviEx Slam Location',
type: 'NameToggle',
netRegex: NetRegexes.nameToggle({ name: 'Leviathan', toggle: '00', capture: false }),
netRegexDe: NetRegexes.nameToggle({ name: 'Leviathan', toggle: '00', capture: false }),
netRegexFr: NetRegexes.nameToggle({ name: 'Léviathan', toggle: '00', capture: false }),
netRegexJa: NetRegexes.nameToggle({ name: 'リヴァイアサン', toggle: '00', capture: false }),
netRegexCn: NetRegexes.nameToggle({ name: '利维亚桑', toggle: '00', capture: false }),
netRegexKo: NetRegexes.nameToggle({ name: '리바이어선', toggle: '00', capture: false }),
condition: (data) => {
return ++data.diveCounter % 3 === 1;
},
// Actor moves between 4.6s and 4.7s; add a tiny bit of time for certainty.
delaySeconds: 5,
promise: async (data) => {
const callData = await callOverlayHandler({
call: 'getCombatants',
});
if (!callData || !callData.combatants || !callData.combatants.length) {
console.error('Dive: failed to get combatants: ${JSON.stringify(callData)}');
return;
}
// This is the real levi, according to hp.
data.slamLevis = callData.combatants.filter((c) => c.BNpcID === 2802);
},
alertText: (data, _matches, output) => {
// Slams happen at +/-~14.6 +/-~13.
const filtered = data.slamLevis.filter((c) => {
const offsetX = Math.abs(Math.abs(c.PosX) - 14.6);
const offsetY = Math.abs(Math.abs(c.PosY) - 13);
return offsetX < 1 && offsetY < 1;
});
if (filtered.length !== 1)
return;
const levi = filtered[0];
if (levi && levi.PosY > 0)
return output.north!();
return output.south!();
},
outputStrings: {
north: Outputs.north,
south: Outputs.south,
},
},
{
id: 'LeviEx Veil of the Whorl',
type: 'Ability',
netRegex: NetRegexes.ability({ source: 'Leviathan', id: '875', capture: false }),
netRegexDe: NetRegexes.ability({ source: 'Leviathan', id: '875', capture: false }),
netRegexFr: NetRegexes.ability({ source: 'Léviathan', id: '875', capture: false }),
netRegexJa: NetRegexes.ability({ source: 'リヴァイアサン', id: '875', capture: false }),
netRegexCn: NetRegexes.ability({ source: '利维亚桑', id: '875', capture: false }),
netRegexKo: NetRegexes.ability({ source: '리바이어선', id: '875', capture: false }),
condition: (data) => Util.isCasterDpsJob(data.job) || Util.isHealerJob(data.job),
suppressSeconds: 9999,
infoText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Attack Head Only',
de: 'Nur den Kopf angreifen',
fr: 'Attaquez seulement la tête',
ja: '頭だけに攻撃',
cn: '攻击头部',
ko: '머리만 공격하기',
},
},
},
{
id: 'LeviEx Mantle of the Whorl',
type: 'Ability',
netRegex: NetRegexes.ability({ source: 'Leviathan\'s Tail', id: '874', capture: false }),
netRegexDe: NetRegexes.ability({ source: 'Leviathans Schwanz', id: '874', capture: false }),
netRegexFr: NetRegexes.ability({ source: 'Queue De Léviathan', id: '874', capture: false }),
netRegexJa: NetRegexes.ability({ source: 'リヴァイアサン・テール', id: '874', capture: false }),
netRegexCn: NetRegexes.ability({ source: '利维亚桑的尾巴', id: '874', capture: false }),
netRegexKo: NetRegexes.ability({ source: '리바이어선 꼬리', id: '874', capture: false }),
condition: (data) => Util.isRangedDpsJob(data.job),
suppressSeconds: 9999,
infoText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Attack Tail Only',
de: 'Nur den Schwanz angreifen',
fr: 'Attaquez seulement la queue',
ja: 'テールだけに攻撃',
cn: '攻击尾巴',
ko: '꼬리만 공격하기',
},
},
},
{
id: 'LeviEx Wavespine Sahagin Add',
type: 'AddedCombatant',
netRegex: NetRegexes.addedCombatant({ name: 'Wavespine Sahagin', capture: false }),
netRegexDe: NetRegexes.addedCombatant({ name: 'Wellendorn-Sahagin', capture: false }),
netRegexFr: NetRegexes.addedCombatant({ name: 'Sahuagin Épine-Du-Ressac', capture: false }),
netRegexJa: NetRegexes.addedCombatant({ name: 'ウェイブスパイン・サハギン', capture: false }),
netRegexCn: NetRegexes.addedCombatant({ name: '波棘鱼人', capture: false }),
netRegexKo: NetRegexes.addedCombatant({ name: '물결등뼈 사하긴', capture: false }),
suppressSeconds: 5,
infoText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: Outputs.killAdds,
},
},
{
id: 'LeviEx Wavetooth Sahagin Add',
type: 'AddedCombatant',
netRegex: NetRegexes.addedCombatant({ name: 'Wavetooth Sahagin', capture: false }),
netRegexDe: NetRegexes.addedCombatant({ name: 'Wellenzahn-Sahagin', capture: false }),
netRegexFr: NetRegexes.addedCombatant({ name: 'Sahuagin Dent-Du-Ressac', capture: false }),
netRegexJa: NetRegexes.addedCombatant({ name: 'ウェイブトゥース・サハギン', capture: false }),
netRegexCn: NetRegexes.addedCombatant({ name: '波齿鱼人', capture: false }),
netRegexKo: NetRegexes.addedCombatant({ name: '물결이빨 사하긴', capture: false }),
infoText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Kill Wavetooth Add',
de: 'Besiege Wellenzahn Add',
fr: 'Tuez l\'add Dent-du-ressac',
ja: 'ウェイブトゥース・サハギンに攻撃',
cn: '优先击杀波齿鱼人',
ko: '물결이빨 사하긴 처치',
},
},
},
{
id: 'LeviEx Wavetooth Sahagin Stun',
type: 'AddedCombatant',
netRegex: NetRegexes.addedCombatant({ name: 'Wavetooth Sahagin' }),
netRegexDe: NetRegexes.addedCombatant({ name: 'Wellenzahn-Sahagin' }),
netRegexFr: NetRegexes.addedCombatant({ name: 'Sahuagin Dent-Du-Ressac' }),
netRegexJa: NetRegexes.addedCombatant({ name: 'ウェイブトゥース・サハギン' }),
netRegexCn: NetRegexes.addedCombatant({ name: '波齿鱼人' }),
netRegexKo: NetRegexes.addedCombatant({ name: '물결이빨 사하긴' }),
condition: (data) => data.CanStun(),
delaySeconds: 5,
alertText: (_data, matches, output) => output.text!({ name: matches.name }),
outputStrings: {
text: Outputs.stunTarget,
},
},
{
id: 'LeviEx Gyre Spume',
type: 'AddedCombatant',
netRegex: NetRegexes.addedCombatant({ name: 'Gyre Spume', capture: false }),
netRegexDe: NetRegexes.addedCombatant({ name: 'Gischtblase', capture: false }),
netRegexFr: NetRegexes.addedCombatant({ name: 'Écume Concentrique', capture: false }),
netRegexJa: NetRegexes.addedCombatant({ name: 'ジャイヤ・スピューム', capture: false }),
netRegexCn: NetRegexes.addedCombatant({ name: '游涡泡沫', capture: false }),
netRegexKo: NetRegexes.addedCombatant({ name: '소용돌이치는 물거품', capture: false }),
suppressSeconds: 5,
infoText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Kill Gyre Spumes',
de: 'Besiege Gischtblase',
fr: 'Tuez les écumes concentriques',
ja: 'ジャイヤ・スピュームに攻撃',
cn: '打黄泡泡',
ko: '노랑 물거품 처치',
},
},
},
{
id: 'LeviEx Wave Spume',
type: 'AddedCombatant',
netRegex: NetRegexes.addedCombatant({ name: 'Wave Spume', capture: false }),
netRegexDe: NetRegexes.addedCombatant({ name: 'Gischtwelle', capture: false }),
netRegexFr: NetRegexes.addedCombatant({ name: 'Écume Ondulante', capture: false }),
netRegexJa: NetRegexes.addedCombatant({ name: 'ウェイブ・スピューム', capture: false }),
netRegexCn: NetRegexes.addedCombatant({ name: '巨浪泡沫', capture: false }),
netRegexKo: NetRegexes.addedCombatant({ name: '파도치는 물거품', capture: false }),
suppressSeconds: 5,
infoText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Wave Spume Adds',
de: 'Gischtwelle Adds',
fr: 'Tuez les écumes ondulantes',
ja: 'ウェイブ・スピューム出現',
cn: '蓝泡泡出现',
ko: '파랑 물거품 출현',
},
},
},
{
id: 'LeviEx Wave Spume Explosion',
type: 'AddedCombatant',
netRegex: NetRegexes.addedCombatant({ name: 'Wave Spume', capture: false }),
netRegexDe: NetRegexes.addedCombatant({ name: 'Gischtwelle', capture: false }),
netRegexFr: NetRegexes.addedCombatant({ name: 'Écume Ondulante', capture: false }),
netRegexJa: NetRegexes.addedCombatant({ name: 'ウェイブ・スピューム', capture: false }),
netRegexCn: NetRegexes.addedCombatant({ name: '巨浪泡沫', capture: false }),
netRegexKo: NetRegexes.addedCombatant({ name: '파도치는 물거품', capture: false }),
// ~35.2 seconds from added combatant until :Aqua Burst:888: explosion.
// Tell everybody because not much else going on in this fight,
// and other people need to get away.
delaySeconds: 30,
suppressSeconds: 5,
alertText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Burst Soon',
de: 'Gischtwelle platzen gleich',
fr: 'Burst bientôt',
ja: 'まもなく爆発',
cn: '黄泡泡即将爆炸',
ko: '물거품 폭발',
},
},
},
{
id: 'LeviEx Elemental Converter',
type: 'NameToggle',
netRegex: NetRegexes.nameToggle({ name: 'Elemental Converter' }),
netRegexDe: NetRegexes.nameToggle({ name: 'Elementarumwandler' }),
netRegexFr: NetRegexes.nameToggle({ name: 'Activateur De La Barrière' }),
netRegexJa: NetRegexes.nameToggle({ name: '魔法障壁発動器' }),
netRegexCn: NetRegexes.nameToggle({ name: '魔法障壁发动器' }),
netRegexKo: NetRegexes.nameToggle({ name: '마법 장벽 발동기' }),
run: (data, matches) => data.converter = !!parseInt(matches.toggle),
},
{
id: 'LeviEx Hit The Button',
type: 'NameToggle',
netRegex: NetRegexes.nameToggle({ name: 'Leviathan', toggle: '00', capture: false }),
netRegexDe: NetRegexes.nameToggle({ name: 'Leviathan', toggle: '00', capture: false }),
netRegexFr: NetRegexes.nameToggle({ name: 'Léviathan', toggle: '00', capture: false }),
netRegexJa: NetRegexes.nameToggle({ name: 'リヴァイアサン', toggle: '00', capture: false }),
netRegexCn: NetRegexes.nameToggle({ name: '利维亚桑', toggle: '00', capture: false }),
netRegexKo: NetRegexes.nameToggle({ name: '리바이어선', toggle: '00', capture: false }),
// The best way to know if it's time to hit the button is if the converter is ready.
// I think this is not true for hard mode, but is true (fingers crossed) for extreme.
condition: (data) => data.converter,
// Some delay for safety, as the button can be hit too early.
delaySeconds: 3.5,
suppressSeconds: 30,
alertText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Hit The Button!',
de: 'Mit Elementarumwandler interagieren!',
fr: 'Activez la barrière !',
ja: '魔法障壁を発動',
cn: '打开开关!',
ko: '장벽 발동!',
},
},
},
],
timelineReplace: [
{
'locale': 'de',
'replaceSync': {
'Elemental Converter': 'Elementarumwandler',
'Leviathan(?!\'s)': 'Leviathan',
'Leviathan\'s Tail': 'Leviathans Schwanz',
'Gyre Spume': 'Gischtblase',
'Wave Spume': 'Gischtwelle',
'Wavetooth Sahagin': 'Wellenzahn-Sahagin',
'Wavespine Sahagin': 'Wellendorn-Sahagin',
},
'replaceText': {
'Aqua Breath': 'Aqua-Atem',
'Aqua Burst': 'Aquatischer Knall',
'Body Slam': 'Bugwelle',
'Briny Veil': 'Wasserspiegelung',
'Dread Tide': 'Hydrophobie',
'Grand Fall': 'Wasserfall',
'Gyre Spume': 'Gischtblase',
'Mantle Of The Whorl': 'Wogenmantel',
'Spinning Dive': 'Drehsprung',
'Tail Whip': 'Schwanzpeitsche',
'Tidal Roar': 'Schrei der Gezeiten',
'Tidal Wave': 'Flutwelle',
'Veil Of The Whorl': 'Wogenschleier',
'Waterspout': 'Wasserhose',
'Wave Spume': 'Gischtwelle',
'Wavespine Sahagin': 'Wellendorn-Sahagin',
'Wavetooth Sahagin': 'Wellenzahn-Sahagin',
},
},
{
'locale': 'fr',
'replaceSync': {
'Elemental Converter': 'activateur de la barrière',
'Leviathan(?!\'s)': 'Léviathan',
'Leviathan\'s Tail': 'queue de Léviathan',
'Gyre Spume': 'écume concentrique',
'Wave Spume': 'écume ondulante',
'Wavetooth Sahagin': 'Sahuagin dent-du-ressac',
'Wavespine Sahagin': 'Sahuagin épine-du-ressac',
},
'replaceText': {
'\\(NW\\)': '(NO)',
'Aqua Breath': 'Aquasouffle',
'Aqua Burst': 'Explosion aquatique',
'Body Slam': 'Charge physique',
'Briny Veil': 'Miroir d\'eau',
'Dread Tide': 'Onde terrifiante',
'Grand Fall': 'Chute grandiose',
'Gyre Spume': 'écume concentrique',
'Mantle Of The Whorl': 'Manteau du Déchaîneur',
'Spinning Dive': 'Piqué tournant',
'Tail Whip': 'Coup caudal',
'Tidal Roar': 'Vague rugissante',
'Tidal Wave': 'Raz-de-marée',
'Veil Of The Whorl': 'Voile du Déchaîneur',
'Waterspout': 'Inondation',
'Wave Spume': 'écume ondulante',
'Wavespine Sahagin': 'Sahuagin épine-du-ressac',
'Wavetooth Sahagin': 'Sahuagin dent-du-ressac',
},
},
{
'locale': 'ja',
'replaceSync': {
'Elemental Converter': '魔法障壁発動器',
'Leviathan(?!\'s)': 'リヴァイアサン',
'Leviathan\'s Tail': 'リヴァイアサン・テール',
'Gyre Spume': 'ジャイヤ・スピューム',
'Wave Spume': 'ウェイブ・スピューム',
'Wavetooth Sahagin': 'ウェイブトゥース・サハギン',
'Wavespine Sahagin': 'ウェイブスパイン・サハギン',
},
'replaceText': {
'Aqua Breath': 'アクアブレス',
'Aqua Burst': 'アクアバースト',
'Body Slam': 'ボディスラム',
'Briny Veil': 'ウォーターミラー',
'Dread Tide': 'ドレッドウォーター',
'Grand Fall': 'グランドフォール',
'Gyre Spume': 'ジャイヤ・スピューム',
'Mantle Of The Whorl': '水神のマント',
'Spinning Dive': 'スピニングダイブ',
'Tail Whip': 'テールウィップ',
'Tidal Roar': 'タイダルロア',
'Tidal Wave': 'タイダルウェイブ',
'Veil Of The Whorl': '水神のヴェール',
'Waterspout': 'オーバーフラッド',
'Wave Spume': 'ウェイブ・スピューム',
'Wavespine Sahagin': 'ウェイブスパイン・サハギン',
'Wavetooth Sahagin': 'ウェイブトゥース・サハギン',
},
},
{
'locale': 'cn',
'replaceSync': {
'Elemental Converter': '魔法障壁发动器',
'Leviathan(?!\'s)': '利维亚桑',
'Leviathan\'s Tail': '利维亚桑的尾巴',
'Gyre Spume': '游涡泡沫',
'Wave Spume': '巨浪泡沫',
'Wavetooth Sahagin': '波齿鱼人',
'Wavespine Sahagin': '波棘鱼人',
},
'replaceText': {
'Aqua Breath': '水流吐息',
'Aqua Burst': '流水爆发',
'Body Slam': '猛撞',
'Briny Veil': '海水镜面',
'Dread Tide': '恐慌潮水',
'Grand Fall': '九天落水',
'Gyre Spume': '游涡泡沫',
'Mantle Of The Whorl': '水神的披风',
'Spinning Dive': '旋转下潜',
'Tail Whip': '扫尾',
'Tidal Roar': '怒潮咆哮',
'Tidal Wave': '巨浪',
'Veil Of The Whorl': '水神的面纱',
'Waterspout': '海龙卷',
'Wave Spume': '巨浪泡沫',
'Wavespine Sahagin': '波棘鱼人',
'Wavetooth Sahagin': '波齿鱼人',
},
},
{
'locale': 'ko',
'replaceSync': {
'Elemental Converter': '마법 장벽 발동기',
'Leviathan(?!\'s)': '리바이어선',
'Leviathan\'s Tail': '리바이어선 꼬리',
'Gyre Spume': '소용돌이치는 물거품',
'Wave Spume': '파도치는 물거품',
'Wavetooth Sahagin': '물결이빨 사하긴',
'Wavespine Sahagin': '물결등뼈 사하긴',
},
'replaceText': {
'Aqua Breath': '물의 숨결',
'Aqua Burst': '물방울 폭발',
'Body Slam': '몸통 박기',
'Briny Veil': '물의 거울',
'Dread Tide': '공포의 물결',
'Grand Fall': '강우',
'Gyre Spume': '소용돌이치는 물거품',
'Mantle Of The Whorl': '수신의 망토',
'Spinning Dive': '고속 돌진',
'Tail Whip': '꼬리 채찍',
'Tidal Roar': '바다의 포효',
'Tidal Wave': '해일',
'Veil Of The Whorl': '수신의 장막',
'Waterspout': '물폭풍',
'Wave Spume': '파도치는 물거품',
'Wavespine Sahagin': '물결등뼈 사하긴',
'Wavetooth Sahagin': '물결이빨 사하긴',
},
},
],
};
export default triggerSet; | the_stack |
import * as vscode from "vscode";
import * as child_process from "child_process";
import * as path from "path";
import * as fs from "fs";
import * as url from "url";
import * as simulate from "cordova-simulate";
import * as os from "os";
import * as io from "socket.io-client";
import * as execa from "execa";
import * as browserHelper from "vscode-js-debug-browsers";
import { LoggingDebugSession, OutputEvent, logger, Logger, ErrorDestination, InitializedEvent } from "vscode-debugadapter";
import { DebugProtocol } from "vscode-debugprotocol";
import { ICordovaLaunchRequestArgs, ICordovaAttachRequestArgs } from "./requestArgs";
import { JsDebugConfigAdapter } from "./jsDebugConfigAdapter";
import * as elementtree from "elementtree";
import { generateRandomPortNumber, retryAsync, promiseGet, findFileInFolderHierarchy, isNullOrUndefined } from "../utils/extensionHelper";
import { TelemetryHelper, ISimulateTelemetryProperties, TelemetryGenerator } from "../utils/telemetryHelper";
import { CordovaProjectHelper, ProjectType } from "../utils/cordovaProjectHelper";
import { Telemetry } from "../utils/telemetry";
import { execCommand, cordovaRunCommand, killChildProcess, cordovaStartCommand } from "./extension";
import { CordovaCDPProxy } from "./cdp-proxy/cordovaCDPProxy";
import { SimulationInfo } from "../common/simulationInfo";
import { settingsHome } from "../utils/settingsHelper";
import { DeferredPromise } from "../common/node/promise";
import { SimulateHelper } from "../utils/simulateHelper";
import { LogLevel } from "../utils/log/logHelper";
import { CordovaIosDeviceLauncher } from "./cordovaIosDeviceLauncher";
import { CordovaWorkspaceManager } from "../extension/cordovaWorkspaceManager";
import { CordovaSessionManager } from "../extension/cordovaSessionManager";
import { SourcemapPathTransformer } from "./cdp-proxy/sourcemapPathTransformer";
import { CordovaSession, CordovaSessionStatus } from "./debugSessionWrapper";
import * as nls from "vscode-nls";
import { NodeVersionHelper } from "../utils/nodeVersionHelper";
import { AdbHelper } from "../utils/android/adb";
import { AndroidTargetManager, AndroidTarget } from "../utils/android/androidTargetManager";
import { IOSTargetManager, IOSTarget } from "../utils/ios/iOSTargetManager";
import { LaunchScenariosManager } from "../utils/launchScenariosManager";
import { OutputChannelLogger } from "../utils/log/outputChannelLogger";
nls.config({ messageFormat: nls.MessageFormat.bundle, bundleFormat: nls.BundleFormat.standalone })();
const localize = nls.loadMessageBundle();
const ANDROID_MANIFEST_PATH = path.join("platforms", "android", "AndroidManifest.xml");
const ANDROID_MANIFEST_PATH_8 = path.join("platforms", "android", "app", "src", "main", "AndroidManifest.xml");
// `RSIDZTW<NL` are process status codes (as per `man ps`), skip them
const PS_FIELDS_SPLITTER_RE = /\s+(?:[RSIDZTW<NL]\s+)?/;
export const CANCELLATION_ERROR_NAME = "tokenCanceled";
export enum TargetType {
Emulator = "emulator",
Device = "device",
Chrome = "chrome",
Edge = "edge",
}
export enum PwaDebugType {
Node = "pwa-node",
Chrome = "pwa-chrome",
}
export enum PlatformType {
Android = "android",
IOS = "ios",
Windows = "windows",
Serve = "serve",
AmazonFireos = "amazon_fireos",
Blackberry10 = "blackberry10",
Firefoxos = "firefoxos",
Ubuntu = "ubuntu",
Wp8 = "wp8",
Browser = "browser",
}
/**
* Enum of possible statuses of debug session
*/
export enum DebugSessionStatus {
/** The session is active */
Active,
/** The session is processing attachment after failed attempt */
Reattaching,
/** Debugger attached to the app */
Attached,
/** The session is handling disconnect request now */
Stopping,
/** The session is stopped */
Stopped,
/** Failed to attach to the app */
AttachFailed,
}
export type DebugConsoleLogger = (message: string, error?: boolean | string) => void;
interface IOSProcessedParams {
iOSVersion: string;
iOSAppPackagePath: string;
webSocketDebuggerUrl: string;
ionicDevServerUrl?: string;
}
interface WebviewData {
devtoolsFrontendUrl: string;
title: string;
url: string;
webSocketDebuggerUrl: string;
}
export class CordovaDebugSession extends LoggingDebugSession {
private static CHROME_DATA_DIR = "chrome_sandbox_dir"; // The directory to use for the sandboxed Chrome instance that gets launched to debug the app
private static NO_LIVERELOAD_WARNING = localize("IonicLiveReloadIsOnlySupportedForIonic1", "Warning: Ionic live reload is currently only supported for Ionic 1 projects. Continuing deployment without Ionic live reload...");
private static pidofNotFoundError = localize("pidofNotFound", "/system/bin/sh: pidof: not found");
private readonly cdpProxyPort: number;
private readonly cdpProxyHostAddress: string;
private readonly stopCommand: string;
private readonly pwaSessionName: PwaDebugType;
private workspaceManager: CordovaWorkspaceManager;
private outputLogger: DebugConsoleLogger;
private adbPortForwardingInfo: { targetDevice: string, port: number };
private ionicLivereloadProcess: child_process.ChildProcess;
private ionicDevServerUrls: string[];
private simulateDebugHost: SocketIOClient.Socket;
private telemetryInitialized: boolean;
private attachedDeferred: DeferredPromise<void>;
private cdpProxyLogLevel: LogLevel;
private jsDebugConfigAdapter: JsDebugConfigAdapter;
private isSettingsInitialized: boolean; // used to prevent parameters reinitialization when attach is called from launch function
private cordovaCdpProxy: CordovaCDPProxy | null;
private browserProc: child_process.ChildProcess;
private onDidTerminateDebugSessionHandler: vscode.Disposable;
private cancellationTokenSource: vscode.CancellationTokenSource;
private vsCodeDebugSession: vscode.DebugSession;
private iOSTargetManager: IOSTargetManager;
private debugSessionStatus: DebugSessionStatus;
private cdpProxyErrorHandlerDescriptor?: vscode.Disposable;
private attachRetryCount: number;
private setChromeExitTypeNormal?: () => void;
constructor(
private cordovaSession: CordovaSession,
private sessionManager: CordovaSessionManager
) {
super();
// constants definition
this.cdpProxyPort = generateRandomPortNumber();
this.cancellationTokenSource = new vscode.CancellationTokenSource();
this.cdpProxyHostAddress = "127.0.0.1"; // localhost
this.stopCommand = "workbench.action.debug.stop"; // the command which simulates a click on the "Stop" button
this.vsCodeDebugSession = cordovaSession.getVSCodeDebugSession();
this.debugSessionStatus = DebugSessionStatus.Active;
this.attachRetryCount = 2;
if (this.vsCodeDebugSession.configuration.platform === PlatformType.IOS
&& !SimulateHelper.isSimulate({
target: this.vsCodeDebugSession.configuration.target,
simulatePort: this.vsCodeDebugSession.configuration.simulatePort,
})
) {
this.pwaSessionName = PwaDebugType.Node; // the name of Node debug session created by js-debug extension
} else {
this.pwaSessionName = PwaDebugType.Chrome; // the name of Chrome debug session created by js-debug extension
}
// variables definition
this.cordovaCdpProxy = null;
this.telemetryInitialized = false;
this.jsDebugConfigAdapter = new JsDebugConfigAdapter();
this.iOSTargetManager = new IOSTargetManager();
this.onDidTerminateDebugSessionHandler = vscode.debug.onDidTerminateDebugSession(
this.handleTerminateDebugSession.bind(this)
);
this.outputLogger = (message: string, error?: boolean | string) => {
let category = "console";
if (error === true) {
category = "stderr";
}
if (typeof error === "string") {
category = error;
}
let newLine = "\n";
if (category === "stdout" || category === "stderr") {
newLine = "";
}
this.sendEvent(new OutputEvent(message + newLine, category));
};
this.attachedDeferred = new DeferredPromise<void>();
}
/**
* Target type for telemetry
*/
private static getTargetType(target: string): string {
if (/emulator/i.test(target)) {
return TargetType.Emulator;
}
if (/chrom/i.test(target)) {
return TargetType.Chrome;
}
return TargetType.Device;
}
protected initializeRequest(response: DebugProtocol.InitializeResponse, args: DebugProtocol.InitializeRequestArguments): void {
// Support default breakpoints filters for exceptions
response.body.exceptionBreakpointFilters = [
{
filter: "all",
label: "Caught Exceptions",
default: false,
},
{
filter: "uncaught",
label: "Uncaught Exceptions",
default: false,
}
];
this.sendResponse(response);
// since this debug adapter can accept configuration requests like 'setBreakpoint' at any time,
// we request them early by sending an 'initializeRequest' to the frontend.
// The frontend will end the configuration sequence by calling 'configurationDone' request.
this.sendEvent(new InitializedEvent());
}
protected launchRequest(response: DebugProtocol.LaunchResponse, launchArgs: ICordovaLaunchRequestArgs, request?: DebugProtocol.Request): Promise<void> {
return new Promise<void>((resolve, reject) => {
if (isNullOrUndefined(launchArgs.cwd)) {
reject(new Error(localize("CwdUndefined", "Launch argument 'cwd' is undefined, please add it to your launch.json. Example: 'cwd': '${workspaceFolder}' to point to your current working directory.")));
}
return this.initializeTelemetry(launchArgs.cwd)
.then(() => {
this.initializeSettings(launchArgs);
})
.then(() => TelemetryHelper.generate("launch", (generator) => {
launchArgs.port = launchArgs.port || 9222;
if (!launchArgs.target) {
if (launchArgs.platform === PlatformType.Browser) {
launchArgs.target = "chrome";
} else {
launchArgs.target = TargetType.Emulator;
}
this.outputLogger(`Parameter target is not set - ${launchArgs.target} will be used`);
}
generator.add("target", CordovaDebugSession.getTargetType(launchArgs.target), false);
if (launchArgs.cwd === null) {
throw new Error(localize("CurrentCWDDoesntContainACordovaProject", "Current working directory doesn't contain a Cordova project. Please open a Cordova project as a workspace root and try again."));
}
launchArgs.timeout = launchArgs.attachTimeout;
let platform = launchArgs.platform && launchArgs.platform.toLowerCase();
TelemetryHelper.sendPluginsList(launchArgs.cwd, CordovaProjectHelper.getInstalledPlugins(launchArgs.cwd));
return Promise.all([
TelemetryHelper.determineProjectTypes(launchArgs.cwd),
this.workspaceManager.getRunArguments(launchArgs.cwd),
this.workspaceManager.getCordovaExecutable(launchArgs.cwd),
])
.then(([projectType, runArguments, cordovaExecutable]) => {
launchArgs.cordovaExecutable = launchArgs.cordovaExecutable || cordovaExecutable;
launchArgs.allEnv = CordovaProjectHelper.getEnvArgument(launchArgs);
generator.add("projectType", TelemetryHelper.prepareProjectTypesTelemetry(projectType), false);
this.outputLogger(localize("LaunchingForPlatform", "Launching for {0} (This may take a while)...", platform));
switch (platform) {
case PlatformType.Android:
generator.add("platform", platform, false);
if (SimulateHelper.isSimulateTarget(launchArgs.target)) {
return this.launchSimulate(launchArgs, projectType, generator);
} else {
return this.launchAndroid(launchArgs, projectType, runArguments);
}
case PlatformType.IOS:
generator.add("platform", platform, false);
if (SimulateHelper.isSimulateTarget(launchArgs.target)) {
return this.launchSimulate(launchArgs, projectType, generator);
} else {
return this.launchIos(launchArgs, projectType, runArguments);
}
case PlatformType.Windows:
generator.add("platform", platform, false);
if (SimulateHelper.isSimulateTarget(launchArgs.target)) {
return this.launchSimulate(launchArgs, projectType, generator);
} else {
throw new Error(`Debugging ${platform} platform is not supported.`);
}
case PlatformType.Serve:
generator.add("platform", platform, false);
return this.launchServe(launchArgs, projectType, runArguments);
// https://github.com/apache/cordova-serve/blob/4ad258947c0e347ad5c0f20d3b48e3125eb24111/src/util.js#L27-L37
case PlatformType.AmazonFireos:
case PlatformType.Blackberry10:
case PlatformType.Firefoxos:
case PlatformType.Ubuntu:
case PlatformType.Wp8:
case PlatformType.Browser:
generator.add("platform", platform, false);
return this.launchSimulate(launchArgs, projectType, generator);
default:
generator.add("unknownPlatform", platform, true);
throw new Error(localize("UnknownPlatform", "Unknown Platform: {0}", platform));
}
})
.catch((err) => {
this.outputLogger(err.message || err, true);
return this.cleanUp().then(() => {
throw err;
});
})
.then(() => {
// For the browser platforms, we call super.launch(), which already attaches. For other platforms, attach here
if (platform !== PlatformType.Serve && platform !== PlatformType.Browser && !SimulateHelper.isSimulateTarget(launchArgs.target)) {
return this.vsCodeDebugSession.customRequest("attach", launchArgs);
}
});
})
.then(() => {
this.sendResponse(response);
this.cordovaSession.setStatus(CordovaSessionStatus.Activated);
resolve();
}))
.catch(err => reject(err));
})
.catch(err => this.terminateWithErrorResponse(err, response));
}
protected attachRequest(response: DebugProtocol.AttachResponse, attachArgs: ICordovaAttachRequestArgs, request?: DebugProtocol.Request): Promise<void> {
return this.doAttach(attachArgs)
.then(() => {
this.attachedDeferred.resolve();
this.sendResponse(response);
this.cordovaSession.setStatus(CordovaSessionStatus.Activated);
})
.catch(err => {
return this.cleanUp()
.finally(() => {
this.terminateWithErrorResponse(err, response);
});
});
}
protected doAttach(attachArgs: ICordovaAttachRequestArgs): Promise<void> {
return new Promise<void>((resolve, reject) => this.initializeTelemetry(attachArgs.cwd)
.then(() => {
this.initializeSettings(attachArgs);
})
.then(() => TelemetryHelper.generate("attach", (generator) => {
attachArgs.port = attachArgs.port || 9222;
attachArgs.target = attachArgs.target || TargetType.Emulator;
generator.add("target", CordovaDebugSession.getTargetType(attachArgs.target), false);
attachArgs.timeout = attachArgs.attachTimeout;
let platform = attachArgs.platform && attachArgs.platform.toLowerCase();
let target = attachArgs.target && attachArgs.target.toLowerCase();
TelemetryHelper.sendPluginsList(attachArgs.cwd, CordovaProjectHelper.getInstalledPlugins(attachArgs.cwd));
return TelemetryHelper.determineProjectTypes(attachArgs.cwd)
.then((projectType) => {
let sourcemapPathTransformer = new SourcemapPathTransformer(attachArgs, projectType);
this.cordovaCdpProxy = new CordovaCDPProxy(
this.cdpProxyHostAddress,
this.cdpProxyPort,
sourcemapPathTransformer,
projectType,
attachArgs
);
this.cordovaCdpProxy.setApplicationTargetPort(attachArgs.port);
generator.add("projectType", TelemetryHelper.prepareProjectTypesTelemetry(projectType), false);
return this.cordovaCdpProxy.createServer(this.cdpProxyLogLevel, this.cancellationTokenSource.token);
})
.then(() => {
if ((platform === PlatformType.Android || platform === PlatformType.IOS) && !SimulateHelper.isSimulateTarget(target)) {
this.outputLogger(localize("AttachingToPlatform", "Attaching to {0}", platform));
switch (platform) {
case PlatformType.Android:
generator.add("platform", platform, false);
return this.attachAndroid(attachArgs);
case PlatformType.IOS:
generator.add("platform", platform, false);
return this.attachIos(attachArgs);
default:
generator.add("unknownPlatform", platform, true);
throw new Error(localize("UnknownPlatform", "Unknown Platform: {0}", platform));
}
} else {
return attachArgs;
}
})
.then((processedAttachArgs: ICordovaAttachRequestArgs & { url?: string }) => {
this.outputLogger(localize("AttachingToApp", "Attaching to app"));
this.outputLogger("", true); // Send blank message on stderr to include a divider between prelude and app starting
if (this.cordovaCdpProxy) {
if (processedAttachArgs.webSocketDebuggerUrl) {
this.cordovaCdpProxy.setBrowserInspectUri(processedAttachArgs.webSocketDebuggerUrl);
}
this.cordovaCdpProxy.configureCDPMessageHandlerAccordingToProcessedAttachArgs(processedAttachArgs);
this.cdpProxyErrorHandlerDescriptor = this.cordovaCdpProxy.onError(async (err: Error) => {
if (this.attachRetryCount > 0) {
this.debugSessionStatus = DebugSessionStatus.Reattaching;
this.attachRetryCount--;
await this.attachmentCleanUp();
this.outputLogger(localize("ReattachingToApp", "Failed attempt to attach to the app. Trying to reattach..."));
void this.doAttach(attachArgs);
} else {
this.showError(err);
this.terminate();
this.cdpProxyErrorHandlerDescriptor?.dispose();
}
});
}
this.establishDebugSession(processedAttachArgs, resolve, reject);
});
})
.catch((err) => {
this.outputLogger(err.message || err.format || err, true);
throw err;
})
)
.catch(err => reject(err))
).then(
() => {
this.debugSessionStatus = DebugSessionStatus.Attached;
},
(err) => {
this.debugSessionStatus = DebugSessionStatus.AttachFailed;
throw err;
}
);
}
protected terminateWithErrorResponse(error: Error, response: DebugProtocol.Response): void {
// We can't print error messages after the debugging session is stopped. This could break the extension work.
if (error.name === CANCELLATION_ERROR_NAME) {
return;
}
const errorString = error.message || error.name || "Error";
this.sendErrorResponse(
response,
{ format: errorString, id: 1 },
undefined,
undefined,
ErrorDestination.User
);
}
protected async disconnectRequest(response: DebugProtocol.DisconnectResponse, args: DebugProtocol.DisconnectArguments, request?: DebugProtocol.Request): Promise<void> {
await this.cleanUp(args.restart);
this.debugSessionStatus = DebugSessionStatus.Stopped;
super.disconnectRequest(response, args, request);
}
private handleTerminateDebugSession(debugSession: vscode.DebugSession) {
if (
debugSession.configuration.cordovaDebugSessionId === this.cordovaSession.getSessionId()
&& debugSession.type === this.pwaSessionName
&& this.debugSessionStatus !== DebugSessionStatus.Reattaching
) {
this.terminate();
}
}
private establishDebugSession(
attachArgs: ICordovaAttachRequestArgs,
resolve?: (value?: void | PromiseLike<void> | undefined) => void,
reject?: (reason?: any) => void
): void {
if (this.cordovaCdpProxy) {
const attachArguments = this.pwaSessionName === PwaDebugType.Chrome ?
this.jsDebugConfigAdapter.createChromeDebuggingConfig(
attachArgs,
this.cdpProxyPort,
this.pwaSessionName,
this.cordovaSession.getSessionId()
) :
this.jsDebugConfigAdapter.createSafariDebuggingConfig(
attachArgs,
this.cdpProxyPort,
this.pwaSessionName,
this.cordovaSession.getSessionId()
);
vscode.debug.startDebugging(
this.workspaceManager.workspaceRoot,
attachArguments,
{
parentSession: this.vsCodeDebugSession,
consoleMode: vscode.DebugConsoleMode.MergeWithParent,
}
)
.then((childDebugSessionStarted: boolean) => {
if (childDebugSessionStarted) {
if (resolve) {
resolve();
}
} else {
reject(new Error(localize("CannotStartChildDebugSession", "Cannot start child debug session")));
}
},
err => {
reject(err);
}
);
} else {
throw new Error(localize("CannotConnectToDebuggerWorkerProxyOffline", "Cannot connect to debugger worker: Chrome debugger proxy is offline"));
}
}
private initializeSettings(args: ICordovaAttachRequestArgs | ICordovaLaunchRequestArgs): void {
if (!this.isSettingsInitialized) {
this.workspaceManager = CordovaWorkspaceManager.getWorkspaceManagerByProjectRootPath(args.cwd);
this.isSettingsInitialized = true;
logger.setup(args.trace ? Logger.LogLevel.Verbose : Logger.LogLevel.Log);
this.cdpProxyLogLevel = args.trace ? LogLevel.Custom : LogLevel.None;
if (args.runtimeVersion) {
NodeVersionHelper.nvmSupport(args);
}
}
}
/**
* Initializes telemetry.
*/
private initializeTelemetry(projectRoot: string): Promise<void> {
if (!this.telemetryInitialized) {
this.telemetryInitialized = true;
let version = JSON.parse(fs.readFileSync(findFileInFolderHierarchy(__dirname, "package.json"), "utf-8")).version;
// Enable telemetry, forced on for now.
return Telemetry.init("cordova-tools-debug-adapter", version, { isExtensionProcess: false, projectRoot: projectRoot })
.catch((e) => {
this.outputLogger(localize("CouldNotInitializeTelemetry", "Could not initialize telemetry. {0}", e.message || e.error || e.data || e));
});
} else {
return Promise.resolve();
}
}
private runAdbCommand(args, errorLogger): Promise<string> {
const originalPath = process.env["PATH"];
if (process.env["ANDROID_HOME"]) {
process.env["PATH"] += path.delimiter + path.join(process.env["ANDROID_HOME"], "platform-tools");
}
return execCommand("adb", args, errorLogger).finally(() => {
process.env["PATH"] = originalPath;
});
}
private launchSimulate(launchArgs: ICordovaLaunchRequestArgs, projectType: ProjectType, generator: TelemetryGenerator): Promise<any> {
let simulateTelemetryPropts: ISimulateTelemetryProperties = {
platform: launchArgs.platform,
target: launchArgs.target,
port: launchArgs.port,
simulatePort: launchArgs.simulatePort,
};
if (launchArgs.hasOwnProperty("livereload")) {
simulateTelemetryPropts.livereload = launchArgs.livereload;
}
if (launchArgs.hasOwnProperty("livereloadDelay")) {
simulateTelemetryPropts.livereloadDelay = launchArgs.livereloadDelay;
}
if (launchArgs.hasOwnProperty("forcePrepare")) {
simulateTelemetryPropts.forcePrepare = launchArgs.forcePrepare;
}
generator.add("simulateOptions", simulateTelemetryPropts, false);
let simulateInfo: SimulationInfo;
let getEditorsTelemetry = this.workspaceManager.getVisibleEditorsCount()
.then((editorsCount) => {
generator.add("visibleTextEditors", editorsCount, false);
}).catch((e) => {
this.outputLogger(localize("CouldntoReadTheVisibleTextEditors", "Could not read the visible text editors. {0}", this.getErrorMessage(e)));
});
let launchSimulate = Promise.resolve()
.then(() => {
let simulateOptions = this.convertLaunchArgsToSimulateArgs(launchArgs);
return this.workspaceManager.launchSimulateServer(launchArgs.cwd, simulateOptions, projectType);
}).then((simInfo: SimulationInfo) => {
simulateInfo = simInfo;
return this.connectSimulateDebugHost(simulateInfo);
}).then(() => {
launchArgs.userDataDir = path.join(settingsHome(), CordovaDebugSession.CHROME_DATA_DIR);
return this.workspaceManager.launchSimHost(launchArgs.target);
}).then(() => {
// Launch Chrome and attach
launchArgs.simulatePort = CordovaProjectHelper.getPortFromURL(simulateInfo.appHostUrl);
launchArgs.url = simulateInfo.appHostUrl;
this.outputLogger(localize("AttachingToApp", "Attaching to app"));
return this.launchChromiumBasedBrowser(launchArgs);
}).catch((e) => {
this.outputLogger(localize("AnErrorOccuredWhileAttachingToTheDebugger", "An error occurred while attaching to the debugger. {0}", this.getErrorMessage(e)));
throw e;
}).then(() => void 0);
return Promise.all([launchSimulate, getEditorsTelemetry]);
}
private changeSimulateViewport(data: simulate.ResizeViewportData): Promise<void> {
return this.attachedDeferred.promise
.then(() => {
if (this.cordovaCdpProxy) {
this.cordovaCdpProxy.getSimPageTargetAPI()?.Emulation.setDeviceMetricsOverride({
width: data.width,
height: data.height,
deviceScaleFactor: 0,
mobile: true,
});
}
});
}
private connectSimulateDebugHost(simulateInfo: SimulationInfo): Promise<void> {
// Connect debug-host to cordova-simulate
let viewportResizeFailMessage = localize("ViewportResizingFailed", "Viewport resizing failed. Please try again.");
return new Promise((resolve, reject) => {
let simulateConnectErrorHandler = (err: any): void => {
this.outputLogger("Error connecting to the simulated app.");
reject(err);
};
this.simulateDebugHost = io.connect(simulateInfo.urlRoot);
this.simulateDebugHost.on("connect_error", simulateConnectErrorHandler);
this.simulateDebugHost.on("connect_timeout", simulateConnectErrorHandler);
this.simulateDebugHost.on("connect", () => {
this.simulateDebugHost.on("resize-viewport", (data: simulate.ResizeViewportData) => {
this.changeSimulateViewport(data).catch(() => {
this.outputLogger(viewportResizeFailMessage, true);
});
});
this.simulateDebugHost.emit("register-debug-host", { handlers: ["resize-viewport"] });
resolve(void 0);
});
});
}
private convertLaunchArgsToSimulateArgs(launchArgs: ICordovaLaunchRequestArgs): simulate.SimulateOptions {
let result: simulate.SimulateOptions = {};
result.platform = launchArgs.platform;
result.target = launchArgs.target;
result.port = launchArgs.simulatePort;
result.livereload = launchArgs.livereload;
result.forceprepare = launchArgs.forcePrepare;
result.simulationpath = launchArgs.simulateTempDir;
result.corsproxy = launchArgs.corsProxy;
result.livereloaddelay = launchArgs.livereloadDelay;
result.spaurlrewrites = launchArgs.spaUrlRewrites;
result.lang = vscode.env.language;
return result;
}
private addBuildFlagToArgs(runArgs: Array<string> = []): Array<string> {
const hasBuildFlag = runArgs.findIndex((arg) => arg.includes("--buildFlag")) > -1;
if (!hasBuildFlag) {
// Workaround for dealing with new build system in XCode 10
// https://github.com/apache/cordova-ios/issues/407
runArgs.unshift("--buildFlag=-UseModernBuildSystem=0");
}
return runArgs;
}
private async launchIos(launchArgs: ICordovaLaunchRequestArgs, projectType: ProjectType, runArguments: string[]): Promise<void> {
if (os.platform() !== "darwin") {
throw new Error(localize("UnableToLaunchiOSOnNonMacMachnines", "Unable to launch iOS on non-mac machines"));
}
const useDefaultCLI = async () => {
this.outputLogger("Continue using standard CLI workflow.");
const debuggableDevices = await this.iOSTargetManager.getOnlineTargets();
launchArgs.target = debuggableDevices.length ? debuggableDevices[0].id : TargetType.Emulator;
};
this.outputLogger(localize("LaunchingApp", "Launching the app (This may take a while)..."));
let workingDirectory = launchArgs.cwd;
let iosDebugProxyPort = launchArgs.iosDebugProxyPort || 9221;
const command = launchArgs.cordovaExecutable || CordovaProjectHelper.getCliCommand(workingDirectory);
let args = ["run", "ios"];
if (launchArgs.runArguments && launchArgs.runArguments.length > 0) {
const launchRunArgs = this.addBuildFlagToArgs(launchArgs.runArguments);
args.push(...launchRunArgs);
} else if (runArguments && runArguments.length) {
const runArgs = this.addBuildFlagToArgs(runArguments);
args.push(...runArgs);
} else {
try {
const target = await this.resolveIOSTarget(launchArgs, false);
if (target) {
args.push(target.isVirtualTarget ? "--emulator" : "--device");
args.push(`--target=${
target.isVirtualTarget && target.simIdentifier && !projectType.isIonic ? target.simIdentifier : target.id
}`);
} else {
this.outputLogger(`Could not find debugable target '${launchArgs.target}'.`, true);
await useDefaultCLI();
}
} catch (err) {
this.outputLogger(err.message || err, true);
await useDefaultCLI();
}
const buildArg = this.addBuildFlagToArgs();
args.push(...buildArg);
if (launchArgs.ionicLiveReload) { // Verify if we are using Ionic livereload
if (projectType.isIonic) {
// Livereload is enabled, let Ionic do the launch
args.push("--livereload");
// '--external' parameter is required since for iOS devices, port forwarding is not yet an option (https://github.com/ionic-team/native-run/issues/20)
if (args.includes("--device")) {
args.push("--external");
}
} else {
this.outputLogger(CordovaDebugSession.NO_LIVERELOAD_WARNING);
}
}
}
if (args.indexOf("--livereload") > -1) {
return this.startIonicDevServer(launchArgs, args).then(() => void 0);
}
// cordova run ios does not terminate, so we do not know when to try and attach.
// Therefore we parse the command's output to find the special key, which means that the application has been successfully launched.
await cordovaRunCommand(command, args, launchArgs.allEnv, workingDirectory, this.outputLogger);
if (args.includes("--device")) {
await CordovaIosDeviceLauncher.startDebugProxy(iosDebugProxyPort);
}
}
private attachIos(attachArgs: ICordovaAttachRequestArgs): Promise<ICordovaAttachRequestArgs> {
return this.resolveIOSTarget(attachArgs, true)
.then((target?: IOSTarget) => {
if (!target) {
throw new Error(`Unable to find the target ${attachArgs.target}`);
}
attachArgs.webkitRangeMin = attachArgs.webkitRangeMin || 9223;
attachArgs.webkitRangeMax = attachArgs.webkitRangeMax || 9322;
attachArgs.attachAttempts = attachArgs.attachAttempts || 20;
attachArgs.attachDelay = attachArgs.attachDelay || 1000;
// Start the tunnel through to the webkit debugger on the device
this.outputLogger("Configuring debugging proxy");
const retry = function <T>(func, condition, retryCount, cancellationToken): Promise<T> {
return retryAsync(func, condition, retryCount, 1, attachArgs.attachDelay, localize("UnableToFindWebview", "Unable to find Webview"), cancellationToken);
};
const getBundleIdentifier = () => {
return CordovaIosDeviceLauncher.getBundleIdentifier(attachArgs.cwd)
.then((packageId: string) => {
return target.isVirtualTarget ?
CordovaIosDeviceLauncher.getPathOnSimulator(packageId, target.simDataPath) :
CordovaIosDeviceLauncher.getPathOnDevice(packageId);
});
};
const getSimulatorProxyPort = (iOSAppPackagePath): Promise<{ iOSAppPackagePath: string, targetPort: number, iOSVersion: string }> => {
return promiseGet(`http://localhost:${attachArgs.port}/json`, localize("UnableToCommunicateWithiOSWebkitDebugProxy", "Unable to communicate with ios_webkit_debug_proxy")).then((response: string) => {
try {
// An example of a json response from IWDP
// [{
// "deviceId": "00008020-XXXXXXXXXXXXXXXX",
// "deviceName": "iPhone name",
// "deviceOSVersion": "13.4.1",
// "url": "localhost:9223"
// }]
let endpointsList = JSON.parse(response);
let devices = endpointsList.filter((entry) =>
target.isVirtualTarget ? entry.deviceId === "SIMULATOR"
: entry.deviceId !== "SIMULATOR"
);
let device = devices[0];
// device.url is of the form 'localhost:port'
return {
iOSAppPackagePath,
targetPort: parseInt(device.url.split(":")[1], 10),
iOSVersion: target.system,
};
} catch (e) {
throw new Error(localize("UnableToFindiOSTargetDeviceOrSimulator", "Unable to find iOS target device/simulator. Please check that \"Settings > Safari > Advanced > Web Inspector = ON\" or try specifying a different \"port\" parameter in launch.json"));
}
});
};
const getWebSocketDebuggerUrl = ({ iOSAppPackagePath, targetPort, iOSVersion }): Promise<IOSProcessedParams> => {
return retry(() =>
promiseGet(`http://localhost:${targetPort}/json`, localize("UnableToCommunicateWithTarget", "Unable to communicate with target"))
.then((response: string) => {
try {
// An example of a json response from IWDP
// [{
// "devtoolsFrontendUrl": "",
// "faviconUrl": "",
// "thumbnailUrl": "/thumb/ionic://localhost/tabs/tab1",
// "title": "Ionic App",
// "url": "ionic://localhost/tabs/tab1",
// "webSocketDebuggerUrl": "ws://localhost:9223/devtools/page/1",
// "appId": "PID:37819"
// }]
const webviewsList: Array<WebviewData> = JSON.parse(response);
if (webviewsList.length === 0) {
throw new Error(localize("UnableToFindTargetApp", "Unable to find target app"));
}
const cordovaWebview = this.getCordovaWebview(webviewsList, iOSAppPackagePath, !!attachArgs.ionicLiveReload);
if (!cordovaWebview.webSocketDebuggerUrl) {
throw new Error(localize("WebsocketDebuggerUrlIsEmpty", "WebSocket Debugger Url is empty"));
}
let ionicDevServerUrl;
if (this.ionicDevServerUrls) {
ionicDevServerUrl = this.ionicDevServerUrls.find(url => cordovaWebview.url.indexOf(url) === 0);
}
return {
webSocketDebuggerUrl: cordovaWebview.webSocketDebuggerUrl,
iOSVersion,
iOSAppPackagePath,
ionicDevServerUrl,
};
} catch (e) {
throw new Error(localize("UnableToFindTargetApp", "Unable to find target app"));
}
}),
(result) => !!result,
5,
this.cancellationTokenSource.token
);
};
const getAttachRequestArgs = (): Promise<ICordovaAttachRequestArgs> =>
CordovaIosDeviceLauncher.startWebkitDebugProxy(attachArgs.port, attachArgs.webkitRangeMin, attachArgs.webkitRangeMax, target)
.then(getBundleIdentifier)
.then(getSimulatorProxyPort)
.then(getWebSocketDebuggerUrl)
.then((iOSProcessedParams: IOSProcessedParams) => {
attachArgs.webSocketDebuggerUrl = iOSProcessedParams.webSocketDebuggerUrl;
attachArgs.iOSVersion = iOSProcessedParams.iOSVersion;
attachArgs.iOSAppPackagePath = iOSProcessedParams.iOSAppPackagePath;
if (iOSProcessedParams.ionicDevServerUrl) {
attachArgs.devServerAddress = url.parse(iOSProcessedParams.ionicDevServerUrl).hostname;
}
return attachArgs;
});
return retry(getAttachRequestArgs, () => true, attachArgs.attachAttempts, this.cancellationTokenSource.token);
});
}
private getCordovaWebview(webviewsList: Array<WebviewData>, iOSAppPackagePath: string, ionicLiveReload: boolean): WebviewData {
let cordovaWebview = webviewsList.find(webviewData => {
if (webviewData.url.includes(iOSAppPackagePath)) {
return true;
}
if (!ionicLiveReload && webviewData.url.startsWith("ionic://")) {
return true;
}
if (this.ionicDevServerUrls) {
return this.ionicDevServerUrls.findIndex(url => webviewData.url.indexOf(url) === 0) >= 0;
}
return false;
});
return cordovaWebview || webviewsList[0];
}
private async attachmentCleanUp(): Promise<void> {
// Clear the Ionic dev server URL if necessary
if (this.ionicDevServerUrls) {
this.ionicDevServerUrls = null;
}
this.cdpProxyErrorHandlerDescriptor?.dispose();
if (this.cordovaCdpProxy) {
await this.cordovaCdpProxy.stopServer();
this.cordovaCdpProxy = null;
}
}
private async cleanUp(restart?: boolean): Promise<void> {
const errorLogger = (message) => this.outputLogger(message, true);
if (this.browserProc) {
this.browserProc.kill("SIGINT");
// Workaround for issue https://github.com/microsoft/vscode-cordova/issues/766
this.setChromeExitTypeNormal?.();
this.browserProc = null;
}
// Stop ADB port forwarding if necessary
let adbPortPromise: Promise<void>;
if (this.adbPortForwardingInfo) {
const adbForwardStopArgs =
["-s", this.adbPortForwardingInfo.targetDevice,
"forward",
"--remove", `tcp:${this.adbPortForwardingInfo.port}`];
adbPortPromise = this.runAdbCommand(adbForwardStopArgs, errorLogger)
.then(() => void 0);
} else {
adbPortPromise = Promise.resolve();
}
// Kill the Ionic dev server if necessary
let killServePromise: Promise<void>;
if (this.ionicLivereloadProcess) {
this.ionicLivereloadProcess.removeAllListeners("exit");
killServePromise = killChildProcess(this.ionicLivereloadProcess).finally(() => {
this.ionicLivereloadProcess = null;
});
} else {
killServePromise = Promise.resolve();
}
await this.attachmentCleanUp();
// Close the simulate debug-host socket if necessary
if (this.simulateDebugHost) {
this.simulateDebugHost.close();
this.simulateDebugHost = null;
}
this.cancellationTokenSource.cancel();
this.cancellationTokenSource.dispose();
// Stop IWDP if necessary
CordovaIosDeviceLauncher.cleanup();
this.onDidTerminateDebugSessionHandler.dispose();
this.sessionManager.terminate(this.cordovaSession.getSessionId(), !!restart);
await logger.dispose();
// Wait on all the cleanups
return adbPortPromise
.finally(() => killServePromise);
}
/**
* Starts an Ionic livereload server ("serve" or "run / emulate --livereload"). Returns a promise fulfilled with the full URL to the server.
*/
private startIonicDevServer(launchArgs: ICordovaLaunchRequestArgs, cliArgs: string[]): Promise<string[]> {
enum IonicDevServerStatus {
ServerReady,
AppReady,
}
if (!launchArgs.runArguments || launchArgs.runArguments.length === 0) {
if (launchArgs.devServerAddress) {
cliArgs.push("--address", launchArgs.devServerAddress);
}
if (launchArgs.hasOwnProperty("devServerPort")) {
if (typeof launchArgs.devServerPort === "number" && launchArgs.devServerPort >= 0 && launchArgs.devServerPort <= 65535) {
cliArgs.push("--port", launchArgs.devServerPort.toString());
} else {
return Promise.reject(new Error(localize("TheValueForDevServerPortMustBeInInterval", "The value for \"devServerPort\" must be a number between 0 and 65535")));
}
}
}
let isServe: boolean = cliArgs[0] === "serve";
let errorRegex: RegExp = /error:.*/i;
let ionicLivereloadProcessStatus = {
serverReady: false,
appReady: false,
};
let serverReadyTimeout: number = launchArgs.devServerTimeout || 60000;
let appReadyTimeout: number = launchArgs.devServerTimeout || 120000; // If we're not serving, the app needs to build and deploy (and potentially start the emulator), which can be very long
let serverOut: string = "";
let serverErr: string = "";
const ansiRegex = /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g;
const isIonic4: boolean = CordovaProjectHelper.isIonicCliVersionGte(launchArgs.cwd, "4.0.0");
let getServerErrorMessage = (channel: string) => {
// Skip Ionic 4 searching port errors because, actually, they are not errors
// https://github.com/ionic-team/ionic-cli/blob/4ee312ad983922ff4398b5900dcfcaebb6ef57df/packages/%40ionic/utils-network/src/index.ts#L85
if (isIonic4) {
const skipErrorMatch = /utils-network error while checking/.test(channel);
if (skipErrorMatch) {
return null;
}
}
let errorMatch = errorRegex.exec(channel);
if (errorMatch) {
return localize("ErrorInTheIonicLiveReloadServer", "Error in the Ionic live reload server: {0}", os.EOL + errorMatch[0]);
}
return null;
};
let getRegexToResolveAppDefer = (cliArgs: string[]): RegExp => {
// Now that the server is ready, listen for the app to be ready as well. For "serve", this is always true, because no build and deploy is involved. For android, we need to
// wait until we encounter the "launch success", for iOS device, the server output is different and instead we need to look for:
//
// ios devices:
// (lldb) run
// success
//
// ios simulators:
// "build succeeded"
let isIosDevice: boolean = cliArgs.indexOf("ios") !== -1 && cliArgs.indexOf("--device") !== -1;
let isIosSimulator: boolean = cliArgs.indexOf("ios") !== -1 && cliArgs.indexOf("--emulator") !== -1;
let iosDeviceAppReadyRegex: RegExp = /created bundle at path|\(lldb\)\W+run\r?\nsuccess/i;
let iosSimulatorAppReadyRegex: RegExp = /build succeeded|native-run ios/i;
let appReadyRegex: RegExp = /launch success|run successful/i;
if (isIosDevice) {
return iosDeviceAppReadyRegex;
}
if (isIosSimulator) {
return iosSimulatorAppReadyRegex;
}
return appReadyRegex;
};
const command = launchArgs.cordovaExecutable || CordovaProjectHelper.getCliCommand(launchArgs.cwd);
this.ionicLivereloadProcess = cordovaStartCommand(command, cliArgs, launchArgs.allEnv, launchArgs.cwd);
const serverStarting = new Promise((_resolve, reject) => {
let rejectTimeout = setTimeout(() => {
reject(localize("StartingIonicDevServerTimedOut", "Starting the Ionic dev server timed out ({0} ms)", serverReadyTimeout));
}, serverReadyTimeout);
let resolveIfPossible = (ready: IonicDevServerStatus, serverUrls?: string[]) => {
if (ready === IonicDevServerStatus.ServerReady && !ionicLivereloadProcessStatus.serverReady) {
clearTimeout(rejectTimeout);
ionicLivereloadProcessStatus.serverReady = true;
this.outputLogger("Building and deploying app");
rejectTimeout = setTimeout(() => {
reject(localize("BuildingAndDeployingTheAppTimedOut", "Building and deploying the app timed out ({0} ms)", appReadyTimeout));
}, appReadyTimeout);
} else if (ready === IonicDevServerStatus.AppReady && ionicLivereloadProcessStatus.serverReady) {
clearTimeout(rejectTimeout);
ionicLivereloadProcessStatus.appReady = true;
_resolve(serverUrls);
}
};
this.ionicLivereloadProcess.on("error", (err: { code: string }) => {
if (err.code === "ENOENT") {
reject(new Error(localize("IonicNotFound", "Ionic not found, please run 'npm install –g ionic' to install it globally")));
} else {
reject(err);
}
});
this.ionicLivereloadProcess.on("exit", (() => {
this.ionicLivereloadProcess = null;
let exitMessage: string = "The Ionic live reload server exited unexpectedly";
let errorMsg = getServerErrorMessage(serverErr);
if (errorMsg) {
// The Ionic live reload server has an error; check if it is related to the devServerAddress to give a better message
if (errorMsg.indexOf("getaddrinfo ENOTFOUND") !== -1 || errorMsg.indexOf("listen EADDRNOTAVAIL") !== -1) {
exitMessage += os.EOL + localize("InvalidAddress", "Invalid address: please provide a valid IP address or hostname for the \"devServerAddress\" property in launch.json");
} else {
exitMessage += os.EOL + errorMsg;
}
}
if (!ionicLivereloadProcessStatus.serverReady && !ionicLivereloadProcessStatus.appReady) {
// We are already debugging; disconnect the session
this.outputLogger(exitMessage, true);
this.stop();
throw new Error(exitMessage);
} else {
// The Ionic dev server wasn't ready yet, so reject its promises
reject(new Error(exitMessage));
}
}).bind(this));
let serverOutputHandler = (data: Buffer) => {
serverOut += data.toString();
this.outputLogger(data.toString(), "stdout");
// Listen for the server to be ready. We check for the "Running dev server: http://localhost:<port>/" and "dev server running: http://localhost:<port>/" strings to decide that.
// Example output of Ionic 1 dev server:
//
// [OK] Development server running!
// Local: http://localhost:8100
// External: http://10.0.75.1:8100, http://172.28.124.161:8100, http://169.254.80.80:8100, http://192.169.8.39:8100
// Example output of Ionic 2 dev server:
//
// Running live reload server: undefined
// Watching: 0=www/**/*, 1=!www/lib/**/*
// Running dev server: http://localhost:8100
// Ionic server commands, enter:
// restart or r to restart the client app from the root
// goto or g and a url to have the app navigate to the given url
// consolelogs or c to enable/disable console log output
// serverlogs or s to enable/disable server log output
// quit or q to shutdown the server and exit
//
// ionic $
// Example output of Ionic dev server (for Ionic2):
//
// > ionic-hello-world@ ionic:serve <path>
// > ionic-app-scripts serve "--v2" "--address" "0.0.0.0" "--port" "8100" "--livereload-port" "35729"
// ionic-app-scripts
// watch started
// build dev started
// clean started
// clean finished
// copy started
// transpile started
// transpile finished
// webpack started
// copy finished
// webpack finished
// sass started
// sass finished
// build dev finished
// watch ready
// dev server running: http://localhost:8100/
const SERVER_URL_RE = /(dev server running|Running dev server|Local):.*(http:\/\/.[^\s]*)/gmi;
let localServerMatchResult = SERVER_URL_RE.exec(serverOut);
if (!ionicLivereloadProcessStatus.serverReady && localServerMatchResult) {
resolveIfPossible(IonicDevServerStatus.ServerReady);
}
if (ionicLivereloadProcessStatus.serverReady && !ionicLivereloadProcessStatus.appReady) {
let regex: RegExp = getRegexToResolveAppDefer(cliArgs);
if (isServe || regex.test(serverOut)) {
const serverUrls = [localServerMatchResult[2]];
const externalUrls = /External:\s(.*)$/im.exec(serverOut);
if (externalUrls) {
const urls = externalUrls[1].split(", ").map(x => x.trim());
serverUrls.push(...urls);
}
launchArgs.devServerPort = CordovaProjectHelper.getPortFromURL(serverUrls[0]);
resolveIfPossible(IonicDevServerStatus.AppReady, serverUrls);
}
}
if (/Multiple network interfaces detected/.test(serverOut)) {
// Ionic does not know which address to use for the dev server, and requires human interaction; error out and let the user know
let errorMessage: string = localize("YourMachineHasMultipleNetworkAddresses",
`Your machine has multiple network addresses. Please specify which one your device or emulator will use to communicate with the dev server by adding a \"devServerAddress\": \"ADDRESS\" property to .vscode/launch.json.
To get the list of addresses run "ionic cordova run PLATFORM --livereload" (where PLATFORM is platform name to run) and wait until prompt with this list is appeared.`);
let addresses: string[] = [];
let addressRegex = /(\d+\) .*)/gm;
let match: string[] = addressRegex.exec(serverOut);
while (match) {
addresses.push(match[1]);
match = addressRegex.exec(serverOut);
}
if (addresses.length > 0) {
// Give the user the list of addresses that Ionic found
// NOTE: since ionic started to use inquirer.js for showing _interactive_ prompts this trick does not work as no output
// of prompt are sent from ionic process which we starts with --no-interactive parameter
errorMessage += [localize("AvailableAdresses", " Available addresses:")].concat(addresses).join(os.EOL + " ");
}
reject(new Error(errorMessage));
}
let errorMsg = getServerErrorMessage(serverOut);
if (errorMsg) {
reject(new Error(errorMsg));
}
};
let serverErrorOutputHandler = (data: Buffer) => {
serverErr += data.toString();
let errorMsg = getServerErrorMessage(serverErr);
if (errorMsg) {
reject(new Error(errorMsg));
}
};
this.ionicLivereloadProcess.stdout.on("data", serverOutputHandler);
this.ionicLivereloadProcess.stderr.on("data", (data: Buffer) => {
if (isIonic4) {
// Ionic 4 writes all logs to stderr completely ignoring stdout
serverOutputHandler(data);
}
serverErrorOutputHandler(data);
});
this.outputLogger(localize("StartingIonicDevServer", "Starting Ionic dev server (live reload: {0})", launchArgs.ionicLiveReload));
});
return serverStarting.then((ionicDevServerUrls: string[]) => {
if (!ionicDevServerUrls || !ionicDevServerUrls.length) {
throw new Error(localize("UnableToDetermineTheIonicDevServerAddress", "Unable to determine the Ionic dev server address, please try re-launching the debugger"));
}
// The dev server address is the captured group at index 1 of the match
this.ionicDevServerUrls = ionicDevServerUrls;
// When ionic 2 cli is installed, output includes ansi characters for color coded output.
this.ionicDevServerUrls = this.ionicDevServerUrls.map(url => url.replace(ansiRegex, ""));
return this.ionicDevServerUrls;
});
}
private async launchChromiumBasedBrowser(args: ICordovaLaunchRequestArgs): Promise<void> {
const port = args.port || 9222;
const chromeArgs: string[] = ["--remote-debugging-port=" + port];
chromeArgs.push(...["--no-first-run", "--no-default-browser-check"]);
if (args.runtimeArgs) {
chromeArgs.push(...args.runtimeArgs);
}
if (args.userDataDir) {
chromeArgs.push("--user-data-dir=" + args.userDataDir);
}
const launchUrl = args.url;
chromeArgs.push(launchUrl);
let browserFinder;
switch(args.target) {
case TargetType.Edge:
browserFinder = new browserHelper.EdgeBrowserFinder(process.env, fs.promises, execa);
break;
case TargetType.Chrome:
default:
browserFinder = new browserHelper.ChromeBrowserFinder(process.env, fs.promises, execa);
}
const browserPath = await browserFinder.findAll();
if (browserPath[0]) {
this.browserProc = child_process.spawn(browserPath[0].path, chromeArgs, {
detached: true,
stdio: ["ignore"],
});
this.browserProc.unref();
this.browserProc.on("error", (err) => {
const errMsg = localize("ChromeError", "Chrome error: {0}", err.message);
this.outputLogger(errMsg, true);
this.stop();
});
this.setChromeExitTypeNormal = this.setChromeExitTypeNormalByUserDataDir.bind(this, args.userDataDir);
this.vsCodeDebugSession.customRequest("attach", args);
}
}
private setChromeExitTypeNormalByUserDataDir(userDataDir: string) {
try {
const preferencesPath = path.resolve(userDataDir, "Default", "Preferences");
const browserPrefs = JSON.parse(fs.readFileSync(preferencesPath, "utf8"));
browserPrefs.profile.exit_type = "normal";
fs.writeFileSync(preferencesPath, JSON.stringify(browserPrefs));
} catch (error) {
this.outputLogger("Warning: Failed to set normal exit type for Chrome browser");
}
}
private launchServe(launchArgs: ICordovaLaunchRequestArgs, projectType: ProjectType, runArguments: string[]): Promise<void> {
let errorLogger = (message) => this.outputLogger(message, true);
// Currently, "ionic serve" is only supported for Ionic projects
if (!projectType.isIonic) {
let errorMessage = localize("ServingToTheBrowserIsSupportedForIonicProjects", "Serving to the browser is currently only supported for Ionic projects");
errorLogger(errorMessage);
return Promise.reject(new Error(errorMessage));
}
let args = ["serve"];
if (launchArgs.runArguments && launchArgs.runArguments.length > -1) {
args.push(...launchArgs.runArguments);
} else if (runArguments && runArguments.length) {
args.push(...runArguments);
} else {
// Set up "ionic serve" args
args.push("--nobrowser");
if (!launchArgs.ionicLiveReload) {
args.push("--nolivereload");
}
}
// Deploy app to browser
return this.startIonicDevServer(launchArgs, args)
.then((devServerUrls: string[]) => {
// Prepare Chrome launch args
launchArgs.url = devServerUrls[0];
launchArgs.userDataDir = path.join(settingsHome(), CordovaDebugSession.CHROME_DATA_DIR);
// Launch Chrome and attach
return this.launchChromiumBasedBrowser(launchArgs);
});
}
private getErrorMessage(e: any): string {
return e.message || e.error || e.data || e;
}
private async getCommandLineArgsForAndroidTarget(launchArgs: ICordovaLaunchRequestArgs): Promise<string[]> {
let targetArgs: string[] = ["--verbose"];
const useDefaultCLI = async () => {
this.outputLogger("Continue using standard CLI workflow.");
targetArgs = ["--verbose"];
const adbHelper = new AdbHelper(launchArgs.cwd);
const debuggableDevices = await adbHelper.getOnlineTargets();
// By default, if the target is not specified, Cordova CLI uses the first online target from ‘adb devices’ list (launched emulators are placed after devices).
// For more information, see https://github.com/apache/cordova-android/blob/bb7d733cdefaa9ed36ec355a42f8224da610a26e/bin/templates/cordova/lib/run.js#L57-L68
launchArgs.target = debuggableDevices.length ? debuggableDevices[0].id : TargetType.Emulator;
};
try {
const target = await this.resolveAndroidTarget(launchArgs, false);
if (target) {
targetArgs.push(target.isVirtualTarget ? "--emulator" : "--device");
targetArgs.push(`--target=${target.id}`);
} else {
this.outputLogger(`Could not find debugable target '${launchArgs.target}'.`, true);
await useDefaultCLI();
}
} catch (error) {
this.outputLogger(error.message || error, true);
await useDefaultCLI();
}
return targetArgs;
}
private async resolveAndroidTarget(configArgs: ICordovaLaunchRequestArgs | ICordovaAttachRequestArgs, isAttachScenario: boolean): Promise<AndroidTarget | undefined> {
const adbHelper = new AdbHelper(configArgs.cwd);
const getFirstOnlineAndroidTarget = async (): Promise<AndroidTarget | undefined> => {
const onlineTargets = await adbHelper.getOnlineTargets();
if (onlineTargets.length) {
const firstDevice = onlineTargets[0];
configArgs.target = firstDevice.id;
return AndroidTarget.fromInterface(firstDevice);
}
};
if (configArgs.target) {
const androidEmulatorManager = new AndroidTargetManager(adbHelper);
const isAnyEmulator = configArgs.target.toLowerCase() === TargetType.Emulator;
const isAnyDevice = configArgs.target.toLowerCase() === TargetType.Device;
const isVirtualTarget = await androidEmulatorManager.isVirtualTarget(configArgs.target);
const saveResult = async (target: AndroidTarget): Promise<void> => {
const launchScenariousManager = new LaunchScenariosManager(configArgs.cwd);
if (isAttachScenario) {
// Save the selected target for attach scenario only if there are more then one online target
const onlineDevices = await adbHelper.getOnlineTargets();
if (onlineDevices.filter(device => target.isVirtualTarget === device.isVirtualTarget).length > 1) {
launchScenariousManager.updateLaunchScenario(configArgs, {target: target.name});
}
} else {
launchScenariousManager.updateLaunchScenario(configArgs, {target: target.name});
}
};
await androidEmulatorManager.collectTargets(isVirtualTarget ? TargetType.Emulator : TargetType.Device);
let targetDevice = await androidEmulatorManager.selectAndPrepareTarget(target => {
const conditionForAttachScenario = isAttachScenario ? target.isOnline : true;
const conditionForNotAnyTarget = isAnyEmulator || isAnyDevice ? true : target.name === configArgs.target || target.id === configArgs.target;
const conditionForVirtualTarget = isVirtualTarget === target.isVirtualTarget;
return conditionForVirtualTarget && conditionForNotAnyTarget && conditionForAttachScenario;
});
if (targetDevice) {
if (isAnyEmulator || isAnyDevice) {
await saveResult(targetDevice);
}
configArgs.target = targetDevice.id;
} else if (isAttachScenario && (isAnyEmulator || isAnyDevice)) {
this.outputLogger("Target has not been selected. Trying to use the first online Android device");
targetDevice = await getFirstOnlineAndroidTarget();
}
return targetDevice;
} else {
// If there is no a target in debug config, use the first online device
const targetDevice = await getFirstOnlineAndroidTarget();
if (!targetDevice) {
throw new Error(localize("ThereIsNoAnyOnlineDebuggableDevice", "The 'target' parameter in the debug configuration is undefined, and there are no any online debuggable targets"));
}
return targetDevice;
}
}
private async resolveIOSTarget(configArgs: ICordovaLaunchRequestArgs | ICordovaAttachRequestArgs, isAttachScenario: boolean): Promise<IOSTarget | undefined> {
const getFirstOnlineIOSTarget = async (): Promise<IOSTarget | undefined> => {
const onlineTargets = await this.iOSTargetManager.getOnlineTargets();
if (onlineTargets.length) {
const firstDevice = onlineTargets[0];
configArgs.target = firstDevice.id;
return firstDevice;
}
};
if (configArgs.target) {
const isAnyEmulator = configArgs.target.toLowerCase() === TargetType.Emulator;
const isAnyDevice = configArgs.target.toLowerCase() === TargetType.Device;
const isVirtualTarget = await this.iOSTargetManager.isVirtualTarget(configArgs.target);
const saveResult = async (target: AndroidTarget): Promise<void> => {
const launchScenariousManager = new LaunchScenariosManager(configArgs.cwd);
if (isAttachScenario) {
// Save the selected target for attach scenario only if there are more then one online target
const onlineDevices = await this.iOSTargetManager.getOnlineTargets();
if (onlineDevices.filter(device => target.isVirtualTarget === device.isVirtualTarget).length > 1) {
launchScenariousManager.updateLaunchScenario(configArgs, {target: target.id});
}
} else {
launchScenariousManager.updateLaunchScenario(configArgs, {target: target.id});
}
};
await this.iOSTargetManager.collectTargets(isVirtualTarget ? TargetType.Emulator : TargetType.Device);
let targetDevice = await this.iOSTargetManager.selectAndPrepareTarget(target => {
const conditionForAttachScenario = isAttachScenario ? target.isOnline : true;
const conditionForNotAnyTarget = isAnyEmulator || isAnyDevice ? true : target.name === configArgs.target || target.id === configArgs.target;
const conditionForVirtualTarget = isVirtualTarget === target.isVirtualTarget;
return conditionForVirtualTarget && conditionForNotAnyTarget && conditionForAttachScenario;
});
if (targetDevice) {
if (isAnyEmulator || isAnyDevice) {
await saveResult(targetDevice);
}
configArgs.target = targetDevice.id;
} else if (isAttachScenario && (isAnyEmulator || isAnyDevice)) {
this.outputLogger("Target has not been selected. Trying to use the first online iOS device");
targetDevice = await getFirstOnlineIOSTarget();
}
return targetDevice;
} else {
// If there is no a target in debug config, use the first online device
const targetDevice = await getFirstOnlineIOSTarget();
if (!targetDevice) {
throw new Error(localize("ThereIsNoAnyOnlineDebuggableDevice", "The 'target' parameter in the debug configuration is undefined, and there are no any online debuggable targets"));
}
return targetDevice;
}
}
private async launchAndroid(launchArgs: ICordovaLaunchRequestArgs, projectType: ProjectType, runArguments: string[]): Promise<void> {
let workingDirectory = launchArgs.cwd;
// Prepare the command line args
let args = ["run", "android"];
if (launchArgs.runArguments && launchArgs.runArguments.length > 0) {
args.push(...launchArgs.runArguments);
} else if (runArguments && runArguments.length) {
args.push(...runArguments);
} else {
const targetArgs = await this.getCommandLineArgsForAndroidTarget(launchArgs);
args.push(...targetArgs);
// Verify if we are using Ionic livereload
if (launchArgs.ionicLiveReload) {
if (projectType.isIonic) {
// Livereload is enabled, let Ionic do the launch
args.push("--livereload");
} else {
this.outputLogger(CordovaDebugSession.NO_LIVERELOAD_WARNING);
}
}
}
if (args.indexOf("--livereload") > -1) {
return this.startIonicDevServer(launchArgs, args).then(() => void 0);
}
const command = launchArgs.cordovaExecutable || CordovaProjectHelper.getCliCommand(workingDirectory);
let cordovaResult = cordovaRunCommand(
command,
args,
launchArgs.allEnv,
workingDirectory,
this.outputLogger,
).then((output) => {
let runOutput = output[0];
let stderr = output[1];
// Ionic ends process with zero code, so we need to look for
// strings with error content to detect failed process
let errorMatch = /(ERROR.*)/.exec(runOutput) || /error:.*/i.exec(stderr);
if (errorMatch) {
// TODO remove this handler after the issue https://github.com/ionic-team/ionic-cli/issues/4809 is resolved
const errorOutputJsonPattern = new RegExp(
`Error: ENOENT: no such file or directory.*\\${path.sep}output\.json`, "mi"
);
if (!errorOutputJsonPattern.test(errorMatch[0])) {
throw new Error(localize("ErrorRunningAndroid", "Error running android"));
}
}
this.outputLogger(localize("AppSuccessfullyLaunched", "App successfully launched"));
});
return cordovaResult;
}
private attachAndroid(attachArgs: ICordovaAttachRequestArgs): Promise<ICordovaAttachRequestArgs> {
let errorLogger = (message: string) => this.outputLogger(message, true);
// Determine which device/emulator we are targeting
let resolveTagetPromise = new Promise<string>(async (resolve, reject) => {
try {
const devicesOutput = await this.runAdbCommand(["devices"], errorLogger);
try {
const result = await this.resolveAndroidTarget(attachArgs, true);
if (!result) {
errorLogger(devicesOutput);
reject(new Error(`Unable to find target ${attachArgs.target}`));
}
resolve(result.id);
} catch (error) {
reject(error);
}
} catch (error) {
let errorCode: string = (<any>error).code;
if (errorCode && errorCode === "ENOENT") {
throw new Error(localize("UnableToFindAdb", "Unable to find adb. Please ensure it is in your PATH and re-open Visual Studio Code"));
}
throw error;
}
});
let packagePromise: Promise<string> = fs.promises.readFile(path.join(attachArgs.cwd, ANDROID_MANIFEST_PATH))
.catch((err) => {
if (err && err.code === "ENOENT") {
return fs.promises.readFile(path.join(attachArgs.cwd, ANDROID_MANIFEST_PATH_8));
}
throw err;
})
.then((manifestContents) => {
let parsedFile = elementtree.XML(manifestContents.toString());
let packageKey = "package";
return parsedFile.attrib[packageKey];
});
return Promise.all([packagePromise, resolveTagetPromise])
.then(([appPackageName, targetDevice]) => {
let pidofCommandArguments = ["-s", targetDevice, "shell", "pidof", appPackageName];
let getPidCommandArguments = ["-s", targetDevice, "shell", "ps"];
let getSocketsCommandArguments = ["-s", targetDevice, "shell", "cat /proc/net/unix"];
let findAbstractNameFunction = () =>
// Get the pid from app package name
this.runAdbCommand(pidofCommandArguments, errorLogger)
.then((pid) => {
if (pid && /^[0-9]+$/.test(pid.trim())) {
return pid.trim();
}
throw Error(CordovaDebugSession.pidofNotFoundError);
}).catch((err) => {
if (err.message !== CordovaDebugSession.pidofNotFoundError) {
return;
}
return this.runAdbCommand(getPidCommandArguments, errorLogger)
.then((psResult) => {
const lines = psResult.split("\n");
const keys = lines.shift().split(PS_FIELDS_SPLITTER_RE);
const nameIdx = keys.indexOf("NAME");
const pidIdx = keys.indexOf("PID");
for (const line of lines) {
const fields = line.trim().split(PS_FIELDS_SPLITTER_RE).filter(field => !!field);
if (fields.length < nameIdx) {
continue;
}
if (fields[nameIdx] === appPackageName) {
return fields[pidIdx];
}
}
});
})
// Get the "_devtools_remote" abstract name by filtering /proc/net/unix with process inodes
.then(pid =>
this.runAdbCommand(getSocketsCommandArguments, errorLogger)
.then((getSocketsResult) => {
const lines = getSocketsResult.split("\n");
const keys = lines.shift().split(/[\s\r]+/);
const flagsIdx = keys.indexOf("Flags");
const stIdx = keys.indexOf("St");
const pathIdx = keys.indexOf("Path");
for (const line of lines) {
const fields = line.split(/[\s\r]+/);
if (fields.length < 8) {
continue;
}
// flag = 00010000 (16) -> accepting connection
// state = 01 (1) -> unconnected
if (fields[flagsIdx] !== "00010000" || fields[stIdx] !== "01") {
continue;
}
const pathField = fields[pathIdx];
if (pathField.length < 1 || pathField[0] !== "@") {
continue;
}
if (pathField.indexOf("_devtools_remote") === -1) {
continue;
}
if (pathField === `@webview_devtools_remote_${pid}`) {
// Matches the plain cordova webview format
return pathField.substr(1);
}
if (pathField === `@${appPackageName}_devtools_remote`) {
// Matches the crosswalk format of "@PACKAGENAME_devtools_remote
return pathField.substr(1);
}
// No match, keep searching
}
})
);
return retryAsync(
findAbstractNameFunction,
(match) => !!match,
5,
1,
5000,
localize("UnableToFindLocalAbstractName", "Unable to find 'localabstract' name of Cordova app"),
this.cancellationTokenSource.token
)
.then((abstractName) => {
// Configure port forwarding to the app
let forwardSocketCommandArguments = ["-s", targetDevice, "forward", `tcp:${attachArgs.port}`, `localabstract:${abstractName}`];
this.outputLogger(localize("ForwardingDebugPort", "Forwarding debug port"));
return this.runAdbCommand(forwardSocketCommandArguments, errorLogger).then(() => {
this.adbPortForwardingInfo = { targetDevice, port: attachArgs.port };
});
});
}).then(() => {
return attachArgs;
});
}
private showError(error: Error): void {
void vscode.window.showErrorMessage(error.message, {
modal: true,
});
// We can't print error messages via debug session logger after the session is stopped. This could break the extension work.
if (this.debugSessionStatus === DebugSessionStatus.Stopped) {
OutputChannelLogger.getMainChannel().log(error.message);
return;
}
this.outputLogger(error.message, true);
}
private async terminate(): Promise<void> {
await vscode.commands.executeCommand(this.stopCommand, undefined, {
sessionId: this.vsCodeDebugSession.id,
});
}
} | the_stack |
// Names from https://blog.codinghorror.com/ascii-pronunciation-rules-for-programmers/
/**
* An inlined enum containing useful character codes (to be used with String.charCodeAt).
* Please leave the const keyword such that it gets inlined when compiled to JavaScript!
* @internal
*/
export const enum CharCode {
Null = 0,
/**
* The `\b` character.
*/
Backspace = 8,
/**
* The `\t` character.
*/
Tab = 9,
/**
* The `\n` character.
*/
LineFeed = 10,
/**
* The `\r` character.
*/
CarriageReturn = 13,
Space = 32,
/**
* The `!` character.
*/
ExclamationMark = 33,
/**
* The `"` character.
*/
DoubleQuote = 34,
/**
* The `#` character.
*/
Hash = 35,
/**
* The `$` character.
*/
DollarSign = 36,
/**
* The `%` character.
*/
PercentSign = 37,
/**
* The `&` character.
*/
Ampersand = 38,
/**
* The `'` character.
*/
SingleQuote = 39,
/**
* The `(` character.
*/
OpenParen = 40,
/**
* The `)` character.
*/
CloseParen = 41,
/**
* The `*` character.
*/
Asterisk = 42,
/**
* The `+` character.
*/
Plus = 43,
/**
* The `,` character.
*/
Comma = 44,
/**
* The `-` character.
*/
Dash = 45,
/**
* The `.` character.
*/
Period = 46,
/**
* The `/` character.
*/
Slash = 47,
Digit0 = 48,
Digit1 = 49,
Digit2 = 50,
Digit3 = 51,
Digit4 = 52,
Digit5 = 53,
Digit6 = 54,
Digit7 = 55,
Digit8 = 56,
Digit9 = 57,
/**
* The `:` character.
*/
Colon = 58,
/**
* The `;` character.
*/
Semicolon = 59,
/**
* The `<` character.
*/
LessThan = 60,
/**
* The `=` character.
*/
Equals = 61,
/**
* The `>` character.
*/
GreaterThan = 62,
/**
* The `?` character.
*/
QuestionMark = 63,
/**
* The `@` character.
*/
AtSign = 64,
A = 65,
B = 66,
C = 67,
D = 68,
E = 69,
F = 70,
G = 71,
H = 72,
I = 73,
J = 74,
K = 75,
L = 76,
M = 77,
N = 78,
O = 79,
P = 80,
Q = 81,
R = 82,
S = 83,
T = 84,
U = 85,
V = 86,
W = 87,
X = 88,
Y = 89,
Z = 90,
/**
* The `[` character.
*/
OpenSquareBracket = 91,
/**
* The `\` character.
*/
Backslash = 92,
/**
* The `]` character.
*/
CloseSquareBracket = 93,
/**
* The `^` character.
*/
Caret = 94,
/**
* The `_` character.
*/
Underline = 95,
/**
* The ``(`)`` character.
*/
BackTick = 96,
a = 97,
b = 98,
c = 99,
d = 100,
e = 101,
f = 102,
g = 103,
h = 104,
i = 105,
j = 106,
k = 107,
l = 108,
m = 109,
n = 110,
o = 111,
p = 112,
q = 113,
r = 114,
s = 115,
t = 116,
u = 117,
v = 118,
w = 119,
x = 120,
y = 121,
z = 122,
/**
* The `{` character.
*/
OpenCurlyBrace = 123,
/**
* The `|` character.
*/
Pipe = 124,
/**
* The `}` character.
*/
CloseCurlyBrace = 125,
/**
* The `~` character.
*/
Tilde = 126,
U_Combining_Grave_Accent = 0x0300,// U+0300Combining Grave Accent
U_Combining_Acute_Accent = 0x0301,// U+0301Combining Acute Accent
U_Combining_Circumflex_Accent = 0x0302,// U+0302Combining Circumflex Accent
U_Combining_Tilde = 0x0303,// U+0303Combining Tilde
U_Combining_Macron = 0x0304,// U+0304Combining Macron
U_Combining_Overline = 0x0305,// U+0305Combining Overline
U_Combining_Breve = 0x0306,// U+0306Combining Breve
U_Combining_Dot_Above = 0x0307,// U+0307Combining Dot Above
U_Combining_Diaeresis = 0x0308,// U+0308Combining Diaeresis
U_Combining_Hook_Above = 0x0309,// U+0309Combining Hook Above
U_Combining_Ring_Above = 0x030A,// U+030ACombining Ring Above
U_Combining_Double_Acute_Accent = 0x030B,// U+030BCombining Double Acute Accent
U_Combining_Caron = 0x030C,// U+030CCombining Caron
U_Combining_Vertical_Line_Above = 0x030D,// U+030DCombining Vertical Line Above
U_Combining_Double_Vertical_Line_Above = 0x030E,// U+030ECombining Double Vertical Line Above
U_Combining_Double_Grave_Accent = 0x030F,// U+030FCombining Double Grave Accent
U_Combining_Candrabindu = 0x0310,// U+0310Combining Candrabindu
U_Combining_Inverted_Breve = 0x0311,// U+0311Combining Inverted Breve
U_Combining_Turned_Comma_Above = 0x0312,// U+0312Combining Turned Comma Above
U_Combining_Comma_Above = 0x0313,// U+0313Combining Comma Above
U_Combining_Reversed_Comma_Above = 0x0314,// U+0314Combining Reversed Comma Above
U_Combining_Comma_Above_Right = 0x0315,// U+0315Combining Comma Above Right
U_Combining_Grave_Accent_Below = 0x0316,// U+0316Combining Grave Accent Below
U_Combining_Acute_Accent_Below = 0x0317,// U+0317Combining Acute Accent Below
U_Combining_Left_Tack_Below = 0x0318,// U+0318Combining Left Tack Below
U_Combining_Right_Tack_Below = 0x0319,// U+0319Combining Right Tack Below
U_Combining_Left_Angle_Above = 0x031A,// U+031ACombining Left Angle Above
U_Combining_Horn = 0x031B,// U+031BCombining Horn
U_Combining_Left_Half_Ring_Below = 0x031C,// U+031CCombining Left Half Ring Below
U_Combining_Up_Tack_Below = 0x031D,// U+031DCombining Up Tack Below
U_Combining_Down_Tack_Below = 0x031E,// U+031ECombining Down Tack Below
U_Combining_Plus_Sign_Below = 0x031F,// U+031FCombining Plus Sign Below
U_Combining_Minus_Sign_Below = 0x0320,// U+0320Combining Minus Sign Below
U_Combining_Palatalized_Hook_Below = 0x0321,// U+0321Combining Palatalized Hook Below
U_Combining_Retroflex_Hook_Below = 0x0322,// U+0322Combining Retroflex Hook Below
U_Combining_Dot_Below = 0x0323,// U+0323Combining Dot Below
U_Combining_Diaeresis_Below = 0x0324,// U+0324Combining Diaeresis Below
U_Combining_Ring_Below = 0x0325,// U+0325Combining Ring Below
U_Combining_Comma_Below = 0x0326,// U+0326Combining Comma Below
U_Combining_Cedilla = 0x0327,// U+0327Combining Cedilla
U_Combining_Ogonek = 0x0328,// U+0328Combining Ogonek
U_Combining_Vertical_Line_Below = 0x0329,// U+0329Combining Vertical Line Below
U_Combining_Bridge_Below = 0x032A,// U+032ACombining Bridge Below
U_Combining_Inverted_Double_Arch_Below = 0x032B,// U+032BCombining Inverted Double Arch Below
U_Combining_Caron_Below = 0x032C,// U+032CCombining Caron Below
U_Combining_Circumflex_Accent_Below = 0x032D,// U+032DCombining Circumflex Accent Below
U_Combining_Breve_Below = 0x032E,// U+032ECombining Breve Below
U_Combining_Inverted_Breve_Below = 0x032F,// U+032FCombining Inverted Breve Below
U_Combining_Tilde_Below = 0x0330,// U+0330Combining Tilde Below
U_Combining_Macron_Below = 0x0331,// U+0331Combining Macron Below
U_Combining_Low_Line = 0x0332,// U+0332Combining Low Line
U_Combining_Double_Low_Line = 0x0333,// U+0333Combining Double Low Line
U_Combining_Tilde_Overlay = 0x0334,// U+0334Combining Tilde Overlay
U_Combining_Short_Stroke_Overlay = 0x0335,// U+0335Combining Short Stroke Overlay
U_Combining_Long_Stroke_Overlay = 0x0336,// U+0336Combining Long Stroke Overlay
U_Combining_Short_Solidus_Overlay = 0x0337,// U+0337Combining Short Solidus Overlay
U_Combining_Long_Solidus_Overlay = 0x0338,// U+0338Combining Long Solidus Overlay
U_Combining_Right_Half_Ring_Below = 0x0339,// U+0339Combining Right Half Ring Below
U_Combining_Inverted_Bridge_Below = 0x033A,// U+033ACombining Inverted Bridge Below
U_Combining_Square_Below = 0x033B,// U+033BCombining Square Below
U_Combining_Seagull_Below = 0x033C,// U+033CCombining Seagull Below
U_Combining_X_Above = 0x033D,// U+033DCombining X Above
U_Combining_Vertical_Tilde = 0x033E,// U+033ECombining Vertical Tilde
U_Combining_Double_Overline = 0x033F,// U+033FCombining Double Overline
U_Combining_Grave_Tone_Mark = 0x0340,// U+0340Combining Grave Tone Mark
U_Combining_Acute_Tone_Mark = 0x0341,// U+0341Combining Acute Tone Mark
U_Combining_Greek_Perispomeni = 0x0342,// U+0342Combining Greek Perispomeni
U_Combining_Greek_Koronis = 0x0343,// U+0343Combining Greek Koronis
U_Combining_Greek_Dialytika_Tonos = 0x0344,// U+0344Combining Greek Dialytika Tonos
U_Combining_Greek_Ypogegrammeni = 0x0345,// U+0345Combining Greek Ypogegrammeni
U_Combining_Bridge_Above = 0x0346,// U+0346Combining Bridge Above
U_Combining_Equals_Sign_Below = 0x0347,// U+0347Combining Equals Sign Below
U_Combining_Double_Vertical_Line_Below = 0x0348,// U+0348Combining Double Vertical Line Below
U_Combining_Left_Angle_Below = 0x0349,// U+0349Combining Left Angle Below
U_Combining_Not_Tilde_Above = 0x034A,// U+034ACombining Not Tilde Above
U_Combining_Homothetic_Above = 0x034B,// U+034BCombining Homothetic Above
U_Combining_Almost_Equal_To_Above = 0x034C,// U+034CCombining Almost Equal To Above
U_Combining_Left_Right_Arrow_Below = 0x034D,// U+034DCombining Left Right Arrow Below
U_Combining_Upwards_Arrow_Below = 0x034E,// U+034ECombining Upwards Arrow Below
U_Combining_Grapheme_Joiner = 0x034F,// U+034FCombining Grapheme Joiner
U_Combining_Right_Arrowhead_Above = 0x0350,// U+0350Combining Right Arrowhead Above
U_Combining_Left_Half_Ring_Above = 0x0351,// U+0351Combining Left Half Ring Above
U_Combining_Fermata = 0x0352,// U+0352Combining Fermata
U_Combining_X_Below = 0x0353,// U+0353Combining X Below
U_Combining_Left_Arrowhead_Below = 0x0354,// U+0354Combining Left Arrowhead Below
U_Combining_Right_Arrowhead_Below = 0x0355,// U+0355Combining Right Arrowhead Below
U_Combining_Right_Arrowhead_And_Up_Arrowhead_Below = 0x0356,// U+0356Combining Right Arrowhead And Up Arrowhead Below
U_Combining_Right_Half_Ring_Above = 0x0357,// U+0357Combining Right Half Ring Above
U_Combining_Dot_Above_Right = 0x0358,// U+0358Combining Dot Above Right
U_Combining_Asterisk_Below = 0x0359,// U+0359Combining Asterisk Below
U_Combining_Double_Ring_Below = 0x035A,// U+035ACombining Double Ring Below
U_Combining_Zigzag_Above = 0x035B,// U+035BCombining Zigzag Above
U_Combining_Double_Breve_Below = 0x035C,// U+035CCombining Double Breve Below
U_Combining_Double_Breve = 0x035D,// U+035DCombining Double Breve
U_Combining_Double_Macron = 0x035E,// U+035ECombining Double Macron
U_Combining_Double_Macron_Below = 0x035F,// U+035FCombining Double Macron Below
U_Combining_Double_Tilde = 0x0360,// U+0360Combining Double Tilde
U_Combining_Double_Inverted_Breve = 0x0361,// U+0361Combining Double Inverted Breve
U_Combining_Double_Rightwards_Arrow_Below = 0x0362,// U+0362Combining Double Rightwards Arrow Below
U_Combining_Latin_Small_Letter_A = 0x0363, // U+0363Combining Latin Small Letter A
U_Combining_Latin_Small_Letter_E = 0x0364, // U+0364Combining Latin Small Letter E
U_Combining_Latin_Small_Letter_I = 0x0365, // U+0365Combining Latin Small Letter I
U_Combining_Latin_Small_Letter_O = 0x0366, // U+0366Combining Latin Small Letter O
U_Combining_Latin_Small_Letter_U = 0x0367, // U+0367Combining Latin Small Letter U
U_Combining_Latin_Small_Letter_C = 0x0368, // U+0368Combining Latin Small Letter C
U_Combining_Latin_Small_Letter_D = 0x0369, // U+0369Combining Latin Small Letter D
U_Combining_Latin_Small_Letter_H = 0x036A, // U+036ACombining Latin Small Letter H
U_Combining_Latin_Small_Letter_M = 0x036B, // U+036BCombining Latin Small Letter M
U_Combining_Latin_Small_Letter_R = 0x036C, // U+036CCombining Latin Small Letter R
U_Combining_Latin_Small_Letter_T = 0x036D, // U+036DCombining Latin Small Letter T
U_Combining_Latin_Small_Letter_V = 0x036E, // U+036ECombining Latin Small Letter V
U_Combining_Latin_Small_Letter_X = 0x036F, // U+036FCombining Latin Small Letter X
/**
* Unicode Character 'LINE SEPARATOR' (U+2028)
* http://www.fileformat.info/info/unicode/char/2028/index.htm
*/
LINE_SEPARATOR = 0x2028,
/**
* Unicode Character 'PARAGRAPH SEPARATOR' (U+2029)
* http://www.fileformat.info/info/unicode/char/2029/index.htm
*/
PARAGRAPH_SEPARATOR = 0x2029,
/**
* Unicode Character 'NEXT LINE' (U+0085)
* http://www.fileformat.info/info/unicode/char/0085/index.htm
*/
NEXT_LINE = 0x0085,
// http://www.fileformat.info/info/unicode/category/Sk/list.htm
U_CIRCUMFLEX = 0x005E,// U+005ECIRCUMFLEX
U_GRAVE_ACCENT = 0x0060,// U+0060GRAVE ACCENT
U_DIAERESIS = 0x00A8,// U+00A8DIAERESIS
U_MACRON = 0x00AF,// U+00AFMACRON
U_ACUTE_ACCENT = 0x00B4,// U+00B4ACUTE ACCENT
U_CEDILLA = 0x00B8,// U+00B8CEDILLA
U_MODIFIER_LETTER_LEFT_ARROWHEAD = 0x02C2,// U+02C2MODIFIER LETTER LEFT ARROWHEAD
U_MODIFIER_LETTER_RIGHT_ARROWHEAD = 0x02C3,// U+02C3MODIFIER LETTER RIGHT ARROWHEAD
U_MODIFIER_LETTER_UP_ARROWHEAD = 0x02C4,// U+02C4MODIFIER LETTER UP ARROWHEAD
U_MODIFIER_LETTER_DOWN_ARROWHEAD = 0x02C5,// U+02C5MODIFIER LETTER DOWN ARROWHEAD
U_MODIFIER_LETTER_CENTRED_RIGHT_HALF_RING = 0x02D2,// U+02D2MODIFIER LETTER CENTRED RIGHT HALF RING
U_MODIFIER_LETTER_CENTRED_LEFT_HALF_RING = 0x02D3,// U+02D3MODIFIER LETTER CENTRED LEFT HALF RING
U_MODIFIER_LETTER_UP_TACK = 0x02D4,// U+02D4MODIFIER LETTER UP TACK
U_MODIFIER_LETTER_DOWN_TACK = 0x02D5,// U+02D5MODIFIER LETTER DOWN TACK
U_MODIFIER_LETTER_PLUS_SIGN = 0x02D6,// U+02D6MODIFIER LETTER PLUS SIGN
U_MODIFIER_LETTER_MINUS_SIGN = 0x02D7,// U+02D7MODIFIER LETTER MINUS SIGN
U_BREVE = 0x02D8,// U+02D8BREVE
U_DOT_ABOVE = 0x02D9,// U+02D9DOT ABOVE
U_RING_ABOVE = 0x02DA,// U+02DARING ABOVE
U_OGONEK = 0x02DB,// U+02DBOGONEK
U_SMALL_TILDE = 0x02DC,// U+02DCSMALL TILDE
U_DOUBLE_ACUTE_ACCENT = 0x02DD,// U+02DDDOUBLE ACUTE ACCENT
U_MODIFIER_LETTER_RHOTIC_HOOK = 0x02DE,// U+02DEMODIFIER LETTER RHOTIC HOOK
U_MODIFIER_LETTER_CROSS_ACCENT = 0x02DF,// U+02DFMODIFIER LETTER CROSS ACCENT
U_MODIFIER_LETTER_EXTRA_HIGH_TONE_BAR = 0x02E5,// U+02E5MODIFIER LETTER EXTRA-HIGH TONE BAR
U_MODIFIER_LETTER_HIGH_TONE_BAR = 0x02E6,// U+02E6MODIFIER LETTER HIGH TONE BAR
U_MODIFIER_LETTER_MID_TONE_BAR = 0x02E7,// U+02E7MODIFIER LETTER MID TONE BAR
U_MODIFIER_LETTER_LOW_TONE_BAR = 0x02E8,// U+02E8MODIFIER LETTER LOW TONE BAR
U_MODIFIER_LETTER_EXTRA_LOW_TONE_BAR = 0x02E9,// U+02E9MODIFIER LETTER EXTRA-LOW TONE BAR
U_MODIFIER_LETTER_YIN_DEPARTING_TONE_MARK = 0x02EA,// U+02EAMODIFIER LETTER YIN DEPARTING TONE MARK
U_MODIFIER_LETTER_YANG_DEPARTING_TONE_MARK = 0x02EB,// U+02EBMODIFIER LETTER YANG DEPARTING TONE MARK
U_MODIFIER_LETTER_UNASPIRATED = 0x02ED,// U+02EDMODIFIER LETTER UNASPIRATED
U_MODIFIER_LETTER_LOW_DOWN_ARROWHEAD = 0x02EF,// U+02EFMODIFIER LETTER LOW DOWN ARROWHEAD
U_MODIFIER_LETTER_LOW_UP_ARROWHEAD = 0x02F0,// U+02F0MODIFIER LETTER LOW UP ARROWHEAD
U_MODIFIER_LETTER_LOW_LEFT_ARROWHEAD = 0x02F1,// U+02F1MODIFIER LETTER LOW LEFT ARROWHEAD
U_MODIFIER_LETTER_LOW_RIGHT_ARROWHEAD = 0x02F2,// U+02F2MODIFIER LETTER LOW RIGHT ARROWHEAD
U_MODIFIER_LETTER_LOW_RING = 0x02F3,// U+02F3MODIFIER LETTER LOW RING
U_MODIFIER_LETTER_MIDDLE_GRAVE_ACCENT = 0x02F4,// U+02F4MODIFIER LETTER MIDDLE GRAVE ACCENT
U_MODIFIER_LETTER_MIDDLE_DOUBLE_GRAVE_ACCENT = 0x02F5,// U+02F5MODIFIER LETTER MIDDLE DOUBLE GRAVE ACCENT
U_MODIFIER_LETTER_MIDDLE_DOUBLE_ACUTE_ACCENT = 0x02F6,// U+02F6MODIFIER LETTER MIDDLE DOUBLE ACUTE ACCENT
U_MODIFIER_LETTER_LOW_TILDE = 0x02F7,// U+02F7MODIFIER LETTER LOW TILDE
U_MODIFIER_LETTER_RAISED_COLON = 0x02F8,// U+02F8MODIFIER LETTER RAISED COLON
U_MODIFIER_LETTER_BEGIN_HIGH_TONE = 0x02F9,// U+02F9MODIFIER LETTER BEGIN HIGH TONE
U_MODIFIER_LETTER_END_HIGH_TONE = 0x02FA,// U+02FAMODIFIER LETTER END HIGH TONE
U_MODIFIER_LETTER_BEGIN_LOW_TONE = 0x02FB,// U+02FBMODIFIER LETTER BEGIN LOW TONE
U_MODIFIER_LETTER_END_LOW_TONE = 0x02FC,// U+02FCMODIFIER LETTER END LOW TONE
U_MODIFIER_LETTER_SHELF = 0x02FD,// U+02FDMODIFIER LETTER SHELF
U_MODIFIER_LETTER_OPEN_SHELF = 0x02FE,// U+02FEMODIFIER LETTER OPEN SHELF
U_MODIFIER_LETTER_LOW_LEFT_ARROW = 0x02FF,// U+02FFMODIFIER LETTER LOW LEFT ARROW
U_GREEK_LOWER_NUMERAL_SIGN = 0x0375,// U+0375GREEK LOWER NUMERAL SIGN
U_GREEK_TONOS = 0x0384,// U+0384GREEK TONOS
U_GREEK_DIALYTIKA_TONOS = 0x0385,// U+0385GREEK DIALYTIKA TONOS
U_GREEK_KORONIS = 0x1FBD,// U+1FBDGREEK KORONIS
U_GREEK_PSILI = 0x1FBF,// U+1FBFGREEK PSILI
U_GREEK_PERISPOMENI = 0x1FC0,// U+1FC0GREEK PERISPOMENI
U_GREEK_DIALYTIKA_AND_PERISPOMENI = 0x1FC1,// U+1FC1GREEK DIALYTIKA AND PERISPOMENI
U_GREEK_PSILI_AND_VARIA = 0x1FCD,// U+1FCDGREEK PSILI AND VARIA
U_GREEK_PSILI_AND_OXIA = 0x1FCE,// U+1FCEGREEK PSILI AND OXIA
U_GREEK_PSILI_AND_PERISPOMENI = 0x1FCF,// U+1FCFGREEK PSILI AND PERISPOMENI
U_GREEK_DASIA_AND_VARIA = 0x1FDD,// U+1FDDGREEK DASIA AND VARIA
U_GREEK_DASIA_AND_OXIA = 0x1FDE,// U+1FDEGREEK DASIA AND OXIA
U_GREEK_DASIA_AND_PERISPOMENI = 0x1FDF,// U+1FDFGREEK DASIA AND PERISPOMENI
U_GREEK_DIALYTIKA_AND_VARIA = 0x1FED,// U+1FEDGREEK DIALYTIKA AND VARIA
U_GREEK_DIALYTIKA_AND_OXIA = 0x1FEE,// U+1FEEGREEK DIALYTIKA AND OXIA
U_GREEK_VARIA = 0x1FEF,// U+1FEFGREEK VARIA
U_GREEK_OXIA = 0x1FFD,// U+1FFDGREEK OXIA
U_GREEK_DASIA = 0x1FFE,// U+1FFEGREEK DASIA
U_OVERLINE = 0x203E, // Unicode Character 'OVERLINE'
/**
* UTF-8 BOM
* Unicode Character 'ZERO WIDTH NO-BREAK SPACE' (U+FEFF)
* http://www.fileformat.info/info/unicode/char/feff/index.htm
*/
UTF8_BOM = 65279
} | the_stack |
import * as THREE from 'three';
import {each, filter, findKey} from 'lodash';
import IslandAmbience from '../editor/areas/island/browser/ambience';
import LocationsNode from '../editor/areas/gameplay/locator/LocationsNode';
import Island from '../../game/scenery/island/Island';
import { createScreen } from './vrScreen';
import { handlePicking, performRaycasting } from './picking';
import { drawFrame } from './vrUtils';
import sceneMapping from '../../game/scenery/island/data/sceneMapping';
import islandOffsets from './data/islandOffsets';
import {tr} from '../../lang';
import { WORLD_SCALE_B, WORLD_SIZE } from '../../utils/lba';
import { getParams } from '../../params';
import GroundInfo from '../../game/scenery/island/physics/GroundInfo';
let islandWrapper = null;
let activeIsland: Island = null;
let loading = false;
let selectedPlanet = 0;
let selectedIsland = 0;
let sectionsPlanes = null;
let light = null;
const planetButtons = [];
const islandButtons = [];
const intersectObjects = [];
const arrow = createArrow();
const invWorldMat = new THREE.Matrix4();
const planets = LocationsNode.children;
const isLBA1 = getParams().game === 'lba1';
export function createTeleportMenu(sceneLight) {
const teleportMenu = new THREE.Object3D();
if (!isLBA1) {
for (let i = 0; i < 4; i += 1) {
const p = createPlanetItem({
idx: i,
text: planets[i].name,
icon: planets[i].icon,
x: -(i - 1.5) * 240,
y: 50,
callback: () => {
if (selectedPlanet !== i) {
selectedPlanet = i;
selectedIsland = 0;
each(planetButtons, pb => pb.draw());
refreshIslandButtons(teleportMenu);
loadIsland(planets[i].children[0].id);
}
}
});
teleportMenu.add(p.mesh);
planetButtons.push(p);
intersectObjects.push(p.mesh);
}
}
refreshIslandButtons(teleportMenu);
const backButton = createButton({
text: tr('backToMainMenu'),
y: 230,
callback: () => {
history.back();
}
});
teleportMenu.add(backButton);
intersectObjects.push(backButton);
islandWrapper = new THREE.Object3D();
const scale = 0.5 / WORLD_SIZE;
islandWrapper.scale.set(scale, scale, scale);
teleportMenu.add(islandWrapper);
arrow.visible = false;
teleportMenu.add(arrow);
light = sceneLight;
return teleportMenu;
}
function refreshIslandButtons(teleportMenu) {
const planet = planets[selectedPlanet];
const islands = filter(planet.children, n => !n.name.match(/^\[DEMO\]/));
// cleanup
for (let i = 0; i < islandButtons.length; i += 1) {
teleportMenu.remove(islandButtons[i].mesh);
const idx = intersectObjects.indexOf(islandButtons[i].mesh);
intersectObjects.splice(idx, 1);
}
islandButtons.length = 0;
for (let i = 0; i < islands.length; i += 1) {
let x;
let y;
if (islands.length <= 3) {
const offset = (islands.length - 1) * 0.5;
x = -(i - offset) * 320;
y = -130;
} else if (i < 3) {
x = -(i - 1) * 320;
y = -130;
} else {
const offset = (islands.length - 4) * 0.5;
x = -((i - 3) - offset) * 320;
y = -230;
}
const isl = createIslandItem({
idx: i,
text: islands[i].name,
x,
y,
callback: () => {
selectedIsland = i;
each(islandButtons, ib => ib.draw());
loadIsland(islands[i].id);
}
});
teleportMenu.add(isl.mesh);
islandButtons.push(isl);
intersectObjects.push(isl.mesh);
}
}
async function loadIsland(name) {
loading = true;
const ambience = IslandAmbience[name];
const island = await Island.loadForPreview(name, ambience);
if (activeIsland) {
islandWrapper.remove(activeIsland.threeObject);
}
activeIsland = island;
islandWrapper.add(island.threeObject);
sectionsPlanes = island.threeObject.getObjectByName('sectionsPlanes');
light.position.applyAxisAngle(
new THREE.Vector3(0, 0, 1),
-(ambience.lightingAlpha * 2 * Math.PI) / 0x1000
);
light.position.applyAxisAngle(
new THREE.Vector3(0, 1, 0),
(-(ambience.lightingBeta * 2 * Math.PI) / 0x1000) + Math.PI
);
const offset = islandOffsets[name];
islandWrapper.position.set(offset.x, -1.4, offset.z);
islandWrapper.quaternion.setFromEuler(
new THREE.Euler(0, THREE.MathUtils.degToRad(offset.angle), 0)
);
islandWrapper.updateMatrixWorld();
invWorldMat.copy(islandWrapper.matrixWorld);
invWorldMat.invert();
loading = false;
}
const clock = new THREE.Clock(false);
clock.start();
export function updateTeleportMenu(game, sceneManager, pickingTarget) {
const time = {
delta: Math.min(clock.getDelta(), 0.05),
elapsed: clock.getElapsedTime()
};
if (activeIsland === null && !loading) {
loadIsland('CITABAU');
}
const hit = handlePicking(intersectObjects, {
game,
pickingTarget
});
if (activeIsland) {
activeIsland.update(null, null, time);
arrow.visible = false;
if (!hit) {
performRaycasting(
sectionsPlanes.children,
{game, sceneManager},
handleGroundIntersection
);
}
}
// The following commented code is used for adjusting the island offset
/*
const {controlsState} = game;
const cv = controlsState.controlVector;
angle += controlsState.angle * 0.01;
islandWrapper.position.add(new THREE.Vector3(cv.x * 0.02, 0, -cv.y * 0.02));
islandWrapper.quaternion.setFromEuler(new THREE.Euler(0, angle, 0));
if (controlsState.action) {
console.log(activeIsland.name, {
x: islandWrapper.position.x,
z: islandWrapper.position.z,
angle: THREE.MathUtils.radToDeg(angle)
});
}
*/
}
const POS = new THREE.Vector3();
const GROUND = new GroundInfo();
function handleGroundIntersection(intersect, triggered, {game, sceneManager}) {
arrow.visible = true;
arrow.position.copy(intersect.point);
POS.copy(intersect.point);
POS.applyMatrix4(invWorldMat);
activeIsland.physics.heightmap.getGroundInfo(POS, GROUND);
arrow.position.y += GROUND.height * (0.5 / WORLD_SIZE);
POS.y = GROUND.height;
if (triggered) {
const section = intersect.object.userData.info;
const scene = findKey(
sceneMapping,
// @ts-ignore
s => s.island === activeIsland.name && s.section === section.index
);
if (scene !== undefined) {
game.resume();
sceneManager.hideMenuAndGoto(Number(scene), false)
.then((newScene) => {
const newHero = newScene.actors[0];
POS.add(new THREE.Vector3(
-((section.x * 64) + 1) * WORLD_SCALE_B,
0,
-(section.z * 64) * WORLD_SCALE_B
));
newHero.physics.position.copy(POS);
newHero.threeObject.position.copy(POS);
});
game.setUiState({teleportMenu: false});
history.replaceState({id: 'game'}, '');
}
}
}
function createPlanetItem({x, y, text, icon: iconSrc, idx, callback}) {
const width = 200;
const height = 220;
const {ctx, mesh} = createScreen({
width,
height,
x,
y,
});
const icon = new Image(160, 160);
icon.src = iconSrc;
let hovering = false;
function draw() {
const selected = idx === selectedPlanet;
drawFrame(ctx, 0, 0, width, height, selected);
ctx.font = '20px LBA';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillStyle = selected || hovering ? 'white' : 'grey';
ctx.shadowColor = 'black';
ctx.shadowOffsetX = 2;
ctx.shadowOffsetY = 2;
ctx.fillText(text, width / 2, 200);
ctx.drawImage(icon, 20, 20, 160, 160);
(mesh.material as THREE.MeshBasicMaterial).map.needsUpdate = true;
}
icon.onload = () => draw();
mesh.visible = true;
mesh.userData = {
callback,
onEnter: () => {
hovering = true;
draw();
},
onLeave: () => {
hovering = false;
draw();
}
};
return {mesh, draw};
}
function createIslandItem({x, y, text, idx, callback}) {
const width = 300;
const height = 80;
const {ctx, mesh} = createScreen({
width,
height,
x,
y,
});
const icon = new Image(40, 40);
icon.src = 'editor/icons/locations/island.svg';
let hovering = false;
const draw = () => {
const selected = idx === selectedIsland;
drawFrame(ctx, 0, 0, width, height, selected);
ctx.font = '20px LBA';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillStyle = selected || hovering ? 'white' : 'grey';
ctx.shadowColor = 'black';
ctx.shadowOffsetX = 2;
ctx.shadowOffsetY = 2;
ctx.fillText(text, 175, 40);
const metrics = ctx.measureText(text);
ctx.drawImage(icon, 115 - (metrics.width * 0.5), 20, 40, 40);
(mesh.material as THREE.MeshBasicMaterial).map.needsUpdate = true;
};
icon.onload = () => draw();
mesh.visible = true;
mesh.userData = {
callback,
onEnter: () => {
hovering = true;
draw();
},
onLeave: () => {
hovering = false;
draw();
}
};
return {mesh, draw};
}
interface ButtonOptions {
x?: number;
y?: number;
text: string;
callback?: Function;
}
function createButton({x, y, text, callback}: ButtonOptions) {
const width = 500;
const height = 75;
const {ctx, mesh} = createScreen({
width,
height,
x,
y,
});
const draw = (hovering = false) => {
drawFrame(ctx, 0, 0, width, height, hovering);
ctx.font = '30px LBA';
ctx.fillStyle = 'white';
ctx.shadowColor = 'black';
ctx.shadowOffsetX = 2;
ctx.shadowOffsetY = 2;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(text, width / 2, height / 2);
(mesh.material as THREE.MeshBasicMaterial).map.needsUpdate = true;
};
draw();
mesh.visible = true;
mesh.userData = {
callback,
onEnter: () => draw(true),
onLeave: () => draw()
};
return mesh;
}
function createArrow() {
const newArrow = new THREE.Object3D();
const material = new THREE.MeshPhongMaterial({color: 0xFF0000});
const cnGeometry = new THREE.ConeGeometry(5, 12, 32);
const cone = new THREE.Mesh(cnGeometry, material);
cone.quaternion.setFromEuler(new THREE.Euler(Math.PI, 0, 0));
cone.position.set(0, 6, 0);
newArrow.add(cone);
const clGeometry = new THREE.CylinderGeometry(1, 1, 10, 32);
const cylinder = new THREE.Mesh(clGeometry, material);
cylinder.position.set(0, 16, 0);
newArrow.add(cylinder);
newArrow.scale.set(0.01, 0.01, 0.01);
return newArrow;
} | the_stack |
import {
CLIENT_NO_SERVER_PING_CLOSE_TIMEOUT,
CONNECTION_RETRY_TIME,
IS_DEBUG,
FLAGS,
LOG_LEVEL_LS
} from '@/ts/utils/consts';
import {
Logger,
LogLevel,
} from 'lines-logger';
import loggerFactory from '@/ts/instances/loggerFactory';
import MessageHandler from '@/ts/message_handlers/MesageHandler';
import {
CurrentUserInfoModel,
CurrentUserInfoWoImage,
CurrentUserSettingsModel,
Location,
MessageStatus,
UserModel
} from '@/ts/types/model';
import {
MessageSupplier,
SessionHolder
} from '@/ts/types/types';
import {
convertLocation,
convertUser,
currentUserInfoDtoToModel,
userSettingsDtoToModel
} from '@/ts/types/converters';
import {
GiphyDto,
MessageModelDto,
RoomNoUsersDto,
UserProfileDto,
UserProfileDtoWoImage,
UserSettingsDto
} from '@/ts/types/dto';
import { sub } from '@/ts/instances/subInstance';
import { DefaultStore } from '@/ts/classes/DefaultStore';
import {WsMessageProcessor }from '@/ts/message_handlers/WsMessageProcessor';
import {
AddChannelMessage,
AddInviteMessage,
AddRoomMessage,
DefaultWsInMessage,
DeleteMessage,
EditMessage,
PingMessage,
PongMessage,
PrintMessage,
SaveChannelSettingsMessage,
SetProfileImageMessage,
SetSettingsMessage,
SetUserProfileMessage,
SetWsIdMessage,
MessagesResponseMessage,
UserProfileChangedMessage,
WebRtcSetConnectionIdMessage,
SyncHistoryResponseMessage,
GetCountryCodeMessage
} from '@/ts/types/messages/wsInMessages';
import {
InternetAppearMessage,
LogoutMessage,
PubSetRooms
} from '@/ts/types/messages/innerMessages';
import {
HandlerType,
HandlerTypes
} from '@/ts/types/messages/baseMessagesInterfaces';
import {
DefaultWsOutMessage,
SyncHistoryOutMessage
} from '@/ts/types/messages/wsOutMessages';
enum WsState {
NOT_INITED, TRIED_TO_CONNECT, CONNECTION_IS_LOST, CONNECTED
}
export default class WsHandler extends MessageHandler implements MessageSupplier {
// how much current time is ahead of the server time
// if current time is in the past it will be negative
private timeDiffWithServer: number = 0;
protected readonly logger: Logger;
protected readonly handlers: HandlerTypes<keyof WsHandler, 'ws'> = {
setSettings: <HandlerType<'setSettings', 'ws'>>this.setSettings,
setUserProfile: <HandlerType<'setUserProfile', 'ws'>>this.setUserProfile,
setProfileImage: <HandlerType<'setProfileImage', 'ws'>>this.setProfileImage,
setWsId: <HandlerType<'setWsId', 'ws'>>this.setWsId,
logout: <HandlerType<'logout', 'ws'>>this.logout,
userProfileChanged: <HandlerType<'userProfileChanged', 'ws'>>this.userProfileChanged,
ping: <HandlerType<'ping', 'ws'>>this.ping,
pong: <HandlerType<'pong', 'ws'>> this.pong
};
private pingTimeoutFunction: number|null = null;
private ws: WebSocket | null = null;
private noServerPingTimeout: any;
private readonly store: DefaultStore;
private readonly sessionHolder: SessionHolder;
private listenWsTimeout: number|null = null;
private readonly API_URL: string;
private readonly messageProc: WsMessageProcessor;
private wsState: WsState = WsState.NOT_INITED;
// this.dom = {
// onlineStatus: $('onlineStatus'),
// onlineClass: 'online',
// offlineClass: OFFLINE_CLASS
// };
// private progressInterval = {}; TODO this was commented along with usage, check if it breaks anything
private wsConnectionId = '';
constructor(API_URL: string, sessionHolder: SessionHolder, store: DefaultStore) {
super();
sub.subscribe('ws', this);
this.API_URL = API_URL;
this.messageProc = new WsMessageProcessor(this, store, 'ws');
this.logger = loggerFactory.getLoggerColor('ws', '#4c002b');
this.sessionHolder = sessionHolder;
this.store = store;
}
sendRawTextToServer(message: string): boolean {
if (this.isWsOpen()) {
this.ws!.send(message);
return true;
} else {
return false;
}
}
public getWsConnectionId () {
return this.wsConnectionId;
}
public async getCountryCode(): Promise<GetCountryCodeMessage> {
return this.messageProc.sendToServerAndAwait({
action: 'getCountryCode'
});
}
public async offerFile(roomId: number, browser: string, name: string, size: number, threadId: number|null): Promise<WebRtcSetConnectionIdMessage> {
return this.messageProc.sendToServerAndAwait({
action: 'offerFile',
roomId,
threadId,
content: {browser, name, size}
});
}
public async offerCall(roomId: number, browser: string): Promise<WebRtcSetConnectionIdMessage> {
return this.messageProc.sendToServerAndAwait({
action: 'offerCall',
roomId: roomId,
content: {browser}
});
}
public acceptFile(connId: string, received: number) {
this.sendToServer({
action: 'acceptFile',
connId,
content: {
received
}
});
}
public replyFile(connId: string, browser: string) {
this.sendToServer({
action: 'replyFile',
connId,
content: {browser}
});
}
public destroyFileConnection(connId: string, content: unknown) {
this.sendToServer({
content,
action: 'destroyFileConnection',
connId
});
}
public destroyPeerFileConnection(connId: string, content: any, opponentWsId: string) {
this.sendToServer({
content,
opponentWsId,
action: 'destroyFileConnection',
connId
});
}
public async search(
searchString: string,
roomId: number,
offset: number,
): Promise<MessagesResponseMessage> {
return this.messageProc.sendToServerAndAwait({
searchString,
roomId,
offset,
action: 'searchMessages'
});
}
public sendEditMessage(
content: string|null,
id: number,
files: number[] | null,
tags: Record<string, number>,
giphies: GiphyDto[]
) {
const newVar = {
id,
action: 'editMessage',
files,
tags,
giphies,
content
};
this.sendToServer(newVar, true);
}
public async sendPrintMessage(
content: string,
roomId: number,
files: number[],
id: number,
timeDiff: number,
parentMessage: number|null,
tags: Record<string, number>,
giphies: GiphyDto[],
): Promise<PrintMessage> {
const newVar = {
files,
id,
timeDiff,
action: 'printMessage',
content,
tags,
parentMessage,
roomId,
giphies
};
return this.messageProc.sendToServerAndAwait(newVar);
}
public async saveSettings(content: UserSettingsDto): Promise<SetSettingsMessage|unknown> {
return this.messageProc.sendToServerAndAwait({
action: 'setSettings',
content
});
}
public showIType(roomId: number): void {
this.sendToServer({
roomId,
action: 'showIType'
});
}
public async saveUser(content: UserProfileDtoWoImage): Promise<SetUserProfileMessage|unknown> {
return this.messageProc.sendToServerAndAwait({
action: 'setUserProfile',
content
});
}
public async sendAddRoom(name: string|null, p2p: boolean, volume: number, notifications: boolean, users: number[], channelId: number|null): Promise<AddRoomMessage> {
return this.messageProc.sendToServerAndAwait({
users,
name,
p2p,
channelId,
action: 'addRoom',
volume,
notifications
});
}
public async syncHistory(
roomIds: number[],
messagesIds: number[],
receivedMessageIds: number[],
onServerMessageIds: number[],
lastSynced: number
): Promise<SyncHistoryResponseMessage> {
let payload: SyncHistoryOutMessage = {
messagesIds,
receivedMessageIds,
onServerMessageIds,
roomIds,
lastSynced,
action: 'syncHistory'
};
return this.messageProc.sendToServerAndAwait(payload);
}
public async sendAddChannel(channelName: string, users: number[]): Promise<AddChannelMessage> {
return this.messageProc.sendToServerAndAwait({
channelName,
users,
action: 'addChannel'
});
}
public async sendRoomSettings(message: RoomNoUsersDto): Promise<void> {
return this.messageProc.sendToServerAndAwait({
...message,
action: 'saveRoomSettings'
});
}
public async sendDeleteChannel(channelId: number): Promise<unknown> {
return this.messageProc.sendToServerAndAwait({
channelId,
action: 'deleteChannel'
});
}
public async sendLeaveChannel(channelId: number): Promise<unknown> {
return this.messageProc.sendToServerAndAwait({
channelId,
action: 'leaveChannel'
});
}
public async saveChannelSettings(
channelName: string,
channelId: number,
channelCreatorId: number,
volume: number,
notifications: boolean,
): Promise<SaveChannelSettingsMessage> {
return this.messageProc.sendToServerAndAwait({
action: 'saveChannelSettings',
channelId,
channelCreatorId,
channelName,
volume,
notifications,
});
}
public async inviteUser(roomId: number, users: number[]): Promise<AddInviteMessage> {
return this.messageProc.sendToServerAndAwait({
roomId,
users,
action: 'inviteUser'
});
}
public async startListening(): Promise<void> {
return new Promise(((resolve, reject) => {
this.logger.log('Starting webSocket')();
if (!this.listenWsTimeout && !this.ws) {
this.ws = new WebSocket(this.wsUrl);
this.ws.onmessage = this.onWsMessage.bind(this);
this.ws.onclose = (e) => {
setTimeout(() => reject(Error('Cannot connect to websocket')));
this.onWsClose(e);
}
this.ws.onopen = () => {
setTimeout(resolve);
this.onWsOpen();
}
} else {
resolve();
}
}));
}
public pingServer() {
this.sendToServer({action: 'ping'}, true);
// TODO not used
// this.answerPong();
// this.pingTimeoutFunction = setTimeout(() => {
// this.logger.error('Force closing socket coz pong time out')();
// this.ws.close(1000, 'Ping timeout');
// }, PING_CLOSE_JS_DELAY);
//
}
public logout(a: LogoutMessage) {
const info = [];
if (this.listenWsTimeout) {
this.listenWsTimeout = null;
info.push('purged timeout');
}
if (this.ws) {
this.ws.onclose = null;
info.push('closed ws');
this.ws.close();
this.ws = null;
}
this.logger.debug('Finished ws: {}', info.join(', '))();
}
public async sendDeleteRoom(roomId: number) {
return this.messageProc.sendToServerAndAwait({
roomId,
action: 'deleteRoom'
});
}
public async sendLeaveRoom(roomId: number) {
return this.messageProc.sendToServerAndAwait({
roomId,
action: 'leaveUser'
});
}
public async setMessageStatus(
messagesIds: number[],
roomId: number,
status: MessageStatus
) {
return this.messageProc.sendToServerAndAwait({
messagesIds,
action: 'setMessageStatus',
status,
roomId // this room event will be published to
});
}
public async sendLoadMessages(
roomId: number,
count: number,
threadId: number|null,
excludeIds: number[]
): Promise<MessagesResponseMessage> {
return this.messageProc.sendToServerAndAwait({
count,
excludeIds,
threadId,
action: 'loadMessages',
roomId
});
}
public async sendLoadMessagesByIds(
roomId: number,
messagesIds: number[]
): Promise<MessagesResponseMessage> {
return this.messageProc.sendToServerAndAwait({
messagesIds,
action: 'loadMessagesByIds',
roomId
});
}
public isWsOpen() {
return this.ws?.readyState === WebSocket.OPEN;
}
public sendRtcData(content: RTCSessionDescriptionInit| RTCIceCandidate, connId: string, opponentWsId: string) {
this.sendToServer({
content,
connId,
opponentWsId,
action: 'sendRtcData'
});
}
public retry(connId: string, opponentWsId: string) {
this.sendToServer({action: 'retryFile', connId, opponentWsId});
}
public replyCall(connId: string, browser: string) {
this.sendToServer({
action: 'replyCall',
connId,
content: {
browser
}
});
}
public destroyCallConnection(connId: string, content: 'decline'| 'hangup') {
this.sendToServer({
content: content,
action: 'destroyCallConnection',
connId
});
}
public async offerMessageConnection(roomId: number): Promise<WebRtcSetConnectionIdMessage> {
return this.messageProc.sendToServerAndAwait({
action: 'offerMessage',
roomId: roomId
});
}
public acceptCall(connId: string) {
this.sendToServer({
action: 'acceptCall',
connId
});
}
public joinCall(connId: string) {
this.sendToServer({
action: 'joinCall',
connId
});
}
public setSettings(m: SetSettingsMessage) {
const a: CurrentUserSettingsModel = userSettingsDtoToModel(m.content);
this.setUserSettings(a);
}
public setUserProfile(m: SetUserProfileMessage) {
const a: CurrentUserInfoWoImage = currentUserInfoDtoToModel(m.content);
a.userId = this.store.userInfo!.userId; // this could came only when we logged in
this.store.setUserInfo(a);
}
public setProfileImage(m: SetProfileImageMessage) {
this.setUserImage(m.content);
}
public convertServerTimeToPC(serverTime: number) {
return serverTime + this.timeDiffWithServer; // serverTime + (Date.now - serverTime) === Date.now
}
public async setWsId(message: SetWsIdMessage) {
this.wsConnectionId = message.opponentWsId;
this.setUserInfo(message.userInfo);
this.setUserSettings(message.userSettings);
this.setUserImage(message.userInfo.userImage);
this.timeDiffWithServer = Date.now() - message.time;
const pubSetRooms: PubSetRooms = {
action: 'init',
channels: message.channels,
handler: 'room',
rooms: message.rooms,
online: message.online,
users: message.users
};
sub.notify(pubSetRooms);
const inetAppear: InternetAppearMessage = {
action: 'internetAppear',
handler: 'any'
};
sub.notify(inetAppear);
this.logger.debug('CONNECTION ID HAS BEEN SET TO {})', this.wsConnectionId)();
if (FLAGS) {
let getCountryCodeMessage = await this.getCountryCode();
let modelLocal: Record<string, Location> = {}
Object.entries(getCountryCodeMessage.content).forEach(([k, v]) => {
modelLocal[k] = convertLocation(v);
});
this.store.setCountryCode(modelLocal);
}
}
public userProfileChanged(message: UserProfileChangedMessage) {
this.store.setUser({
id: message.userId,
user: message.user,
image: message.userImage,
sex: message.sex
});
}
public ping(message: PingMessage) {
this.startNoPingTimeout();
this.sendToServer({action: 'pong', time: message.time});
}
public pong(message: PongMessage) {
// private answerPong() {
if (this.pingTimeoutFunction) {
this.logger.debug('Clearing pingTimeoutFunction')();
clearTimeout(this.pingTimeoutFunction);
this.pingTimeoutFunction = null;
}
// }
}
private setUserInfo(userInfo: UserProfileDto) {
const um: CurrentUserInfoWoImage = currentUserInfoDtoToModel(userInfo);
this.store.setUserInfo(um);
}
private setUserSettings(userInfo: UserSettingsDto) {
const um: UserSettingsDto = userSettingsDtoToModel(userInfo);
const logLevel: LogLevel = userInfo.logs || (IS_DEBUG ? 'trace' : 'error');
localStorage.setItem(LOG_LEVEL_LS, logLevel);
loggerFactory.setLogWarnings(logLevel);
this.store.setUserSettings(um);
}
private setUserImage(image: string) {
this.store.setUserImage(image);
}
private onWsOpen() {
this.setStatus(true);
this.startNoPingTimeout();
this.wsState = WsState.CONNECTED;
this.logger.debug('Connection has been established')();
}
private onWsMessage(message: MessageEvent) {
let data = this.messageProc.parseMessage(message.data);
if (data) {
this.messageProc.handleMessage(data);
}
}
// private hideGrowlProgress(key: number) {
// let progInter = this.progressInterval[key];
// if (progInter) {
// this.logger.debug('Removing progressInterval {}', key)();
// progInter.growl.hide();
// if (progInter.interval) {
// clearInterval(progInter.interval);
// }
// delete this.progressInterval[key];
// }
// }
// sendPreventDuplicates(data, skipGrowl) {
// this.messageId++;
// data.messageId = this.messageId;
// let jsonRequest = JSON.stringify(data);
// if (!this.duplicates[jsonRequest]) {
// this.duplicates[jsonRequest] = Date.now();
// this.sendRawTextToServer(jsonRequest, skipGrowl, data);
// setTimeout(() => {
// delete this.duplicates[jsonRequest];
// }, 5000);
// } else {
// this.logger.warn('blocked duplicate from sending: {}', jsonRequest)();
// }
// }
private setStatus(isOnline: boolean) {
this.store.setIsOnline(isOnline);
this.logger.debug('Setting online to {}', isOnline)();
}
private onWsClose(e: CloseEvent) {
this.logger.log('Got onclose event')();
this.ws = null;
this.setStatus(false);
// tornado drops connection if exception occurs during processing an event we send from WsHandler
this.messageProc.onDropConnection(e.code === 1006 ? 'Server error' : 'Connection to server is lost')
// for (let k in this.progressInterval) {
// this.hideGrowlProgress(k);
// }
if (this.noServerPingTimeout) {
clearTimeout(this.noServerPingTimeout);
this.noServerPingTimeout = null;
}
const reason = e.reason || e;
if (e.code === 403) {
const message = `Server has forbidden request because '${reason}'. Logging out...`;
this.logger.error('onWsClose {}', message)();
this.store.growlError(message);
let message1: LogoutMessage = {
action: 'logout',
handler: 'any'
};
sub.notify(message1);
return;
} else if (this.wsState === WsState.NOT_INITED) {
// this.store.growlError( 'Can\'t establish connection with server');
this.logger.warn('Chat server is down because {}', reason)();
this.wsState = WsState.TRIED_TO_CONNECT;
} else if (this.wsState === WsState.CONNECTED) {
// this.store.growlError( `Connection to chat server has been lost, because ${reason}`);
this.logger.error(
'Connection to WebSocket has failed because "{}". Trying to reconnect every {}ms',
e.reason, CONNECTION_RETRY_TIME)();
}
if (this.wsState !== WsState.TRIED_TO_CONNECT) {
this.wsState = WsState.CONNECTION_IS_LOST;
}
// Try to reconnect in 10 seconds
this.listenWsTimeout = window.setTimeout(() => this.listenWS(), CONNECTION_RETRY_TIME);
}
private listenWS() {
this.ws = new WebSocket(this.wsUrl);
this.ws.onmessage = this.onWsMessage.bind(this);
this.ws.onclose = this.onWsClose.bind(this);
this.ws.onopen = this.onWsOpen.bind(this);
}
private get wsUrl() {
return `${this.API_URL}?id=${this.wsConnectionId}&sessionId=${this.sessionHolder.session}`;
}
private sendToServer<T extends DefaultWsOutMessage<string>>(messageRequest: T, skipGrowl = false): boolean {
const isSent = this.messageProc.sendToServer(messageRequest);
if (!isSent && !skipGrowl) {
this.logger.warn('Can\'t send message, because connection is lost :(')();
}
return isSent;
}
private startNoPingTimeout() {
if (this.noServerPingTimeout) {
clearTimeout(this.noServerPingTimeout);
this.logger.debug('Clearing noServerPingTimeout')();
this.noServerPingTimeout = null;
}
this.noServerPingTimeout = setTimeout(() => {
if (this.ws) {
this.logger.error('Force closing socket coz server didn\'t ping us')();
this.ws.close(1000, 'Sever didn\'t ping us');
}
}, CLIENT_NO_SERVER_PING_CLOSE_TIMEOUT);
}
notifyCallActive(param: { connectionId: string | null; opponentWsId: string; roomId: number }) {
this.sendToServer({
action: 'notifyCallActive',
connId: param.connectionId,
opponentWsId: param.opponentWsId,
roomId: param.roomId
})
}
} | the_stack |
import * as Typesettable from "typesettable";
import { Dataset } from "../core/dataset";
import { Formatter, identity } from "../core/formatters";
import { Bounds, Point, SimpleSelection } from "../core/interfaces";
import { memThunk, Thunk } from "../memoize";
import * as Utils from "../utils";
import { StackExtent } from "../utils/stackingUtils";
import { Label, LabelFontSizePx } from "../components/label";
import { Bar, BarOrientation } from "./barPlot";
import { Plot } from "./plot";
export class StackedBar<X, Y> extends Bar<X, Y> {
protected static _EXTREMA_LABEL_MARGIN_FROM_BAR = 5;
private _extremaFormatter: Formatter = identity();
private _labelArea: SimpleSelection<void>;
private _measurer: Typesettable.CacheMeasurer;
private _writer: Typesettable.Writer;
private _stackingOrder: Utils.Stacking.IStackingOrder;
private _stackingResult: Thunk<Utils.Stacking.StackingResult> = memThunk(
() => this.datasets(),
() => this.position().accessor,
() => this.length().accessor,
() => this._stackingOrder,
(datasets, positionAccessor, lengthAccessor, stackingOrder) => {
return Utils.Stacking.stack(datasets, positionAccessor, lengthAccessor, stackingOrder);
},
);
private _stackedExtent: Thunk<number[]> = memThunk(
this._stackingResult,
() => this.position().accessor,
() => this._filterForProperty(this._isVertical ? "y" : "x"),
(stackingResult, positionAccessor, filter) => {
return Utils.Stacking.stackedExtent(stackingResult, positionAccessor, filter);
},
);
/**
* A StackedBar Plot stacks bars across Datasets based on the primary value of the bars.
* On a vertical StackedBar Plot, the bars with the same X value are stacked.
* On a horizontal StackedBar Plot, the bars with the same Y value are stacked.
*
* @constructor
* @param {Scale} xScale
* @param {Scale} yScale
* @param {string} [orientation="vertical"] One of "vertical"/"horizontal".
*/
constructor(orientation: BarOrientation = "vertical") {
super(orientation);
this.addClass("stacked-bar-plot");
this._stackingOrder = "bottomup";
}
/**
* Gets the stacking order of the plot.
*/
public stackingOrder(): Utils.Stacking.IStackingOrder;
/**
* Sets the stacking order of the plot.
*
* By default, stacked plots are "bottomup", meaning for positive data, the
* first series will be placed at the bottom of the scale and subsequent
* data series will by stacked on top. This can be reveresed by setting
* stacking order to "topdown".
*
* @returns {Plots.StackedArea} This plot
*/
public stackingOrder(stackingOrder: Utils.Stacking.IStackingOrder): this;
public stackingOrder(stackingOrder?: Utils.Stacking.IStackingOrder): any {
if (stackingOrder == null) {
return this._stackingOrder;
}
this._stackingOrder = stackingOrder;
this._onDatasetUpdate();
return this;
}
/**
* Gets the Formatter for the stacked bar extrema labels.
*/
public extremaFormatter(): Formatter;
/**
* Sets the Formatter for the stacked bar extrema labels. Extrema labels are the
* numbers at the very top and bottom of the stack that aren't associated
* with a single datum. Their value will be passed through this formatter
* before being displayed.
*
* @param {Formatter} formatter
* @returns {this}
*/
public extremaFormatter(formatter: Formatter): this;
public extremaFormatter(formatter?: Formatter): any {
if (arguments.length === 0) {
return this._extremaFormatter;
} else {
this._extremaFormatter = formatter;
this.render();
return this;
}
}
public labelFontSize(): LabelFontSizePx;
public labelFontSize(fontSize: LabelFontSizePx): this;
public labelFontSize(fontSize?: LabelFontSizePx): LabelFontSizePx | this {
if (fontSize == null) {
return super.labelFontSize();
} else {
if (this._labelArea != null) {
// clearing to remove outdated font-size classes
this._labelArea.attr("class", null)
.classed(Bar._LABEL_AREA_CLASS, true)
.classed(`label-${this._labelFontSize}`, true);
}
super.labelFontSize(fontSize);
return this;
}
}
protected _setup() {
super._setup();
this._labelArea = this._renderArea
.append("g")
.classed(Bar._LABEL_AREA_CLASS, true)
.classed(`label-${this._labelFontSize}`, true);
const context = new Typesettable.SvgContext(this._labelArea.node() as SVGElement);
this._measurer = new Typesettable.CacheMeasurer(context);
this._writer = new Typesettable.Writer(this._measurer, context);
}
protected _drawLabels() {
super._drawLabels();
// remove all current labels before redrawing
this._labelArea.selectAll("g").remove();
const baselineValue = +this.baselineValue();
const positionScale = this.position().scale;
const lengthScale = this.length().scale;
const { maximumExtents, minimumExtents } = Utils.Stacking.stackedExtents<Date | string | number>(this._stackingResult());
const anyTooWide: boolean[] = [];
/**
* Try drawing the text at the center of the bounds. This method does not draw
* the text if the text would overflow outside of the plot.
*
* @param text
* @param bounds
* @returns {boolean}
*/
const maybeDrawLabel = (text: string, bounds: Bounds, barThickness: number) => {
const { x, y } = bounds.topLeft;
const width = bounds.bottomRight.x - bounds.topLeft.x;
const height = bounds.bottomRight.y - bounds.topLeft.y;
const textTooLong = this._isVertical
? width > barThickness
: height > barThickness;
if (!textTooLong) {
const labelContainer = this._labelArea.append("g").attr("transform", `translate(${x}, ${y})`);
labelContainer.classed("stacked-bar-label", true);
const writeOptions: Typesettable.IWriteOptions = {
xAlign: "center",
yAlign: "center",
};
this._writer.write(text, width, height, writeOptions, labelContainer.node());
}
return textTooLong;
};
const drawLabelsForExtents = (
stacks: Utils.Map<string | number, StackExtent<Date | number | string>>,
computeLabelTopLeft: (
stackEdge: Point,
textDimensions: Typesettable.IDimensions,
barThickness: number,
) => Point,
) => {
const attrToProjector = this._generateAttrToProjector();
const plotWidth = this.width();
const plotHeight = this.height();
stacks.forEach((stack) => {
if (stack.extent !== baselineValue) {
// only draw sums for values not at the baseline
const text = this.extremaFormatter()(stack.extent);
const textDimensions = this._measurer.measure(text);
const { stackedDatum } = stack;
const { originalDatum, originalIndex, originalDataset } = stackedDatum;
// only consider stack extents that are on the screen
if (!this._isDatumOnScreen(
attrToProjector,
plotWidth,
plotHeight,
originalDatum,
originalIndex,
originalDataset)) {
return;
}
const barThickness = Plot._scaledAccessor(this.attr(Bar._BAR_THICKNESS_KEY))(originalDatum, originalIndex, originalDataset);
/*
* The stackEdge is aligned at the edge of the stack in the length dimension,
* and in the center of the stack in the thickness dimension.
*/
const stackEdgeLength = lengthScale.scale(stack.extent);
const stackCenterPosition =
this._getPositionAttr(positionScale.scale(stack.axisValue), barThickness) + barThickness / 2;
const stackEdge = this._isVertical
? {
x: stackCenterPosition,
y: stackEdgeLength,
}
: {
x: stackEdgeLength,
y: stackCenterPosition,
};
const topLeft = computeLabelTopLeft(stackEdge, textDimensions, barThickness);
const isTooWide = maybeDrawLabel(
text,
{
topLeft,
bottomRight: {
x: topLeft.x + textDimensions.width,
y: topLeft.y + textDimensions.height,
},
},
barThickness,
);
anyTooWide.push(isTooWide);
}
});
};
drawLabelsForExtents(maximumExtents, (stackEdge, measurement, thickness) => {
const primaryTextMeasurement = this._isVertical ? measurement.width : measurement.height;
const secondaryTextMeasurement = this._isVertical ? measurement.height : measurement.width;
return {
x: this._isVertical
? stackEdge.x - primaryTextMeasurement / 2
: stackEdge.x + StackedBar._EXTREMA_LABEL_MARGIN_FROM_BAR,
y: this._isVertical
? stackEdge.y - secondaryTextMeasurement
: stackEdge.y - primaryTextMeasurement / 2,
};
});
drawLabelsForExtents(minimumExtents, (stackEdge, measurement, thickness) => {
const primaryTextMeasurement = this._isVertical ? measurement.width : measurement.height;
const secondaryTextMeasurement = this._isVertical ? measurement.height : measurement.width;
return {
x: this._isVertical
? stackEdge.x - primaryTextMeasurement / 2
: stackEdge.x - secondaryTextMeasurement,
y: this._isVertical
? stackEdge.y + StackedBar._EXTREMA_LABEL_MARGIN_FROM_BAR
: stackEdge.y - primaryTextMeasurement / 2,
};
});
if (anyTooWide.some((d) => d)) {
this._labelArea.selectAll("g").remove();
}
}
protected _generateAttrToProjector() {
const attrToProjector = super._generateAttrToProjector();
const valueAttr = this._isVertical ? "y" : "x";
const lengthScale = this.length().scale;
const lengthAccessor = this.length().accessor;
const positionAccessor = this.position().accessor;
const normalizedPositionAccessor = (datum: any, index: number, dataset: Dataset) => {
return Utils.Stacking.normalizeKey(positionAccessor(datum, index, dataset));
};
const stackingResult = this._stackingResult();
const getStart = (d: any, i: number, dataset: Dataset) =>
lengthScale.scale(stackingResult.get(dataset).get(normalizedPositionAccessor(d, i, dataset)).offset);
const getEnd = (d: any, i: number, dataset: Dataset) =>
lengthScale.scale(+lengthAccessor(d, i, dataset) +
stackingResult.get(dataset).get(normalizedPositionAccessor(d, i, dataset)).offset);
const heightF = (d: any, i: number, dataset: Dataset) => {
return Math.abs(getEnd(d, i, dataset) - getStart(d, i, dataset));
};
attrToProjector[this._isVertical ? "height" : "width"] = heightF;
const attrFunction = (d: any, i: number, dataset: Dataset) =>
+lengthAccessor(d, i, dataset) < 0 ? getStart(d, i, dataset) : getEnd(d, i, dataset);
attrToProjector[valueAttr] = (d: any, i: number, dataset: Dataset) =>
this._isVertical ? attrFunction(d, i, dataset) : attrFunction(d, i, dataset) - heightF(d, i, dataset);
return attrToProjector;
}
protected getExtentsForProperty(attr: string) {
const primaryAttr = this._isVertical ? "y" : "x";
if (attr === primaryAttr) {
return [this._stackedExtent()];
} else {
return super.getExtentsForProperty(attr);
}
}
public invalidateCache() {
super.invalidateCache();
if (this._measurer != null) {
this._measurer.reset();
}
}
} | the_stack |
import * as koa from 'koa';
import { EventEmitter } from 'events';
declare class Timing {
constructor();
start(name: any): _EggCore.T101;
end(name: any): any;
toJSON(): any;
}
/**
* BaseContextClass is a base class that can be extended,
* it's instantiated in context level,
* {@link Helper}, {@link Service} is extending it.
*/
declare class BaseContextClass {
ctx: any;
app: any;
config: any;
service: any;
/**
* @constructor
* @param {Context} ctx - context instance
* @since 1.0.0
*/
constructor(ctx: any);
}
declare class Lifecycle extends EventEmitter {
options: _EggCore.T102;
readyTimeout: number;
/**
* @param {object} options - options
* @param {String} options.baseDir - the directory of application
* @param {EggCore} options.app - Application instance
* @param {Logger} options.logger - logger
*/
constructor(options: _EggCore.T102);
app: any;
logger: any;
timing: any;
legacyReadyCallback(name: any, opt: any): any;
addBootHook(hook: any): void;
addFunctionAsBootHook(hook: any): void;
/**
* init boots and trigger config did config
*/
init(): void;
registerBeforeStart(scope: any): void;
registerBeforeClose(fn: any): void;
close(): Promise<void>;
triggerConfigWillLoad(): void;
triggerConfigDidLoad(): void;
triggerDidLoad(): void;
triggerWillReady(): void;
triggerDidReady(err: any): void;
triggerServerDidReady(): void;
}
/**
* Load files from directory to target object.
* @since 1.0.0
*/
declare class FileLoader {
options: _EggCore.T105 & _EggCore.T104;
/**
* @constructor
* @param {Object} options - options
* @param {String|Array} options.directory - directories to be loaded
* @param {Object} options.target - attach the target object from loaded files
* @param {String} options.match - match the files when load, support glob, default to all js files
* @param {String} options.ignore - ignore the files when load, support glob
* @param {Function} options.initializer - custom file exports, receive two parameters, first is the inject object(if not js file, will be content buffer), second is an `options` object that contain `path`
* @param {Boolean} options.call - determine whether invoke when exports is function
* @param {Boolean} options.override - determine whether override the property when get the same name
* @param {Object} options.inject - an object that be the argument when invoke the function
* @param {Function} options.filter - a function that filter the exports which can be loaded
* @param {String|Function} options.caseStyle - set property's case when converting a filepath to property list.
*/
constructor(options: _EggCore.T104);
/**
* attach items to target object. Mapping the directory to properties.
* `app/controller/group/repository.js` => `target.group.repository`
* @return {Object} target
* @since 1.0.0
*/
load(): any;
/**
* Parse files from given directories, then return an items list, each item contains properties and exports.
*
* For example, parse `app/controller/group/repository.js`
*
* ```
* module.exports = app => {
* return class RepositoryController extends app.Controller {};
* }
* ```
*
* It returns a item
*
* ```
* {
* properties: [ 'group', 'repository' ],
* exports: app => { ... },
* }
* ```
*
* `Properties` is an array that contains the directory of a filepath.
*
* `Exports` depends on type, if exports is a function, it will be called. if initializer is specified, it will be called with exports for customizing.
* @return {Array} items
* @since 1.0.0
*/
parse(): any[];
}
/**
* Same as {@link FileLoader}, but it will attach file to `inject[fieldClass]`. The exports will be lazy loaded, such as `ctx.group.repository`.
* @extends FileLoader
* @since 1.0.0
*/
declare class ContextLoader extends FileLoader {
/**
* @constructor
* @param {Object} options - options same as {@link FileLoader}
* @param {String} options.fieldClass - determine the field name of inject object.
*/
constructor(options: _EggCore.T106);
}
declare class EggLoader {
options: _EggCore.T103;
app: any;
lifecycle: any;
timing: any;
pkg: any;
eggPaths: any[];
serverEnv: string;
appInfo: any;
serverScope: any;
/**
* @constructor
* @param {Object} options - options
* @param {String} options.baseDir - the directory of application
* @param {EggCore} options.app - Application instance
* @param {Logger} options.logger - logger
* @param {Object} [options.plugins] - custom plugins
* @since 1.0.0
*/
constructor(options: _EggCore.T103);
/**
* Get home directory
* @return {String} home directory
* @since 3.4.0
*/
getHomedir(): string;
/**
* Get app info
* @return {AppInfo} appInfo
* @since 1.0.0
*/
getAppInfo(): any;
/**
* Load single file, will invoke when export is function
*
* @param {String} filepath - fullpath
* @param {Array} arguments - pass rest arguments into the function when invoke
* @return {Object} exports
* @example
* ```js
* app.loader.loadFile(path.join(app.options.baseDir, 'config/router.js'));
* ```
* @since 1.0.0
*/
loadFile(filepath: string, ...inject: any[]): any;
/**
* Get all loadUnit
*
* loadUnit is a directory that can be loaded by EggLoader, it has the same structure.
* loadUnit has a path and a type(app, framework, plugin).
*
* The order of the loadUnits:
*
* 1. plugin
* 2. framework
* 3. app
*
* @return {Array} loadUnits
* @since 1.0.0
*/
getLoadUnits(): any[];
/**
* Load files using {@link FileLoader}, inject to {@link Application}
* @param {String|Array} directory - see {@link FileLoader}
* @param {String} property - see {@link FileLoader}
* @param {Object} opt - see {@link FileLoader}
* @since 1.0.0
*/
loadToApp(directory: string | any[], property: string, opt: any): void;
/**
* Load files using {@link ContextLoader}
* @param {String|Array} directory - see {@link ContextLoader}
* @param {String} property - see {@link ContextLoader}
* @param {Object} opt - see {@link ContextLoader}
* @since 1.0.0
*/
loadToContext(directory: string | any[], property: string, opt: any): void;
/**
* @member {FileLoader} EggLoader#FileLoader
* @since 1.0.0
*/
FileLoader: typeof FileLoader;
/**
* @member {ContextLoader} EggLoader#ContextLoader
* @since 1.0.0
*/
ContextLoader: typeof ContextLoader;
getTypeFiles(filename: any): string[];
resolveModule(filepath: any): string;
}
declare class EggCore extends koa {
timing: Timing;
BaseContextClass: typeof BaseContextClass;
Controller: typeof BaseContextClass;
Service: typeof BaseContextClass;
lifecycle: Lifecycle;
loader: EggLoader;
/**
* @constructor
* @param {Object} options - options
* @param {String} [options.baseDir=process.cwd()] - the directory of application
* @param {String} [options.type=application|agent] - whether it's running in app worker or agent worker
* @param {Object} [options.plugins] - custom plugins
* @since 1.0.0
*/
constructor(options?: _EggCore.T100);
/**
* override koa's app.use, support generator function
* @param {Function} fn - middleware
* @return {Application} app
* @since 1.0.0
*/
use(fn: (...args: any[]) => any): any;
/**
* Whether `application` or `agent`
* @member {String}
* @since 1.0.0
*/
type: string;
/**
* The current directory of application
* @member {String}
* @see {@link AppInfo#baseDir}
* @since 1.0.0
*/
baseDir: string;
/**
* Alias to {@link https://npmjs.com/package/depd}
* @member {Function}
* @since 1.0.0
*/
deprecate: any;
/**
* The name of application
* @member {String}
* @see {@link AppInfo#name}
* @since 1.0.0
*/
name: any;
/**
* Retrieve enabled plugins
* @member {Object}
* @since 1.0.0
*/
plugins: any;
/**
* The configuration of application
* @member {Config}
* @since 1.0.0
*/
config: any;
/**
* Execute scope after loaded and before app start.
*
* Notice:
* This method is now NOT recommanded and reguarded as a deprecated one,
* For plugin development, we should use `didLoad` instead.
* For application development, we should use `willReady` instead.
*
* @see https://eggjs.org/en/advanced/loader.html#beforestart
*
* @param {Function|GeneratorFunction|AsyncFunction} scope function will execute before app start
*/
beforeStart(scope: any): void;
/**
* register an callback function that will be invoked when application is ready.
* @see https://github.com/node-modules/ready
* @since 1.0.0
* @param {boolean|Error|Function} flagOrFunction -
* @return {Promise|null} return promise when argument is undefined
* @example
* const app = new Application(...);
* app.ready(err => {
* if (err) throw err;
* console.log('done');
* });
*/
ready(flagOrFunction: boolean | ((...args: any[]) => any) | Error): Promise<any>;
/**
* If a client starts asynchronously, you can register `readyCallback`,
* then the application will wait for the callback to ready
*
* It will log when the callback is not invoked after 10s
*
* Recommend to use {@link EggCore#beforeStart}
* @since 1.0.0
*
* @param {String} name - readyCallback task name
* @param {object} opts -
* - {Number} [timeout=10000] - emit `ready_timeout` when it doesn't finish but reach the timeout
* - {Boolean} [isWeakDep=false] - whether it's a weak dependency
* @return {Function} - a callback
* @example
* const done = app.readyCallback('mysql');
* mysql.ready(done);
*/
readyCallback(name: string, opts: any): (...args: any[]) => any;
/**
* Register a function that will be called when app close.
*
* Notice:
* This method is now NOT recommanded directly used,
* Developers SHOULDN'T use app.beforeClose directly now,
* but in the form of class to implement beforeClose instead.
*
* @see https://eggjs.org/en/advanced/loader.html#beforeclose
*
* @param {Function} fn - the function that can be generator function or async function.
*/
beforeClose(fn: (...args: any[]) => any): void;
/**
* Close all, it will close
* - callbacks registered by beforeClose
* - emit `close` event
* - remove add listeners
*
* If error is thrown when it's closing, the promise will reject.
* It will also reject after following call.
* @return {Promise} promise
* @since 1.0.0
*/
close(): Promise<any>;
/**
* get router
* @member {Router} EggCore#router
* @since 1.0.0
*/
router: any;
/**
* Alias to {@link Router#url}
* @param {String} name - Router name
* @param {Object} params - more parameters
* @return {String} url
*/
url(name: string, params: any): string;
del(...args: any[]): this;
/**
* Convert a generator function to a promisable one.
*
* Notice: for other kinds of functions, it directly returns you what it is.
*
* @param {Function} fn The inputted function.
* @return {AsyncFunction} An async promise-based function.
* @example
```javascript
const fn = function* (arg) {
return arg;
};
const wrapped = app.toAsyncFunction(fn);
wrapped(true).then((value) => console.log(value));
```
*/
toAsyncFunction(fn: (...args: any[]) => any): any;
/**
* Convert an object with generator functions to a Promisable one.
* @param {Mixed} obj The inputted object.
* @return {Promise} A Promisable result.
* @example
```javascript
const fn = function* (arg) {
return arg;
};
const arr = [ fn(1), fn(2) ];
const promise = app.toPromise(arr);
promise.then(res => console.log(res));
```
*/
toPromise(obj: any): Promise<any>;
}
declare const _EggCore: _EggCore.T108;
declare namespace _EggCore {
export interface T100 {
baseDir?: string;
type?: string;
plugins?: any;
}
export interface T101 {
name: any;
start: number;
end: any;
duration: any;
pid: number;
index: any;
}
export interface T102 {
baseDir: string;
app: any;
logger: any;
}
export interface T103 {
baseDir: string;
app: any;
logger: any;
plugins?: any;
}
export interface T104 {
directory: string | any[];
target: any;
match: string;
ignore: string;
initializer: (...args: any[]) => any;
call: boolean;
override: boolean;
inject: any;
filter: (...args: any[]) => any;
caseStyle: string | ((...args: any[]) => any);
}
export interface T105 {
directory: any;
target: any;
match: any;
ignore: any;
lowercaseFirst: boolean;
caseStyle: string;
initializer: any;
call: boolean;
override: boolean;
inject: any;
filter: any;
}
export interface T106 {
fieldClass: string;
}
export interface T107 {
extensions: any;
loadFile(filepath: any): any;
methods: string[];
callFn(fn: any, args: any, ctx: any): Promise<any>;
middleware(fn: any): any;
getCalleeFromStack(withLine: any, stackIndex: any): any;
getResolvedFilename(filepath: any, baseDir: any): any;
}
export interface T108 {
EggCore: typeof EggCore;
EggLoader: typeof EggLoader;
BaseContextClass: typeof BaseContextClass;
utils: _EggCore.T107;
}
}
export = _EggCore; | the_stack |
import * as firewall from './firewall';
import * as globals from './globals';
import * as local_instance from './local-instance';
import * as logging from '../lib/logging/logging';
import * as metrics from './metrics';
import * as network_options from '../generic/network-options';
import * as remote_user from './remote-user';
import * as social from '../interfaces/social';
import * as freedom_social2 from '../interfaces/social2';
import * as ui_connector from './ui_connector';
import * as uproxy_core_api from '../interfaces/uproxy_core_api';
import ui = ui_connector.connector;
import * as jsurl from 'jsurl';
import storage = globals.storage;
declare var freedom: freedom.FreedomInModuleEnv;
var NETWORK_OPTIONS = network_options.NETWORK_OPTIONS;
var log :logging.Log = new logging.Log('social');
export var LOGIN_TIMEOUT :number = 5000; // ms
// PREFIX is the string prefix indicating which social providers in the
// freedom manifest we want to treat as social providers for uProxy.
var PREFIX :string = 'SOCIAL-';
// Global mapping of social network names (without prefix) to actual Network
// instances that interact with that social network.
//
// TODO: rather than make this global, this should be a parameter of the core.
// This simplified Social to being a SocialNetwork and removes the need for
// this module. `initializeNetworks` becomes part of the core constructor.
export var networks:{[networkName:string] :{[userId:string]:social.Network}} = {};
export function removeNetwork(networkName :string, userId :string) :void {
delete networks[networkName][userId];
notifyUI(networkName, userId);
}
/**
* Goes through network names and gets a reference to each social provider.
*/
export function initializeNetworks() :void {
for (var dependency in freedom) {
if (freedom.hasOwnProperty(dependency)) {
if (dependency.indexOf(PREFIX) !== 0 ||
('social' !== freedom[dependency].api &&
'social2' !== freedom[dependency].api)) {
continue;
}
var name = dependency.substring(PREFIX.length);
networks[name] = {};
}
}
}
/**
* Retrieves reference to the network |networkName|.
*/
export function getNetwork(networkName :string, userId :string) :social.Network {
if (!(networkName in networks)) {
throw new Error(`unknown network ${networkName}`);
}
if (!(userId in networks[networkName])) {
throw new Error(`${userId} is not logged into network ${networkName}`);
}
return networks[networkName][userId];
}
export function getOnlineNetworks() :social.NetworkState[] {
var networkStates :social.NetworkState[] = [];
for (var networkName in networks) {
for (var userId in networks[networkName]) {
networkStates.push(networks[networkName][userId].getNetworkState());
}
}
return networkStates;
}
export function notifyUI(networkName :string, userId :string) {
if (typeof networks[networkName] === 'undefined') {
throw Error('Trying to update UI with unknown network ' + networkName);
}
var network = getNetwork(networkName, userId);
var online = false;
var userName = '';
var imageData = '';
if (network !== null) {
online = true;
userName = network.myInstance.userName;
imageData = network.myInstance.imageData;
}
var payload :social.NetworkMessage = {
name: networkName,
online: online,
userId: userId,
userName: userName,
imageData: imageData
};
ui.update(uproxy_core_api.Update.NETWORK, payload);
}
// Implements those portions of the Network interface for which the logic is
// common to multiple Network implementations. Essentially an abstract base
// class for Network implementations. TODO: with typescript 1.5, there are now
// abstract classes, use them?
export class AbstractNetwork implements social.Network {
public roster :{[userId:string] :remote_user.User};
public myInstance :local_instance.LocalInstance;
private SaveKeys = {
ME: 'me'
}
constructor(public name :string, private metrics_ :metrics.Metrics) {
this.roster = {};
}
public getStorePath = () :string => {
return this.myInstance.instanceId + '/roster/';
}
/**
* Returns the local instance. If it doesn't exist, load local instance
* from storage, or create a new one if this is the first time this uProxy
* installation has interacted with this network.
*/
protected prepareLocalInstance_ = (userId :string) :Promise<void> => {
var key = this.name + userId;
return storage.load<social.LocalInstanceState>(key).then((result) => {
this.myInstance = new local_instance.LocalInstance(this, userId, result);
log.info('loaded local instance from storage',
result, this.myInstance.instanceId);
}, (e) => {
this.myInstance = new local_instance.LocalInstance(this, userId);
log.info('generating new local instance', this.myInstance.instanceId);
return this.myInstance.saveToStorage();
});
}
/**
* Updates metrics on login state/user count
*/
protected updateMetrics() {
if (this.metrics_) {
// One of the users will be us. Take that one out
var networkName = this.name;
var numUsers:number;
numUsers = Object.keys(this.roster).length - 1;
if (NETWORK_OPTIONS[this.name]) {
if (NETWORK_OPTIONS[this.name].metricsName) {
networkName = NETWORK_OPTIONS[this.name].metricsName;
}
if (NETWORK_OPTIONS[this.name].rosterFunction) {
numUsers = NETWORK_OPTIONS[this.name].rosterFunction(
Object.keys(this.roster));
}
}
this.metrics_.userCount(
networkName,
this.myInstance.getUserProfile().userId,
numUsers);
}
}
//===================== Social.Network implementation ====================//
/**
* Adds a new user to the roster. Promise will be rejected if the user is
* already in the roster.
*/
public addUser = (userId :string) :remote_user.User => {
if (!this.isNewFriend_(userId)) {
log.warn('Cannot add already existing user', userId);
}
var newUser = new remote_user.User(this, userId);
this.roster[userId] = newUser;
this.updateMetrics();
return newUser;
}
/**
* Removes a user from the roster. Does not throw an error because this is
* as expected.
*/
public removeUser = (userId :string) => {
if (userId in this.roster) {
delete this.roster[userId];
} else {
log.error('Cannot remove user that does not exist in roster', userId);
}
}
/**
* Returns a User object for userId. If the userId is not found in the
* roster, a new User object will be created - in that case the User may
* be missing fields like .name if it is not found in storage.
*/
protected getOrAddUser_ = (userId :string) :remote_user.User => {
if (this.isNewFriend_(userId)) {
return this.addUser(userId);
}
return this.getUser(userId);
}
/**
* Helper to determine if |userId| is a "new friend".
*/
protected isNewFriend_ = (userId :string) :boolean => {
return !(userId in this.roster);
}
public getLocalInstanceId = () : string => {
return this.myInstance.instanceId;
}
public getUser = (userId :string) :remote_user.User => {
return this.roster[userId];
}
public resendInstanceHandshakes = () :void => {
// Do nothing for non-freedom networks (e.g. manual).
}
public inviteGitHubUser = (data :uproxy_core_api.CreateInviteArgs): Promise<void> => {
throw new Error('Operation not implemented.');
}
//================ Subclasses must override these methods ================//
// From Social.Network:
public login = (loginType :uproxy_core_api.LoginType,
userName ?:string) : Promise<void> => {
throw new Error('Operation not implemented');
}
public logout = () : Promise<void> => {
throw new Error('Operation not implemented');
}
public flushQueuedInstanceMessages = () :void => {
throw new Error('Operation not implemented');
}
public send = (user :remote_user.User,
recipientClientId :string,
message :social.PeerMessage) : Promise<void> => {
throw new Error('Operation not implemented');
}
public getInviteUrl = (data :uproxy_core_api.CreateInviteArgs) : Promise<string> => {
throw new Error('Operation not implemented');
}
public sendEmail = (to: string, subject: string, body: string) : void => {
throw new Error('Operation not implemented');
}
public getNetworkState = () :social.NetworkState => {
throw new Error('Operation not implemented');
}
public areAllContactsUproxy = () : boolean => {
// Default to false.
var options :social.NetworkOptions = NETWORK_OPTIONS[this.name];
return options ? options.areAllContactsUproxy === true : false;
}
public isEncrypted = (): boolean => {
// Default to false.
var options: social.NetworkOptions = NETWORK_OPTIONS[this.name];
return options ? options.isEncrypted === true : false;
}
public acceptInvitation = (tokenObj ?:social.InviteTokenData, userId ?:string) : Promise<void> => {
throw new Error('Operation not implemented');
}
public getKeyFromClientId = (clientId :string) : string => {
var beginPgpString = '-----BEGIN PGP PUBLIC KEY BLOCK-----';
var endPgpString = '-----END PGP PUBLIC KEY BLOCK-----\r\n';
var start = clientId.lastIndexOf(beginPgpString);
return clientId.slice(start).match(beginPgpString + '(.|[\r\n])*' + endPgpString)[0];
}
public removeUserFromStorage = (userId :string): Promise<void> => {
throw new Error('Operation not implemented');
}
} // class AbstractNetwork
// A Social.Network implementation that deals with a Freedom social provider.
//
// Handles events from the social provider. 'onUserProfile' events directly
// affect the roster of this network, while 'onClientState' and 'onMessage'
// events are passed on to the relevant user (provided the user exists).
export class FreedomNetwork extends AbstractNetwork {
private freedomApi_ :freedom_social2.FreedomSocialProvider;
// TODO: give real typing to provider_. Ask Freedom not to use overloaded
// types.
private provider_ :any; // Special freedom object which is both a function
// and object... cannot typescript.
// Promise that delays all message handling until fully logged in.
private onceLoggedIn_ :Promise<void>;
// ID returned by setInterval call for monitoring.
private monitorIntervalId_ :NodeJS.Timer = null;
private fulfillLogout_ : () => void;
private onceLoggedOut_ : Promise<void>;
/**
* Initializes the Freedom social provider for this FreedomNetwork and
* attaches event handlers.
*/
constructor(public name :string, metrics :metrics.Metrics) {
super(name, metrics);
this.provider_ = freedom[PREFIX + name];
this.onceLoggedIn_ = null;
this.freedomApi_ = this.provider_();
this.freedomApi_.on('onUserProfile',
this.delayForLogin_(this.handleUserProfile));
this.freedomApi_.on('onClientState',
this.delayForLogin_(this.handleClientState));
this.freedomApi_.on('onMessage',
this.delayForLogin_(this.handleMessage));
}
/**
* Functor that delays until the network is logged in.
* Resulting function will instantly fail if not already in the process of
* logging in.
* TODO: This should either be factored into a wrapper class to 'sanitize'
* social providers' async behavior, or directly into freedom.
*/
private delayForLogin_ = (handler :Function) => {
return (arg :any) => {
if (!this.onceLoggedIn_) {
log.error('Attempting to call delayForLogin_ before trying to login');
return;
}
return this.onceLoggedIn_.then(() => {
handler(arg);
});
}
}
/**
* Handler for receiving 'onUserProfile' messages. First, determines whether
* the UserProfile belongs to ourselves or a remote contact. Then,
* updates / adds the user data to the roster.
*
* NOTE: Our own 'Instance Handshake' is specific to this particular
* network, and can only be prepared after receiving our own vcard for the
* first time.
* TODO: Check if the above statement on vcard is actually true.
*
* Public to permit testing.
*/
public handleUserProfile = (profile :freedom.Social.UserProfile) : void => {
var userId = profile.userId;
if (!firewall.isValidUserProfile(profile, null)) {
log.error('Firewall: invalid user profile', profile);
return;
}
// Check if this is ourself, in which case we update our own info.
if (userId == this.myInstance.userId) {
// TODO: we may want to verify that our status is ONLINE before
// sending out any instance messages.
log.info('Received own UserProfile', profile);
// Update UI with own information.
var userProfileMessage :social.UserProfileMessage = {
userId: profile.userId,
name: profile.name,
imageData: profile.imageData
};
ui.update(uproxy_core_api.Update.USER_SELF, <social.UserData>{
network: this.name,
user: userProfileMessage
});
this.myInstance.updateProfile(userProfileMessage);
}
log.debug('Received UserProfile', profile);
this.getOrAddUser_(userId).update(profile);
}
/**
* Handler for receiving 'onClientState' messages. Passes these messages to
* the relevant user, which will manage its own clients.
*
* It is possible that the roster entry does not yet exist for a user,
* yet we receive a client state from them. In this case, create a
* place-holder user until we receive more user information.
*
* Assumes we are in fact fully logged in.
*
* Public to permit testing.
*/
public handleClientState = (freedomClient :freedom.Social.ClientState) => {
if (!firewall.isValidClientState(freedomClient, null)) {
log.error('Firewall: invalid client state:', freedomClient);
return;
}
var client :social.ClientState =
freedomClientToUproxyClient(freedomClient);
if (client.userId == this.myInstance.userId &&
client.clientId === this.myInstance.clientId) {
if (client.status === social.ClientStatus.OFFLINE) {
// Our client is disconnected, log out of the social network
// (the social provider is responsible for clean up so we don't
// need to call logout here).
this.fulfillLogout_();
}
log.info('received own ClientState', client);
return;
}
this.getOrAddUser_(client.userId).handleClient(client);
}
/**
* When receiving a message from a social provider, delegate it to the
* correct user, which will delegate to the correct client.
*
* It is possible that the roster entry does not yet exist for a user,
* yet we receive a message from them. In this case, create a place-holder
* user until we receive more user information.
*
* Public to permit testing.
*/
public handleMessage = (incoming :freedom.Social.IncomingMessage) => {
if (!firewall.isValidIncomingMessage(incoming, null)) {
log.error('Firewall: invalid incoming message:', incoming);
return;
}
var userId = incoming.from.userId;
var client :social.ClientState =
freedomClientToUproxyClient(incoming.from);
var user = this.getOrAddUser_(userId);
if (!user.clientIdToStatusMap[client.clientId]) {
// Add client.
user.handleClient(client);
}
var msg :social.VersionedPeerMessage = JSON.parse(incoming.message);
log.info('received message', {
userFrom: user.userId,
clientFrom: client.clientId,
instanceFrom: user.clientToInstance(client.clientId),
msg: msg
});
user.handleMessage(client.clientId, msg);
}
public restoreFromStorage() {
log.info('Loading users from storage');
return storage.keys().then((keys :string[]) => {
var myKey = this.getStorePath();
for (var i in keys) {
if (keys[i].indexOf(myKey) === 0) {
var userId = keys[i].substring(myKey.length);
if (this.isNewFriend_(userId)) {
this.addUser(userId);
}
}
}
});
}
//===================== Social.Network implementation ====================//
public login = (loginType :uproxy_core_api.LoginType,
userName ?:string) : Promise<void> => {
var interactive :boolean;
var rememberLogin :boolean;
if (loginType === uproxy_core_api.LoginType.INITIAL) {
interactive = true;
rememberLogin = true;
} else if (loginType === uproxy_core_api.LoginType.RECONNECT) {
interactive = false;
rememberLogin = false;
} else if (loginType === uproxy_core_api.LoginType.TEST) {
// interactive is true so that MockOAuth is used, rather than looking
// for refresh tokens in storage.
interactive = true;
rememberLogin = false;
}
var request :freedom_social2.LoginRequest = null;
if (this.isFirebase_()) {
// Firebase enforces only 1 login per agent per userId at a time.
// TODO: ideally we should use the instanceId for the agent string,
// that way the clientId we get will just be in the form
// userId/instanceId and can eliminate the 1st round of instance
// messages. However we don't know the instanceId until after we login,
// because each instanceId is generated or loaded from storage based
// on the userId. Some possibilities:
// - modify the freedom API to set our agent after login (once we
// know our userId)
// - change the way we generate the instanceId to not depend on what
// userId is logged in.
// If we change agent to use instanceId, we also should modify
// Firebase code to change disconnected clients to OFFLINE, rather
// than removing them.
var agent = 'uproxy' + Math.random().toString().substring(2, 12);
request = {
agent: agent,
version: '0.1',
url: 'https://popping-heat-4874.firebaseio.com/',
interactive: interactive,
rememberLogin: rememberLogin
};
} else if (this.name === 'Quiver') {
if (!userName) {
// userName may not be passed in for reconnect.
userName = globals.settings.quiverUserName;
}
request = {
agent: Math.random().toString().substring(2, 12),
version: '0.1',
url: 'https://github.com/uProxy/uProxy',
interactive: interactive,
rememberLogin: rememberLogin,
userName: userName,
pgpKeyName: '<uproxy>'
};
} else {
request = {
agent: 'uproxy',
version: '0.1',
url: 'https://github.com/uProxy/uProxy',
interactive: interactive,
rememberLogin: rememberLogin
};
}
this.onceLoggedIn_ = this.freedomApi_.login(request)
.then((freedomClient :freedom.Social.ClientState) => {
var userId = freedomClient.userId;
if (userId in networks[this.name]) {
// If user is already logged in with the same (network, userId)
// log out from existing network before replacing it.
networks[this.name][userId].logout();
}
networks[this.name][userId] = this;
// Upon successful login, save local client information.
this.startMonitor_();
log.info('logged into network', this.name);
return this.prepareLocalInstance_(userId).then(() => {
this.myInstance.clientId = freedomClient.clientId;
// Notify UI that this network is online before we fulfill
// the onceLoggedIn_ promise. This ensures that the UI knows
// that the network is online before we send user updates.
notifyUI(this.name, userId);
});
});
return this.onceLoggedIn_
.then(() => {
this.onceLoggedOut_ = new Promise((F, R) => {
this.fulfillLogout_ = F;
}).then(() => {
this.stopMonitor_();
for (var userId in this.roster) {
this.roster[userId].handleLogout();
}
removeNetwork(this.name, this.myInstance.userId);
log.debug('Fulfilling onceLoggedOut_');
}).catch((e) => {
log.error('Error fulfilling onceLoggedOut_', e.message);
});
this.restoreFromStorage();
})
.catch((e) => {
log.error('Could not login to network');
throw e;
});
}
public logout = () : Promise<void> => {
return this.freedomApi_.logout().then(() => {
this.fulfillLogout_();
}).catch((e) => {
log.error('Error while logging out:', e.message);
return Promise.reject(e);
});
}
public processCloudNetworkData(networkData :any) :string {
if ((typeof networkData) === 'string') {
networkData = JSON.parse(networkData);
}
// If we are enforcing validity, we require that the proxy server be
// in our list of approved servers. If it's not, trigger an error
if (globals.settings.enforceProxyServerValidity &&
!(networkData.host in globals.settings.validProxyServers)) {
throw new Error('Domain policy prohibits unknown proxy servers');
}
// if we have a host key saved, make sure there is no conflict with
// the invitation, then used the saved version
if (networkData.host in globals.settings.validProxyServers) {
if ('hostKey' in networkData &&
networkData.hostKey !== globals.settings.validProxyServers[networkData.host]) {
throw new Error('Conflict between saved key in settings and key in invitation');
}
networkData.hostKey = globals.settings.validProxyServers[networkData.host];
}
return JSON.stringify(networkData);
}
public acceptInvitation = (tokenObj ?:social.InviteTokenData, userId ?:string) : Promise<void> => {
// TODO: networkData will be an Object for Quiver, but a string (userId)
// for GitHub, and a string (JSON format) for Firebase networks. We
// should update the Freedom social providers so they all take the same
// type.
var networkData :Object = null;
if (tokenObj) {
networkData = tokenObj.networkData;
if (this.name === 'Cloud') {
networkData = this.processCloudNetworkData(networkData);
}
} else if (userId) {
networkData = userId;
}
return this.freedomApi_.acceptUserInvitation(networkData).then(() => {
if (tokenObj && tokenObj.permission && tokenObj.userId &&
// Cloud doesn't require invite permissions at the uProxy layer.
this.name !== 'Cloud') {
var user = this.getOrAddUser_(tokenObj.userId);
user.handleInvitePermissions(tokenObj);
}
}).catch((e) => {
log.error('Error calling acceptUserInvitation: ' +
JSON.stringify(networkData), e.message);
});
}
// Sends an in-band invite to a friend to be a uProxy contact.
public inviteGitHubUser = (data :uproxy_core_api.CreateInviteArgs): Promise<void> => {
if (!data.userId) {
// Sanity check failed.
return Promise.reject('userId not set for inviteGitHubUser');
}
return this.freedomApi_.inviteUser(data.userId).catch((e) => {
log.error('Error calling inviteUser: ', data, e.message);
return Promise.reject('Error calling inviteUser: ' + data.userId + e.message);
}).then(() => {
if (data.isOffering || data.isRequesting) {
var user = this.getOrAddUser_(data.userId);
if (data.isOffering) {
user.consent.localGrantsAccessToRemote = true;
}
if (data.isRequesting) {
user.consent.localRequestsAccessFromRemote = true;
}
user.saveToStorage();
// No need to update UI until they accept our invite.
}
return Promise.resolve();
});
}
// Returns an invite url for the user to send to friends out-of-band.
//
// For cloud, the url gives friends access to a cloud server. The data.userId
// identifies a cloud server owned by the user, which is being shared
// with someone else.
// For other social networks, the url adds the local user as a uproxy
// contact for friends who use the url. The userId isn't used.
public getInviteUrl = (data :uproxy_core_api.CreateInviteArgs) : Promise<string> => {
// data.userId is expected to be defined for cloud, but not Quiver,
// Facebook, or GMail
return this.freedomApi_.inviteUser(data.userId || '')
.then((networkData: Object) => {
// Set permissionData only if the user is requesting / granting access.
var permissionData :social.InviteTokenPermissions;
if (data.isRequesting || data.isOffering) {
var token = this.myInstance.generateInvitePermissionToken(
data.isRequesting, data.isOffering);
permissionData = {
token: token,
isRequesting: data.isRequesting,
isOffering: data.isOffering
};
}
if (this.name === 'Quiver' || this.name === 'Cloud') {
// TODO: once we think all/most users have versions of uProxy
// that support jsurl style invites, we should update all our
// social networks to generate those invites.
var urlParams :string[] = [
'v=2',
'networkName=' + this.name,
'userName=' + encodeURIComponent(this.myInstance.userName),
'networkData=' + jsurl.stringify(networkData)
];
if (permissionData) {
urlParams.push('permission=' + jsurl.stringify(permissionData));
urlParams.push('userId=' + this.myInstance.userId);
urlParams.push('instanceId=' + this.myInstance.instanceId);
}
return 'https://www.uproxy.org/invite?' + urlParams.join('&');
} else {
var tokenObj :any = {
v: 1,
networkName: this.name,
userName: this.myInstance.userName,
networkData: networkData
};
if (permissionData) {
tokenObj['permission'] = permissionData;
tokenObj['userId'] = this.myInstance.userId;
tokenObj['instanceId'] = this.myInstance.instanceId;
}
return 'https://www.uproxy.org/invite#' +
btoa(JSON.stringify(tokenObj));
}
})
}
public sendEmail = (to: string, subject: string, body: string): void => {
this.freedomApi_.sendEmail(to, subject, body).catch((e :Error) => {
log.error('Error sending email', e);
});
}
/**
* Promise the sending of |msg| to a client with id |clientId|.
*/
public send = (user :remote_user.User,
clientId :string,
message :social.PeerMessage) : Promise<void> => {
var versionedMessage :social.VersionedPeerMessage = {
type: message.type,
data: message.data,
version: globals.effectiveMessageVersion()
};
var messageString = JSON.stringify(versionedMessage);
log.info('sending message', {
userTo: user.userId,
clientTo: clientId,
// Instance may be undefined if we are making an instance request,
// i.e. we know that a client is ONLINE with uProxy, but don't
// yet have their instance info. This is not an error.
instanceTo: user.clientToInstance(clientId),
msg: messageString
});
return this.freedomApi_.sendMessage(clientId, messageString);
}
// TODO: We should make a class for monitors or generally to encapsulate
// setInterval/clearInterval calls. Then we could call monitor.start
// and monitor.stop.
private startMonitor_ = () : void => {
if (this.monitorIntervalId_) {
// clear any existing monitor
log.error('startMonitor_ called with monitor already running');
this.stopMonitor_();
} else if (!this.isMonitoringEnabled_()) {
return;
}
var monitorCallback = () => {
this.updateMetrics();
for (var userId in this.roster) {
this.getUser(userId).monitor();
}
};
this.monitorIntervalId_ = setInterval(monitorCallback, 15000);
}
private stopMonitor_ = () : void => {
if (this.monitorIntervalId_) {
clearInterval(this.monitorIntervalId_);
}
this.monitorIntervalId_ = null;
}
public resendInstanceHandshakes = () : void => {
for (var userId in this.roster) {
this.roster[userId].resendInstanceHandshakes();
}
}
private isFirebase_ = () : boolean => {
// Default to false.
var options :social.NetworkOptions = NETWORK_OPTIONS[this.name];
return options ? options.isFirebase === true : false;
}
private isMonitoringEnabled_ = () : boolean => {
// Default to true.
var options :social.NetworkOptions = NETWORK_OPTIONS[this.name];
return options ? options.enableMonitoring === true : true;
}
public getNetworkState = () :social.NetworkState => {
var rosterState :{[userId :string] :social.UserData} = {};
for (var userId in this.roster) {
var userState = this.roster[userId].currentStateForUI()
if (userState !== null) {
rosterState[userId] = userState;
}
}
return {
name: this.name,
profile: this.myInstance.getUserProfile(),
roster: rosterState
};
}
public removeUserFromStorage = (userId :string) : Promise<void> => {
// Remove user from roster.
this.removeUser(userId);
// Remove user from storage.
const rosterKey = this.getStorePath() + userId;
return storage.destroy(rosterKey).then(() => {
if (this.name === 'Cloud') {
// In addition to the roster key, cloud contacts have another key
// of the form 'instance_id/user_id' we need to remove from storage
const cloudKey = this.getStorePath().replace('roster/', userId);
return storage.destroy(cloudKey).then(() => {
// Remove user from cloud social provider
return this.freedomApi_.removeUser(userId);
});
}
});
}
} // class Social.FreedomNetwork
export function freedomClientToUproxyClient(
freedomClientState :freedom.Social.ClientState) :social.ClientState {
// Convert status from Freedom style enum value ({'ONLINE': 'ONLINE',
// 'OFFLINE: 'OFFLINE'}) to TypeScript style {'ONLINE': 4000, 4000: 'ONLINE',
// 'OFFLINE': 4001, 4001: 'OFFLINE'} value.
var state :social.ClientState = {
userId: freedomClientState.userId,
clientId: freedomClientState.clientId,
status: (<any>social.ClientStatus)[freedomClientState.status],
timestamp: freedomClientState.timestamp
};
return state;
} | the_stack |
@preserve
Astronomy library for JavaScript (browser and Node.js).
https://github.com/cosinekitty/astronomy
MIT License
Copyright (c) 2019-2021 Don Cross <cosinekitty@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/**
* @fileoverview Astronomy calculation library for browser scripting and Node.js.
* @author Don Cross <cosinekitty@gmail.com>
* @license MIT
*/
'use strict';
export type FlexibleDateTime = Date | number | AstroTime;
/**
* @brief The speed of light in AU/day.
*/
export const C_AUDAY = 173.1446326846693;
/**
* @brief The number of kilometers per astronomical unit.
*/
export const KM_PER_AU = 1.4959787069098932e+8;
/**
* @brief The factor to convert degrees to radians = pi/180.
*/
export const DEG2RAD = 0.017453292519943296;
/**
* @brief The factor to convert sidereal hours to radians = pi/12.
*/
export const HOUR2RAD = 0.2617993877991494365;
/**
* @brief The factor to convert radians to degrees = 180/pi.
*/
export const RAD2DEG = 57.295779513082321;
/**
* @brief The factor to convert radians to sidereal hours = 12/pi.
*/
export const RAD2HOUR = 3.819718634205488;
// Jupiter radius data are nominal values obtained from:
// https://www.iau.org/static/resolutions/IAU2015_English.pdf
// https://nssdc.gsfc.nasa.gov/planetary/factsheet/jupiterfact.html
/**
* @brief The equatorial radius of Jupiter, expressed in kilometers.
*/
export const JUPITER_EQUATORIAL_RADIUS_KM = 71492.0;
/**
* @brief The polar radius of Jupiter, expressed in kilometers.
*/
export const JUPITER_POLAR_RADIUS_KM = 66854.0;
/**
* @brief The volumetric mean radius of Jupiter, expressed in kilometers.
*/
export const JUPITER_MEAN_RADIUS_KM = 69911.0;
// The radii of Jupiter's four major moons are obtained from:
// https://ssd.jpl.nasa.gov/?sat_phys_par
/**
* @brief The mean radius of Jupiter's moon Io, expressed in kilometers.
*/
export const IO_RADIUS_KM = 1821.6;
/**
* @brief The mean radius of Jupiter's moon Europa, expressed in kilometers.
*/
export const EUROPA_RADIUS_KM = 1560.8;
/**
* @brief The mean radius of Jupiter's moon Ganymede, expressed in kilometers.
*/
export const GANYMEDE_RADIUS_KM = 2631.2;
/**
* @brief The mean radius of Jupiter's moon Callisto, expressed in kilometers.
*/
export const CALLISTO_RADIUS_KM = 2410.3;
const DAYS_PER_TROPICAL_YEAR = 365.24217;
const J2000 = new Date('2000-01-01T12:00:00Z');
const PI2 = 2 * Math.PI;
const ARC = 3600 * (180 / Math.PI); // arcseconds per radian
const ASEC2RAD = 4.848136811095359935899141e-6;
const ASEC180 = 180 * 60 * 60; // arcseconds per 180 degrees (or pi radians)
const ASEC360 = 2 * ASEC180; // arcseconds per 360 degrees (or 2*pi radians)
const ANGVEL = 7.2921150e-5;
const AU_PER_PARSEC = ASEC180 / Math.PI; // exact definition of how many AU = one parsec
const SUN_MAG_1AU = -0.17 - 5 * Math.log10(AU_PER_PARSEC); // formula from JPL Horizons
const MEAN_SYNODIC_MONTH = 29.530588; // average number of days for Moon to return to the same phase
const SECONDS_PER_DAY = 24 * 3600;
const MILLIS_PER_DAY = SECONDS_PER_DAY * 1000;
const SOLAR_DAYS_PER_SIDEREAL_DAY = 0.9972695717592592;
const SUN_RADIUS_KM = 695700.0;
const SUN_RADIUS_AU = SUN_RADIUS_KM / KM_PER_AU;
const EARTH_FLATTENING = 0.996647180302104;
const EARTH_EQUATORIAL_RADIUS_KM = 6378.1366;
const EARTH_EQUATORIAL_RADIUS_AU = EARTH_EQUATORIAL_RADIUS_KM / KM_PER_AU;
const EARTH_POLAR_RADIUS_KM = EARTH_EQUATORIAL_RADIUS_KM * EARTH_FLATTENING;
const EARTH_MEAN_RADIUS_KM = 6371.0; /* mean radius of the Earth's geoid, without atmosphere */
const EARTH_ATMOSPHERE_KM = 88.0; /* effective atmosphere thickness for lunar eclipses */
const EARTH_ECLIPSE_RADIUS_KM = EARTH_MEAN_RADIUS_KM + EARTH_ATMOSPHERE_KM;
const MOON_EQUATORIAL_RADIUS_KM = 1738.1;
const MOON_MEAN_RADIUS_KM = 1737.4;
const MOON_POLAR_RADIUS_KM = 1736.0;
const MOON_EQUATORIAL_RADIUS_AU = (MOON_EQUATORIAL_RADIUS_KM / KM_PER_AU);
const REFRACTION_NEAR_HORIZON = 34 / 60; // degrees of refractive "lift" seen for objects near horizon
const EARTH_MOON_MASS_RATIO = 81.30056;
/*
Masses of the Sun and outer planets, used for:
(1) Calculating the Solar System Barycenter
(2) Integrating the movement of Pluto
https://web.archive.org/web/20120220062549/http://iau-comm4.jpl.nasa.gov/de405iom/de405iom.pdf
Page 10 in the above document describes the constants used in the DE405 ephemeris.
The following are G*M values (gravity constant * mass) in [au^3 / day^2].
This side-steps issues of not knowing the exact values of G and masses M[i];
the products GM[i] are known extremely accurately.
*/
const SUN_GM = 0.2959122082855911e-03;
const JUPITER_GM = 0.2825345909524226e-06;
const SATURN_GM = 0.8459715185680659e-07;
const URANUS_GM = 0.1292024916781969e-07;
const NEPTUNE_GM = 0.1524358900784276e-07;
let ob2000: number; // lazy-evaluated mean obliquity of the ecliptic at J2000, in radians
let cos_ob2000: number;
let sin_ob2000: number;
function VerifyBoolean(b: boolean): boolean {
if (b !== true && b !== false) {
console.trace();
throw `Value is not boolean: ${b}`;
}
return b;
}
function VerifyNumber(x: number): number {
if (!Number.isFinite(x)) {
console.trace();
throw `Value is not a finite number: ${x}`;
}
return x;
}
function Frac(x: number): number {
return x - Math.floor(x);
}
/**
* @brief Calculates the angle in degrees between two vectors.
*
* Given a pair of vectors, this function returns the angle in degrees
* between the two vectors in 3D space.
* The angle is measured in the plane that contains both vectors.
*
* @param {Vector} a
* The first of a pair of vectors between which to measure an angle.
*
* @param {Vector} b
* The second of a pair of vectors between which to measure an angle.
*
* @returns {number}
* The angle between the two vectors expressed in degrees.
* The value is in the range [0, 180].
*/
export function AngleBetween(a: Vector, b: Vector): number {
const aa = (a.x * a.x + a.y * a.y + a.z * a.z);
if (Math.abs(aa) < 1.0e-8)
throw `AngleBetween: first vector is too short.`;
const bb = (b.x * b.x + b.y * b.y + b.z * b.z);
if (Math.abs(bb) < 1.0e-8)
throw `AngleBetween: second vector is too short.`;
const dot = (a.x * b.x + a.y * b.y + a.z * b.z) / Math.sqrt(aa * bb);
if (dot <= -1.0)
return 180;
if (dot >= +1.0)
return 0;
const angle = RAD2DEG * Math.acos(dot);
return angle;
}
/**
* @brief String constants that represent the solar system bodies supported by Astronomy Engine.
*
* The following strings represent solar system bodies supported by various Astronomy Engine functions.
* Not every body is supported by every function; consult the documentation for each function
* to find which bodies it supports.
*
* "Sun", "Moon", "Mercury", "Venus", "Earth", "Mars", "Jupiter",
* "Saturn", "Uranus", "Neptune", "Pluto",
* "SSB" (Solar System Barycenter),
* "EMB" (Earth/Moon Barycenter)
*
* You can also use enumeration syntax for the bodies, like
* `Astronomy.Body.Moon`, `Astronomy.Body.Jupiter`, etc.
*
* @enum {string}
*/
export enum Body {
Sun = 'Sun',
Moon = 'Moon',
Mercury = 'Mercury',
Venus = 'Venus',
Earth = 'Earth',
Mars = 'Mars',
Jupiter = 'Jupiter',
Saturn = 'Saturn',
Uranus = 'Uranus',
Neptune = 'Neptune',
Pluto = 'Pluto',
SSB = 'SSB', // Solar System Barycenter
EMB = 'EMB' // Earth/Moon Barycenter
}
enum PrecessDirection {
From2000,
Into2000
}
interface PlanetInfo {
OrbitalPeriod: number;
}
interface PlanetTable {
[body: string]: PlanetInfo;
}
const Planet: PlanetTable = {
Mercury: {OrbitalPeriod: 87.969},
Venus: {OrbitalPeriod: 224.701},
Earth: {OrbitalPeriod: 365.256},
Mars: {OrbitalPeriod: 686.980},
Jupiter: {OrbitalPeriod: 4332.589},
Saturn: {OrbitalPeriod: 10759.22},
Uranus: {OrbitalPeriod: 30685.4},
Neptune: {OrbitalPeriod: 60189.0},
Pluto: {OrbitalPeriod: 90560.0}
};
type VsopModel = number[][][][];
interface VsopTable {
[body: string]: VsopModel;
}
const vsop: VsopTable = {
Mercury: [
[
[
[4.40250710144, 0.00000000000, 0.00000000000],
[0.40989414977, 1.48302034195, 26087.90314157420],
[0.05046294200, 4.47785489551, 52175.80628314840],
[0.00855346844, 1.16520322459, 78263.70942472259],
[0.00165590362, 4.11969163423, 104351.61256629678],
[0.00034561897, 0.77930768443, 130439.51570787099],
[0.00007583476, 3.71348404924, 156527.41884944518]
],
[
[26087.90313685529, 0.00000000000, 0.00000000000],
[0.01131199811, 6.21874197797, 26087.90314157420],
[0.00292242298, 3.04449355541, 52175.80628314840],
[0.00075775081, 6.08568821653, 78263.70942472259],
[0.00019676525, 2.80965111777, 104351.61256629678]
]
],
[
[
[0.11737528961, 1.98357498767, 26087.90314157420],
[0.02388076996, 5.03738959686, 52175.80628314840],
[0.01222839532, 3.14159265359, 0.00000000000],
[0.00543251810, 1.79644363964, 78263.70942472259],
[0.00129778770, 4.83232503958, 104351.61256629678],
[0.00031866927, 1.58088495658, 130439.51570787099],
[0.00007963301, 4.60972126127, 156527.41884944518]
],
[
[0.00274646065, 3.95008450011, 26087.90314157420],
[0.00099737713, 3.14159265359, 0.00000000000]
]
],
[
[
[0.39528271651, 0.00000000000, 0.00000000000],
[0.07834131818, 6.19233722598, 26087.90314157420],
[0.00795525558, 2.95989690104, 52175.80628314840],
[0.00121281764, 6.01064153797, 78263.70942472259],
[0.00021921969, 2.77820093972, 104351.61256629678],
[0.00004354065, 5.82894543774, 130439.51570787099]
],
[
[0.00217347740, 4.65617158665, 26087.90314157420],
[0.00044141826, 1.42385544001, 52175.80628314840]
]
]
],
Venus: [
[
[
[3.17614666774, 0.00000000000, 0.00000000000],
[0.01353968419, 5.59313319619, 10213.28554621100],
[0.00089891645, 5.30650047764, 20426.57109242200],
[0.00005477194, 4.41630661466, 7860.41939243920],
[0.00003455741, 2.69964447820, 11790.62908865880],
[0.00002372061, 2.99377542079, 3930.20969621960],
[0.00001317168, 5.18668228402, 26.29831979980],
[0.00001664146, 4.25018630147, 1577.34354244780],
[0.00001438387, 4.15745084182, 9683.59458111640],
[0.00001200521, 6.15357116043, 30639.85663863300]
],
[
[10213.28554621638, 0.00000000000, 0.00000000000],
[0.00095617813, 2.46406511110, 10213.28554621100],
[0.00007787201, 0.62478482220, 20426.57109242200]
]
],
[
[
[0.05923638472, 0.26702775812, 10213.28554621100],
[0.00040107978, 1.14737178112, 20426.57109242200],
[0.00032814918, 3.14159265359, 0.00000000000]
],
[
[0.00287821243, 1.88964962838, 10213.28554621100]
]
],
[
[
[0.72334820891, 0.00000000000, 0.00000000000],
[0.00489824182, 4.02151831717, 10213.28554621100],
[0.00001658058, 4.90206728031, 20426.57109242200],
[0.00001378043, 1.12846591367, 11790.62908865880],
[0.00001632096, 2.84548795207, 7860.41939243920],
[0.00000498395, 2.58682193892, 9683.59458111640],
[0.00000221985, 2.01346696541, 19367.18916223280],
[0.00000237454, 2.55136053886, 15720.83878487840]
],
[
[0.00034551041, 0.89198706276, 10213.28554621100]
]
]
],
Earth: [
[
[
[1.75347045673, 0.00000000000, 0.00000000000],
[0.03341656453, 4.66925680415, 6283.07584999140],
[0.00034894275, 4.62610242189, 12566.15169998280],
[0.00003417572, 2.82886579754, 3.52311834900],
[0.00003497056, 2.74411783405, 5753.38488489680],
[0.00003135899, 3.62767041756, 77713.77146812050],
[0.00002676218, 4.41808345438, 7860.41939243920],
[0.00002342691, 6.13516214446, 3930.20969621960],
[0.00001273165, 2.03709657878, 529.69096509460],
[0.00001324294, 0.74246341673, 11506.76976979360],
[0.00000901854, 2.04505446477, 26.29831979980],
[0.00001199167, 1.10962946234, 1577.34354244780],
[0.00000857223, 3.50849152283, 398.14900340820],
[0.00000779786, 1.17882681962, 5223.69391980220],
[0.00000990250, 5.23268072088, 5884.92684658320],
[0.00000753141, 2.53339052847, 5507.55323866740],
[0.00000505267, 4.58292599973, 18849.22754997420],
[0.00000492392, 4.20505711826, 775.52261132400],
[0.00000356672, 2.91954114478, 0.06731030280],
[0.00000284125, 1.89869240932, 796.29800681640],
[0.00000242879, 0.34481445893, 5486.77784317500],
[0.00000317087, 5.84901948512, 11790.62908865880],
[0.00000271112, 0.31486255375, 10977.07880469900],
[0.00000206217, 4.80646631478, 2544.31441988340],
[0.00000205478, 1.86953770281, 5573.14280143310],
[0.00000202318, 2.45767790232, 6069.77675455340],
[0.00000126225, 1.08295459501, 20.77539549240],
[0.00000155516, 0.83306084617, 213.29909543800]
],
[
[6283.07584999140, 0.00000000000, 0.00000000000],
[0.00206058863, 2.67823455808, 6283.07584999140],
[0.00004303419, 2.63512233481, 12566.15169998280]
],
[
[0.00008721859, 1.07253635559, 6283.07584999140]
]
],
[
[],
[
[0.00227777722, 3.41376620530, 6283.07584999140],
[0.00003805678, 3.37063423795, 12566.15169998280]
]
],
[
[
[1.00013988784, 0.00000000000, 0.00000000000],
[0.01670699632, 3.09846350258, 6283.07584999140],
[0.00013956024, 3.05524609456, 12566.15169998280],
[0.00003083720, 5.19846674381, 77713.77146812050],
[0.00001628463, 1.17387558054, 5753.38488489680],
[0.00001575572, 2.84685214877, 7860.41939243920],
[0.00000924799, 5.45292236722, 11506.76976979360],
[0.00000542439, 4.56409151453, 3930.20969621960],
[0.00000472110, 3.66100022149, 5884.92684658320],
[0.00000085831, 1.27079125277, 161000.68573767410],
[0.00000057056, 2.01374292245, 83996.84731811189],
[0.00000055736, 5.24159799170, 71430.69561812909],
[0.00000174844, 3.01193636733, 18849.22754997420],
[0.00000243181, 4.27349530790, 11790.62908865880]
],
[
[0.00103018607, 1.10748968172, 6283.07584999140],
[0.00001721238, 1.06442300386, 12566.15169998280]
],
[
[0.00004359385, 5.78455133808, 6283.07584999140]
]
]
],
Mars: [
[
[
[6.20347711581, 0.00000000000, 0.00000000000],
[0.18656368093, 5.05037100270, 3340.61242669980],
[0.01108216816, 5.40099836344, 6681.22485339960],
[0.00091798406, 5.75478744667, 10021.83728009940],
[0.00027744987, 5.97049513147, 3.52311834900],
[0.00010610235, 2.93958560338, 2281.23049651060],
[0.00012315897, 0.84956094002, 2810.92146160520],
[0.00008926784, 4.15697846427, 0.01725365220],
[0.00008715691, 6.11005153139, 13362.44970679920],
[0.00006797556, 0.36462229657, 398.14900340820],
[0.00007774872, 3.33968761376, 5621.84292321040],
[0.00003575078, 1.66186505710, 2544.31441988340],
[0.00004161108, 0.22814971327, 2942.46342329160],
[0.00003075252, 0.85696614132, 191.44826611160],
[0.00002628117, 0.64806124465, 3337.08930835080],
[0.00002937546, 6.07893711402, 0.06731030280],
[0.00002389414, 5.03896442664, 796.29800681640],
[0.00002579844, 0.02996736156, 3344.13554504880],
[0.00001528141, 1.14979301996, 6151.53388830500],
[0.00001798806, 0.65634057445, 529.69096509460],
[0.00001264357, 3.62275122593, 5092.15195811580],
[0.00001286228, 3.06796065034, 2146.16541647520],
[0.00001546404, 2.91579701718, 1751.53953141600],
[0.00001024902, 3.69334099279, 8962.45534991020],
[0.00000891566, 0.18293837498, 16703.06213349900],
[0.00000858759, 2.40093811940, 2914.01423582380],
[0.00000832715, 2.46418619474, 3340.59517304760],
[0.00000832720, 4.49495782139, 3340.62968035200],
[0.00000712902, 3.66335473479, 1059.38193018920],
[0.00000748723, 3.82248614017, 155.42039943420],
[0.00000723861, 0.67497311481, 3738.76143010800],
[0.00000635548, 2.92182225127, 8432.76438481560],
[0.00000655162, 0.48864064125, 3127.31333126180],
[0.00000550474, 3.81001042328, 0.98032106820],
[0.00000552750, 4.47479317037, 1748.01641306700],
[0.00000425966, 0.55364317304, 6283.07584999140],
[0.00000415131, 0.49662285038, 213.29909543800],
[0.00000472167, 3.62547124025, 1194.44701022460],
[0.00000306551, 0.38052848348, 6684.74797174860],
[0.00000312141, 0.99853944405, 6677.70173505060],
[0.00000293198, 4.22131299634, 20.77539549240],
[0.00000302375, 4.48618007156, 3532.06069281140],
[0.00000274027, 0.54222167059, 3340.54511639700],
[0.00000281079, 5.88163521788, 1349.86740965880],
[0.00000231183, 1.28242156993, 3870.30339179440],
[0.00000283602, 5.76885434940, 3149.16416058820],
[0.00000236117, 5.75503217933, 3333.49887969900],
[0.00000274033, 0.13372524985, 3340.67973700260],
[0.00000299395, 2.78323740866, 6254.62666252360]
],
[
[3340.61242700512, 0.00000000000, 0.00000000000],
[0.01457554523, 3.60433733236, 3340.61242669980],
[0.00168414711, 3.92318567804, 6681.22485339960],
[0.00020622975, 4.26108844583, 10021.83728009940],
[0.00003452392, 4.73210393190, 3.52311834900],
[0.00002586332, 4.60670058555, 13362.44970679920],
[0.00000841535, 4.45864030426, 2281.23049651060]
],
[
[0.00058152577, 2.04961712429, 3340.61242669980],
[0.00013459579, 2.45738706163, 6681.22485339960]
]
],
[
[
[0.03197134986, 3.76832042431, 3340.61242669980],
[0.00298033234, 4.10616996305, 6681.22485339960],
[0.00289104742, 0.00000000000, 0.00000000000],
[0.00031365539, 4.44651053090, 10021.83728009940],
[0.00003484100, 4.78812549260, 13362.44970679920]
],
[
[0.00217310991, 6.04472194776, 3340.61242669980],
[0.00020976948, 3.14159265359, 0.00000000000],
[0.00012834709, 1.60810667915, 6681.22485339960]
]
],
[
[
[1.53033488271, 0.00000000000, 0.00000000000],
[0.14184953160, 3.47971283528, 3340.61242669980],
[0.00660776362, 3.81783443019, 6681.22485339960],
[0.00046179117, 4.15595316782, 10021.83728009940],
[0.00008109733, 5.55958416318, 2810.92146160520],
[0.00007485318, 1.77239078402, 5621.84292321040],
[0.00005523191, 1.36436303770, 2281.23049651060],
[0.00003825160, 4.49407183687, 13362.44970679920],
[0.00002306537, 0.09081579001, 2544.31441988340],
[0.00001999396, 5.36059617709, 3337.08930835080],
[0.00002484394, 4.92545639920, 2942.46342329160],
[0.00001960195, 4.74249437639, 3344.13554504880],
[0.00001167119, 2.11260868341, 5092.15195811580],
[0.00001102816, 5.00908403998, 398.14900340820],
[0.00000899066, 4.40791133207, 529.69096509460],
[0.00000992252, 5.83861961952, 6151.53388830500],
[0.00000807354, 2.10217065501, 1059.38193018920],
[0.00000797915, 3.44839203899, 796.29800681640],
[0.00000740975, 1.49906336885, 2146.16541647520]
],
[
[0.01107433345, 2.03250524857, 3340.61242669980],
[0.00103175887, 2.37071847807, 6681.22485339960],
[0.00012877200, 0.00000000000, 0.00000000000],
[0.00010815880, 2.70888095665, 10021.83728009940]
],
[
[0.00044242249, 0.47930604954, 3340.61242669980],
[0.00008138042, 0.86998389204, 6681.22485339960]
]
]
],
Jupiter: [
[
[
[0.59954691494, 0.00000000000, 0.00000000000],
[0.09695898719, 5.06191793158, 529.69096509460],
[0.00573610142, 1.44406205629, 7.11354700080],
[0.00306389205, 5.41734730184, 1059.38193018920],
[0.00097178296, 4.14264726552, 632.78373931320],
[0.00072903078, 3.64042916389, 522.57741809380],
[0.00064263975, 3.41145165351, 103.09277421860],
[0.00039806064, 2.29376740788, 419.48464387520],
[0.00038857767, 1.27231755835, 316.39186965660],
[0.00027964629, 1.78454591820, 536.80451209540],
[0.00013589730, 5.77481040790, 1589.07289528380],
[0.00008246349, 3.58227925840, 206.18554843720],
[0.00008768704, 3.63000308199, 949.17560896980],
[0.00007368042, 5.08101194270, 735.87651353180],
[0.00006263150, 0.02497628807, 213.29909543800],
[0.00006114062, 4.51319998626, 1162.47470440780],
[0.00004905396, 1.32084470588, 110.20632121940],
[0.00005305285, 1.30671216791, 14.22709400160],
[0.00005305441, 4.18625634012, 1052.26838318840],
[0.00004647248, 4.69958103684, 3.93215326310],
[0.00003045023, 4.31676431084, 426.59819087600],
[0.00002609999, 1.56667394063, 846.08283475120],
[0.00002028191, 1.06376530715, 3.18139373770],
[0.00001764763, 2.14148655117, 1066.49547719000],
[0.00001722972, 3.88036268267, 1265.56747862640],
[0.00001920945, 0.97168196472, 639.89728631400],
[0.00001633223, 3.58201833555, 515.46387109300],
[0.00001431999, 4.29685556046, 625.67019231240],
[0.00000973272, 4.09764549134, 95.97922721780]
],
[
[529.69096508814, 0.00000000000, 0.00000000000],
[0.00489503243, 4.22082939470, 529.69096509460],
[0.00228917222, 6.02646855621, 7.11354700080],
[0.00030099479, 4.54540782858, 1059.38193018920],
[0.00020720920, 5.45943156902, 522.57741809380],
[0.00012103653, 0.16994816098, 536.80451209540],
[0.00006067987, 4.42422292017, 103.09277421860],
[0.00005433968, 3.98480737746, 419.48464387520],
[0.00004237744, 5.89008707199, 14.22709400160]
],
[
[0.00047233601, 4.32148536482, 7.11354700080],
[0.00030649436, 2.92977788700, 529.69096509460],
[0.00014837605, 3.14159265359, 0.00000000000]
]
],
[
[
[0.02268615702, 3.55852606721, 529.69096509460],
[0.00109971634, 3.90809347197, 1059.38193018920],
[0.00110090358, 0.00000000000, 0.00000000000],
[0.00008101428, 3.60509572885, 522.57741809380],
[0.00006043996, 4.25883108339, 1589.07289528380],
[0.00006437782, 0.30627119215, 536.80451209540]
],
[
[0.00078203446, 1.52377859742, 529.69096509460]
]
],
[
[
[5.20887429326, 0.00000000000, 0.00000000000],
[0.25209327119, 3.49108639871, 529.69096509460],
[0.00610599976, 3.84115365948, 1059.38193018920],
[0.00282029458, 2.57419881293, 632.78373931320],
[0.00187647346, 2.07590383214, 522.57741809380],
[0.00086792905, 0.71001145545, 419.48464387520],
[0.00072062974, 0.21465724607, 536.80451209540],
[0.00065517248, 5.97995884790, 316.39186965660],
[0.00029134542, 1.67759379655, 103.09277421860],
[0.00030135335, 2.16132003734, 949.17560896980],
[0.00023453271, 3.54023522184, 735.87651353180],
[0.00022283743, 4.19362594399, 1589.07289528380],
[0.00023947298, 0.27458037480, 7.11354700080],
[0.00013032614, 2.96042965363, 1162.47470440780],
[0.00009703360, 1.90669633585, 206.18554843720],
[0.00012749023, 2.71550286592, 1052.26838318840],
[0.00007057931, 2.18184839926, 1265.56747862640],
[0.00006137703, 6.26418240033, 846.08283475120],
[0.00002616976, 2.00994012876, 1581.95934828300]
],
[
[0.01271801520, 2.64937512894, 529.69096509460],
[0.00061661816, 3.00076460387, 1059.38193018920],
[0.00053443713, 3.89717383175, 522.57741809380],
[0.00031185171, 4.88276958012, 536.80451209540],
[0.00041390269, 0.00000000000, 0.00000000000]
]
]
],
Saturn: [
[
[
[0.87401354025, 0.00000000000, 0.00000000000],
[0.11107659762, 3.96205090159, 213.29909543800],
[0.01414150957, 4.58581516874, 7.11354700080],
[0.00398379389, 0.52112032699, 206.18554843720],
[0.00350769243, 3.30329907896, 426.59819087600],
[0.00206816305, 0.24658372002, 103.09277421860],
[0.00079271300, 3.84007056878, 220.41264243880],
[0.00023990355, 4.66976924553, 110.20632121940],
[0.00016573588, 0.43719228296, 419.48464387520],
[0.00014906995, 5.76903183869, 316.39186965660],
[0.00015820290, 0.93809155235, 632.78373931320],
[0.00014609559, 1.56518472000, 3.93215326310],
[0.00013160301, 4.44891291899, 14.22709400160],
[0.00015053543, 2.71669915667, 639.89728631400],
[0.00013005299, 5.98119023644, 11.04570026390],
[0.00010725067, 3.12939523827, 202.25339517410],
[0.00005863206, 0.23656938524, 529.69096509460],
[0.00005227757, 4.20783365759, 3.18139373770],
[0.00006126317, 1.76328667907, 277.03499374140],
[0.00005019687, 3.17787728405, 433.71173787680],
[0.00004592550, 0.61977744975, 199.07200143640],
[0.00004005867, 2.24479718502, 63.73589830340],
[0.00002953796, 0.98280366998, 95.97922721780],
[0.00003873670, 3.22283226966, 138.51749687070],
[0.00002461186, 2.03163875071, 735.87651353180],
[0.00003269484, 0.77492638211, 949.17560896980],
[0.00001758145, 3.26580109940, 522.57741809380],
[0.00001640172, 5.50504453050, 846.08283475120],
[0.00001391327, 4.02333150505, 323.50541665740],
[0.00001580648, 4.37265307169, 309.27832265580],
[0.00001123498, 2.83726798446, 415.55249061210],
[0.00001017275, 3.71700135395, 227.52618943960],
[0.00000848642, 3.19150170830, 209.36694217490]
],
[
[213.29909521690, 0.00000000000, 0.00000000000],
[0.01297370862, 1.82834923978, 213.29909543800],
[0.00564345393, 2.88499717272, 7.11354700080],
[0.00093734369, 1.06311793502, 426.59819087600],
[0.00107674962, 2.27769131009, 206.18554843720],
[0.00040244455, 2.04108104671, 220.41264243880],
[0.00019941774, 1.27954390470, 103.09277421860],
[0.00010511678, 2.74880342130, 14.22709400160],
[0.00006416106, 0.38238295041, 639.89728631400],
[0.00004848994, 2.43037610229, 419.48464387520],
[0.00004056892, 2.92133209468, 110.20632121940],
[0.00003768635, 3.64965330780, 3.93215326310]
],
[
[0.00116441330, 1.17988132879, 7.11354700080],
[0.00091841837, 0.07325195840, 213.29909543800],
[0.00036661728, 0.00000000000, 0.00000000000],
[0.00015274496, 4.06493179167, 206.18554843720]
]
],
[
[
[0.04330678039, 3.60284428399, 213.29909543800],
[0.00240348302, 2.85238489373, 426.59819087600],
[0.00084745939, 0.00000000000, 0.00000000000],
[0.00030863357, 3.48441504555, 220.41264243880],
[0.00034116062, 0.57297307557, 206.18554843720],
[0.00014734070, 2.11846596715, 639.89728631400],
[0.00009916667, 5.79003188904, 419.48464387520],
[0.00006993564, 4.73604689720, 7.11354700080],
[0.00004807588, 5.43305312061, 316.39186965660]
],
[
[0.00198927992, 4.93901017903, 213.29909543800],
[0.00036947916, 3.14159265359, 0.00000000000],
[0.00017966989, 0.51979431110, 426.59819087600]
]
],
[
[
[9.55758135486, 0.00000000000, 0.00000000000],
[0.52921382865, 2.39226219573, 213.29909543800],
[0.01873679867, 5.23549604660, 206.18554843720],
[0.01464663929, 1.64763042902, 426.59819087600],
[0.00821891141, 5.93520042303, 316.39186965660],
[0.00547506923, 5.01532618980, 103.09277421860],
[0.00371684650, 2.27114821115, 220.41264243880],
[0.00361778765, 3.13904301847, 7.11354700080],
[0.00140617506, 5.70406606781, 632.78373931320],
[0.00108974848, 3.29313390175, 110.20632121940],
[0.00069006962, 5.94099540992, 419.48464387520],
[0.00061053367, 0.94037691801, 639.89728631400],
[0.00048913294, 1.55733638681, 202.25339517410],
[0.00034143772, 0.19519102597, 277.03499374140],
[0.00032401773, 5.47084567016, 949.17560896980],
[0.00020936596, 0.46349251129, 735.87651353180],
[0.00009796004, 5.20477537945, 1265.56747862640],
[0.00011993338, 5.98050967385, 846.08283475120],
[0.00020839300, 1.52102476129, 433.71173787680],
[0.00015298404, 3.05943814940, 529.69096509460],
[0.00006465823, 0.17732249942, 1052.26838318840],
[0.00011380257, 1.73105427040, 522.57741809380],
[0.00003419618, 4.94550542171, 1581.95934828300]
],
[
[0.06182981340, 0.25843511480, 213.29909543800],
[0.00506577242, 0.71114625261, 206.18554843720],
[0.00341394029, 5.79635741658, 426.59819087600],
[0.00188491195, 0.47215589652, 220.41264243880],
[0.00186261486, 3.14159265359, 0.00000000000],
[0.00143891146, 1.40744822888, 7.11354700080]
],
[
[0.00436902572, 4.78671677509, 213.29909543800]
]
]
],
Uranus: [
[
[
[5.48129294297, 0.00000000000, 0.00000000000],
[0.09260408234, 0.89106421507, 74.78159856730],
[0.01504247898, 3.62719260920, 1.48447270830],
[0.00365981674, 1.89962179044, 73.29712585900],
[0.00272328168, 3.35823706307, 149.56319713460],
[0.00070328461, 5.39254450063, 63.73589830340],
[0.00068892678, 6.09292483287, 76.26607127560],
[0.00061998615, 2.26952066061, 2.96894541660],
[0.00061950719, 2.85098872691, 11.04570026390],
[0.00026468770, 3.14152083966, 71.81265315070],
[0.00025710476, 6.11379840493, 454.90936652730],
[0.00021078850, 4.36059339067, 148.07872442630],
[0.00017818647, 1.74436930289, 36.64856292950],
[0.00014613507, 4.73732166022, 3.93215326310],
[0.00011162509, 5.82681796350, 224.34479570190],
[0.00010997910, 0.48865004018, 138.51749687070],
[0.00009527478, 2.95516862826, 35.16409022120],
[0.00007545601, 5.23626582400, 109.94568878850],
[0.00004220241, 3.23328220918, 70.84944530420],
[0.00004051900, 2.27755017300, 151.04766984290],
[0.00003354596, 1.06549007380, 4.45341812490],
[0.00002926718, 4.62903718891, 9.56122755560],
[0.00003490340, 5.48306144511, 146.59425171800],
[0.00003144069, 4.75199570434, 77.75054398390],
[0.00002922333, 5.35235361027, 85.82729883120],
[0.00002272788, 4.36600400036, 70.32818044240],
[0.00002051219, 1.51773566586, 0.11187458460],
[0.00002148602, 0.60745949945, 38.13303563780],
[0.00001991643, 4.92437588682, 277.03499374140],
[0.00001376226, 2.04283539351, 65.22037101170],
[0.00001666902, 3.62744066769, 380.12776796000],
[0.00001284107, 3.11347961505, 202.25339517410],
[0.00001150429, 0.93343589092, 3.18139373770],
[0.00001533221, 2.58594681212, 52.69019803950],
[0.00001281604, 0.54271272721, 222.86032299360],
[0.00001372139, 4.19641530878, 111.43016149680],
[0.00001221029, 0.19900650030, 108.46121608020],
[0.00000946181, 1.19253165736, 127.47179660680],
[0.00001150989, 4.17898916639, 33.67961751290]
],
[
[74.78159860910, 0.00000000000, 0.00000000000],
[0.00154332863, 5.24158770553, 74.78159856730],
[0.00024456474, 1.71260334156, 1.48447270830],
[0.00009258442, 0.42829732350, 11.04570026390],
[0.00008265977, 1.50218091379, 63.73589830340],
[0.00009150160, 1.41213765216, 149.56319713460]
]
],
[
[
[0.01346277648, 2.61877810547, 74.78159856730],
[0.00062341400, 5.08111189648, 149.56319713460],
[0.00061601196, 3.14159265359, 0.00000000000],
[0.00009963722, 1.61603805646, 76.26607127560],
[0.00009926160, 0.57630380333, 73.29712585900]
],
[
[0.00034101978, 0.01321929936, 74.78159856730]
]
],
[
[
[19.21264847206, 0.00000000000, 0.00000000000],
[0.88784984413, 5.60377527014, 74.78159856730],
[0.03440836062, 0.32836099706, 73.29712585900],
[0.02055653860, 1.78295159330, 149.56319713460],
[0.00649322410, 4.52247285911, 76.26607127560],
[0.00602247865, 3.86003823674, 63.73589830340],
[0.00496404167, 1.40139935333, 454.90936652730],
[0.00338525369, 1.58002770318, 138.51749687070],
[0.00243509114, 1.57086606044, 71.81265315070],
[0.00190522303, 1.99809394714, 1.48447270830],
[0.00161858838, 2.79137786799, 148.07872442630],
[0.00143706183, 1.38368544947, 11.04570026390],
[0.00093192405, 0.17437220467, 36.64856292950],
[0.00071424548, 4.24509236074, 224.34479570190],
[0.00089806014, 3.66105364565, 109.94568878850],
[0.00039009723, 1.66971401684, 70.84944530420],
[0.00046677296, 1.39976401694, 35.16409022120],
[0.00039025624, 3.36234773834, 277.03499374140],
[0.00036755274, 3.88649278513, 146.59425171800],
[0.00030348723, 0.70100838798, 151.04766984290],
[0.00029156413, 3.18056336700, 77.75054398390],
[0.00022637073, 0.72518687029, 529.69096509460],
[0.00011959076, 1.75043392140, 984.60033162190],
[0.00025620756, 5.25656086672, 380.12776796000]
],
[
[0.01479896629, 3.67205697578, 74.78159856730]
]
]
],
Neptune: [
[
[
[5.31188633046, 0.00000000000, 0.00000000000],
[0.01798475530, 2.90101273890, 38.13303563780],
[0.01019727652, 0.48580922867, 1.48447270830],
[0.00124531845, 4.83008090676, 36.64856292950],
[0.00042064466, 5.41054993053, 2.96894541660],
[0.00037714584, 6.09221808686, 35.16409022120],
[0.00033784738, 1.24488874087, 76.26607127560],
[0.00016482741, 0.00007727998, 491.55792945680],
[0.00009198584, 4.93747051954, 39.61750834610],
[0.00008994250, 0.27462171806, 175.16605980020]
],
[
[38.13303563957, 0.00000000000, 0.00000000000],
[0.00016604172, 4.86323329249, 1.48447270830],
[0.00015744045, 2.27887427527, 38.13303563780]
]
],
[
[
[0.03088622933, 1.44104372644, 38.13303563780],
[0.00027780087, 5.91271884599, 76.26607127560],
[0.00027623609, 0.00000000000, 0.00000000000],
[0.00015355489, 2.52123799551, 36.64856292950],
[0.00015448133, 3.50877079215, 39.61750834610]
]
],
[
[
[30.07013205828, 0.00000000000, 0.00000000000],
[0.27062259632, 1.32999459377, 38.13303563780],
[0.01691764014, 3.25186135653, 36.64856292950],
[0.00807830553, 5.18592878704, 1.48447270830],
[0.00537760510, 4.52113935896, 35.16409022120],
[0.00495725141, 1.57105641650, 491.55792945680],
[0.00274571975, 1.84552258866, 175.16605980020],
[0.00012012320, 1.92059384991, 1021.24889455140],
[0.00121801746, 5.79754470298, 76.26607127560],
[0.00100896068, 0.37702724930, 73.29712585900],
[0.00135134092, 3.37220609835, 39.61750834610],
[0.00007571796, 1.07149207335, 388.46515523820]
]
]
]
};
export function DeltaT_EspenakMeeus(ut: number): number {
var u: number, u2: number, u3: number, u4: number, u5: number, u6: number, u7: number;
/*
Fred Espenak writes about Delta-T generically here:
https://eclipse.gsfc.nasa.gov/SEhelp/deltaT.html
https://eclipse.gsfc.nasa.gov/SEhelp/deltat2004.html
He provides polynomial approximations for distant years here:
https://eclipse.gsfc.nasa.gov/SEhelp/deltatpoly2004.html
They start with a year value 'y' such that y=2000 corresponds
to the UTC Date 15-January-2000. Convert difference in days
to mean tropical years.
*/
const y = 2000 + ((ut - 14) / DAYS_PER_TROPICAL_YEAR);
if (y < -500) {
u = (y - 1820) / 100;
return -20 + (32 * u * u);
}
if (y < 500) {
u = y / 100;
u2 = u * u;
u3 = u * u2;
u4 = u2 * u2;
u5 = u2 * u3;
u6 = u3 * u3;
return 10583.6 - 1014.41 * u + 33.78311 * u2 - 5.952053 * u3 - 0.1798452 * u4 + 0.022174192 * u5 + 0.0090316521 * u6;
}
if (y < 1600) {
u = (y - 1000) / 100;
u2 = u * u;
u3 = u * u2;
u4 = u2 * u2;
u5 = u2 * u3;
u6 = u3 * u3;
return 1574.2 - 556.01 * u + 71.23472 * u2 + 0.319781 * u3 - 0.8503463 * u4 - 0.005050998 * u5 + 0.0083572073 * u6;
}
if (y < 1700) {
u = y - 1600;
u2 = u * u;
u3 = u * u2;
return 120 - 0.9808 * u - 0.01532 * u2 + u3 / 7129.0;
}
if (y < 1800) {
u = y - 1700;
u2 = u * u;
u3 = u * u2;
u4 = u2 * u2;
return 8.83 + 0.1603 * u - 0.0059285 * u2 + 0.00013336 * u3 - u4 / 1174000;
}
if (y < 1860) {
u = y - 1800;
u2 = u * u;
u3 = u * u2;
u4 = u2 * u2;
u5 = u2 * u3;
u6 = u3 * u3;
u7 = u3 * u4;
return 13.72 - 0.332447 * u + 0.0068612 * u2 + 0.0041116 * u3 - 0.00037436 * u4 + 0.0000121272 * u5 - 0.0000001699 * u6 + 0.000000000875 * u7;
}
if (y < 1900) {
u = y - 1860;
u2 = u * u;
u3 = u * u2;
u4 = u2 * u2;
u5 = u2 * u3;
return 7.62 + 0.5737 * u - 0.251754 * u2 + 0.01680668 * u3 - 0.0004473624 * u4 + u5 / 233174;
}
if (y < 1920) {
u = y - 1900;
u2 = u * u;
u3 = u * u2;
u4 = u2 * u2;
return -2.79 + 1.494119 * u - 0.0598939 * u2 + 0.0061966 * u3 - 0.000197 * u4;
}
if (y < 1941) {
u = y - 1920;
u2 = u * u;
u3 = u * u2;
return 21.20 + 0.84493 * u - 0.076100 * u2 + 0.0020936 * u3;
}
if (y < 1961) {
u = y - 1950;
u2 = u * u;
u3 = u * u2;
return 29.07 + 0.407 * u - u2 / 233 + u3 / 2547;
}
if (y < 1986) {
u = y - 1975;
u2 = u * u;
u3 = u * u2;
return 45.45 + 1.067 * u - u2 / 260 - u3 / 718;
}
if (y < 2005) {
u = y - 2000;
u2 = u * u;
u3 = u * u2;
u4 = u2 * u2;
u5 = u2 * u3;
return 63.86 + 0.3345 * u - 0.060374 * u2 + 0.0017275 * u3 + 0.000651814 * u4 + 0.00002373599 * u5;
}
if (y < 2050) {
u = y - 2000;
return 62.92 + 0.32217 * u + 0.005589 * u * u;
}
if (y < 2150) {
u = (y - 1820) / 100;
return -20 + 32 * u * u - 0.5628 * (2150 - y);
}
/* all years after 2150 */
u = (y - 1820) / 100;
return -20 + (32 * u * u);
}
export type DeltaTimeFunction = (ut: number) => number;
export function DeltaT_JplHorizons(ut: number): number {
return DeltaT_EspenakMeeus(Math.min(ut, 17.0 * DAYS_PER_TROPICAL_YEAR));
}
let DeltaT: DeltaTimeFunction = DeltaT_EspenakMeeus;
export function SetDeltaTFunction(func: DeltaTimeFunction) {
DeltaT = func;
}
/**
* @ignore
*
* @brief Calculates Terrestrial Time (TT) from Universal Time (UT).
*
* @param {number} ut
* The Universal Time expressed as a floating point number of days since the 2000.0 epoch.
*
* @returns {number}
* A Terrestrial Time expressed as a floating point number of days since the 2000.0 epoch.
*/
function TerrestrialTime(ut: number): number {
return ut + DeltaT(ut) / 86400;
}
/**
* @brief The date and time of an astronomical observation.
*
* Objects of type `AstroTime` are used throughout the internals
* of the Astronomy library, and are included in certain return objects.
* Use the constructor or the {@link MakeTime} function to create an `AstroTime` object.
*
* @property {Date} date
* The JavaScript Date object for the given date and time.
* This Date corresponds to the numeric day value stored in the `ut` property.
*
* @property {number} ut
* Universal Time (UT1/UTC) in fractional days since the J2000 epoch.
* Universal Time represents time measured with respect to the Earth's rotation,
* tracking mean solar days.
* The Astronomy library approximates UT1 and UTC as being the same thing.
* This gives sufficient accuracy for the precision requirements of this project.
*
* @property {number} tt
* Terrestrial Time in fractional days since the J2000 epoch.
* TT represents a continuously flowing ephemeris timescale independent of
* any variations of the Earth's rotation, and is adjusted from UT
* using a best-fit piecewise polynomial model devised by
* [Espenak and Meeus](https://eclipse.gsfc.nasa.gov/SEhelp/deltatpoly2004.html).
*/
export class AstroTime {
date: Date;
ut: number;
tt: number;
/**
* @param {FlexibleDateTime} date
* A JavaScript Date object, a numeric UTC value expressed in J2000 days, or another AstroTime object.
*/
constructor(date: FlexibleDateTime) {
if (date instanceof AstroTime) {
// Construct a clone of the AstroTime passed in.
this.date = date.date;
this.ut = date.ut;
this.tt = date.tt;
return;
}
const MillisPerDay = 1000 * 3600 * 24;
if ((date instanceof Date) && Number.isFinite(date.valueOf())) {
this.date = date;
this.ut = (date.valueOf() - J2000.valueOf()) / MillisPerDay;
this.tt = TerrestrialTime(this.ut);
return;
}
if (Number.isFinite(date)) {
this.date = new Date(J2000.valueOf() + <number>date * MillisPerDay);
this.ut = <number>date;
this.tt = TerrestrialTime(this.ut);
return;
}
throw 'Argument must be a Date object, an AstroTime object, or a numeric UTC Julian date.';
}
/**
* @brief Creates an `AstroTime` value from a Terrestrial Time (TT) day value.
*
* This function can be used in rare cases where a time must be based
* on Terrestrial Time (TT) rather than Universal Time (UT).
* Most developers will want to invoke `new AstroTime(ut)` with a universal time
* instead of this function, because usually time is based on civil time adjusted
* by leap seconds to match the Earth's rotation, rather than the uniformly
* flowing TT used to calculate solar system dynamics. In rare cases
* where the caller already knows TT, this function is provided to create
* an `AstroTime` value that can be passed to Astronomy Engine functions.
*
* @param {number} tt
* The number of days since the J2000 epoch as expressed in Terrestrial Time.
*
* @returns {AstroTime}
* An `AstroTime` object for the specified terrestrial time.
*/
static FromTerrestrialTime(tt: number): AstroTime {
let time = new AstroTime(tt);
for (; ;) {
const err = tt - time.tt;
if (Math.abs(err) < 1.0e-12)
return time;
time = time.AddDays(err);
}
}
/**
* Formats an `AstroTime` object as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601)
* date/time string in UTC, to millisecond resolution.
* Example: `2018-08-17T17:22:04.050Z`
* @returns {string}
*/
toString(): string {
return this.date.toISOString();
}
/**
* Returns a new `AstroTime` object adjusted by the floating point number of days.
* Does NOT modify the original `AstroTime` object.
*
* @param {number} days
* The floating point number of days by which to adjust the given date and time.
* Positive values adjust the date toward the future, and
* negative values adjust the date toward the past.
*
* @returns {AstroTime}
*/
AddDays(days: number): AstroTime {
// This is slightly wrong, but the error is tiny.
// We really should be adding to TT, not to UT.
// But using TT would require creating an inverse function for DeltaT,
// which would be quite a bit of extra calculation.
// I estimate the error is in practice on the order of 10^(-7)
// times the value of 'days'.
// This is based on a typical drift of 1 second per year between UT and TT.
return new AstroTime(this.ut + days);
}
}
function InterpolateTime(time1: AstroTime, time2: AstroTime, fraction: number): AstroTime {
return new AstroTime(time1.ut + fraction * (time2.ut - time1.ut));
}
/**
* @brief A `Date`, `number`, or `AstroTime` value that specifies the date and time of an astronomical event.
*
* `FlexibleDateTime` is a placeholder type that represents three different types
* that may be passed to many Astronomy Engine functions: a JavaScript `Date` object,
* a number representing the real-valued number of UT days since the J2000 epoch,
* or an {@link AstroTime} object.
*
* This flexibility is for convenience of outside callers.
* Internally, Astronomy Engine always converts a `FlexibleTime` parameter
* to an `AstroTime` object by calling {@link MakeTime}.
*
* @typedef {Date | number | AstroTime} FlexibleDateTime
*/
/**
* @brief Converts multiple date/time formats to `AstroTime` format.
*
* Given a Date object or a number days since noon (12:00) on January 1, 2000 (UTC),
* this function creates an {@link AstroTime} object.
*
* Given an {@link AstroTime} object, returns the same object unmodified.
* Use of this function is not required for any of the other exposed functions in this library,
* because they all guarantee converting date/time parameters to `AstroTime`
* as needed. However, it may be convenient for callers who need to understand
* the difference between UTC and TT (Terrestrial Time). In some use cases,
* converting once to `AstroTime` format and passing the result into multiple
* function calls may be more efficient than passing in native JavaScript Date objects.
*
* @param {FlexibleDateTime} date
* A Date object, a number of UTC days since the J2000 epoch (noon on January 1, 2000),
* or an AstroTime object. See remarks above.
*
* @returns {AstroTime}
*/
export function MakeTime(date: FlexibleDateTime): AstroTime {
if (date instanceof AstroTime) {
return date;
}
return new AstroTime(date);
}
const iaudata = [
[[0, 0, 0, 0, 1], [-172064161, -174666, 33386, 92052331, 9086, 15377]],
[[0, 0, 2, -2, 2], [-13170906, -1675, -13696, 5730336, -3015, -4587]],
[[0, 0, 2, 0, 2], [-2276413, -234, 2796, 978459, -485, 1374]],
[[0, 0, 0, 0, 2], [2074554, 207, -698, -897492, 470, -291]],
[[0, 1, 0, 0, 0], [1475877, -3633, 11817, 73871, -184, -1924]],
[[0, 1, 2, -2, 2], [-516821, 1226, -524, 224386, -677, -174]],
[[1, 0, 0, 0, 0], [711159, 73, -872, -6750, 0, 358]],
[[0, 0, 2, 0, 1], [-387298, -367, 380, 200728, 18, 318]],
[[1, 0, 2, 0, 2], [-301461, -36, 816, 129025, -63, 367]],
[[0, -1, 2, -2, 2], [215829, -494, 111, -95929, 299, 132]],
[[0, 0, 2, -2, 1], [128227, 137, 181, -68982, -9, 39]],
[[-1, 0, 2, 0, 2], [123457, 11, 19, -53311, 32, -4]],
[[-1, 0, 0, 2, 0], [156994, 10, -168, -1235, 0, 82]],
[[1, 0, 0, 0, 1], [63110, 63, 27, -33228, 0, -9]],
[[-1, 0, 0, 0, 1], [-57976, -63, -189, 31429, 0, -75]],
[[-1, 0, 2, 2, 2], [-59641, -11, 149, 25543, -11, 66]],
[[1, 0, 2, 0, 1], [-51613, -42, 129, 26366, 0, 78]],
[[-2, 0, 2, 0, 1], [45893, 50, 31, -24236, -10, 20]],
[[0, 0, 0, 2, 0], [63384, 11, -150, -1220, 0, 29]],
[[0, 0, 2, 2, 2], [-38571, -1, 158, 16452, -11, 68]],
[[0, -2, 2, -2, 2], [32481, 0, 0, -13870, 0, 0]],
[[-2, 0, 0, 2, 0], [-47722, 0, -18, 477, 0, -25]],
[[2, 0, 2, 0, 2], [-31046, -1, 131, 13238, -11, 59]],
[[1, 0, 2, -2, 2], [28593, 0, -1, -12338, 10, -3]],
[[-1, 0, 2, 0, 1], [20441, 21, 10, -10758, 0, -3]],
[[2, 0, 0, 0, 0], [29243, 0, -74, -609, 0, 13]],
[[0, 0, 2, 0, 0], [25887, 0, -66, -550, 0, 11]],
[[0, 1, 0, 0, 1], [-14053, -25, 79, 8551, -2, -45]],
[[-1, 0, 0, 2, 1], [15164, 10, 11, -8001, 0, -1]],
[[0, 2, 2, -2, 2], [-15794, 72, -16, 6850, -42, -5]],
[[0, 0, -2, 2, 0], [21783, 0, 13, -167, 0, 13]],
[[1, 0, 0, -2, 1], [-12873, -10, -37, 6953, 0, -14]],
[[0, -1, 0, 0, 1], [-12654, 11, 63, 6415, 0, 26]],
[[-1, 0, 2, 2, 1], [-10204, 0, 25, 5222, 0, 15]],
[[0, 2, 0, 0, 0], [16707, -85, -10, 168, -1, 10]],
[[1, 0, 2, 2, 2], [-7691, 0, 44, 3268, 0, 19]],
[[-2, 0, 2, 0, 0], [-11024, 0, -14, 104, 0, 2]],
[[0, 1, 2, 0, 2], [7566, -21, -11, -3250, 0, -5]],
[[0, 0, 2, 2, 1], [-6637, -11, 25, 3353, 0, 14]],
[[0, -1, 2, 0, 2], [-7141, 21, 8, 3070, 0, 4]],
[[0, 0, 0, 2, 1], [-6302, -11, 2, 3272, 0, 4]],
[[1, 0, 2, -2, 1], [5800, 10, 2, -3045, 0, -1]],
[[2, 0, 2, -2, 2], [6443, 0, -7, -2768, 0, -4]],
[[-2, 0, 0, 2, 1], [-5774, -11, -15, 3041, 0, -5]],
[[2, 0, 2, 0, 1], [-5350, 0, 21, 2695, 0, 12]],
[[0, -1, 2, -2, 1], [-4752, -11, -3, 2719, 0, -3]],
[[0, 0, 0, -2, 1], [-4940, -11, -21, 2720, 0, -9]],
[[-1, -1, 0, 2, 0], [7350, 0, -8, -51, 0, 4]],
[[2, 0, 0, -2, 1], [4065, 0, 6, -2206, 0, 1]],
[[1, 0, 0, 2, 0], [6579, 0, -24, -199, 0, 2]],
[[0, 1, 2, -2, 1], [3579, 0, 5, -1900, 0, 1]],
[[1, -1, 0, 0, 0], [4725, 0, -6, -41, 0, 3]],
[[-2, 0, 2, 0, 2], [-3075, 0, -2, 1313, 0, -1]],
[[3, 0, 2, 0, 2], [-2904, 0, 15, 1233, 0, 7]],
[[0, -1, 0, 2, 0], [4348, 0, -10, -81, 0, 2]],
[[1, -1, 2, 0, 2], [-2878, 0, 8, 1232, 0, 4]],
[[0, 0, 0, 1, 0], [-4230, 0, 5, -20, 0, -2]],
[[-1, -1, 2, 2, 2], [-2819, 0, 7, 1207, 0, 3]],
[[-1, 0, 2, 0, 0], [-4056, 0, 5, 40, 0, -2]],
[[0, -1, 2, 2, 2], [-2647, 0, 11, 1129, 0, 5]],
[[-2, 0, 0, 0, 1], [-2294, 0, -10, 1266, 0, -4]],
[[1, 1, 2, 0, 2], [2481, 0, -7, -1062, 0, -3]],
[[2, 0, 0, 0, 1], [2179, 0, -2, -1129, 0, -2]],
[[-1, 1, 0, 1, 0], [3276, 0, 1, -9, 0, 0]],
[[1, 1, 0, 0, 0], [-3389, 0, 5, 35, 0, -2]],
[[1, 0, 2, 0, 0], [3339, 0, -13, -107, 0, 1]],
[[-1, 0, 2, -2, 1], [-1987, 0, -6, 1073, 0, -2]],
[[1, 0, 0, 0, 2], [-1981, 0, 0, 854, 0, 0]],
[[-1, 0, 0, 1, 0], [4026, 0, -353, -553, 0, -139]],
[[0, 0, 2, 1, 2], [1660, 0, -5, -710, 0, -2]],
[[-1, 0, 2, 4, 2], [-1521, 0, 9, 647, 0, 4]],
[[-1, 1, 0, 1, 1], [1314, 0, 0, -700, 0, 0]],
[[0, -2, 2, -2, 1], [-1283, 0, 0, 672, 0, 0]],
[[1, 0, 2, 2, 1], [-1331, 0, 8, 663, 0, 4]],
[[-2, 0, 2, 2, 2], [1383, 0, -2, -594, 0, -2]],
[[-1, 0, 0, 0, 2], [1405, 0, 4, -610, 0, 2]],
[[1, 1, 2, -2, 2], [1290, 0, 0, -556, 0, 0]]
];
interface NutationAngles {
dpsi: number;
deps: number;
}
function iau2000b(time: AstroTime): NutationAngles {
var i: number, t: number, el: number, elp: number, f: number, d: number, om: number, arg: number, dp: number,
de: number, sarg: number, carg: number;
var nals: number[], cls: number[];
function mod(x: number): number {
return (x % ASEC360) * ASEC2RAD;
}
t = time.tt / 36525;
el = mod(485868.249036 + t * 1717915923.2178);
elp = mod(1287104.79305 + t * 129596581.0481);
f = mod(335779.526232 + t * 1739527262.8478);
d = mod(1072260.70369 + t * 1602961601.2090);
om = mod(450160.398036 - t * 6962890.5431);
dp = 0;
de = 0;
for (i = 76; i >= 0; --i) {
nals = iaudata[i][0];
cls = iaudata[i][1];
arg = (nals[0] * el + nals[1] * elp + nals[2] * f + nals[3] * d + nals[4] * om) % PI2;
sarg = Math.sin(arg);
carg = Math.cos(arg);
dp += (cls[0] + cls[1] * t) * sarg + cls[2] * carg;
de += (cls[3] + cls[4] * t) * carg + cls[5] * sarg;
}
return {
dpsi: -0.000135 + (dp * 1.0e-7),
deps: +0.000388 + (de * 1.0e-7)
};
}
function mean_obliq(time: AstroTime): number {
var t = time.tt / 36525;
var asec = (
((((-0.0000000434 * t
- 0.000000576) * t
+ 0.00200340) * t
- 0.0001831) * t
- 46.836769) * t + 84381.406
);
return asec / 3600.0;
}
interface EarthTiltInfo {
tt: number;
dpsi: number;
deps: number;
ee: number;
mobl: number;
tobl: number;
}
var cache_e_tilt: EarthTiltInfo;
function e_tilt(time: AstroTime): EarthTiltInfo {
if (!cache_e_tilt || Math.abs(cache_e_tilt.tt - time.tt) > 1.0e-6) {
const nut = iau2000b(time);
const mean_ob = mean_obliq(time);
const true_ob = mean_ob + (nut.deps / 3600);
cache_e_tilt = {
tt: time.tt,
dpsi: nut.dpsi,
deps: nut.deps,
ee: nut.dpsi * Math.cos(mean_ob * DEG2RAD) / 15,
mobl: mean_ob,
tobl: true_ob
};
}
return cache_e_tilt;
}
function ecl2equ_vec(time: AstroTime, pos: ArrayVector): ArrayVector {
var obl = mean_obliq(time) * DEG2RAD;
var cos_obl = Math.cos(obl);
var sin_obl = Math.sin(obl);
return [
pos[0],
pos[1] * cos_obl - pos[2] * sin_obl,
pos[1] * sin_obl + pos[2] * cos_obl
];
}
export let CalcMoonCount = 0;
function CalcMoon(time: AstroTime) {
++CalcMoonCount;
const T = time.tt / 36525;
interface PascalArray1 {
min: number;
array: number[];
}
interface PascalArray2 {
min: number;
array: PascalArray1[];
}
function DeclareArray1(xmin: number, xmax: number): PascalArray1 {
const array = [];
let i: number;
for (i = 0; i <= xmax - xmin; ++i) {
array.push(0);
}
return {min: xmin, array: array};
}
function DeclareArray2(xmin: number, xmax: number, ymin: number, ymax: number): PascalArray2 {
const array = [];
for (let i = 0; i <= xmax - xmin; ++i) {
array.push(DeclareArray1(ymin, ymax));
}
return {min: xmin, array: array};
}
function ArrayGet2(a: PascalArray2, x: number, y: number) {
const m = a.array[x - a.min];
return m.array[y - m.min];
}
function ArraySet2(a: PascalArray2, x: number, y: number, v: number) {
const m = a.array[x - a.min];
m.array[y - m.min] = v;
}
let S: number, MAX: number, ARG: number, FAC: number, I: number, J: number, T2: number, DGAM: number, DLAM: number,
N: number, GAM1C: number, SINPI: number, L0: number, L: number, LS: number, F: number, D: number, DL0: number,
DL: number, DLS: number, DF: number, DD: number, DS: number;
let coArray = DeclareArray2(-6, 6, 1, 4);
let siArray = DeclareArray2(-6, 6, 1, 4);
function CO(x: number, y: number) {
return ArrayGet2(coArray, x, y);
}
function SI(x: number, y: number) {
return ArrayGet2(siArray, x, y);
}
function SetCO(x: number, y: number, v: number) {
return ArraySet2(coArray, x, y, v);
}
function SetSI(x: number, y: number, v: number) {
return ArraySet2(siArray, x, y, v);
}
type ThetaFunc = (real: number, imag: number) => void;
function AddThe(c1: number, s1: number, c2: number, s2: number, func: ThetaFunc): void {
func(c1 * c2 - s1 * s2, s1 * c2 + c1 * s2);
}
function Sine(phi: number): number {
return Math.sin(PI2 * phi);
}
T2 = T * T;
DLAM = 0;
DS = 0;
GAM1C = 0;
SINPI = 3422.7000;
var S1 = Sine(0.19833 + 0.05611 * T);
var S2 = Sine(0.27869 + 0.04508 * T);
var S3 = Sine(0.16827 - 0.36903 * T);
var S4 = Sine(0.34734 - 5.37261 * T);
var S5 = Sine(0.10498 - 5.37899 * T);
var S6 = Sine(0.42681 - 0.41855 * T);
var S7 = Sine(0.14943 - 5.37511 * T);
DL0 = 0.84 * S1 + 0.31 * S2 + 14.27 * S3 + 7.26 * S4 + 0.28 * S5 + 0.24 * S6;
DL = 2.94 * S1 + 0.31 * S2 + 14.27 * S3 + 9.34 * S4 + 1.12 * S5 + 0.83 * S6;
DLS = -6.40 * S1 - 1.89 * S6;
DF = 0.21 * S1 + 0.31 * S2 + 14.27 * S3 - 88.70 * S4 - 15.30 * S5 + 0.24 * S6 - 1.86 * S7;
DD = DL0 - DLS;
DGAM = (-3332E-9 * Sine(0.59734 - 5.37261 * T)
- 539E-9 * Sine(0.35498 - 5.37899 * T)
- 64E-9 * Sine(0.39943 - 5.37511 * T));
L0 = PI2 * Frac(0.60643382 + 1336.85522467 * T - 0.00000313 * T2) + DL0 / ARC;
L = PI2 * Frac(0.37489701 + 1325.55240982 * T + 0.00002565 * T2) + DL / ARC;
LS = PI2 * Frac(0.99312619 + 99.99735956 * T - 0.00000044 * T2) + DLS / ARC;
F = PI2 * Frac(0.25909118 + 1342.22782980 * T - 0.00000892 * T2) + DF / ARC;
D = PI2 * Frac(0.82736186 + 1236.85308708 * T - 0.00000397 * T2) + DD / ARC;
for (I = 1; I <= 4; ++I) {
switch (I) {
case 1:
ARG = L;
MAX = 4;
FAC = 1.000002208;
break;
case 2:
ARG = LS;
MAX = 3;
FAC = 0.997504612 - 0.002495388 * T;
break;
case 3:
ARG = F;
MAX = 4;
FAC = 1.000002708 + 139.978 * DGAM;
break;
case 4:
ARG = D;
MAX = 6;
FAC = 1.0;
break;
default:
throw `Internal error: I = ${I}`; // persuade TypeScript that ARG, ... are all initialized before use.
}
SetCO(0, I, 1);
SetCO(1, I, Math.cos(ARG) * FAC);
SetSI(0, I, 0);
SetSI(1, I, Math.sin(ARG) * FAC);
for (J = 2; J <= MAX; ++J) {
AddThe(CO(J - 1, I), SI(J - 1, I), CO(1, I), SI(1, I), (c: number, s: number) => (SetCO(J, I, c), SetSI(J, I, s)));
}
for (J = 1; J <= MAX; ++J) {
SetCO(-J, I, CO(J, I));
SetSI(-J, I, -SI(J, I));
}
}
interface ComplexValue {
x: number;
y: number;
}
function Term(p: number, q: number, r: number, s: number): ComplexValue {
var result = {x: 1, y: 0};
var I = [0, p, q, r, s]; // I[0] is not used; it is a placeholder
for (var k = 1; k <= 4; ++k)
if (I[k] !== 0)
AddThe(result.x, result.y, CO(I[k], k), SI(I[k], k), (c: number, s: number) => (result.x = c, result.y = s));
return result;
}
function AddSol(coeffl: number, coeffs: number, coeffg: number, coeffp: number, p: number, q: number, r: number, s: number): void {
var result = Term(p, q, r, s);
DLAM += coeffl * result.y;
DS += coeffs * result.y;
GAM1C += coeffg * result.x;
SINPI += coeffp * result.x;
}
AddSol(13.9020, 14.0600, -0.0010, 0.2607, 0, 0, 0, 4);
AddSol(0.4030, -4.0100, 0.3940, 0.0023, 0, 0, 0, 3);
AddSol(2369.9120, 2373.3600, 0.6010, 28.2333, 0, 0, 0, 2);
AddSol(-125.1540, -112.7900, -0.7250, -0.9781, 0, 0, 0, 1);
AddSol(1.9790, 6.9800, -0.4450, 0.0433, 1, 0, 0, 4);
AddSol(191.9530, 192.7200, 0.0290, 3.0861, 1, 0, 0, 2);
AddSol(-8.4660, -13.5100, 0.4550, -0.1093, 1, 0, 0, 1);
AddSol(22639.5000, 22609.0700, 0.0790, 186.5398, 1, 0, 0, 0);
AddSol(18.6090, 3.5900, -0.0940, 0.0118, 1, 0, 0, -1);
AddSol(-4586.4650, -4578.1300, -0.0770, 34.3117, 1, 0, 0, -2);
AddSol(3.2150, 5.4400, 0.1920, -0.0386, 1, 0, 0, -3);
AddSol(-38.4280, -38.6400, 0.0010, 0.6008, 1, 0, 0, -4);
AddSol(-0.3930, -1.4300, -0.0920, 0.0086, 1, 0, 0, -6);
AddSol(-0.2890, -1.5900, 0.1230, -0.0053, 0, 1, 0, 4);
AddSol(-24.4200, -25.1000, 0.0400, -0.3000, 0, 1, 0, 2);
AddSol(18.0230, 17.9300, 0.0070, 0.1494, 0, 1, 0, 1);
AddSol(-668.1460, -126.9800, -1.3020, -0.3997, 0, 1, 0, 0);
AddSol(0.5600, 0.3200, -0.0010, -0.0037, 0, 1, 0, -1);
AddSol(-165.1450, -165.0600, 0.0540, 1.9178, 0, 1, 0, -2);
AddSol(-1.8770, -6.4600, -0.4160, 0.0339, 0, 1, 0, -4);
AddSol(0.2130, 1.0200, -0.0740, 0.0054, 2, 0, 0, 4);
AddSol(14.3870, 14.7800, -0.0170, 0.2833, 2, 0, 0, 2);
AddSol(-0.5860, -1.2000, 0.0540, -0.0100, 2, 0, 0, 1);
AddSol(769.0160, 767.9600, 0.1070, 10.1657, 2, 0, 0, 0);
AddSol(1.7500, 2.0100, -0.0180, 0.0155, 2, 0, 0, -1);
AddSol(-211.6560, -152.5300, 5.6790, -0.3039, 2, 0, 0, -2);
AddSol(1.2250, 0.9100, -0.0300, -0.0088, 2, 0, 0, -3);
AddSol(-30.7730, -34.0700, -0.3080, 0.3722, 2, 0, 0, -4);
AddSol(-0.5700, -1.4000, -0.0740, 0.0109, 2, 0, 0, -6);
AddSol(-2.9210, -11.7500, 0.7870, -0.0484, 1, 1, 0, 2);
AddSol(1.2670, 1.5200, -0.0220, 0.0164, 1, 1, 0, 1);
AddSol(-109.6730, -115.1800, 0.4610, -0.9490, 1, 1, 0, 0);
AddSol(-205.9620, -182.3600, 2.0560, 1.4437, 1, 1, 0, -2);
AddSol(0.2330, 0.3600, 0.0120, -0.0025, 1, 1, 0, -3);
AddSol(-4.3910, -9.6600, -0.4710, 0.0673, 1, 1, 0, -4);
AddSol(0.2830, 1.5300, -0.1110, 0.0060, 1, -1, 0, 4);
AddSol(14.5770, 31.7000, -1.5400, 0.2302, 1, -1, 0, 2);
AddSol(147.6870, 138.7600, 0.6790, 1.1528, 1, -1, 0, 0);
AddSol(-1.0890, 0.5500, 0.0210, 0.0000, 1, -1, 0, -1);
AddSol(28.4750, 23.5900, -0.4430, -0.2257, 1, -1, 0, -2);
AddSol(-0.2760, -0.3800, -0.0060, -0.0036, 1, -1, 0, -3);
AddSol(0.6360, 2.2700, 0.1460, -0.0102, 1, -1, 0, -4);
AddSol(-0.1890, -1.6800, 0.1310, -0.0028, 0, 2, 0, 2);
AddSol(-7.4860, -0.6600, -0.0370, -0.0086, 0, 2, 0, 0);
AddSol(-8.0960, -16.3500, -0.7400, 0.0918, 0, 2, 0, -2);
AddSol(-5.7410, -0.0400, 0.0000, -0.0009, 0, 0, 2, 2);
AddSol(0.2550, 0.0000, 0.0000, 0.0000, 0, 0, 2, 1);
AddSol(-411.6080, -0.2000, 0.0000, -0.0124, 0, 0, 2, 0);
AddSol(0.5840, 0.8400, 0.0000, 0.0071, 0, 0, 2, -1);
AddSol(-55.1730, -52.1400, 0.0000, -0.1052, 0, 0, 2, -2);
AddSol(0.2540, 0.2500, 0.0000, -0.0017, 0, 0, 2, -3);
AddSol(0.0250, -1.6700, 0.0000, 0.0031, 0, 0, 2, -4);
AddSol(1.0600, 2.9600, -0.1660, 0.0243, 3, 0, 0, 2);
AddSol(36.1240, 50.6400, -1.3000, 0.6215, 3, 0, 0, 0);
AddSol(-13.1930, -16.4000, 0.2580, -0.1187, 3, 0, 0, -2);
AddSol(-1.1870, -0.7400, 0.0420, 0.0074, 3, 0, 0, -4);
AddSol(-0.2930, -0.3100, -0.0020, 0.0046, 3, 0, 0, -6);
AddSol(-0.2900, -1.4500, 0.1160, -0.0051, 2, 1, 0, 2);
AddSol(-7.6490, -10.5600, 0.2590, -0.1038, 2, 1, 0, 0);
AddSol(-8.6270, -7.5900, 0.0780, -0.0192, 2, 1, 0, -2);
AddSol(-2.7400, -2.5400, 0.0220, 0.0324, 2, 1, 0, -4);
AddSol(1.1810, 3.3200, -0.2120, 0.0213, 2, -1, 0, 2);
AddSol(9.7030, 11.6700, -0.1510, 0.1268, 2, -1, 0, 0);
AddSol(-0.3520, -0.3700, 0.0010, -0.0028, 2, -1, 0, -1);
AddSol(-2.4940, -1.1700, -0.0030, -0.0017, 2, -1, 0, -2);
AddSol(0.3600, 0.2000, -0.0120, -0.0043, 2, -1, 0, -4);
AddSol(-1.1670, -1.2500, 0.0080, -0.0106, 1, 2, 0, 0);
AddSol(-7.4120, -6.1200, 0.1170, 0.0484, 1, 2, 0, -2);
AddSol(-0.3110, -0.6500, -0.0320, 0.0044, 1, 2, 0, -4);
AddSol(0.7570, 1.8200, -0.1050, 0.0112, 1, -2, 0, 2);
AddSol(2.5800, 2.3200, 0.0270, 0.0196, 1, -2, 0, 0);
AddSol(2.5330, 2.4000, -0.0140, -0.0212, 1, -2, 0, -2);
AddSol(-0.3440, -0.5700, -0.0250, 0.0036, 0, 3, 0, -2);
AddSol(-0.9920, -0.0200, 0.0000, 0.0000, 1, 0, 2, 2);
AddSol(-45.0990, -0.0200, 0.0000, -0.0010, 1, 0, 2, 0);
AddSol(-0.1790, -9.5200, 0.0000, -0.0833, 1, 0, 2, -2);
AddSol(-0.3010, -0.3300, 0.0000, 0.0014, 1, 0, 2, -4);
AddSol(-6.3820, -3.3700, 0.0000, -0.0481, 1, 0, -2, 2);
AddSol(39.5280, 85.1300, 0.0000, -0.7136, 1, 0, -2, 0);
AddSol(9.3660, 0.7100, 0.0000, -0.0112, 1, 0, -2, -2);
AddSol(0.2020, 0.0200, 0.0000, 0.0000, 1, 0, -2, -4);
AddSol(0.4150, 0.1000, 0.0000, 0.0013, 0, 1, 2, 0);
AddSol(-2.1520, -2.2600, 0.0000, -0.0066, 0, 1, 2, -2);
AddSol(-1.4400, -1.3000, 0.0000, 0.0014, 0, 1, -2, 2);
AddSol(0.3840, -0.0400, 0.0000, 0.0000, 0, 1, -2, -2);
AddSol(1.9380, 3.6000, -0.1450, 0.0401, 4, 0, 0, 0);
AddSol(-0.9520, -1.5800, 0.0520, -0.0130, 4, 0, 0, -2);
AddSol(-0.5510, -0.9400, 0.0320, -0.0097, 3, 1, 0, 0);
AddSol(-0.4820, -0.5700, 0.0050, -0.0045, 3, 1, 0, -2);
AddSol(0.6810, 0.9600, -0.0260, 0.0115, 3, -1, 0, 0);
AddSol(-0.2970, -0.2700, 0.0020, -0.0009, 2, 2, 0, -2);
AddSol(0.2540, 0.2100, -0.0030, 0.0000, 2, -2, 0, -2);
AddSol(-0.2500, -0.2200, 0.0040, 0.0014, 1, 3, 0, -2);
AddSol(-3.9960, 0.0000, 0.0000, 0.0004, 2, 0, 2, 0);
AddSol(0.5570, -0.7500, 0.0000, -0.0090, 2, 0, 2, -2);
AddSol(-0.4590, -0.3800, 0.0000, -0.0053, 2, 0, -2, 2);
AddSol(-1.2980, 0.7400, 0.0000, 0.0004, 2, 0, -2, 0);
AddSol(0.5380, 1.1400, 0.0000, -0.0141, 2, 0, -2, -2);
AddSol(0.2630, 0.0200, 0.0000, 0.0000, 1, 1, 2, 0);
AddSol(0.4260, 0.0700, 0.0000, -0.0006, 1, 1, -2, -2);
AddSol(-0.3040, 0.0300, 0.0000, 0.0003, 1, -1, 2, 0);
AddSol(-0.3720, -0.1900, 0.0000, -0.0027, 1, -1, -2, 2);
AddSol(0.4180, 0.0000, 0.0000, 0.0000, 0, 0, 4, 0);
AddSol(-0.3300, -0.0400, 0.0000, 0.0000, 3, 0, 2, 0);
function ADDN(coeffn: number, p: number, q: number, r: number, s: number) {
return coeffn * Term(p, q, r, s).y;
}
N = 0;
N += ADDN(-526.069, 0, 0, 1, -2);
N += ADDN(-3.352, 0, 0, 1, -4);
N += ADDN(+44.297, +1, 0, 1, -2);
N += ADDN(-6.000, +1, 0, 1, -4);
N += ADDN(+20.599, -1, 0, 1, 0);
N += ADDN(-30.598, -1, 0, 1, -2);
N += ADDN(-24.649, -2, 0, 1, 0);
N += ADDN(-2.000, -2, 0, 1, -2);
N += ADDN(-22.571, 0, +1, 1, -2);
N += ADDN(+10.985, 0, -1, 1, -2);
DLAM += (
+0.82 * Sine(0.7736 - 62.5512 * T) + 0.31 * Sine(0.0466 - 125.1025 * T)
+ 0.35 * Sine(0.5785 - 25.1042 * T) + 0.66 * Sine(0.4591 + 1335.8075 * T)
+ 0.64 * Sine(0.3130 - 91.5680 * T) + 1.14 * Sine(0.1480 + 1331.2898 * T)
+ 0.21 * Sine(0.5918 + 1056.5859 * T) + 0.44 * Sine(0.5784 + 1322.8595 * T)
+ 0.24 * Sine(0.2275 - 5.7374 * T) + 0.28 * Sine(0.2965 + 2.6929 * T)
+ 0.33 * Sine(0.3132 + 6.3368 * T)
);
S = F + DS / ARC;
let lat_seconds = (1.000002708 + 139.978 * DGAM) * (18518.511 + 1.189 + GAM1C) * Math.sin(S) - 6.24 * Math.sin(3 * S) + N;
return {
geo_eclip_lon: PI2 * Frac((L0 + DLAM / ARC) / PI2),
geo_eclip_lat: (Math.PI / (180 * 3600)) * lat_seconds,
distance_au: (ARC * EARTH_EQUATORIAL_RADIUS_AU) / (0.999953253 * SINPI)
};
}
function precession(pos: ArrayVector, time: AstroTime, dir: PrecessDirection): ArrayVector {
const r = precession_rot(time, dir);
return [
r.rot[0][0] * pos[0] + r.rot[1][0] * pos[1] + r.rot[2][0] * pos[2],
r.rot[0][1] * pos[0] + r.rot[1][1] * pos[1] + r.rot[2][1] * pos[2],
r.rot[0][2] * pos[0] + r.rot[1][2] * pos[1] + r.rot[2][2] * pos[2]
];
}
function precession_rot(time: AstroTime, dir: PrecessDirection): RotationMatrix {
const t = time.tt / 36525;
let eps0 = 84381.406;
let psia = (((((-0.0000000951 * t
+ 0.000132851) * t
- 0.00114045) * t
- 1.0790069) * t
+ 5038.481507) * t);
let omegaa = (((((+0.0000003337 * t
- 0.000000467) * t
- 0.00772503) * t
+ 0.0512623) * t
- 0.025754) * t + eps0);
let chia = (((((-0.0000000560 * t
+ 0.000170663) * t
- 0.00121197) * t
- 2.3814292) * t
+ 10.556403) * t);
eps0 *= ASEC2RAD;
psia *= ASEC2RAD;
omegaa *= ASEC2RAD;
chia *= ASEC2RAD;
const sa = Math.sin(eps0);
const ca = Math.cos(eps0);
const sb = Math.sin(-psia);
const cb = Math.cos(-psia);
const sc = Math.sin(-omegaa);
const cc = Math.cos(-omegaa);
const sd = Math.sin(chia);
const cd = Math.cos(chia);
const xx = cd * cb - sb * sd * cc;
const yx = cd * sb * ca + sd * cc * cb * ca - sa * sd * sc;
const zx = cd * sb * sa + sd * cc * cb * sa + ca * sd * sc;
const xy = -sd * cb - sb * cd * cc;
const yy = -sd * sb * ca + cd * cc * cb * ca - sa * cd * sc;
const zy = -sd * sb * sa + cd * cc * cb * sa + ca * cd * sc;
const xz = sb * sc;
const yz = -sc * cb * ca - sa * cc;
const zz = -sc * cb * sa + cc * ca;
if (dir === PrecessDirection.Into2000) {
// Perform rotation from epoch to J2000.0.
return new RotationMatrix([
[xx, yx, zx],
[xy, yy, zy],
[xz, yz, zz]
]);
}
if (dir === PrecessDirection.From2000) {
// Perform rotation from J2000.0 to epoch.
return new RotationMatrix([
[xx, xy, xz],
[yx, yy, yz],
[zx, zy, zz]
]);
}
throw 'Invalid precess direction';
}
function era(time: AstroTime): number { // Earth Rotation Angle
const thet1 = 0.7790572732640 + 0.00273781191135448 * time.ut;
const thet3 = time.ut % 1;
let theta = 360 * ((thet1 + thet3) % 1);
if (theta < 0) {
theta += 360;
}
return theta;
}
function sidereal_time(time: AstroTime): number { // calculates Greenwich Apparent Sidereal Time (GAST)
const t = time.tt / 36525;
let eqeq = 15 * e_tilt(time).ee; // Replace with eqeq=0 to get GMST instead of GAST (if we ever need it)
const theta = era(time);
const st = (eqeq + 0.014506 +
((((-0.0000000368 * t
- 0.000029956) * t
- 0.00000044) * t
+ 1.3915817) * t
+ 4612.156534) * t);
let gst = ((st / 3600 + theta) % 360) / 15;
if (gst < 0) {
gst += 24;
}
return gst; // return sidereal hours in the half-open range [0, 24).
}
function inverse_terra(ovec: ArrayVector, st: number): Observer {
// Convert from AU to kilometers
const x = ovec[0] * KM_PER_AU;
const y = ovec[1] * KM_PER_AU;
const z = ovec[2] * KM_PER_AU;
const p = Math.sqrt(x * x + y * y);
let lon_deg: number, lat_deg: number, height_km: number;
if (p < 1.0e-6) {
// Special case: within 1 millimeter of a pole!
// Use arbitrary longitude, and latitude determined by polarity of z.
lon_deg = 0;
lat_deg = (z > 0.0) ? +90 : -90;
// Elevation is calculated directly from z.
height_km = Math.abs(z) - EARTH_POLAR_RADIUS_KM;
} else {
const stlocl = Math.atan2(y, x);
// Calculate exact longitude.
lon_deg = (RAD2DEG * stlocl) - (15.0 * st);
// Normalize longitude to the range (-180, +180].
while (lon_deg <= -180)
lon_deg += 360;
while (lon_deg > +180)
lon_deg -= 360;
// Numerically solve for exact latitude, using Newton's Method.
const F = EARTH_FLATTENING * EARTH_FLATTENING;
// Start with initial latitude estimate, based on a spherical Earth.
let lat = Math.atan2(z, p);
let cos: number, sin: number, denom: number;
for (; ;) {
// Calculate the error function W(lat).
// We try to find the root of W, meaning where the error is 0.
cos = Math.cos(lat);
sin = Math.sin(lat);
const factor = (F - 1) * EARTH_EQUATORIAL_RADIUS_KM;
const cos2 = cos * cos;
const sin2 = sin * sin;
const radicand = cos2 + F * sin2;
denom = Math.sqrt(radicand);
const W = (factor * sin * cos) / denom - z * cos + p * sin;
if (Math.abs(W) < 1.0e-12)
break; // The error is now negligible
// Error is still too large. Find the next estimate.
// Calculate D = the derivative of W with respect to lat.
const D = factor * ((cos2 - sin2) / denom - sin2 * cos2 * (F - 1) / (factor * radicand)) + z * sin + p * cos;
lat -= W / D;
}
// We now have a solution for the latitude in radians.
lat_deg = RAD2DEG * lat;
// Solve for exact height in meters.
// There are two formulas I can use. Use whichever has the less risky denominator.
const adjust = EARTH_EQUATORIAL_RADIUS_KM / denom;
if (Math.abs(sin) > Math.abs(cos))
height_km = z / sin - F * adjust;
else
height_km = p / cos - adjust;
}
return new Observer(lat_deg, lon_deg, 1000 * height_km);
}
function terra(observer: Observer, st: number): TerraInfo {
const df = 1 - 0.003352819697896; // flattening of the Earth
const df2 = df * df;
const phi = observer.latitude * DEG2RAD;
const sinphi = Math.sin(phi);
const cosphi = Math.cos(phi);
const c = 1 / Math.sqrt(cosphi * cosphi + df2 * sinphi * sinphi);
const s = df2 * c;
const ht_km = observer.height / 1000;
const ach = EARTH_EQUATORIAL_RADIUS_KM * c + ht_km;
const ash = EARTH_EQUATORIAL_RADIUS_KM * s + ht_km;
const stlocl = (15 * st + observer.longitude) * DEG2RAD;
const sinst = Math.sin(stlocl);
const cosst = Math.cos(stlocl);
return {
pos: [ach * cosphi * cosst / KM_PER_AU, ach * cosphi * sinst / KM_PER_AU, ash * sinphi / KM_PER_AU],
vel: [-ANGVEL * ach * cosphi * sinst * 86400, ANGVEL * ach * cosphi * cosst * 86400, 0]
};
}
function nutation(pos: ArrayVector, time: AstroTime, dir: PrecessDirection): ArrayVector {
const r = nutation_rot(time, dir);
return [
r.rot[0][0] * pos[0] + r.rot[1][0] * pos[1] + r.rot[2][0] * pos[2],
r.rot[0][1] * pos[0] + r.rot[1][1] * pos[1] + r.rot[2][1] * pos[2],
r.rot[0][2] * pos[0] + r.rot[1][2] * pos[1] + r.rot[2][2] * pos[2]
];
}
function nutation_rot(time: AstroTime, dir: PrecessDirection): RotationMatrix {
const tilt = e_tilt(time);
const oblm = tilt.mobl * DEG2RAD;
const oblt = tilt.tobl * DEG2RAD;
const psi = tilt.dpsi * ASEC2RAD;
const cobm = Math.cos(oblm);
const sobm = Math.sin(oblm);
const cobt = Math.cos(oblt);
const sobt = Math.sin(oblt);
const cpsi = Math.cos(psi);
const spsi = Math.sin(psi);
const xx = cpsi;
const yx = -spsi * cobm;
const zx = -spsi * sobm;
const xy = spsi * cobt;
const yy = cpsi * cobm * cobt + sobm * sobt;
const zy = cpsi * sobm * cobt - cobm * sobt;
const xz = spsi * sobt;
const yz = cpsi * cobm * sobt - sobm * cobt;
const zz = cpsi * sobm * sobt + cobm * cobt;
if (dir === PrecessDirection.From2000) {
// convert J2000 to of-date
return new RotationMatrix([
[xx, xy, xz],
[yx, yy, yz],
[zx, zy, zz]
]);
}
if (dir === PrecessDirection.Into2000) {
// convert of-date to J2000
return new RotationMatrix([
[xx, yx, zx],
[xy, yy, zy],
[xz, yz, zz]
]);
}
throw 'Invalid precess direction';
}
function gyration(pos: ArrayVector, time: AstroTime, dir: PrecessDirection) {
// Combine nutation and precession into a single operation I call "gyration".
// The order they are composed depends on the direction,
// because both directions are mutual inverse functions.
return (dir === PrecessDirection.Into2000) ?
precession(nutation(pos, time, dir), time, dir) :
nutation(precession(pos, time, dir), time, dir);
}
function geo_pos(time: AstroTime, observer: Observer): ArrayVector {
const gast = sidereal_time(time);
const pos = terra(observer, gast).pos;
return gyration(pos, time, PrecessDirection.Into2000);
}
/**
* @brief A 3D Cartesian vector with a time attached to it.
*
* Holds the Cartesian coordinates of a vector in 3D space,
* along with the time at which the vector is valid.
*
* @property {number} x The x-coordinate expressed in astronomical units (AU).
* @property {number} y The y-coordinate expressed in astronomical units (AU).
* @property {number} z The z-coordinate expressed in astronomical units (AU).
* @property {AstroTime} t The time at which the vector is valid.
*/
export class Vector {
constructor(
public x: number,
public y: number,
public z: number,
public t: AstroTime) {
}
/**
* Returns the length of the vector in astronomical units (AU).
* @returns {number}
*/
Length(): number {
return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
}
}
/**
* @brief A combination of a position vector, a velocity vector, and a time.
*
* Holds the state vector of a body at a given time, including its position,
* velocity, and the time they are valid.
*
* @property {number} x The position x-coordinate expressed in astronomical units (AU).
* @property {number} y The position y-coordinate expressed in astronomical units (AU).
* @property {number} z The position z-coordinate expressed in astronomical units (AU).
* @property {number} vx The velocity x-coordinate expressed in AU/day.
* @property {number} vy The velocity y-coordinate expressed in AU/day.
* @property {number} vz The velocity z-coordinate expressed in AU/day.
* @property {AstroTime} t The time at which the vector is valid.
*/
export class StateVector {
constructor(
public x: number,
public y: number,
public z: number,
public vx: number,
public vy: number,
public vz: number,
public t: AstroTime) {
}
}
/**
* @brief Holds spherical coordinates: latitude, longitude, distance.
*
* Spherical coordinates represent the location of
* a point using two angles and a distance.
*
* @property {number} lat The latitude angle: -90..+90 degrees.
* @property {number} lon The longitude angle: 0..360 degrees.
* @property {number} dist Distance in AU.
*/
export class Spherical {
lat: number;
lon: number;
dist: number;
constructor(lat: number, lon: number, dist: number) {
this.lat = VerifyNumber(lat);
this.lon = VerifyNumber(lon);
this.dist = VerifyNumber(dist);
}
}
/**
* @brief Holds right ascension, declination, and distance of a celestial object.
*
* @property {number} ra
* Right ascension in sidereal hours: [0, 24).
*
* @property {number} dec
* Declination in degrees: [-90, +90].
*
* @property {number} dist
* Distance to the celestial object expressed in
* <a href="https://en.wikipedia.org/wiki/Astronomical_unit">astronomical units</a> (AU).
*
* @property {Vector} vec
* The equatorial coordinates in cartesian form, using AU distance units.
* x = direction of the March equinox,
* y = direction of the June solstice,
* z = north.
*/
export class EquatorialCoordinates {
ra: number;
dec: number;
dist: number;
vec: Vector;
constructor(ra: number, dec: number, dist: number, vec: Vector) {
this.ra = VerifyNumber(ra);
this.dec = VerifyNumber(dec);
this.dist = VerifyNumber(dist);
this.vec = vec;
}
}
function IsValidRotationArray(rot: number[][]) {
if (!(rot instanceof Array) || (rot.length !== 3))
return false;
for (let i = 0; i < 3; ++i) {
if (!(rot[i] instanceof Array) || (rot[i].length !== 3))
return false;
for (let j = 0; j < 3; ++j)
if (!Number.isFinite(rot[i][j]))
return false;
}
return true;
}
type ArrayVector = [number, number, number];
interface TerraInfo {
pos: ArrayVector;
vel: ArrayVector;
}
/**
* @brief Contains a rotation matrix that can be used to transform one coordinate system to another.
*
* @property {number[][]} rot
* A normalized 3x3 rotation matrix. For example, the identity matrix is represented
* as `[[1, 0, 0], [0, 1, 0], [0, 0, 1]]`.
*/
export class RotationMatrix {
constructor(public rot: number[][]) {
}
}
/**
* @brief Creates a rotation matrix that can be used to transform one coordinate system to another.
*
* This function verifies that the `rot` parameter is of the correct format:
* a number[3][3] array. It throws an exception if `rot` is not of that shape.
* Otherwise it creates a new {@link RotationMatrix} object based on `rot`.
*
* @param {number[][]} rot
* An array [3][3] of numbers. Defines a rotation matrix used to premultiply
* a 3D vector to reorient it into another coordinate system.
*
* @returns {RotationMatrix}
*/
export function MakeRotation(rot: number[][]) {
if (!IsValidRotationArray(rot))
throw 'Argument must be a [3][3] array of numbers';
return new RotationMatrix(rot);
}
/**
* @brief Represents the location of an object seen by an observer on the Earth.
*
* Holds azimuth (compass direction) and altitude (angle above/below the horizon)
* of a celestial object as seen by an observer at a particular location on the Earth's surface.
* Also holds right ascension and declination of the same object.
* All of these coordinates are optionally adjusted for atmospheric refraction;
* therefore the right ascension and declination values may not exactly match
* those found inside a corresponding {@link EquatorialCoordinates} object.
*
* @property {number} azimuth
* A horizontal compass direction angle in degrees measured starting at north
* and increasing positively toward the east.
* The value is in the range [0, 360).
* North = 0, east = 90, south = 180, west = 270.
*
* @property {number} altitude
* A vertical angle in degrees above (positive) or below (negative) the horizon.
* The value is in the range [-90, +90].
* The altitude angle is optionally adjusted upward due to atmospheric refraction.
*
* @property {number} ra
* The right ascension of the celestial body in sidereal hours.
* The value is in the reange [0, 24).
* If `altitude` was adjusted for atmospheric reaction, `ra`
* is likewise adjusted.
*
* @property {number} dec
* The declination of of the celestial body in degrees.
* The value in the range [-90, +90].
* If `altitude` was adjusted for atmospheric reaction, `dec`
* is likewise adjusted.
*/
export class HorizontalCoordinates {
azimuth: number;
altitude: number;
ra: number;
dec: number;
constructor(azimuth: number, altitude: number, ra: number, dec: number) {
this.azimuth = VerifyNumber(azimuth);
this.altitude = VerifyNumber(altitude);
this.ra = VerifyNumber(ra);
this.dec = VerifyNumber(dec);
}
}
/**
* @brief Ecliptic coordinates of a celestial body.
*
* The origin and date of the coordinate system may vary depending on the caller's usage.
* In general, ecliptic coordinates are measured with respect to the mean plane of the Earth's
* orbit around the Sun.
* Includes Cartesian coordinates `(ex, ey, ez)` measured in
* <a href="https://en.wikipedia.org/wiki/Astronomical_unit">astronomical units</a> (AU)
* and spherical coordinates `(elon, elat)` measured in degrees.
*
* @property {Vector} vec
* Ecliptic cartesian vector with components measured in astronomical units (AU).
* The x-axis is within the ecliptic plane and is oriented in the direction of the
* <a href="https://en.wikipedia.org/wiki/Equinox_(celestial_coordinates)">equinox</a>.
* The y-axis is within the ecliptic plane and is oriented 90 degrees
* counterclockwise from the equinox, as seen from above the Sun's north pole.
* The z-axis is oriented perpendicular to the ecliptic plane,
* along the direction of the Sun's north pole.
*
* @property {number} elat
* The ecliptic latitude of the body in degrees.
* This is the angle north or south of the ecliptic plane.
* The value is in the range [-90, +90].
* Positive values are north and negative values are south.
*
* @property {number} elon
* The ecliptic longitude of the body in degrees.
* This is the angle measured counterclockwise around the ecliptic plane,
* as seen from above the Sun's north pole.
* This is the same direction that the Earth orbits around the Sun.
* The angle is measured starting at 0 from the equinox and increases
* up to 360 degrees.
*/
export class EclipticCoordinates {
vec: Vector;
elat: number;
elon: number;
constructor(vec: Vector, elat: number, elon: number) {
this.vec = vec;
this.elat = VerifyNumber(elat);
this.elon = VerifyNumber(elon);
}
}
function VectorFromArray(av: ArrayVector, time: AstroTime): Vector {
return new Vector(av[0], av[1], av[2], time);
}
function vector2radec(pos: ArrayVector, time: AstroTime): EquatorialCoordinates {
const vec = VectorFromArray(pos, time);
const xyproj = vec.x * vec.x + vec.y * vec.y;
const dist = Math.sqrt(xyproj + vec.z * vec.z);
if (xyproj === 0) {
if (vec.z === 0)
throw 'Indeterminate sky coordinates';
return new EquatorialCoordinates(0, (vec.z < 0) ? -90 : +90, dist, vec);
}
let ra = RAD2HOUR * Math.atan2(vec.y, vec.x);
if (ra < 0)
ra += 24;
const dec = RAD2DEG * Math.atan2(pos[2], Math.sqrt(xyproj));
return new EquatorialCoordinates(ra, dec, dist, vec);
}
function spin(angle: number, pos: ArrayVector): ArrayVector {
const angr = angle * DEG2RAD;
const c = Math.cos(angr);
const s = Math.sin(angr);
return [c * pos[0] + s * pos[1], c * pos[1] - s * pos[0], pos[2]];
}
/**
* @brief Converts equatorial coordinates to horizontal coordinates.
*
* Given a date and time, a geographic location of an observer on the Earth, and
* equatorial coordinates (right ascension and declination) of a celestial body,
* returns horizontal coordinates (azimuth and altitude angles) for that body
* as seen by that observer. Allows optional correction for atmospheric refraction.
*
* @param {FlexibleDateTime} date
* The date and time for which to find horizontal coordinates.
*
* @param {Observer} observer
* The location of the observer for which to find horizontal coordinates.
*
* @param {number} ra
* Right ascension in sidereal hours of the celestial object,
* referred to the mean equinox of date for the J2000 epoch.
*
* @param {number} dec
* Declination in degrees of the celestial object,
* referred to the mean equator of date for the J2000 epoch.
* Positive values are north of the celestial equator and negative values are south.
*
* @param {string} refraction
* If omitted or has a false-like value (false, null, undefined, etc.)
* the calculations are performed without any correction for atmospheric
* refraction. If the value is the string `"normal"`,
* uses the recommended refraction correction based on Meeus "Astronomical Algorithms"
* with a linear taper more than 1 degree below the horizon. The linear
* taper causes the refraction to linearly approach 0 as the altitude of the
* body approaches the nadir (-90 degrees).
* If the value is the string `"jplhor"`, uses a JPL Horizons
* compatible formula. This is the same algorithm as `"normal"`,
* only without linear tapering; this can result in physically impossible
* altitudes of less than -90 degrees, which may cause problems for some applications.
* (The `"jplhor"` option was created for unit testing against data
* generated by JPL Horizons, and is otherwise not recommended for use.)
*
* @returns {HorizontalCoordinates}
*/
export function Horizon(date: FlexibleDateTime, observer: Observer, ra: number, dec: number, refraction?: string): HorizontalCoordinates {
// based on NOVAS equ2hor()
let time = MakeTime(date);
VerifyObserver(observer);
VerifyNumber(ra);
VerifyNumber(dec);
const sinlat = Math.sin(observer.latitude * DEG2RAD);
const coslat = Math.cos(observer.latitude * DEG2RAD);
const sinlon = Math.sin(observer.longitude * DEG2RAD);
const coslon = Math.cos(observer.longitude * DEG2RAD);
const sindc = Math.sin(dec * DEG2RAD);
const cosdc = Math.cos(dec * DEG2RAD);
const sinra = Math.sin(ra * HOUR2RAD);
const cosra = Math.cos(ra * HOUR2RAD);
// Calculate three mutually perpendicular unit vectors
// in equatorial coordinates: uze, une, uwe.
//
// uze = The direction of the observer's local zenith (straight up).
// une = The direction toward due north on the observer's horizon.
// uwe = The direction toward due west on the observer's horizon.
//
// HOWEVER, these are uncorrected for the Earth's rotation due to the time of day.
//
// The components of these 3 vectors are as follows:
// x = direction from center of Earth toward 0 degrees longitude (the prime meridian) on equator.
// y = direction from center of Earth toward 90 degrees west longitude on equator.
// z = direction from center of Earth toward the north pole.
let uze: ArrayVector = [coslat * coslon, coslat * sinlon, sinlat];
let une: ArrayVector = [-sinlat * coslon, -sinlat * sinlon, coslat];
let uwe: ArrayVector = [sinlon, -coslon, 0];
// Correct the vectors uze, une, uwe for the Earth's rotation by calculating
// sideral time. Call spin() for each uncorrected vector to rotate about
// the Earth's axis to yield corrected unit vectors uz, un, uw.
// Multiply sidereal hours by -15 to convert to degrees and flip eastward
// rotation of the Earth to westward apparent movement of objects with time.
const spin_angle = -15 * sidereal_time(time);
let uz = spin(spin_angle, uze);
let un = spin(spin_angle, une);
let uw = spin(spin_angle, uwe);
// Convert angular equatorial coordinates (RA, DEC) to
// cartesian equatorial coordinates in 'p', using the
// same orientation system as uze, une, uwe.
let p = [cosdc * cosra, cosdc * sinra, sindc];
// Use dot products of p with the zenith, north, and west
// vectors to obtain the cartesian coordinates of the body in
// the observer's horizontal orientation system.
// pz = zenith component [-1, +1]
// pn = north component [-1, +1]
// pw = west component [-1, +1]
const pz = p[0] * uz[0] + p[1] * uz[1] + p[2] * uz[2];
const pn = p[0] * un[0] + p[1] * un[1] + p[2] * un[2];
const pw = p[0] * uw[0] + p[1] * uw[1] + p[2] * uw[2];
// proj is the "shadow" of the body vector along the observer's flat ground.
let proj = Math.sqrt(pn * pn + pw * pw);
// Calculate az = azimuth (compass direction clockwise from East.)
let az: number;
if (proj > 0) {
// If the body is not exactly straight up/down, it has an azimuth.
// Invert the angle to produce degrees eastward from north.
az = -RAD2DEG * Math.atan2(pw, pn);
if (az < 0) az += 360;
} else {
// The body is straight up/down, so it does not have an azimuth.
// Report an arbitrary but reasonable value.
az = 0;
}
// zd = the angle of the body away from the observer's zenith, in degrees.
let zd = RAD2DEG * Math.atan2(proj, pz);
let out_ra = ra;
let out_dec = dec;
if (refraction) {
let zd0 = zd;
let refr = Refraction(refraction, 90 - zd);
zd -= refr;
if (refr > 0.0 && zd > 3.0e-4) {
const sinzd = Math.sin(zd * DEG2RAD);
const coszd = Math.cos(zd * DEG2RAD);
const sinzd0 = Math.sin(zd0 * DEG2RAD);
const coszd0 = Math.cos(zd0 * DEG2RAD);
var pr = [];
for (let j = 0; j < 3; ++j) {
pr.push(((p[j] - coszd0 * uz[j]) / sinzd0) * sinzd + uz[j] * coszd);
}
proj = Math.sqrt(pr[0] * pr[0] + pr[1] * pr[1]);
if (proj > 0) {
out_ra = RAD2HOUR * Math.atan2(pr[1], pr[0]);
if (out_ra < 0) {
out_ra += 24;
}
} else {
out_ra = 0;
}
out_dec = RAD2DEG * Math.atan2(pr[2], proj);
}
}
return new HorizontalCoordinates(az, 90 - zd, out_ra, out_dec);
}
function VerifyObserver(observer: Observer): Observer {
if (!(observer instanceof Observer)) {
throw `Not an instance of the Observer class: ${observer}`;
}
VerifyNumber(observer.latitude);
VerifyNumber(observer.longitude);
VerifyNumber(observer.height);
if (observer.latitude < -90 || observer.latitude > +90) {
throw `Latitude ${observer.latitude} is out of range. Must be -90..+90.`;
}
return observer;
}
/**
* @brief Represents the geographic location of an observer on the surface of the Earth.
*
* @property {number} latitude
* The observer's geographic latitude in degrees north of the Earth's equator.
* The value is negative for observers south of the equator.
* Must be in the range -90 to +90.
*
* @property {number} longitude
* The observer's geographic longitude in degrees east of the prime meridian
* passing through Greenwich, England.
* The value is negative for observers west of the prime meridian.
* The value should be kept in the range -180 to +180 to minimize floating point errors.
*
* @property {number} height
* The observer's elevation above mean sea level, expressed in meters.
*/
export class Observer {
constructor(
public latitude: number,
public longitude: number,
public height: number) {
VerifyObserver(this);
}
}
/**
* @brief Returns apparent geocentric true ecliptic coordinates of date for the Sun.
*
* This function is used for calculating the times of equinoxes and solstices.
*
* <i>Geocentric</i> means coordinates as the Sun would appear to a hypothetical observer
* at the center of the Earth.
* <i>Ecliptic coordinates of date</i> are measured along the plane of the Earth's mean
* orbit around the Sun, using the
* <a href="https://en.wikipedia.org/wiki/Equinox_(celestial_coordinates)">equinox</a>
* of the Earth as adjusted for precession and nutation of the Earth's
* axis of rotation on the given date.
*
* @param {FlexibleDateTime} date
* The date and time at which to calculate the Sun's apparent location as seen from
* the center of the Earth.
*
* @returns {EclipticCoordinates}
*/
export function SunPosition(date: FlexibleDateTime): EclipticCoordinates {
// Correct for light travel time from the Sun.
// This is really the same as correcting for aberration.
// Otherwise season calculations (equinox, solstice) will all be early by about 8 minutes!
const time = MakeTime(date).AddDays(-1 / C_AUDAY);
// Get heliocentric cartesian coordinates of Earth in J2000.
const earth2000 = CalcVsop(vsop.Earth, time);
// Convert to geocentric location of the Sun.
const sun2000: ArrayVector = [-earth2000.x, -earth2000.y, -earth2000.z];
// Convert to equator-of-date equatorial cartesian coordinates.
const [gx, gy, gz] = gyration(sun2000, time, PrecessDirection.From2000);
// Convert to ecliptic coordinates of date.
const true_obliq = DEG2RAD * e_tilt(time).tobl;
const cos_ob = Math.cos(true_obliq);
const sin_ob = Math.sin(true_obliq);
const vec = new Vector(gx, gy, gz, time);
const sun_ecliptic = RotateEquatorialToEcliptic(vec, cos_ob, sin_ob);
return sun_ecliptic;
}
/**
* @brief Calculates equatorial coordinates of a Solar System body at a given time.
*
* Returns topocentric equatorial coordinates (right ascension and declination)
* in one of two different systems: J2000 or true-equator-of-date.
* Allows optional correction for aberration.
* Always corrects for light travel time (represents the object as seen by the observer
* with light traveling to the Earth at finite speed, not where the object is right now).
* <i>Topocentric</i> refers to a position as seen by an observer on the surface of the Earth.
* This function corrects for
* <a href="https://en.wikipedia.org/wiki/Parallax">parallax</a>
* of the object between a geocentric observer and a topocentric observer.
* This is most significant for the Moon, because it is so close to the Earth.
* However, it can have a small effect on the apparent positions of other bodies.
*
* @param {Body} body
* The body for which to find equatorial coordinates.
* Not allowed to be `"Earth"`.
*
* @param {FlexibleDateTime} date
* Specifies the date and time at which the body is to be observed.
*
* @param {Observer} observer
* The location on the Earth of the observer.
*
* @param {bool} ofdate
* Pass `true` to return equatorial coordinates of date,
* i.e. corrected for precession and nutation at the given date.
* This is needed to get correct horizontal coordinates when you call
* {@link Horizon}.
* Pass `false` to return equatorial coordinates in the J2000 system.
*
* @param {bool} aberration
* Pass `true` to correct for
* <a href="https://en.wikipedia.org/wiki/Aberration_of_light">aberration</a>,
* or `false` to leave uncorrected.
*
* @returns {EquatorialCoordinates}
* The topocentric coordinates of the body as adjusted for the given observer.
*/
export function Equator(body: Body, date: FlexibleDateTime, observer: Observer, ofdate: boolean, aberration: boolean): EquatorialCoordinates {
VerifyObserver(observer);
VerifyBoolean(ofdate);
VerifyBoolean(aberration);
const time = MakeTime(date);
const gc_observer = geo_pos(time, observer);
const gc = GeoVector(body, time, aberration);
const j2000: ArrayVector = [
gc.x - gc_observer[0],
gc.y - gc_observer[1],
gc.z - gc_observer[2]
];
if (!ofdate)
return vector2radec(j2000, time);
const datevect = gyration(j2000, time, PrecessDirection.From2000);
return vector2radec(datevect, time);
}
/**
* @brief Calculates geocentric equatorial coordinates of an observer on the surface of the Earth.
*
* This function calculates a vector from the center of the Earth to
* a point on or near the surface of the Earth, expressed in equatorial
* coordinates. It takes into account the rotation of the Earth at the given
* time, along with the given latitude, longitude, and elevation of the observer.
*
* The caller may pass `ofdate` as `true` to return coordinates relative to the Earth's
* equator at the specified time, or `false` to use the J2000 equator.
*
* The returned vector has components expressed in astronomical units (AU).
* To convert to kilometers, multiply the `x`, `y`, and `z` values by
* the constant value {@link KM_PER_AU}.
*
* The inverse of this function is also available: {@link VectorObserver}.
*
* @param {FlexibleDateTime} date
* The date and time for which to calculate the observer's position vector.
*
* @param {Observer} observer
* The geographic location of a point on or near the surface of the Earth.
*
* @param {boolean} ofdate
* Selects the date of the Earth's equator in which to express the equatorial coordinates.
* The caller may pass `false` to use the orientation of the Earth's equator
* at noon UTC on January 1, 2000, in which case this function corrects for precession
* and nutation of the Earth as it was at the moment specified by the `time` parameter.
* Or the caller may pass `true` to use the Earth's equator at `time`
* as the orientation.
*
* @returns {Vector}
* An equatorial vector from the center of the Earth to the specified location
* on (or near) the Earth's surface.
*/
export function ObserverVector(date: FlexibleDateTime, observer: Observer, ofdate: boolean): Vector {
const time = MakeTime(date);
const gast = sidereal_time(time);
let ovec = terra(observer, gast).pos;
if (!ofdate)
ovec = gyration(ovec, time, PrecessDirection.Into2000);
return VectorFromArray(ovec, time);
}
/**
* @brief Calculates the geographic location corresponding to an equatorial vector.
*
* This is the inverse function of {@link ObserverVector}.
* Given a geocentric equatorial vector, it returns the geographic
* latitude, longitude, and elevation for that vector.
*
* @param {Vector} vector
* The geocentric equatorial position vector for which to find geographic coordinates.
* The components are expressed in Astronomical Units (AU).
* You can calculate AU by dividing kilometers by the constant {@link KM_PER_AU}.
* The time `vector.t` determines the Earth's rotation.
*
* @param {boolean} ofdate
* Selects the date of the Earth's equator in which `vector` is expressed.
* The caller may select `false` to use the orientation of the Earth's equator
* at noon UTC on January 1, 2000, in which case this function corrects for precession
* and nutation of the Earth as it was at the moment specified by `vector.t`.
* Or the caller may select `true` to use the Earth's equator at `vector.t`
* as the orientation.
*
* @returns {Observer}
* The geographic latitude, longitude, and elevation above sea level
* that corresponds to the given equatorial vector.
*/
export function VectorObserver(vector: Vector, ofdate: boolean): Observer {
const gast = sidereal_time(vector.t);
let ovec: ArrayVector = [vector.x, vector.y, vector.z];
if (!ofdate) {
ovec = precession(ovec, vector.t, PrecessDirection.From2000);
ovec = nutation(ovec, vector.t, PrecessDirection.From2000);
}
return inverse_terra(ovec, gast);
}
/**
* @brief Calculates the gravitational acceleration experienced by an observer on the Earth.
*
* This function implements the WGS 84 Ellipsoidal Gravity Formula.
* The result is a combination of inward gravitational acceleration
* with outward centrifugal acceleration, as experienced by an observer
* in the Earth's rotating frame of reference.
* The resulting value increases toward the Earth's poles and decreases
* toward the equator, consistent with changes of the weight measured
* by a spring scale of a fixed mass moved to different latitudes and heights
* on the Earth.
*
* @param {number} latitude
* The latitude of the observer in degrees north or south of the equator.
* By formula symmetry, positive latitudes give the same answer as negative
* latitudes, so the sign does not matter.
*
* @param {number} height
* The height above the sea level geoid in meters.
* No range checking is done; however, accuracy is only valid in the
* range 0 to 100000 meters.
*
* @returns {number}
* The effective gravitational acceleration expressed in meters per second squared [m/s^2].
*/
export function ObserverGravity(latitude: number, height: number): number {
const s = Math.sin(latitude * DEG2RAD);
const s2 = s * s;
const g0 = 9.7803253359 * (1.0 + 0.00193185265241 * s2) / Math.sqrt(1.0 - 0.00669437999013 * s2);
return g0 * (1.0 - (3.15704e-07 - 2.10269e-09 * s2) * height + 7.37452e-14 * height * height);
}
function RotateEquatorialToEcliptic(equ: Vector, cos_ob: number, sin_ob: number): EclipticCoordinates {
// Rotate equatorial vector to obtain ecliptic vector.
const ex = equ.x;
const ey = equ.y * cos_ob + equ.z * sin_ob;
const ez = -equ.y * sin_ob + equ.z * cos_ob;
const xyproj = Math.sqrt(ex * ex + ey * ey);
let elon = 0;
if (xyproj > 0) {
elon = RAD2DEG * Math.atan2(ey, ex);
if (elon < 0) elon += 360;
}
let elat = RAD2DEG * Math.atan2(ez, xyproj);
let ecl = new Vector(ex, ey, ez, equ.t);
return new EclipticCoordinates(ecl, elat, elon);
}
/**
* @brief Converts equatorial Cartesian coordinates to ecliptic Cartesian and angular coordinates.
*
* Given J2000 equatorial Cartesian coordinates,
* returns J2000 ecliptic latitude, longitude, and cartesian coordinates.
* You can call {@link GeoVector} and pass the resulting vector to this function.
*
* @param {Vector} equ
* A vector in the J2000 equatorial coordinate system.
*
* @returns {EclipticCoordinates}
*/
export function Ecliptic(equ: Vector): EclipticCoordinates {
// Based on NOVAS functions equ2ecl() and equ2ecl_vec().
if (ob2000 === undefined) {
// Lazy-evaluate and keep the mean obliquity of the ecliptic at J2000.
// This way we don't need to crunch the numbers more than once.
ob2000 = DEG2RAD * e_tilt(MakeTime(J2000)).mobl;
cos_ob2000 = Math.cos(ob2000);
sin_ob2000 = Math.sin(ob2000);
}
return RotateEquatorialToEcliptic(equ, cos_ob2000, sin_ob2000);
}
/**
* @brief Calculates the geocentric Cartesian coordinates for the Moon in the J2000 equatorial system.
*
* Based on the Nautical Almanac Office's <i>Improved Lunar Ephemeris</i> of 1954,
* which in turn derives from E. W. Brown's lunar theories.
* Adapted from Turbo Pascal code from the book
* <a href="https://www.springer.com/us/book/9783540672210">Astronomy on the Personal Computer</a>
* by Montenbruck and Pfleger.
*
* @param {FlexibleDateTime} date
* The date and time for which to calculate the Moon's geocentric position.
*
* @returns {Vector}
*/
export function GeoMoon(date: FlexibleDateTime): Vector {
var time = MakeTime(date);
var moon = CalcMoon(time);
// Convert geocentric ecliptic spherical coords to cartesian coords.
var dist_cos_lat = moon.distance_au * Math.cos(moon.geo_eclip_lat);
var gepos: ArrayVector = [
dist_cos_lat * Math.cos(moon.geo_eclip_lon),
dist_cos_lat * Math.sin(moon.geo_eclip_lon),
moon.distance_au * Math.sin(moon.geo_eclip_lat)
];
// Convert ecliptic coordinates to equatorial coordinates, both in mean equinox of date.
var mpos1 = ecl2equ_vec(time, gepos);
// Convert from mean equinox of date to J2000...
var mpos2 = precession(mpos1, time, PrecessDirection.Into2000);
return new Vector(mpos2[0], mpos2[1], mpos2[2], time);
}
function VsopFormula(formula: any, t: number, clamp_angle: boolean): number {
let tpower = 1;
let coord = 0;
for (let series of formula) {
let sum = 0;
for (let [ampl, phas, freq] of series)
sum += ampl * Math.cos(phas + (t * freq));
let incr = tpower * sum;
if (clamp_angle)
incr %= PI2; // improve precision for longitudes: they can be hundreds of radians
coord += incr;
tpower *= t;
}
return coord;
}
function VsopDeriv(formula: any, t: number) {
let tpower = 1; // t^s
let dpower = 0; // t^(s-1)
let deriv = 0;
let s = 0;
for (let series of formula) {
let sin_sum = 0;
let cos_sum = 0;
for (let [ampl, phas, freq] of series) {
let angle = phas + (t * freq);
sin_sum += ampl * freq * Math.sin(angle);
if (s > 0)
cos_sum += ampl * Math.cos(angle);
}
deriv += (s * dpower * cos_sum) - (tpower * sin_sum);
dpower = tpower;
tpower *= t;
++s;
}
return deriv;
}
const DAYS_PER_MILLENNIUM = 365250;
const LON_INDEX = 0;
const LAT_INDEX = 1;
const RAD_INDEX = 2;
function VsopRotate(eclip: ArrayVector): TerseVector {
// Convert ecliptic cartesian coordinates to equatorial cartesian coordinates.
return new TerseVector(
eclip[0] + 0.000000440360 * eclip[1] - 0.000000190919 * eclip[2],
-0.000000479966 * eclip[0] + 0.917482137087 * eclip[1] - 0.397776982902 * eclip[2],
0.397776982902 * eclip[1] + 0.917482137087 * eclip[2]
);
}
function VsopSphereToRect(lon: number, lat: number, radius: number): ArrayVector {
// Convert spherical coordinates to ecliptic cartesian coordinates.
const r_coslat = radius * Math.cos(lat);
const coslon = Math.cos(lon);
const sinlon = Math.sin(lon);
return [
r_coslat * coslon,
r_coslat * sinlon,
radius * Math.sin(lat)
];
}
function CalcVsop(model: VsopModel, time: AstroTime): Vector {
const t = time.tt / DAYS_PER_MILLENNIUM; // millennia since 2000
const lon = VsopFormula(model[LON_INDEX], t, true);
const lat = VsopFormula(model[LAT_INDEX], t, false);
const rad = VsopFormula(model[RAD_INDEX], t, false);
const eclip = VsopSphereToRect(lon, lat, rad);
return VsopRotate(eclip).ToAstroVector(time);
}
function CalcVsopPosVel(model: VsopModel, tt: number): body_state_t {
const t = tt / DAYS_PER_MILLENNIUM;
// Calculate the VSOP "B" trigonometric series to obtain ecliptic spherical coordinates.
const lon = VsopFormula(model[LON_INDEX], t, true);
const lat = VsopFormula(model[LAT_INDEX], t, false);
const rad = VsopFormula(model[RAD_INDEX], t, false);
const dlon_dt = VsopDeriv(model[LON_INDEX], t);
const dlat_dt = VsopDeriv(model[LAT_INDEX], t);
const drad_dt = VsopDeriv(model[RAD_INDEX], t);
// Use spherical coords and spherical derivatives to calculate
// the velocity vector in rectangular coordinates.
const coslon = Math.cos(lon);
const sinlon = Math.sin(lon);
const coslat = Math.cos(lat);
const sinlat = Math.sin(lat);
const vx = (
+(drad_dt * coslat * coslon)
- (rad * sinlat * coslon * dlat_dt)
- (rad * coslat * sinlon * dlon_dt)
);
const vy = (
+(drad_dt * coslat * sinlon)
- (rad * sinlat * sinlon * dlat_dt)
+ (rad * coslat * coslon * dlon_dt)
);
const vz = (
+(drad_dt * sinlat)
+ (rad * coslat * dlat_dt)
);
const eclip_pos = VsopSphereToRect(lon, lat, rad);
// Convert speed units from [AU/millennium] to [AU/day].
const eclip_vel: ArrayVector = [
vx / DAYS_PER_MILLENNIUM,
vy / DAYS_PER_MILLENNIUM,
vz / DAYS_PER_MILLENNIUM
];
// Rotate the vectors from ecliptic to equatorial coordinates.
const equ_pos = VsopRotate(eclip_pos);
const equ_vel = VsopRotate(eclip_vel);
return new body_state_t(tt, equ_pos, equ_vel);
}
function AdjustBarycenter(ssb: Vector, time: AstroTime, body: Body, pmass: number): void {
const shift = pmass / (pmass + SUN_GM);
const planet = CalcVsop(vsop[body], time);
ssb.x += shift * planet.x;
ssb.y += shift * planet.y;
ssb.z += shift * planet.z;
}
function CalcSolarSystemBarycenter(time: AstroTime): Vector {
const ssb = new Vector(0.0, 0.0, 0.0, time);
AdjustBarycenter(ssb, time, Body.Jupiter, JUPITER_GM);
AdjustBarycenter(ssb, time, Body.Saturn, SATURN_GM);
AdjustBarycenter(ssb, time, Body.Uranus, URANUS_GM);
AdjustBarycenter(ssb, time, Body.Neptune, NEPTUNE_GM);
return ssb;
}
// Pluto integrator begins ----------------------------------------------------
const PLUTO_NUM_STATES = 41;
const PLUTO_TIME_STEP = 36500;
const PlutoStateTable: BodyStateTableEntry[] = [
[-730000.0, [-26.1182072321076, -14.3761681778250, 3.3844025152995], [1.6339372163656e-03, -2.7861699588508e-03, -1.3585880229445e-03]]
, [-693500.0, [43.6599275018261, 15.7782921408811, -8.2269833881374], [-2.5043046295860e-04, 2.1163039457238e-03, 7.3466073583102e-04]]
, [-657000.0, [-17.0086014985033, 33.0590743876420, 15.4080189624259], [-1.9676551946049e-03, -1.8337707766770e-03, 2.0125441459959e-05]]
, [-620500.0, [26.9005106893171, -21.5285596810214, -14.7987712668075], [2.2939261196998e-03, 1.7431871970059e-03, -1.4585639832643e-04]]
, [-584000.0, [20.2303809506997, 43.2669666571891, 7.3829660919234], [-1.9754081700585e-03, 5.3457141292226e-04, 7.5929169129793e-04]]
, [-547500.0, [-22.5571440338751, -19.2958112538447, 0.7806423603826], [2.1494578646505e-03, -2.4266772630044e-03, -1.4013084013574e-03]]
, [-511000.0, [43.0236236810360, 19.6179542007347, -6.8406553041565], [-4.7729923671058e-04, 2.0208979483877e-03, 7.7191815992131e-04]]
, [-474500.0, [-20.4245105862934, 29.5157679318005, 15.3408675727018], [-1.8003167284198e-03, -2.1025226687937e-03, -1.1262333332859e-04]]
, [-438000.0, [30.7746921076872, -18.2366370153037, -14.9455358798963], [2.0113162005465e-03, 1.9353827024189e-03, -2.0937793168297e-06]]
, [-401500.0, [16.7235440456361, 44.0505598318603, 8.6886113939440], [-2.0565226049264e-03, 3.2710694138777e-04, 7.2006155046579e-04]]
, [-365000.0, [-18.4891734360057, -23.1428732331142, -1.6436720878799], [2.5524223225832e-03, -2.0035792463879e-03, -1.3910737531294e-03]]
, [-328500.0, [42.0853950560734, 22.9742531259520, -5.5131410205412], [-6.7105845193949e-04, 1.9177289500465e-03, 7.9770011059534e-04]]
, [-292000.0, [-23.2753639151193, 25.8185142987694, 15.0553815885983], [-1.6062295460975e-03, -2.3395961498533e-03, -2.4377362639479e-04]]
, [-255500.0, [33.9015793210130, -14.9421228983498, -14.8664994855707], [1.7455105487563e-03, 2.0655068871494e-03, 1.1695000657630e-04]]
, [-219000.0, [13.3770189322702, 44.4442211120183, 9.8260227015847], [-2.1171882923251e-03, 1.3114714542921e-04, 6.7884578840323e-04]]
, [-182500.0, [-14.1723844533379, -26.0054690135836, -3.8387026446526], [2.8419751785822e-03, -1.5579441656564e-03, -1.3408416711060e-03]]
, [-146000.0, [40.9468572586403, 25.9049735920209, -4.2563362404988], [-8.3652705194051e-04, 1.8129497136404e-03, 8.1564228273060e-04]]
, [-109500.0, [-25.5839689598009, 22.0699164999425, 14.5902026036780], [-1.3923977856331e-03, -2.5442249745422e-03, -3.7169906721828e-04]]
, [-73000.0, [36.4035708396756, -11.7473067389593, -14.6304139635223], [1.5037714418941e-03, 2.1500325702247e-03, 2.1523781242948e-04]]
, [-36500.0, [10.2436041239517, 44.5280986402285, 10.8048664487066], [-2.1615839201823e-03, -5.1418983893534e-05, 6.3687060751430e-04]]
, [0.0, [-9.8753695807739, -27.9789262247367, -5.7537118247043], [3.0287533248818e-03, -1.1276087003636e-03, -1.2651326732361e-03]]
, [36500.0, [39.7009143866164, 28.4327664903825, -3.0906026170881], [-9.7720559866138e-04, 1.7121518344796e-03, 8.2822409843551e-04]]
, [73000.0, [-27.3620419812795, 18.4265651225706, 13.9975343005914], [-1.1690934621340e-03, -2.7143131627458e-03, -4.9312695340367e-04]]
, [109500.0, [38.3556091850032, -8.7643800131842, -14.2951819118807], [1.2922798115839e-03, 2.2032141141126e-03, 2.9606522103424e-04]]
, [146000.0, [7.3929490279056, 44.3826789515344, 11.6295002148543], [-2.1932815453830e-03, -2.1751799585364e-04, 5.9556516201114e-04]]
, [182500.0, [-5.8649529029432, -29.1987619981354, -7.3502494912123], [3.1339384323665e-03, -7.4205968379701e-04, -1.1783357537604e-03]]
, [219000.0, [38.4269476345329, 30.5667598351632, -2.0378379641214], [-1.0958945370084e-03, 1.6194885149659e-03, 8.3705272532546e-04]]
, [255500.0, [-28.6586488201636, 15.0309000931701, 13.3365724093667], [-9.4611899595408e-04, -2.8506813871559e-03, -6.0508645822989e-04]]
, [292000.0, [39.8319806717528, -6.0784057667647, -13.9098153586562], [1.1117769689167e-03, 2.2362097830152e-03, 3.6230548231153e-04]]
, [328500.0, [4.8371523764030, 44.0723119541530, 12.3146147867802], [-2.2164547537724e-03, -3.6790365636785e-04, 5.5542723844616e-04]]
, [365000.0, [-2.2619763759487, -29.8581508706765, -8.6502366418978], [3.1821176368396e-03, -4.0915169873994e-04, -1.0895893040652e-03]]
, [401500.0, [37.1576590087419, 32.3528396259588, -1.0950381786229], [-1.1988412606830e-03, 1.5356290902995e-03, 8.4339118209852e-04]]
, [438000.0, [-29.5767402292299, 11.8635359435865, 12.6313230398719], [-7.2292830060955e-04, -2.9587820140709e-03, -7.0824296450300e-04]]
, [474500.0, [40.9541099577599, -3.6589805945370, -13.4994699563950], [9.5387298337127e-04, 2.2572135462477e-03, 4.1826529781128e-04]]
, [511000.0, [2.4859523114116, 43.6181887566155, 12.8914184596699], [-2.2339745420393e-03, -5.1034757181916e-04, 5.1485330196245e-04]]
, [547500.0, [1.0594791441638, -30.1357921778687, -9.7458684762963], [3.1921591684898e-03, -1.1305312796150e-04, -9.9954096945965e-04]]
, [584000.0, [35.8778640130144, 33.8942263660709, -0.2245246362769], [-1.2941245730845e-03, 1.4560427668319e-03, 8.4762160640137e-04]]
, [620500.0, [-30.2026537318923, 8.7794211940578, 11.8609238187578], [-4.9002221381806e-04, -3.0438768469137e-03, -8.0605935262763e-04]]
, [657000.0, [41.8536204011376, -1.3790965838042, -13.0624345337527], [8.0674627557124e-04, 2.2702374399791e-03, 4.6832587475465e-04]]
, [693500.0, [0.2468843977112, 43.0303960481227, 13.3909343344167], [-2.2436121787266e-03, -6.5238074250728e-04, 4.7172729553196e-04]]
, [730000.0, [4.2432528370899, -30.1182016908248, -10.7074412313491], [3.1725847067411e-03, 1.6098461202270e-04, -9.0672150593868e-04]]
];
class TerseVector {
constructor(
public x: number,
public y: number,
public z: number) {
}
ToAstroVector(t: AstroTime) {
return new Vector(this.x, this.y, this.z, t);
}
quadrature() {
return this.x * this.x + this.y * this.y + this.z * this.z;
}
add(other: TerseVector): TerseVector {
return new TerseVector(this.x + other.x, this.y + other.y, this.z + other.z);
}
sub(other: TerseVector): TerseVector {
return new TerseVector(this.x - other.x, this.y - other.y, this.z - other.z);
}
incr(other: TerseVector) {
this.x += other.x;
this.y += other.y;
this.z += other.z;
}
decr(other: TerseVector) {
this.x -= other.x;
this.y -= other.y;
this.z -= other.z;
}
mul(scalar: number): TerseVector {
return new TerseVector(scalar * this.x, scalar * this.y, scalar * this.z);
}
div(scalar: number): TerseVector {
return new TerseVector(this.x / scalar, this.y / scalar, this.z / scalar);
}
mean(other: TerseVector): TerseVector {
return new TerseVector(
(this.x + other.x) / 2,
(this.y + other.y) / 2,
(this.z + other.z) / 2
);
}
}
class body_state_t {
constructor(
public tt: number,
public r: TerseVector,
public v: TerseVector) {
}
}
type BodyStateTableEntry = [number, ArrayVector, ArrayVector];
function BodyStateFromTable(entry: BodyStateTableEntry): body_state_t {
let [tt, [rx, ry, rz], [vx, vy, vz]] = entry;
return new body_state_t(tt, new TerseVector(rx, ry, rz), new TerseVector(vx, vy, vz));
}
function AdjustBarycenterPosVel(ssb: body_state_t, tt: number, body: Body, planet_gm: number): body_state_t {
const shift = planet_gm / (planet_gm + SUN_GM);
const planet = CalcVsopPosVel(vsop[body], tt);
ssb.r.incr(planet.r.mul(shift));
ssb.v.incr(planet.v.mul(shift));
return planet;
}
function AccelerationIncrement(small_pos: TerseVector, gm: number, major_pos: TerseVector): TerseVector {
const delta = major_pos.sub(small_pos);
const r2 = delta.quadrature();
return delta.mul(gm / (r2 * Math.sqrt(r2)));
}
class major_bodies_t {
Jupiter: body_state_t;
Saturn: body_state_t;
Uranus: body_state_t;
Neptune: body_state_t;
Sun: body_state_t;
constructor(tt: number) {
// Accumulate the Solar System Barycenter position.
let ssb = new body_state_t(tt, new TerseVector(0, 0, 0), new TerseVector(0, 0, 0));
this.Jupiter = AdjustBarycenterPosVel(ssb, tt, Body.Jupiter, JUPITER_GM);
this.Saturn = AdjustBarycenterPosVel(ssb, tt, Body.Saturn, SATURN_GM);
this.Uranus = AdjustBarycenterPosVel(ssb, tt, Body.Uranus, URANUS_GM);
this.Neptune = AdjustBarycenterPosVel(ssb, tt, Body.Neptune, NEPTUNE_GM);
// Convert planets' [pos, vel] vectors from heliocentric to barycentric.
this.Jupiter.r.decr(ssb.r);
this.Jupiter.v.decr(ssb.v);
this.Saturn.r.decr(ssb.r);
this.Saturn.v.decr(ssb.v);
this.Uranus.r.decr(ssb.r);
this.Uranus.v.decr(ssb.v);
this.Neptune.r.decr(ssb.r);
this.Neptune.v.decr(ssb.v);
// Convert heliocentric SSB to barycentric Sun.
this.Sun = new body_state_t(tt, ssb.r.mul(-1), ssb.v.mul(-1));
}
Acceleration(pos: TerseVector): TerseVector {
// Use barycentric coordinates of the Sun and major planets to calculate
// the gravitational acceleration vector experienced at location 'pos'.
let acc = AccelerationIncrement(pos, SUN_GM, this.Sun.r);
acc.incr(AccelerationIncrement(pos, JUPITER_GM, this.Jupiter.r));
acc.incr(AccelerationIncrement(pos, SATURN_GM, this.Saturn.r));
acc.incr(AccelerationIncrement(pos, URANUS_GM, this.Uranus.r));
acc.incr(AccelerationIncrement(pos, NEPTUNE_GM, this.Neptune.r));
return acc;
}
}
/**
* @ignore
*
* @brief The state of a body at an incremental step in a gravity simulation.
*
* This is an internal data structure used to represent the
* position, velocity, and acceleration vectors of a body
* in a gravity simulation at a given moment in time.
*
* @property tt
* The J2000 terrestrial time of the state [days].
*
* @property r
* The position vector [au].
*
* @property v
* The velocity vector [au/day].
*
* @property a
* The acceleration vector [au/day^2].
*/
class body_grav_calc_t {
constructor(
public tt: number,
public r: TerseVector,
public v: TerseVector,
public a: TerseVector) {
}
}
class grav_sim_t {
constructor(
public bary: major_bodies_t,
public grav: body_grav_calc_t) {
}
}
function UpdatePosition(dt: number, r: TerseVector, v: TerseVector, a: TerseVector): TerseVector {
return new TerseVector(
r.x + dt * (v.x + dt * a.x / 2),
r.y + dt * (v.y + dt * a.y / 2),
r.z + dt * (v.z + dt * a.z / 2)
);
}
function GravSim(tt2: number, calc1: body_grav_calc_t): grav_sim_t {
const dt = tt2 - calc1.tt;
// Calculate where the major bodies (Sun, Jupiter...Neptune) will be at tt2.
const bary2 = new major_bodies_t(tt2);
// Estimate position of small body as if current acceleration applies across the whole time interval.
const approx_pos = UpdatePosition(dt, calc1.r, calc1.v, calc1.a);
// Calculate the average acceleration of the endpoints.
// This becomes our estimate of the mean effective acceleration over the whole interval.
const mean_acc = bary2.Acceleration(approx_pos).mean(calc1.a);
// Refine the estimates of [pos, vel, acc] at tt2 using the mean acceleration.
const pos = UpdatePosition(dt, calc1.r, calc1.v, mean_acc);
const vel = calc1.v.add(mean_acc.mul(dt));
const acc = bary2.Acceleration(pos);
const grav = new body_grav_calc_t(tt2, pos, vel, acc);
return new grav_sim_t(bary2, grav);
}
const PLUTO_DT = 250;
const PLUTO_NSTEPS = (PLUTO_TIME_STEP / PLUTO_DT) + 1;
const pluto_cache: body_grav_calc_t[][] = [];
function ClampIndex(frac: number, nsteps: number) {
const index = Math.floor(frac);
if (index < 0)
return 0;
if (index >= nsteps)
return nsteps - 1;
return index;
}
function GravFromState(entry: BodyStateTableEntry) {
const state = BodyStateFromTable(entry);
const bary = new major_bodies_t(state.tt);
const r = state.r.add(bary.Sun.r);
const v = state.v.add(bary.Sun.v);
const a = bary.Acceleration(r);
const grav = new body_grav_calc_t(state.tt, r, v, a);
return new grav_sim_t(bary, grav);
}
function GetSegment(cache: body_grav_calc_t[][], tt: number): body_grav_calc_t[] | null {
const t0: number = PlutoStateTable[0][0];
if (tt < t0 || tt > PlutoStateTable[PLUTO_NUM_STATES - 1][0]) {
// Don't bother calculating a segment. Let the caller crawl backward/forward to this time.
return null;
}
const seg_index = ClampIndex((tt - t0) / PLUTO_TIME_STEP, PLUTO_NUM_STATES - 1);
if (!cache[seg_index]) {
const seg: body_grav_calc_t[] = cache[seg_index] = [];
// Each endpoint is exact.
seg[0] = GravFromState(PlutoStateTable[seg_index]).grav;
seg[PLUTO_NSTEPS - 1] = GravFromState(PlutoStateTable[seg_index + 1]).grav;
// Simulate forwards from the lower time bound.
let i: number;
let step_tt = seg[0].tt;
for (i = 1; i < PLUTO_NSTEPS - 1; ++i)
seg[i] = GravSim(step_tt += PLUTO_DT, seg[i - 1]).grav;
// Simulate backwards from the upper time bound.
step_tt = seg[PLUTO_NSTEPS - 1].tt;
var reverse = [];
reverse[PLUTO_NSTEPS - 1] = seg[PLUTO_NSTEPS - 1];
for (i = PLUTO_NSTEPS - 2; i > 0; --i)
reverse[i] = GravSim(step_tt -= PLUTO_DT, reverse[i + 1]).grav;
// Fade-mix the two series so that there are no discontinuities.
for (i = PLUTO_NSTEPS - 2; i > 0; --i) {
const ramp = i / (PLUTO_NSTEPS - 1);
seg[i].r = seg[i].r.mul(1 - ramp).add(reverse[i].r.mul(ramp));
seg[i].v = seg[i].v.mul(1 - ramp).add(reverse[i].v.mul(ramp));
seg[i].a = seg[i].a.mul(1 - ramp).add(reverse[i].a.mul(ramp));
}
}
return cache[seg_index];
}
function CalcPlutoOneWay(entry: BodyStateTableEntry, target_tt: number, dt: number) {
let sim = GravFromState(entry);
const n = Math.ceil((target_tt - sim.grav.tt) / dt);
for (let i = 0; i < n; ++i)
sim = GravSim((i + 1 === n) ? target_tt : (sim.grav.tt + dt), sim.grav);
return sim;
}
function CalcPluto(time: AstroTime): Vector {
let r, bary;
const seg = GetSegment(pluto_cache, time.tt);
if (!seg) {
// The target time is outside the year range 0000..4000.
// Calculate it by crawling backward from 0000 or forward from 4000.
// FIXFIXFIX - This is super slow. Could optimize this with extra caching if needed.
let sim;
if (time.tt < PlutoStateTable[0][0])
sim = CalcPlutoOneWay(PlutoStateTable[0], time.tt, -PLUTO_DT);
else
sim = CalcPlutoOneWay(PlutoStateTable[PLUTO_NUM_STATES - 1], time.tt, +PLUTO_DT);
r = sim.grav.r;
bary = sim.bary;
} else {
const left = ClampIndex((time.tt - seg[0].tt) / PLUTO_DT, PLUTO_NSTEPS - 1);
const s1 = seg[left];
const s2 = seg[left + 1];
// Find mean acceleration vector over the interval.
const acc = s1.a.mean(s2.a);
// Use Newtonian mechanics to extrapolate away from t1 in the positive time direction.
const ra = UpdatePosition(time.tt - s1.tt, s1.r, s1.v, acc);
// Use Newtonian mechanics to extrapolate away from t2 in the negative time direction.
const rb = UpdatePosition(time.tt - s2.tt, s2.r, s2.v, acc);
// Use fade in/out idea to blend the two position estimates.
const ramp = (time.tt - s1.tt) / PLUTO_DT;
r = ra.mul(1 - ramp).add(rb.mul(ramp));
bary = new major_bodies_t(time.tt);
}
return r.sub(bary.Sun.r).ToAstroVector(time);
}
// Pluto integrator ends -----------------------------------------------------
// Jupiter Moons begins ------------------------------------------------------
type jm_term_t = [number, number, number]; // amplitude, phase, frequency
type jm_series_t = jm_term_t[];
interface jupiter_moon_t {
mu: number;
al: [number, number];
a: jm_series_t;
l: jm_series_t;
z: jm_series_t;
zeta: jm_series_t;
}
const Rotation_JUP_EQJ = new RotationMatrix([
[9.9943276533865444e-01, -3.3677107469764142e-02, 0.0000000000000000e+00],
[3.0395942890628476e-02, 9.0205791235280897e-01, 4.3054338854229507e-01],
[-1.4499455966335291e-02, -4.3029916940910073e-01, 9.0256988127375404e-01]
]);
const JupiterMoonModel: jupiter_moon_t[] = [
// [0] Io
{
mu: 2.8248942843381399e-07,
al: [1.4462132960212239e+00, 3.5515522861824000e+00],
a: [
[0.0028210960212903, 0.0000000000000000e+00, 0.0000000000000000e+00]
],
l: [
[-0.0001925258348666, 4.9369589722644998e+00, 1.3584836583050000e-02],
[-0.0000970803596076, 4.3188796477322002e+00, 1.3034138432430000e-02],
[-0.0000898817416500, 1.9080016428616999e+00, 3.0506486715799999e-03],
[-0.0000553101050262, 1.4936156681568999e+00, 1.2938928911549999e-02]
],
z: [
[0.0041510849668155, 4.0899396355450000e+00, -1.2906864146660001e-02],
[0.0006260521444113, 1.4461888986270000e+00, 3.5515522949801999e+00],
[0.0000352747346169, 2.1256287034577999e+00, 1.2727416566999999e-04]
],
zeta: [
[0.0003142172466014, 2.7964219722923001e+00, -2.3150960980000000e-03],
[0.0000904169207946, 1.0477061879627001e+00, -5.6920638196000003e-04]
]
},
// [1] Europa
{
mu: 2.8248327439289299e-07,
al: [-3.7352634374713622e-01, 1.7693227111234699e+00],
a: [
[0.0044871037804314, 0.0000000000000000e+00, 0.0000000000000000e+00],
[0.0000004324367498, 1.8196456062910000e+00, 1.7822295777568000e+00]
],
l: [
[0.0008576433172936, 4.3188693178264002e+00, 1.3034138308049999e-02],
[0.0004549582875086, 1.4936531751079001e+00, 1.2938928819619999e-02],
[0.0003248939825174, 1.8196494533458001e+00, 1.7822295777568000e+00],
[-0.0003074250079334, 4.9377037005910998e+00, 1.3584832867240000e-02],
[0.0001982386144784, 1.9079869054759999e+00, 3.0510121286900001e-03],
[0.0001834063551804, 2.1402853388529000e+00, 1.4500978933800000e-03],
[-0.0001434383188452, 5.6222140366630002e+00, 8.9111478887838003e-01],
[-0.0000771939140944, 4.3002724372349999e+00, 2.6733443704265998e+00]
],
z: [
[-0.0093589104136341, 4.0899396509038999e+00, -1.2906864146660001e-02],
[0.0002988994545555, 5.9097265185595003e+00, 1.7693227079461999e+00],
[0.0002139036390350, 2.1256289300016000e+00, 1.2727418406999999e-04],
[0.0001980963564781, 2.7435168292649998e+00, 6.7797343008999997e-04],
[0.0001210388158965, 5.5839943711203004e+00, 3.2056614899999997e-05],
[0.0000837042048393, 1.6094538368039000e+00, -9.0402165808846002e-01],
[0.0000823525166369, 1.4461887708689001e+00, 3.5515522949801999e+00]
],
zeta: [
[0.0040404917832303, 1.0477063169425000e+00, -5.6920640539999997e-04],
[0.0002200421034564, 3.3368857864364001e+00, -1.2491307306999999e-04],
[0.0001662544744719, 2.4134862374710999e+00, 0.0000000000000000e+00],
[0.0000590282470983, 5.9719930968366004e+00, -3.0561602250000000e-05]
]
},
// [2] Ganymede
{
mu: 2.8249818418472298e-07,
al: [2.8740893911433479e-01, 8.7820792358932798e-01],
a: [
[0.0071566594572575, 0.0000000000000000e+00, 0.0000000000000000e+00],
[0.0000013930299110, 1.1586745884981000e+00, 2.6733443704265998e+00]
],
l: [
[0.0002310797886226, 2.1402987195941998e+00, 1.4500978438400001e-03],
[-0.0001828635964118, 4.3188672736968003e+00, 1.3034138282630000e-02],
[0.0001512378778204, 4.9373102372298003e+00, 1.3584834812520000e-02],
[-0.0001163720969778, 4.3002659861490002e+00, 2.6733443704265998e+00],
[-0.0000955478069846, 1.4936612842567001e+00, 1.2938928798570001e-02],
[0.0000815246854464, 5.6222137132535002e+00, 8.9111478887838003e-01],
[-0.0000801219679602, 1.2995922951532000e+00, 1.0034433456728999e+00],
[-0.0000607017260182, 6.4978769669238001e-01, 5.0172167043264004e-01]
],
z: [
[0.0014289811307319, 2.1256295942738999e+00, 1.2727413029000001e-04],
[0.0007710931226760, 5.5836330003496002e+00, 3.2064341100000001e-05],
[0.0005925911780766, 4.0899396636447998e+00, -1.2906864146660001e-02],
[0.0002045597496146, 5.2713683670371996e+00, -1.2523544076106000e-01],
[0.0001785118648258, 2.8743156721063001e-01, 8.7820792442520001e-01],
[0.0001131999784893, 1.4462127277818000e+00, 3.5515522949801999e+00],
[-0.0000658778169210, 2.2702423990985001e+00, -1.7951364394536999e+00],
[0.0000497058888328, 5.9096792204858000e+00, 1.7693227129285001e+00]
],
zeta: [
[0.0015932721570848, 3.3368862796665000e+00, -1.2491307058000000e-04],
[0.0008533093128905, 2.4133881688166001e+00, 0.0000000000000000e+00],
[0.0003513347911037, 5.9720789850126996e+00, -3.0561017709999999e-05],
[-0.0001441929255483, 1.0477061764435001e+00, -5.6920632124000004e-04]
]
},
// [3] Callisto
{
mu: 2.8249214488990899e-07,
al: [-3.6203412913757038e-01, 3.7648623343382798e-01],
a: [
[0.0125879701715314, 0.0000000000000000e+00, 0.0000000000000000e+00],
[0.0000035952049470, 6.4965776007116005e-01, 5.0172168165034003e-01],
[0.0000027580210652, 1.8084235781510001e+00, 3.1750660413359002e+00]
],
l: [
[0.0005586040123824, 2.1404207189814999e+00, 1.4500979323100001e-03],
[-0.0003805813868176, 2.7358844897852999e+00, 2.9729650620000000e-05],
[0.0002205152863262, 6.4979652596399995e-01, 5.0172167243580001e-01],
[0.0001877895151158, 1.8084787604004999e+00, 3.1750660413359002e+00],
[0.0000766916975242, 6.2720114319754998e+00, 1.3928364636651001e+00],
[0.0000747056855106, 1.2995916202344000e+00, 1.0034433456728999e+00]
],
z: [
[0.0073755808467977, 5.5836071576083999e+00, 3.2065099140000001e-05],
[0.0002065924169942, 5.9209831565786004e+00, 3.7648624194703001e-01],
[0.0001589869764021, 2.8744006242622999e-01, 8.7820792442520001e-01],
[-0.0001561131605348, 2.1257397865089001e+00, 1.2727441285000001e-04],
[0.0001486043380971, 1.4462134301023000e+00, 3.5515522949801999e+00],
[0.0000635073108731, 5.9096803285953996e+00, 1.7693227129285001e+00],
[0.0000599351698525, 4.1125517584797997e+00, -2.7985797954588998e+00],
[0.0000540660842731, 5.5390350845569003e+00, 2.8683408228299999e-03],
[-0.0000489596900866, 4.6218149483337996e+00, -6.2695712529518999e-01]
],
zeta: [
[0.0038422977898495, 2.4133922085556998e+00, 0.0000000000000000e+00],
[0.0022453891791894, 5.9721736773277003e+00, -3.0561255249999997e-05],
[-0.0002604479450559, 3.3368746306408998e+00, -1.2491309972000001e-04],
[0.0000332112143230, 5.5604137742336999e+00, 2.9003768850700000e-03]
]
}
];
/**
* @brief Holds the positions and velocities of Jupiter's major 4 moons.
*
* The {@link JupiterMoons} function returns an object of this type
* to report position and velocity vectors for Jupiter's largest 4 moons
* Io, Europa, Ganymede, and Callisto. Each position vector is relative
* to the center of Jupiter. Both position and velocity are oriented in
* the EQJ system (that is, using Earth's equator at the J2000 epoch).
* The positions are expressed in astronomical units (AU),
* and the velocities in AU/day.
*
* @property {StateVector[]} moon
* An array of state vectors, one for each of the four major moons
* of Jupiter, in the following order: 0=Io, 1=Europa, 2=Ganymede, 3=Callisto.
*/
export class JupiterMoonsInfo {
constructor(public moon: StateVector[]) {
}
}
function JupiterMoon_elem2pv(
time: AstroTime,
mu: number,
elem: [number, number, number, number, number, number]): StateVector {
// Translation of FORTRAN subroutine ELEM2PV from:
// https://ftp.imcce.fr/pub/ephem/satel/galilean/L1/L1.2/
const A = elem[0];
const AL = elem[1];
const K = elem[2];
const H = elem[3];
const Q = elem[4];
const P = elem[5];
const AN = Math.sqrt(mu / (A * A * A));
let CE: number, SE: number, DE: number;
let EE = AL + K * Math.sin(AL) - H * Math.cos(AL);
do {
CE = Math.cos(EE);
SE = Math.sin(EE);
DE = (AL - EE + K * SE - H * CE) / (1.0 - K * CE - H * SE);
EE += DE;
}
while (Math.abs(DE) >= 1.0e-12);
CE = Math.cos(EE);
SE = Math.sin(EE);
const DLE = H * CE - K * SE;
const RSAM1 = -K * CE - H * SE;
const ASR = 1.0 / (1.0 + RSAM1);
const PHI = Math.sqrt(1.0 - K * K - H * H);
const PSI = 1.0 / (1.0 + PHI);
const X1 = A * (CE - K - PSI * H * DLE);
const Y1 = A * (SE - H + PSI * K * DLE);
const VX1 = AN * ASR * A * (-SE - PSI * H * RSAM1);
const VY1 = AN * ASR * A * (+CE + PSI * K * RSAM1);
const F2 = 2.0 * Math.sqrt(1.0 - Q * Q - P * P);
const P2 = 1.0 - 2.0 * P * P;
const Q2 = 1.0 - 2.0 * Q * Q;
const PQ = 2.0 * P * Q;
return new StateVector(
X1 * P2 + Y1 * PQ,
X1 * PQ + Y1 * Q2,
(Q * Y1 - X1 * P) * F2,
VX1 * P2 + VY1 * PQ,
VX1 * PQ + VY1 * Q2,
(Q * VY1 - VX1 * P) * F2,
time
);
}
function CalcJupiterMoon(time: AstroTime, m: jupiter_moon_t): StateVector {
// This is a translation of FORTRAN code by Duriez, Lainey, and Vienne:
// https://ftp.imcce.fr/pub/ephem/satel/galilean/L1/L1.2/
const t = time.tt + 18262.5; // number of days since 1950-01-01T00:00:00Z
// Calculate 6 orbital elements at the given time t
const elem: [number, number, number, number, number, number] = [0, m.al[0] + (t * m.al[1]), 0, 0, 0, 0];
for (let [amplitude, phase, frequency] of m.a)
elem[0] += amplitude * Math.cos(phase + (t * frequency));
for (let [amplitude, phase, frequency] of m.l)
elem[1] += amplitude * Math.sin(phase + (t * frequency));
elem[1] %= PI2;
if (elem[1] < 0)
elem[1] += PI2;
for (let [amplitude, phase, frequency] of m.z) {
const arg = phase + (t * frequency);
elem[2] += amplitude * Math.cos(arg);
elem[3] += amplitude * Math.sin(arg);
}
for (let [amplitude, phase, frequency] of m.zeta) {
const arg = phase + (t * frequency);
elem[4] += amplitude * Math.cos(arg);
elem[5] += amplitude * Math.sin(arg);
}
// Convert the oribital elements into position vectors in the Jupiter equatorial system (JUP).
const state = JupiterMoon_elem2pv(time, m.mu, elem);
// Re-orient position and velocity vectors from Jupiter-equatorial (JUP) to Earth-equatorial in J2000 (EQJ).
return RotateState(Rotation_JUP_EQJ, state);
}
/**
* @brief Calculates jovicentric positions and velocities of Jupiter's largest 4 moons.
*
* Calculates position and velocity vectors for Jupiter's moons
* Io, Europa, Ganymede, and Callisto, at the given date and time.
* The vectors are jovicentric (relative to the center of Jupiter).
* Their orientation is the Earth's equatorial system at the J2000 epoch (EQJ).
* The position components are expressed in astronomical units (AU), and the
* velocity components are in AU/day.
*
* To convert to heliocentric vectors, call {@link HelioVector}
* with `Astronomy.Body.Jupiter` to get Jupiter's heliocentric position, then
* add the jovicentric vectors. Likewise, you can call {@link GeoVector}
* to convert to geocentric vectors.
*
* @param {FlexibleDateTime} date The date and time for which to calculate Jupiter's moons.
* @return {JupiterMoonsInfo} Position and velocity vectors of Jupiter's largest 4 moons.
*/
export function JupiterMoons(date: FlexibleDateTime): JupiterMoonsInfo {
const time = new AstroTime(date);
let infolist: StateVector[] = [];
for (let moon of JupiterMoonModel)
infolist.push(CalcJupiterMoon(time, moon));
return new JupiterMoonsInfo(infolist);
}
// Jupiter Moons ends --------------------------------------------------------
/**
* @brief Calculates a vector from the center of the Sun to the given body at the given time.
*
* Calculates heliocentric (i.e., with respect to the center of the Sun)
* Cartesian coordinates in the J2000 equatorial system of a celestial
* body at a specified time. The position is not corrected for light travel time or aberration.
*
* @param {Body} body
* One of the strings
* `"Sun"`, `"Moon"`, `"Mercury"`, `"Venus"`,
* `"Earth"`, `"Mars"`, `"Jupiter"`, `"Saturn"`,
* `"Uranus"`, `"Neptune"`, `"Pluto"`,
* `"SSB"`, or `"EMB"`.
*
* @param {FlexibleDateTime} date
* The date and time for which the body's position is to be calculated.
*
* @returns {Vector}
*/
export function HelioVector(body: Body, date: FlexibleDateTime): Vector {
var time = MakeTime(date);
if (body in vsop)
return CalcVsop(vsop[body], time);
if (body === Body.Pluto)
return CalcPluto(time);
if (body === Body.Sun)
return new Vector(0, 0, 0, time);
if (body === Body.Moon) {
var e = CalcVsop(vsop.Earth, time);
var m = GeoMoon(time);
return new Vector(e.x + m.x, e.y + m.y, e.z + m.z, time);
}
if (body === Body.EMB) {
const e = CalcVsop(vsop.Earth, time);
const m = GeoMoon(time);
const denom = 1.0 + EARTH_MOON_MASS_RATIO;
return new Vector(e.x + (m.x / denom), e.y + (m.y / denom), e.z + (m.z / denom), time);
}
if (body === Body.SSB)
return CalcSolarSystemBarycenter(time);
throw `HelioVector: Unknown body "${body}"`;
}
/**
* @brief Calculates the distance between a body and the Sun at a given time.
*
* Given a date and time, this function calculates the distance between
* the center of `body` and the center of the Sun.
* For the planets Mercury through Neptune, this function is significantly
* more efficient than calling {@link HelioVector} followed by taking the length
* of the resulting vector.
*
* @param {Body} body
* A body for which to calculate a heliocentric distance:
* the Sun, Moon, or any of the planets.
*
* @param {FlexibleDateTime} date
* The date and time for which to calculate the heliocentric distance.
*
* @returns {number}
* The heliocentric distance in AU.
*/
export function HelioDistance(body: Body, date: FlexibleDateTime): number {
const time = MakeTime(date);
if (body in vsop)
return VsopFormula(vsop[body][RAD_INDEX], time.tt / DAYS_PER_MILLENNIUM, false);
return HelioVector(body, time).Length();
}
/**
* @brief Calculates a vector from the center of the Earth to the given body at the given time.
*
* Calculates geocentric (i.e., with respect to the center of the Earth)
* Cartesian coordinates in the J2000 equatorial system of a celestial
* body at a specified time. The position is always corrected for light travel time:
* this means the position of the body is "back-dated" based on how long it
* takes light to travel from the body to an observer on the Earth.
* Also, the position can optionally be corrected for aberration, an effect
* causing the apparent direction of the body to be shifted based on
* transverse movement of the Earth with respect to the rays of light
* coming from that body.
*
* @param {Body} body
* One of the strings
* `"Sun"`, `"Moon"`, `"Mercury"`, `"Venus"`,
* `"Earth"`, `"Mars"`, `"Jupiter"`, `"Saturn"`,
* `"Uranus"`, `"Neptune"`, or `"Pluto"`.
*
* @param {FlexibleDateTime} date
* The date and time for which the body's position is to be calculated.
*
* @param {bool} aberration
* Pass `true` to correct for
* <a href="https://en.wikipedia.org/wiki/Aberration_of_light">aberration</a>,
* or `false` to leave uncorrected.
*
* @returns {Vector}
*/
export function GeoVector(body: Body, date: FlexibleDateTime, aberration: boolean): Vector {
VerifyBoolean(aberration);
const time = MakeTime(date);
if (body === Body.Moon)
return GeoMoon(time);
if (body === Body.Earth)
return new Vector(0, 0, 0, time);
let earth: Vector | null = null;
let h: Vector;
let geo: Vector;
let dt: number = 0;
let ltime = time;
// Correct for light-travel time, to get position of body as seen from Earth's center.
for (let iter = 0; iter < 10; ++iter) {
h = HelioVector(body, ltime);
if (aberration) {
/*
Include aberration, so make a good first-order approximation
by backdating the Earth's position also.
This is confusing, but it works for objects within the Solar System
because the distance the Earth moves in that small amount of light
travel time (a few minutes to a few hours) is well approximated
by a line segment that substends the angle seen from the remote
body viewing Earth. That angle is pretty close to the aberration
angle of the moving Earth viewing the remote body.
In other words, both of the following approximate the aberration angle:
(transverse distance Earth moves) / (distance to body)
(transverse speed of Earth) / (speed of light).
*/
earth = CalcVsop(vsop.Earth, ltime);
} else {
if (!earth) {
// No aberration, so calculate Earth's position once, at the time of observation.
earth = CalcVsop(vsop.Earth, time);
}
}
geo = new Vector(h.x - earth.x, h.y - earth.y, h.z - earth.z, time);
let ltime2 = time.AddDays(-geo.Length() / C_AUDAY);
dt = Math.abs(ltime2.tt - ltime.tt);
if (dt < 1.0e-9)
return geo;
ltime = ltime2;
}
throw `Light-travel time solver did not converge: dt=${dt}`;
}
function ExportState(terse: body_state_t, time: AstroTime): StateVector {
return new StateVector(terse.r.x, terse.r.y, terse.r.z, terse.v.x, terse.v.y, terse.v.z, time);
}
/**
* @brief Calculates barycentric position and velocity vectors for the given body.
*
* Given a body and a time, calculates the barycentric position and velocity
* vectors for the center of that body at that time.
* The vectors are expressed in equatorial J2000 coordinates (EQJ).
*
* @param {Body} body
* The celestial body whose barycentric state vector is to be calculated.
* Supported values are `Body.Sun`, `Body.SSB`, and all planets except Pluto:
* `Body.Mercury`, `Body.Venus`, `Body.Earth`, `Body.Mars`, `Body.Jupiter`,
* `Body.Saturn`, `Body.Uranus`, `Body.Neptune`.
* @param {FlexibleDateTime} date
* The date and time for which to calculate position and velocity.
* @returns {StateVector}
* An object that contains barycentric position and velocity vectors.
*/
export function BaryState(body: Body, date: FlexibleDateTime): StateVector {
const time = MakeTime(date);
if (body == Body.SSB) {
// Trivial case: the solar system barycenter itself.
return new StateVector(0, 0, 0, 0, 0, 0, time);
}
// Find the barycentric positions and velocities for the 5 major bodies:
// Sun, Jupiter, Saturn, Uranus, Neptune.
const bary = new major_bodies_t(time.tt);
// If the caller is asking for one of the major bodies, we can immediately return the answer.
switch (body) {
case Body.Sun:
return ExportState(bary.Sun, time);
case Body.Jupiter:
return ExportState(bary.Jupiter, time);
case Body.Saturn:
return ExportState(bary.Saturn, time);
case Body.Uranus:
return ExportState(bary.Uranus, time);
case Body.Neptune:
return ExportState(bary.Neptune, time);
}
// Otherwise, we need to calculate the heliocentric state of the given body
// and add the Sun's heliocentric state to obtain the body's barycentric state.
// BarySun + HelioBody = BaryBody
// Handle the remaining VSOP bodies: Mercury, Venus, Earth, Mars.
if (body in vsop) {
const planet = CalcVsopPosVel(vsop[body], time.tt);
return new StateVector(
bary.Sun.r.x + planet.r.x,
bary.Sun.r.y + planet.r.y,
bary.Sun.r.z + planet.r.z,
bary.Sun.v.x + planet.v.x,
bary.Sun.v.y + planet.v.y,
bary.Sun.v.z + planet.v.z,
time
);
}
// FIXFIXFIX: later, we can add support for Pluto, Moon, EMB, etc.
throw `BaryState: Unsupported body "${body}"`;
}
function QuadInterp(tm: number, dt: number, fa: number, fm: number, fb: number) {
let Q = (fb + fa) / 2 - fm;
let R = (fb - fa) / 2;
let S = fm;
let x: number;
if (Q == 0) {
// This is a line, not a parabola.
if (R == 0) {
// This is a HORIZONTAL line... can't make progress!
return null;
}
x = -S / R;
if (x < -1 || x > +1) return null; // out of bounds
} else {
// It really is a parabola. Find roots x1, x2.
let u = R * R - 4 * Q * S;
if (u <= 0) return null;
let ru = Math.sqrt(u);
let x1 = (-R + ru) / (2 * Q);
let x2 = (-R - ru) / (2 * Q);
if (-1 <= x1 && x1 <= +1) {
if (-1 <= x2 && x2 <= +1) return null;
x = x1;
} else if (-1 <= x2 && x2 <= +1) {
x = x2;
} else {
return null;
}
}
let t = tm + x * dt;
let df_dt = (2 * Q * x + R) / dt;
return {x: x, t: t, df_dt: df_dt};
}
export interface SearchOptions {
dt_tolerance_seconds?: number;
init_f1?: number;
init_f2?: number;
iter_limit?: number;
}
/**
* @brief Options for the {@link Search} function.
*
* @typedef {object} SearchOptions
*
* @property {number | undefined} dt_tolerance_seconds
* The number of seconds for a time window smaller than which the search
* is considered successful. Using too large a tolerance can result in
* an inaccurate time estimate. Using too small a tolerance can cause
* excessive computation, or can even cause the search to fail because of
* limited floating-point resolution. Defaults to 1 second.
*
* @property {number | undefined} init_f1
* As an optimization, if the caller of {@link Search}
* has already calculated the value of the function being searched (the parameter `func`)
* at the time coordinate `t1`, it can pass in that value as `init_f1`.
* For very expensive calculations, this can measurably improve performance.
*
* @property {number | undefined} init_f2
* The same as `init_f1`, except this is the optional initial value of `func(t2)`
* instead of `func(t1)`.
*
* @property {number | undefined} iter_limit
*/
/**
* @brief Finds the time when a function ascends through zero.
*
* Search for next time <i>t</i> (such that <i>t</i> is between `t1` and `t2`)
* that `func(t)` crosses from a negative value to a non-negative value.
* The given function must have "smooth" behavior over the entire inclusive range [`t1`, `t2`],
* meaning that it behaves like a continuous differentiable function.
* It is not required that `t1` < `t2`; `t1` > `t2`
* allows searching backward in time.
* Note: `t1` and `t2` must be chosen such that there is no possibility
* of more than one zero-crossing (ascending or descending), or it is possible
* that the "wrong" event will be found (i.e. not the first event after t1)
* or even that the function will return `null`, indicating that no event was found.
*
* @param {function(AstroTime): number} func
* The function to find an ascending zero crossing for.
* The function must accept a single parameter of type {@link AstroTime}
* and return a numeric value.
*
* @param {AstroTime} t1
* The lower time bound of a search window.
*
* @param {AstroTime} t2
* The upper time bound of a search window.
*
* @param {SearchOptions | undefined} options
* Options that can tune the behavior of the search.
* Most callers can omit this argument.
*
* @returns {AstroTime | null}
* If the search is successful, returns the date and time of the solution.
* If the search fails, returns `null`.
*/
export function Search(
f: (t: AstroTime) => number,
t1: AstroTime,
t2: AstroTime,
options?: SearchOptions
): AstroTime | null {
const dt_tolerance_seconds = VerifyNumber((options && options.dt_tolerance_seconds) || 1);
const dt_days = Math.abs(dt_tolerance_seconds / SECONDS_PER_DAY);
let f1 = (options && options.init_f1) || f(t1);
let f2 = (options && options.init_f2) || f(t2);
let fmid: number = NaN;
let iter = 0;
let iter_limit = (options && options.iter_limit) || 20;
let calc_fmid = true;
while (true) {
if (++iter > iter_limit)
throw `Excessive iteration in Search()`;
let tmid = InterpolateTime(t1, t2, 0.5);
let dt = tmid.ut - t1.ut;
if (Math.abs(dt) < dt_days) {
// We are close enough to the event to stop the search.
return tmid;
}
if (calc_fmid)
fmid = f(tmid);
else
calc_fmid = true; // we already have the correct value of fmid from the previous loop
// Quadratic interpolation:
// Try to find a parabola that passes through the 3 points we have sampled:
// (t1,f1), (tmid,fmid), (t2,f2).
let q = QuadInterp(tmid.ut, t2.ut - tmid.ut, f1, fmid, f2);
// Did we find an approximate root-crossing?
if (q) {
// Evaluate the function at our candidate solution.
let tq = MakeTime(q.t);
let fq = f(tq);
if (q.df_dt !== 0) {
if (Math.abs(fq / q.df_dt) < dt_days) {
// The estimated time error is small enough that we can quit now.
return tq;
}
// Try guessing a tighter boundary with the interpolated root at the center.
let dt_guess = 1.2 * Math.abs(fq / q.df_dt);
if (dt_guess < dt / 10) {
let tleft = tq.AddDays(-dt_guess);
let tright = tq.AddDays(+dt_guess);
if ((tleft.ut - t1.ut) * (tleft.ut - t2.ut) < 0) {
if ((tright.ut - t1.ut) * (tright.ut - t2.ut) < 0) {
let fleft = f(tleft);
let fright = f(tright);
if (fleft < 0 && fright >= 0) {
f1 = fleft;
f2 = fright;
t1 = tleft;
t2 = tright;
fmid = fq;
calc_fmid = false;
continue;
}
}
}
}
}
}
if (f1 < 0 && fmid >= 0) {
t2 = tmid;
f2 = fmid;
continue;
}
if (fmid < 0 && f2 >= 0) {
t1 = tmid;
f1 = fmid;
continue;
}
// Either there is no ascending zero-crossing in this range
// or the search window is too wide.
return null;
}
}
function LongitudeOffset(diff: number): number {
let offset = diff;
while (offset <= -180) offset += 360;
while (offset > 180) offset -= 360;
return offset;
}
function NormalizeLongitude(lon: number): number {
while (lon < 0) lon += 360;
while (lon >= 360) lon -= 360;
return lon;
}
/**
* @brief Searches for when the Sun reaches a given ecliptic longitude.
*
* Searches for the moment in time when the center of the Sun reaches a given apparent
* ecliptic longitude, as seen from the center of the Earth, within a given range of dates.
* This function can be used to determine equinoxes and solstices.
* However, it is usually more convenient and efficient to call {@link Seasons}
* to calculate equinoxes and solstices for a given calendar year.
* `SearchSunLongitude` is more general in that it allows searching for arbitrary longitude values.
*
* @param {number} targetLon
* The desired ecliptic longitude of date in degrees.
* This may be any value in the range [0, 360), although certain
* values have conventional meanings:
*
* When `targetLon` is 0, finds the March equinox,
* which is the moment spring begins in the northern hemisphere
* and the beginning of autumn in the southern hemisphere.
*
* When `targetLon` is 180, finds the September equinox,
* which is the moment autumn begins in the northern hemisphere and
* spring begins in the southern hemisphere.
*
* When `targetLon` is 90, finds the northern solstice, which is the
* moment summer begins in the northern hemisphere and winter
* begins in the southern hemisphere.
*
* When `targetLon` is 270, finds the southern solstice, which is the
* moment winter begins in the northern hemisphere and summer
* begins in the southern hemisphere.
*
* @param {FlexibleDateTime} dateStart
* A date and time known to be earlier than the desired longitude event.
*
* @param {number} limitDays
* A floating point number of days, which when added to `dateStart`,
* yields a date and time known to be after the desired longitude event.
*
* @returns {AstroTime | null}
* The date and time when the Sun reaches the apparent ecliptic longitude `targetLon`
* within the range of times specified by `dateStart` and `limitDays`.
* If the Sun does not reach the target longitude within the specified time range, or the
* time range is excessively wide, the return value is `null`.
* To avoid a `null` return value, the caller must pick a time window around
* the event that is within a few days but not so small that the event might fall outside the window.
*/
export function SearchSunLongitude(targetLon: number, dateStart: FlexibleDateTime, limitDays: number): AstroTime | null {
function sun_offset(t: AstroTime): number {
let pos = SunPosition(t);
return LongitudeOffset(pos.elon - targetLon);
}
VerifyNumber(targetLon);
VerifyNumber(limitDays);
let t1 = MakeTime(dateStart);
let t2 = t1.AddDays(limitDays);
return Search(sun_offset, t1, t2);
}
/**
* @brief Returns one body's ecliptic longitude with respect to another, as seen from the Earth.
*
* This function determines where one body appears around the ecliptic plane
* (the plane of the Earth's orbit around the Sun) as seen from the Earth,
* relative to the another body's apparent position.
* The function returns an angle in the half-open range [0, 360) degrees.
* The value is the ecliptic longitude of `body1` relative to the ecliptic
* longitude of `body2`.
*
* The angle is 0 when the two bodies are at the same ecliptic longitude
* as seen from the Earth. The angle increases in the prograde direction
* (the direction that the planets orbit the Sun and the Moon orbits the Earth).
*
* When the angle is 180 degrees, it means the two bodies appear on opposite sides
* of the sky for an Earthly observer.
*
* Neither `body1` nor `body2` is allowed to be `Body.Earth`.
* If this happens, the function throws an exception.
*
* @param {Body} body1
* The first body, whose longitude is to be found relative to the second body.
*
* @param {Body} body2
* The second body, relative to which the longitude of the first body is to be found.
*
* @param {FlexibleDateTime} date
* The date and time of the observation.
*
* @returns {number}
* An angle in the range [0, 360), expressed in degrees.
*/
export function PairLongitude(body1: Body, body2: Body, date: FlexibleDateTime): number {
if (body1 === Body.Earth || body2 === Body.Earth)
throw 'The Earth does not have a longitude as seen from itself.';
const time = MakeTime(date);
const vector1 = GeoVector(body1, time, false);
const eclip1 = Ecliptic(vector1);
const vector2 = GeoVector(body2, time, false);
const eclip2 = Ecliptic(vector2);
return NormalizeLongitude(eclip1.elon - eclip2.elon);
}
/**
* @brief Calculates the angular separation between the Sun and the given body.
*
* Returns the full angle seen from
* the Earth, between the given body and the Sun.
* Unlike {@link PairLongitude}, this function does not
* project the body's "shadow" onto the ecliptic;
* the angle is measured in 3D space around the plane that
* contains the centers of the Earth, the Sun, and `body`.
*
* @param {Body} body
* The name of a supported celestial body other than the Earth.
*
* @param {FlexibleDateTime} date
* The time at which the angle from the Sun is to be found.
*
* @returns {number}
* An angle in degrees in the range [0, 180].
*/
export function AngleFromSun(body: Body, date: FlexibleDateTime): number {
if (body == Body.Earth)
throw 'The Earth does not have an angle as seen from itself.';
const time = MakeTime(date);
const sv = GeoVector(Body.Sun, time, true);
const bv = GeoVector(body, time, true);
const angle = AngleBetween(sv, bv);
return angle;
}
/**
* @brief Calculates heliocentric ecliptic longitude based on the J2000 equinox.
*
* @param {Body} body
* The name of a celestial body other than the Sun.
*
* @param {FlexibleDateTime} date
* The date and time for which to calculate the ecliptic longitude.
*
* @returns {number}
* The ecliptic longitude angle of the body in degrees measured counterclockwise around the mean
* plane of the Earth's orbit, as seen from above the Sun's north pole.
* Ecliptic longitude starts at 0 at the J2000
* <a href="https://en.wikipedia.org/wiki/Equinox_(celestial_coordinates)">equinox</a> and
* increases in the same direction the Earth orbits the Sun.
* The returned value is always in the range [0, 360).
*/
export function EclipticLongitude(body: Body, date: FlexibleDateTime): number {
if (body === Body.Sun)
throw 'Cannot calculate heliocentric longitude of the Sun.';
const hv = HelioVector(body, date);
const eclip = Ecliptic(hv);
return eclip.elon;
}
function VisualMagnitude(body: Body, phase: number, helio_dist: number, geo_dist: number): number {
// For Mercury and Venus, see: https://iopscience.iop.org/article/10.1086/430212
let c0: number, c1 = 0, c2 = 0, c3 = 0;
switch (body) {
case Body.Mercury:
c0 = -0.60;
c1 = +4.98;
c2 = -4.88;
c3 = +3.02;
break;
case Body.Venus:
if (phase < 163.6) {
c0 = -4.47;
c1 = +1.03;
c2 = +0.57;
c3 = +0.13;
} else {
c0 = 0.98;
c1 = -1.02;
}
break;
case Body.Mars:
c0 = -1.52;
c1 = +1.60;
break;
case Body.Jupiter:
c0 = -9.40;
c1 = +0.50;
break;
case Body.Uranus:
c0 = -7.19;
c1 = +0.25;
break;
case Body.Neptune:
c0 = -6.87;
break;
case Body.Pluto:
c0 = -1.00;
c1 = +4.00;
break;
default:
throw `VisualMagnitude: unsupported body ${body}`;
}
const x = phase / 100;
let mag = c0 + x * (c1 + x * (c2 + x * c3));
mag += 5 * Math.log10(helio_dist * geo_dist);
return mag;
}
function SaturnMagnitude(phase: number, helio_dist: number, geo_dist: number, gc: Vector, time: AstroTime) {
// Based on formulas by Paul Schlyter found here:
// http://www.stjarnhimlen.se/comp/ppcomp.html#15
// We must handle Saturn's rings as a major component of its visual magnitude.
// Find geocentric ecliptic coordinates of Saturn.
const eclip = Ecliptic(gc);
const ir = DEG2RAD * 28.06; // tilt of Saturn's rings to the ecliptic, in radians
const Nr = DEG2RAD * (169.51 + (3.82e-5 * time.tt)); // ascending node of Saturn's rings, in radians
// Find tilt of Saturn's rings, as seen from Earth.
const lat = DEG2RAD * eclip.elat;
const lon = DEG2RAD * eclip.elon;
const tilt = Math.asin(Math.sin(lat) * Math.cos(ir) - Math.cos(lat) * Math.sin(ir) * Math.sin(lon - Nr));
const sin_tilt = Math.sin(Math.abs(tilt));
let mag = -9.0 + 0.044 * phase;
mag += sin_tilt * (-2.6 + 1.2 * sin_tilt);
mag += 5 * Math.log10(helio_dist * geo_dist);
return {mag: mag, ring_tilt: RAD2DEG * tilt};
}
function MoonMagnitude(phase: number, helio_dist: number, geo_dist: number): number {
// https://astronomy.stackexchange.com/questions/10246/is-there-a-simple-analytical-formula-for-the-lunar-phase-brightness-curve
let rad = phase * DEG2RAD;
let rad2 = rad * rad;
let rad4 = rad2 * rad2;
let mag = -12.717 + 1.49 * Math.abs(rad) + 0.0431 * rad4;
const moon_mean_distance_au = 385000.6 / KM_PER_AU;
let geo_au = geo_dist / moon_mean_distance_au;
mag += 5 * Math.log10(helio_dist * geo_au);
return mag;
}
/**
* @brief Information about the apparent brightness and sunlit phase of a celestial object.
*
* @property {AstroTime} time
* The date and time pertaining to the other calculated values in this object.
*
* @property {number} mag
* The <a href="https://en.wikipedia.org/wiki/Apparent_magnitude">apparent visual magnitude</a> of the celestial body.
*
* @property {number} phase_angle
* The angle in degrees as seen from the center of the celestial body between the Sun and the Earth.
* The value is always in the range 0 to 180.
* The phase angle provides a measure of what fraction of the body's face appears
* illuminated by the Sun as seen from the Earth.
* When the observed body is the Sun, the `phase` property is set to 0,
* although this has no physical meaning because the Sun emits, rather than reflects, light.
* When the phase is near 0 degrees, the body appears "full".
* When it is 90 degrees, the body appears "half full".
* And when it is 180 degrees, the body appears "new" and is very difficult to see
* because it is both dim and lost in the Sun's glare as seen from the Earth.
*
* @property {number} phase_fraction
* The fraction of the body's face that is illuminated by the Sun, as seen from the Earth.
* Calculated from `phase_angle` for convenience.
* This value ranges from 0 to 1.
*
* @property {number} helio_dist
* The distance between the center of the Sun and the center of the body in
* <a href="https://en.wikipedia.org/wiki/Astronomical_unit">astronomical units</a> (AU).
*
* @property {number} geo_dist
* The distance between the center of the Earth and the center of the body in AU.
*
* @property {Vector} gc
* Geocentric coordinates: the 3D vector from the center of the Earth to the center of the body.
* The components are in expressed in AU and are oriented with respect to the J2000 equatorial plane.
*
* @property {Vector} hc
* Heliocentric coordinates: The 3D vector from the center of the Sun to the center of the body.
* Like `gc`, `hc` is expressed in AU and oriented with respect
* to the J2000 equatorial plane.
*
* @property {number | undefined} ring_tilt
* For Saturn, this is the angular tilt of the planet's rings in degrees away
* from the line of sight from the Earth. When the value is near 0, the rings
* appear edge-on from the Earth and are therefore difficult to see.
* When `ring_tilt` approaches its maximum value (about 27 degrees),
* the rings appear widest and brightest from the Earth.
* Unlike the <a href="https://ssd.jpl.nasa.gov/horizons.cgi">JPL Horizons</a> online tool,
* this library includes the effect of the ring tilt angle in the calculated value
* for Saturn's visual magnitude.
* For all bodies other than Saturn, the value of `ring_tilt` is `undefined`.
*/
export class IlluminationInfo {
phase_fraction: number;
constructor(
public time: AstroTime,
public mag: number,
public phase_angle: number,
public helio_dist: number,
public geo_dist: number,
public gc: Vector,
public hc: Vector,
public ring_tilt?: number) {
this.phase_fraction = (1 + Math.cos(DEG2RAD * phase_angle)) / 2;
}
}
/**
* @brief Calculates visual magnitude and related information about a body.
*
* Calculates the phase angle, visual magnitude,
* and other values relating to the body's illumination
* at the given date and time, as seen from the Earth.
*
* @param {Body} body
* The name of the celestial body being observed.
* Not allowed to be `"Earth"`.
*
* @param {FlexibleDateTime} date
* The date and time for which to calculate the illumination data for the given body.
*
* @returns {IlluminationInfo}
*/
export function Illumination(body: Body, date: FlexibleDateTime): IlluminationInfo {
if (body === Body.Earth)
throw `The illumination of the Earth is not defined.`;
const time = MakeTime(date);
const earth = CalcVsop(vsop.Earth, time);
let phase: number; // phase angle in degrees between Earth and Sun as seen from body
let hc: Vector; // vector from Sun to body
let gc: Vector; // vector from Earth to body
let mag: number; // visual magnitude
if (body === Body.Sun) {
gc = new Vector(-earth.x, -earth.y, -earth.z, time);
hc = new Vector(0, 0, 0, time);
phase = 0; // a placeholder value; the Sun does not have an illumination phase because it emits, rather than reflects, light.
} else {
if (body === Body.Moon) {
// For extra numeric precision, use geocentric moon formula directly.
gc = GeoMoon(time);
hc = new Vector(earth.x + gc.x, earth.y + gc.y, earth.z + gc.z, time);
} else {
// For planets, heliocentric vector is most direct to calculate.
hc = HelioVector(body, date);
gc = new Vector(hc.x - earth.x, hc.y - earth.y, hc.z - earth.z, time);
}
phase = AngleBetween(gc, hc);
}
let geo_dist = gc.Length(); // distance from body to center of Earth
let helio_dist = hc.Length(); // distance from body to center of Sun
let ring_tilt; // only reported for Saturn
if (body === Body.Sun) {
mag = SUN_MAG_1AU + 5 * Math.log10(geo_dist);
} else if (body === Body.Moon) {
mag = MoonMagnitude(phase, helio_dist, geo_dist);
} else if (body === Body.Saturn) {
const saturn = SaturnMagnitude(phase, helio_dist, geo_dist, gc, time);
mag = saturn.mag;
ring_tilt = saturn.ring_tilt;
} else {
mag = VisualMagnitude(body, phase, helio_dist, geo_dist);
}
return new IlluminationInfo(time, mag, phase, helio_dist, geo_dist, gc, hc, ring_tilt);
}
function SynodicPeriod(body: Body): number {
if (body === Body.Earth)
throw 'The Earth does not have a synodic period as seen from itself.';
if (body === Body.Moon)
return MEAN_SYNODIC_MONTH;
// Calculate the synodic period of the planet from its and the Earth's sidereal periods.
// The sidereal period of a planet is how long it takes to go around the Sun in days, on average.
// The synodic period of a planet is how long it takes between consecutive oppositions
// or conjunctions, on average.
let planet = Planet[body];
if (!planet)
throw `Not a valid planet name: ${body}`;
// See here for explanation of the formula:
// https://en.wikipedia.org/wiki/Elongation_(astronomy)#Elongation_period
const Te = Planet.Earth.OrbitalPeriod;
const Tp = planet.OrbitalPeriod;
const synodicPeriod = Math.abs(Te / (Te / Tp - 1));
return synodicPeriod;
}
/**
* @brief Searches for when the Earth and a given body reach a relative ecliptic longitude separation.
*
* Searches for the date and time the relative ecliptic longitudes of
* the specified body and the Earth, as seen from the Sun, reach a certain
* difference. This function is useful for finding conjunctions and oppositions
* of the planets. For the opposition of a superior planet (Mars, Jupiter, ..., Pluto),
* or the inferior conjunction of an inferior planet (Mercury, Venus),
* call with `targetRelLon` = 0. The 0 value indicates that both
* planets are on the same ecliptic longitude line, ignoring the other planet's
* distance above or below the plane of the Earth's orbit.
* For superior conjunctions, call with `targetRelLon` = 180.
* This means the Earth and the other planet are on opposite sides of the Sun.
*
* @param {Body} body
* The name of a planet other than the Earth.
*
* @param {number} targetRelLon
* The desired angular difference in degrees between the ecliptic longitudes
* of `body` and the Earth. Must be in the range (-180, +180].
*
* @param {FlexibleDateTime} startDate
* The date and time after which to find the next occurrence of the
* body and the Earth reaching the desired relative longitude.
*
* @returns {AstroTime}
* The time when the Earth and the body next reach the specified relative longitudes.
*/
export function SearchRelativeLongitude(body: Body, targetRelLon: number, startDate: FlexibleDateTime): AstroTime {
VerifyNumber(targetRelLon);
const planet = Planet[body];
if (!planet)
throw `Cannot search relative longitude because body is not a planet: ${body}`;
if (body === Body.Earth)
throw 'Cannot search relative longitude for the Earth (it is always 0)';
// Determine whether the Earth "gains" (+1) on the planet or "loses" (-1)
// as both race around the Sun.
const direction = (planet.OrbitalPeriod > Planet.Earth.OrbitalPeriod) ? +1 : -1;
function offset(t: AstroTime): number {
const plon = EclipticLongitude(body, t);
const elon = EclipticLongitude(Body.Earth, t);
const diff = direction * (elon - plon);
return LongitudeOffset(diff - targetRelLon);
}
let syn = SynodicPeriod(body);
let time = MakeTime(startDate);
// Iterate until we converge on the desired event.
// Calculate the error angle, which will be a negative number of degrees,
// meaning we are "behind" the target relative longitude.
let error_angle = offset(time);
if (error_angle > 0) error_angle -= 360; // force searching forward in time
for (let iter = 0; iter < 100; ++iter) {
// Estimate how many days in the future (positive) or past (negative)
// we have to go to get closer to the target relative longitude.
let day_adjust = (-error_angle / 360) * syn;
time = time.AddDays(day_adjust);
if (Math.abs(day_adjust) * SECONDS_PER_DAY < 1)
return time;
let prev_angle = error_angle;
error_angle = offset(time);
if (Math.abs(prev_angle) < 30) {
// Improve convergence for Mercury/Mars (eccentric orbits)
// by adjusting the synodic period to more closely match the
// variable speed of both planets in this part of their respective orbits.
if (prev_angle !== error_angle) {
let ratio = prev_angle / (prev_angle - error_angle);
if (ratio > 0.5 && ratio < 2.0)
syn *= ratio;
}
}
}
throw `Relative longitude search failed to converge for ${body} near ${time.toString()} (error_angle = ${error_angle}).`;
}
/**
* @brief Determines the moon's phase expressed as an ecliptic longitude.
*
* @param {FlexibleDateTime} date
* The date and time for which to calculate the moon's phase.
*
* @returns {number}
* A value in the range [0, 360) indicating the difference
* in ecliptic longitude between the center of the Sun and the
* center of the Moon, as seen from the center of the Earth.
* Certain longitude values have conventional meanings:
*
* * 0 = new moon
* * 90 = first quarter
* * 180 = full moon
* * 270 = third quarter
*/
export function MoonPhase(date: FlexibleDateTime): number {
return PairLongitude(Body.Moon, Body.Sun, date);
}
/**
* @brief Searches for the date and time that the Moon reaches a specified phase.
*
* Lunar phases are defined in terms of geocentric ecliptic longitudes
* with respect to the Sun. When the Moon and the Sun have the same ecliptic
* longitude, that is defined as a new moon. When the two ecliptic longitudes
* are 180 degrees apart, that is defined as a full moon.
* To enumerate quarter lunar phases, it is simpler to call
* {@link SearchMoonQuarter} once, followed by repeatedly calling
* {@link NextMoonQuarter}. `SearchMoonPhase` is only
* necessary for finding other lunar phases than the usual quarter phases.
*
* @param {number} targetLon
* The difference in geocentric ecliptic longitude between the Sun and Moon
* that specifies the lunar phase being sought. This can be any value
* in the range [0, 360). Here are some helpful examples:
* 0 = new moon,
* 90 = first quarter,
* 180 = full moon,
* 270 = third quarter.
*
* @param {FlexibleDateTime} dateStart
* The beginning of the window of time in which to search.
*
* @param {number} limitDays
* The floating point number of days after `dateStart`
* that limits the window of time in which to search.
*
* @returns {AstroTime | null}
* If the specified lunar phase occurs after `dateStart`
* and before `limitDays` days after `dateStart`,
* this function returns the date and time of the first such occurrence.
* Otherwise, it returns `null`.
*/
export function SearchMoonPhase(targetLon: number, dateStart: FlexibleDateTime, limitDays: number): AstroTime | null {
function moon_offset(t: AstroTime): number {
let mlon: number = MoonPhase(t);
return LongitudeOffset(mlon - targetLon);
}
VerifyNumber(targetLon);
VerifyNumber(limitDays);
// To avoid discontinuities in the moon_offset function causing problems,
// we need to approximate when that function will next return 0.
// We probe it with the start time and take advantage of the fact
// that every lunar phase repeats roughly every 29.5 days.
// There is a surprising uncertainty in the quarter timing,
// due to the eccentricity of the moon's orbit.
// I have seen more than 0.9 days away from the simple prediction.
// To be safe, we take the predicted time of the event and search
// +/-1.5 days around it (a 3.0-day wide window).
// But we must return null if the final result goes beyond limitDays after dateStart.
const uncertainty = 1.5;
let ta = MakeTime(dateStart);
let ya = moon_offset(ta);
if (ya > 0) ya -= 360; // force searching forward in time, not backward
let est_dt = -(MEAN_SYNODIC_MONTH * ya) / 360;
let dt1 = est_dt - uncertainty;
if (dt1 > limitDays)
return null; // not possible for moon phase to occur within the specified window
let dt2 = Math.min(limitDays, est_dt + uncertainty);
let t1 = ta.AddDays(dt1);
let t2 = ta.AddDays(dt2);
return Search(moon_offset, t1, t2);
}
/**
* @brief A quarter lunar phase, along with when it occurs.
*
* @property {number} quarter
* An integer as follows:
* 0 = new moon,
* 1 = first quarter,
* 2 = full moon,
* 3 = third quarter.
*
* @property {AstroTime} time
* The date and time of the quarter lunar phase.
*/
export class MoonQuarter {
constructor(
public quarter: number,
public time: AstroTime) {
}
}
/**
* @brief Finds the first quarter lunar phase after the specified date and time.
*
* The quarter lunar phases are: new moon, first quarter, full moon, and third quarter.
* To enumerate quarter lunar phases, call `SearchMoonQuarter` once,
* then pass its return value to {@link NextMoonQuarter} to find the next
* `MoonQuarter`. Keep calling `NextMoonQuarter` in a loop,
* passing the previous return value as the argument to the next call.
*
* @param {FlexibleDateTime} dateStart
* The date and time after which to find the first quarter lunar phase.
*
* @returns {MoonQuarter}
*/
export function SearchMoonQuarter(dateStart: FlexibleDateTime): MoonQuarter {
// Determine what the next quarter phase will be.
let phaseStart = MoonPhase(dateStart);
let quarterStart = Math.floor(phaseStart / 90);
let quarter = (quarterStart + 1) % 4;
let time = SearchMoonPhase(90 * quarter, dateStart, 10);
if (!time)
throw 'Cannot find moon quarter';
return new MoonQuarter(quarter, time);
}
/**
* @brief Finds the next quarter lunar phase in a series.
*
* Given a {@link MoonQuarter} object, finds the next consecutive
* quarter lunar phase. See remarks in {@link SearchMoonQuarter}
* for explanation of usage.
*
* @param {MoonQuarter} mq
* The return value of a prior call to {@link MoonQuarter} or `NextMoonQuarter`.
*/
export function NextMoonQuarter(mq: MoonQuarter): MoonQuarter {
// Skip 6 days past the previous found moon quarter to find the next one.
// This is less than the minimum possible increment.
// So far I have seen the interval well contained by the range (6.5, 8.3) days.
let date = new Date(mq.time.date.valueOf() + 6 * MILLIS_PER_DAY);
return SearchMoonQuarter(date);
}
function BodyRadiusAu(body: Body): number {
// For the purposes of calculating rise/set times,
// only the Sun and Moon appear large enough to an observer
// on the Earth for their radius to matter.
// All other bodies are treated as points.
switch (body) {
case Body.Sun:
return SUN_RADIUS_AU;
case Body.Moon:
return MOON_EQUATORIAL_RADIUS_AU;
default:
return 0;
}
}
/**
* @brief Finds the next rise or set time for a body.
*
* Finds a rise or set time for the given body as
* seen by an observer at the specified location on the Earth.
* Rise time is defined as the moment when the top of the body
* is observed to first appear above the horizon in the east.
* Set time is defined as the moment the top of the body
* is observed to sink below the horizon in the west.
* The times are adjusted for typical atmospheric refraction conditions.
*
* @param {Body} body
* The name of the body to find the rise or set time for.
*
* @param {Observer} observer
* Specifies the geographic coordinates and elevation above sea level of the observer.
*
* @param {number} direction
* Either +1 to find rise time or -1 to find set time.
* Any other value will cause an exception to be thrown.
*
* @param {FlexibleDateTime} dateStart
* The date and time after which the specified rise or set time is to be found.
*
* @param {number} limitDays
* The fractional number of days after `dateStart` that limits
* when the rise or set time is to be found.
*
* @returns {AstroTime | null}
* The date and time of the rise or set event, or null if no such event
* occurs within the specified time window.
*/
export function SearchRiseSet(body: Body, observer: Observer, direction: number, dateStart: FlexibleDateTime, limitDays: number): AstroTime | null {
VerifyObserver(observer);
VerifyNumber(limitDays);
let body_radius_au: number = BodyRadiusAu(body);
function peak_altitude(t: AstroTime): number {
// Return the angular altitude above or below the horizon
// of the highest part (the peak) of the given object.
// This is defined as the apparent altitude of the center of the body plus
// the body's angular radius.
// The 'direction' variable in the enclosing function controls
// whether the angle is measured positive above the horizon or
// positive below the horizon, depending on whether the caller
// wants rise times or set times, respectively.
const ofdate = Equator(body, t, observer, true, true);
const hor = Horizon(t, observer, ofdate.ra, ofdate.dec);
const alt = hor.altitude + RAD2DEG * (body_radius_au / ofdate.dist) + REFRACTION_NEAR_HORIZON;
return direction * alt;
}
if (body === Body.Earth)
throw 'Cannot find rise or set time of the Earth.';
// See if the body is currently above/below the horizon.
// If we are looking for next rise time and the body is below the horizon,
// we use the current time as the lower time bound and the next culmination
// as the upper bound.
// If the body is above the horizon, we search for the next bottom and use it
// as the lower bound and the next culmination after that bottom as the upper bound.
// The same logic applies for finding set times, only we swap the hour angles.
// The peak_altitude() function already considers the 'direction' parameter.
let ha_before: number, ha_after: number;
if (direction === +1) {
ha_before = 12; // minimum altitude (bottom) happens BEFORE the body rises.
ha_after = 0; // maximum altitude (culmination) happens AFTER the body rises.
} else if (direction === -1) {
ha_before = 0; // culmination happens BEFORE the body sets.
ha_after = 12; // bottom happens AFTER the body sets.
} else {
throw `SearchRiseSet: Invalid direction parameter ${direction} -- must be +1 or -1`;
}
let time_start = MakeTime(dateStart);
let time_before: AstroTime;
let evt_before: HourAngleEvent;
let evt_after: HourAngleEvent;
let alt_before = peak_altitude(time_start);
let alt_after: number;
if (alt_before > 0) {
// We are past the sought event, so we have to wait for the next "before" event (culm/bottom).
evt_before = SearchHourAngle(body, observer, ha_before, time_start);
time_before = evt_before.time;
alt_before = peak_altitude(time_before);
} else {
// We are before or at the sought event, so we find the next "after" event (bottom/culm),
// and use the current time as the "before" event.
time_before = time_start;
}
evt_after = SearchHourAngle(body, observer, ha_after, time_before);
alt_after = peak_altitude(evt_after.time);
while (true) {
if (alt_before <= 0 && alt_after > 0) {
// Search between evt_before and evt_after for the desired event.
let tx = Search(peak_altitude, time_before, evt_after.time, {init_f1: alt_before, init_f2: alt_after});
if (tx)
return tx;
}
// If we didn't find the desired event, use time_after to find the next before-event.
evt_before = SearchHourAngle(body, observer, ha_before, evt_after.time);
evt_after = SearchHourAngle(body, observer, ha_after, evt_before.time);
if (evt_before.time.ut >= time_start.ut + limitDays)
return null;
time_before = evt_before.time;
alt_before = peak_altitude(evt_before.time);
alt_after = peak_altitude(evt_after.time);
}
}
/**
* @brief Horizontal position of a body upon reaching an hour angle.
*
* Returns information about an occurrence of a celestial body
* reaching a given hour angle as seen by an observer at a given
* location on the surface of the Earth.
*
* @property {AstroTime} time
* The date and time of the celestial body reaching the hour angle.
*
* @property {HorizontalCoordinates} hor
* Topocentric horizontal coordinates for the body
* at the time indicated by the `time` property.
*/
export class HourAngleEvent {
constructor(
public time: AstroTime,
public hor: HorizontalCoordinates) {
}
}
/**
* @brief Finds when a body will reach a given hour angle.
*
* Finds the next time the given body is seen to reach the specified
* <a href="https://en.wikipedia.org/wiki/Hour_angle">hour angle</a>
* by the given observer.
* Providing `hourAngle` = 0 finds the next maximum altitude event (culmination).
* Providing `hourAngle` = 12 finds the next minimum altitude event.
* Note that, especially close to the Earth's poles, a body as seen on a given day
* may always be above the horizon or always below the horizon, so the caller cannot
* assume that a culminating object is visible nor that an object is below the horizon
* at its minimum altitude.
*
* @param {Body} body
* The name of a celestial body other than the Earth.
*
* @param {Observer} observer
* Specifies the geographic coordinates and elevation above sea level of the observer.
*
* @param {number} hourAngle
* The hour angle expressed in
* <a href="https://en.wikipedia.org/wiki/Sidereal_time">sidereal</a>
* hours for which the caller seeks to find the body attain.
* The value must be in the range [0, 24).
* The hour angle represents the number of sidereal hours that have
* elapsed since the most recent time the body crossed the observer's local
* <a href="https://en.wikipedia.org/wiki/Meridian_(astronomy)">meridian</a>.
* This specifying `hourAngle` = 0 finds the moment in time
* the body reaches the highest angular altitude in a given sidereal day.
*
* @param {FlexibleDateTime} dateStart
* The date and time after which the desired hour angle crossing event
* is to be found.
*
* @returns {HourAngleEvent}
*/
export function SearchHourAngle(body: Body, observer: Observer, hourAngle: number, dateStart: FlexibleDateTime): HourAngleEvent {
VerifyObserver(observer);
let time = MakeTime(dateStart);
let iter = 0;
if (body === Body.Earth)
throw 'Cannot search for hour angle of the Earth.';
VerifyNumber(hourAngle);
if (hourAngle < 0.0 || hourAngle >= 24.0)
throw `Invalid hour angle ${hourAngle}`;
while (true) {
++iter;
// Calculate Greenwich Apparent Sidereal Time (GAST) at the given time.
let gast = sidereal_time(time);
let ofdate = Equator(body, time, observer, true, true);
// Calculate the adjustment needed in sidereal time to bring
// the hour angle to the desired value.
let delta_sidereal_hours = ((hourAngle + ofdate.ra - observer.longitude / 15) - gast) % 24;
if (iter === 1) {
// On the first iteration, always search forward in time.
if (delta_sidereal_hours < 0)
delta_sidereal_hours += 24;
} else {
// On subsequent iterations, we make the smallest possible adjustment,
// either forward or backward in time.
if (delta_sidereal_hours < -12)
delta_sidereal_hours += 24;
else if (delta_sidereal_hours > +12)
delta_sidereal_hours -= 24;
}
// If the error is tolerable (less than 0.1 seconds), stop searching.
if (Math.abs(delta_sidereal_hours) * 3600 < 0.1) {
const hor = Horizon(time, observer, ofdate.ra, ofdate.dec, 'normal');
return new HourAngleEvent(time, hor);
}
// We need to loop another time to get more accuracy.
// Update the terrestrial time adjusting by sidereal time.
let delta_days = (delta_sidereal_hours / 24) * SOLAR_DAYS_PER_SIDEREAL_DAY;
time = time.AddDays(delta_days);
}
}
/**
* @brief When the seasons change for a given calendar year.
*
* Represents the dates and times of the two solstices
* and the two equinoxes in a given calendar year.
* These four events define the changing of the seasons on the Earth.
*
* @property {AstroTime} mar_equinox
* The date and time of the March equinox in the given calendar year.
* This is the moment in March that the plane of the Earth's equator passes
* through the center of the Sun; thus the Sun's declination
* changes from a negative number to a positive number.
* The March equinox defines
* the beginning of spring in the northern hemisphere and
* the beginning of autumn in the southern hemisphere.
*
* @property {AstroTime} jun_solstice
* The date and time of the June solstice in the given calendar year.
* This is the moment in June that the Sun reaches its most positive
* declination value.
* At this moment the Earth's north pole is most tilted most toward the Sun.
* The June solstice defines
* the beginning of summer in the northern hemisphere and
* the beginning of winter in the southern hemisphere.
*
* @property {AstroTime} sep_equinox
* The date and time of the September equinox in the given calendar year.
* This is the moment in September that the plane of the Earth's equator passes
* through the center of the Sun; thus the Sun's declination
* changes from a positive number to a negative number.
* The September equinox defines
* the beginning of autumn in the northern hemisphere and
* the beginning of spring in the southern hemisphere.
*
* @property {AstroTime} dec_solstice
* The date and time of the December solstice in the given calendar year.
* This is the moment in December that the Sun reaches its most negative
* declination value.
* At this moment the Earth's south pole is tilted most toward the Sun.
* The December solstice defines
* the beginning of winter in the northern hemisphere and
* the beginning of summer in the southern hemisphere.
*/
export class SeasonInfo {
constructor(
public mar_equinox: AstroTime,
public jun_solstice: AstroTime,
public sep_equinox: AstroTime,
public dec_solstice: AstroTime) {
}
}
/**
* @brief Finds the equinoxes and solstices for a given calendar year.
*
* @param {number | AstroTime} year
* The integer value or `AstroTime` object that specifies
* the UTC calendar year for which to find equinoxes and solstices.
*
* @returns {SeasonInfo}
*/
export function Seasons(year: (number | AstroTime)): SeasonInfo {
function find(targetLon: number, month: number, day: number): AstroTime {
let startDate = new Date(Date.UTC(<number>year, month - 1, day));
let time = SearchSunLongitude(targetLon, startDate, 4);
if (!time)
throw `Cannot find season change near ${startDate.toISOString()}`;
return time;
}
if ((year instanceof Date) && Number.isFinite(year.valueOf()))
year = year.getUTCFullYear();
if (!Number.isSafeInteger(year))
throw `Cannot calculate seasons because year argument ${year} is neither a Date nor a safe integer.`;
let mar_equinox = find(0, 3, 19);
let jun_solstice = find(90, 6, 19);
let sep_equinox = find(180, 9, 21);
let dec_solstice = find(270, 12, 20);
return new SeasonInfo(mar_equinox, jun_solstice, sep_equinox, dec_solstice);
}
/**
* @brief The viewing conditions of a body relative to the Sun.
*
* Represents the angular separation of a body from the Sun as seen from the Earth
* and the relative ecliptic longitudes between that body and the Earth as seen from the Sun.
*
* @property {AstroTime} time
* The date and time of the observation.
*
* @property {string} visibility
* Either `"morning"` or `"evening"`,
* indicating when the body is most easily seen.
*
* @property {number} elongation
* The angle in degrees, as seen from the center of the Earth,
* of the apparent separation between the body and the Sun.
* This angle is measured in 3D space and is not projected onto the ecliptic plane.
* When `elongation` is less than a few degrees, the body is very
* difficult to see from the Earth because it is lost in the Sun's glare.
* The elongation is always in the range [0, 180].
*
* @property {number} ecliptic_separation
* The absolute value of the difference between the body's ecliptic longitude
* and the Sun's ecliptic longitude, both as seen from the center of the Earth.
* This angle measures around the plane of the Earth's orbit (the ecliptic),
* and ignores how far above or below that plane the body is.
* The ecliptic separation is measured in degrees and is always in the range [0, 180].
*
* @see {@link Elongation}
*/
export class ElongationEvent {
constructor(
public time: AstroTime,
public visibility: string,
public elongation: number,
public ecliptic_separation: number) {
}
}
/**
* @brief Calculates the viewing conditions of a body relative to the Sun.
*
* Calculates angular separation of a body from the Sun as seen from the Earth
* and the relative ecliptic longitudes between that body and the Earth as seen from the Sun.
* See the return type {@link ElongationEvent} for details.
*
* This function is helpful for determining how easy
* it is to view a planet away from the Sun's glare on a given date.
* It also determines whether the object is visible in the morning or evening;
* this is more important the smaller the elongation is.
* It is also used to determine how far a planet is from opposition, conjunction, or quadrature.
*
* @param {Body} body
* The name of the observed body. Not allowed to be `"Earth"`.
*
* @returns {ElongationEvent}
*/
export function Elongation(body: Body, date: FlexibleDateTime): ElongationEvent {
let time = MakeTime(date);
let lon = PairLongitude(body, Body.Sun, time);
let vis: string;
if (lon > 180) {
vis = 'morning';
lon = 360 - lon;
} else {
vis = 'evening';
}
let angle = AngleFromSun(body, time);
return new ElongationEvent(time, vis, angle, lon);
}
/**
* @brief Finds the next time Mercury or Venus reaches maximum elongation.
*
* Searches for the next maximum elongation event for Mercury or Venus
* that occurs after the given start date. Calling with other values
* of `body` will result in an exception.
* Maximum elongation occurs when the body has the greatest
* angular separation from the Sun, as seen from the Earth.
* Returns an `ElongationEvent` object containing the date and time of the next
* maximum elongation, the elongation in degrees, and whether
* the body is visible in the morning or evening.
*
* @param {Body} body Either `"Mercury"` or `"Venus"`.
* @param {FlexibleDateTime} startDate The date and time after which to search for the next maximum elongation event.
*
* @returns {ElongationEvent}
*/
export function SearchMaxElongation(body: Body, startDate: FlexibleDateTime): ElongationEvent {
const dt = 0.01;
function neg_slope(t: AstroTime): number {
// The slope de/dt goes from positive to negative at the maximum elongation event.
// But Search() is designed for functions that ascend through zero.
// So this function returns the negative slope.
const t1 = t.AddDays(-dt / 2);
const t2 = t.AddDays(+dt / 2);
let e1 = AngleFromSun(body, t1);
let e2 = AngleFromSun(body, t2);
let m = (e1 - e2) / dt;
return m;
}
let startTime = MakeTime(startDate);
interface InferiorPlanetEntry {
s1: number;
s2: number;
}
interface InferiorPlanetTable {
[body: string]: InferiorPlanetEntry;
}
const table: InferiorPlanetTable = {
Mercury: {s1: 50.0, s2: 85.0},
Venus: {s1: 40.0, s2: 50.0}
};
const planet: InferiorPlanetEntry = table[body];
if (!planet)
throw 'SearchMaxElongation works for Mercury and Venus only.';
let iter = 0;
while (++iter <= 2) {
// Find current heliocentric relative longitude between the
// inferior planet and the Earth.
let plon = EclipticLongitude(body, startTime);
let elon = EclipticLongitude(Body.Earth, startTime);
let rlon = LongitudeOffset(plon - elon); // clamp to (-180, +180]
// The slope function is not well-behaved when rlon is near 0 degrees or 180 degrees
// because there is a cusp there that causes a discontinuity in the derivative.
// So we need to guard against searching near such times.
let rlon_lo: number, rlon_hi: number, adjust_days: number;
if (rlon >= -planet.s1 && rlon < +planet.s1) {
// Seek to the window [+s1, +s2].
adjust_days = 0;
// Search forward for the time t1 when rel lon = +s1.
rlon_lo = +planet.s1;
// Search forward for the time t2 when rel lon = +s2.
rlon_hi = +planet.s2;
} else if (rlon >= +planet.s2 || rlon < -planet.s2) {
// Seek to the next search window at [-s2, -s1].
adjust_days = 0;
// Search forward for the time t1 when rel lon = -s2.
rlon_lo = -planet.s2;
// Search forward for the time t2 when rel lon = -s1.
rlon_hi = -planet.s1;
} else if (rlon >= 0) {
// rlon must be in the middle of the window [+s1, +s2].
// Search BACKWARD for the time t1 when rel lon = +s1.
adjust_days = -SynodicPeriod(body) / 4;
rlon_lo = +planet.s1;
rlon_hi = +planet.s2;
// Search forward from t1 to find t2 such that rel lon = +s2.
} else {
// rlon must be in the middle of the window [-s2, -s1].
// Search BACKWARD for the time t1 when rel lon = -s2.
adjust_days = -SynodicPeriod(body) / 4;
rlon_lo = -planet.s2;
// Search forward from t1 to find t2 such that rel lon = -s1.
rlon_hi = -planet.s1;
}
let t_start = startTime.AddDays(adjust_days);
let t1 = SearchRelativeLongitude(body, rlon_lo, t_start);
let t2 = SearchRelativeLongitude(body, rlon_hi, t1);
// Now we have a time range [t1,t2] that brackets a maximum elongation event.
// Confirm the bracketing.
let m1 = neg_slope(t1);
if (m1 >= 0)
throw `SearchMaxElongation: internal error: m1 = ${m1}`;
let m2 = neg_slope(t2);
if (m2 <= 0)
throw `SearchMaxElongation: internal error: m2 = ${m2}`;
// Use the generic search algorithm to home in on where the slope crosses from negative to positive.
let tx = Search(neg_slope, t1, t2, {init_f1: m1, init_f2: m2, dt_tolerance_seconds: 10});
if (!tx)
throw `SearchMaxElongation: failed search iter ${iter} (t1=${t1.toString()}, t2=${t2.toString()})`;
if (tx.tt >= startTime.tt)
return Elongation(body, tx);
// This event is in the past (earlier than startDate).
// We need to search forward from t2 to find the next possible window.
// We never need to search more than twice.
startTime = t2.AddDays(1);
}
throw `SearchMaxElongation: failed to find event after 2 tries.`;
}
/**
* @brief Searches for the date and time Venus will next appear brightest as seen from the Earth.
*
* @param {Body} body
* Currently only `"Venus"` is supported.
* Mercury's peak magnitude occurs at superior conjunction, when it is virtually impossible to see from Earth,
* so peak magnitude events have little practical value for that planet.
* The Moon reaches peak magnitude very close to full moon, which can be found using
* {@link SearchMoonQuarter} or {@link SearchMoonPhase}.
* The other planets reach peak magnitude very close to opposition,
* which can be found using {@link SearchRelativeLongitude}.
*
* @param {FlexibleDateTime} startDate
* The date and time after which to find the next peak magnitude event.
*
* @returns {IlluminationInfo}
*/
export function SearchPeakMagnitude(body: Body, startDate: FlexibleDateTime): IlluminationInfo {
if (body !== Body.Venus)
throw 'SearchPeakMagnitude currently works for Venus only.';
const dt = 0.01;
function slope(t: AstroTime): number {
// The Search() function finds a transition from negative to positive values.
// The derivative of magnitude y with respect to time t (dy/dt)
// is negative as an object gets brighter, because the magnitude numbers
// get smaller. At peak magnitude dy/dt = 0, then as the object gets dimmer,
// dy/dt > 0.
const t1 = t.AddDays(-dt / 2);
const t2 = t.AddDays(+dt / 2);
const y1 = Illumination(body, t1).mag;
const y2 = Illumination(body, t2).mag;
const m = (y2 - y1) / dt;
return m;
}
let startTime = MakeTime(startDate);
// s1 and s2 are relative longitudes within which peak magnitude of Venus can occur.
const s1 = 10.0;
const s2 = 30.0;
let iter = 0;
while (++iter <= 2) {
// Find current heliocentric relative longitude between the
// inferior planet and the Earth.
let plon = EclipticLongitude(body, startTime);
let elon = EclipticLongitude(Body.Earth, startTime);
let rlon = LongitudeOffset(plon - elon); // clamp to (-180, +180]
// The slope function is not well-behaved when rlon is near 0 degrees or 180 degrees
// because there is a cusp there that causes a discontinuity in the derivative.
// So we need to guard against searching near such times.
let rlon_lo: number, rlon_hi: number, adjust_days: number;
if (rlon >= -s1 && rlon < +s1) {
// Seek to the window [+s1, +s2].
adjust_days = 0;
// Search forward for the time t1 when rel lon = +s1.
rlon_lo = +s1;
// Search forward for the time t2 when rel lon = +s2.
rlon_hi = +s2;
} else if (rlon >= +s2 || rlon < -s2) {
// Seek to the next search window at [-s2, -s1].
adjust_days = 0;
// Search forward for the time t1 when rel lon = -s2.
rlon_lo = -s2;
// Search forward for the time t2 when rel lon = -s1.
rlon_hi = -s1;
} else if (rlon >= 0) {
// rlon must be in the middle of the window [+s1, +s2].
// Search BACKWARD for the time t1 when rel lon = +s1.
adjust_days = -SynodicPeriod(body) / 4;
rlon_lo = +s1;
// Search forward from t1 to find t2 such that rel lon = +s2.
rlon_hi = +s2;
} else {
// rlon must be in the middle of the window [-s2, -s1].
// Search BACKWARD for the time t1 when rel lon = -s2.
adjust_days = -SynodicPeriod(body) / 4;
rlon_lo = -s2;
// Search forward from t1 to find t2 such that rel lon = -s1.
rlon_hi = -s1;
}
let t_start = startTime.AddDays(adjust_days);
let t1 = SearchRelativeLongitude(body, rlon_lo, t_start);
let t2 = SearchRelativeLongitude(body, rlon_hi, t1);
// Now we have a time range [t1,t2] that brackets a maximum magnitude event.
// Confirm the bracketing.
let m1 = slope(t1);
if (m1 >= 0)
throw `SearchPeakMagnitude: internal error: m1 = ${m1}`;
let m2 = slope(t2);
if (m2 <= 0)
throw `SearchPeakMagnitude: internal error: m2 = ${m2}`;
// Use the generic search algorithm to home in on where the slope crosses from negative to positive.
let tx = Search(slope, t1, t2, {init_f1: m1, init_f2: m2, dt_tolerance_seconds: 10});
if (!tx)
throw `SearchPeakMagnitude: failed search iter ${iter} (t1=${t1.toString()}, t2=${t2.toString()})`;
if (tx.tt >= startTime.tt)
return Illumination(body, tx);
// This event is in the past (earlier than startDate).
// We need to search forward from t2 to find the next possible window.
// We never need to search more than twice.
startTime = t2.AddDays(1);
}
throw `SearchPeakMagnitude: failed to find event after 2 tries.`;
}
/**
* @brief A closest or farthest point in a body's orbit around its primary.
*
* For a planet orbiting the Sun, apsis is a perihelion or aphelion, respectively.
* For the Moon orbiting the Earth, apsis is a perigee or apogee, respectively.
*
* @property {AstroTime} time
* The date and time of the apsis.
*
* @property {number} kind
* For a closest approach (perigee or perihelion), `kind` is 0.
* For a farthest distance event (apogee or aphelion), `kind` is 1.
*
* @property {number} dist_au
* The distance between the centers of the two bodies in astronomical units (AU).
*
* @property {number} dist_km
* The distance between the centers of the two bodies in kilometers.
*
* @see {@link SearchLunarApsis}
* @see {@link NextLunarApsis}
*/
export class Apsis {
dist_km: number;
constructor(
public time: AstroTime,
public kind: number,
public dist_au: number) {
this.dist_km = dist_au * KM_PER_AU;
}
}
/**
* @brief Finds the next perigee or apogee of the Moon.
*
* Finds the next perigee (closest approach) or apogee (farthest remove) of the Moon
* that occurs after the specified date and time.
*
* @param {FlexibleDateTime} startDate
* The date and time after which to find the next perigee or apogee.
*
* @returns {Apsis}
*/
export function SearchLunarApsis(startDate: FlexibleDateTime): Apsis {
const dt = 0.001;
function distance_slope(t: AstroTime): number {
let t1 = t.AddDays(-dt / 2);
let t2 = t.AddDays(+dt / 2);
let r1 = CalcMoon(t1).distance_au;
let r2 = CalcMoon(t2).distance_au;
let m = (r2 - r1) / dt;
return m;
}
function negative_distance_slope(t: AstroTime): number {
return -distance_slope(t);
}
// Check the rate of change of the distance dr/dt at the start time.
// If it is positive, the Moon is currently getting farther away,
// so start looking for apogee.
// Conversely, if dr/dt < 0, start looking for perigee.
// Either way, the polarity of the slope will change, so the product will be negative.
// Handle the crazy corner case of exactly touching zero by checking for m1*m2 <= 0.
let t1 = MakeTime(startDate);
let m1 = distance_slope(t1);
const increment = 5; // number of days to skip in each iteration
for (var iter = 0; iter * increment < 2 * MEAN_SYNODIC_MONTH; ++iter) {
let t2 = t1.AddDays(increment);
let m2 = distance_slope(t2);
if (m1 * m2 <= 0) {
// The time range [t1, t2] contains an apsis.
// Figure out whether it is perigee or apogee.
if (m1 < 0 || m2 > 0) {
// We found a minimum distance event: perigee.
// Search the time range [t1, t2] for the time when the slope goes
// from negative to positive.
let tx = Search(distance_slope, t1, t2, {init_f1: m1, init_f2: m2});
if (!tx)
throw 'SearchLunarApsis INTERNAL ERROR: perigee search failed!';
let dist = CalcMoon(tx).distance_au;
return new Apsis(tx, 0, dist);
}
if (m1 > 0 || m2 < 0) {
// We found a maximum distance event: apogee.
// Search the time range [t1, t2] for the time when the slope goes
// from positive to negative.
let tx = Search(negative_distance_slope, t1, t2, {init_f1: -m1, init_f2: -m2});
if (!tx)
throw 'SearchLunarApsis INTERNAL ERROR: apogee search failed!';
let dist = CalcMoon(tx).distance_au;
return new Apsis(tx, 1, dist);
}
// This should never happen; it should not be possible for consecutive
// times t1 and t2 to both have zero slope.
throw 'SearchLunarApsis INTERNAL ERROR: cannot classify apsis event!';
}
t1 = t2;
m1 = m2;
}
// It should not be possible to fail to find an apsis within 2 synodic months.
throw 'SearchLunarApsis INTERNAL ERROR: could not find apsis within 2 synodic months of start date.';
}
/**
* @brief Finds the next lunar apsis (perigee or apogee) in a series.
*
* Given a lunar apsis returned by an initial call to {@link SearchLunarApsis},
* or a previous call to `NextLunarApsis`, finds the next lunar apsis.
* If the given apsis is a perigee, this function finds the next apogee, and vice versa.
*
* @param {Apsis} apsis
* A lunar perigee or apogee event.
*
* @returns {Apsis}
* The successor apogee for the given perigee, or the successor perigee for the given apogee.
*/
export function NextLunarApsis(apsis: Apsis): Apsis {
const skip = 11; // number of days to skip to start looking for next apsis event
let next = SearchLunarApsis(apsis.time.AddDays(skip));
if (next.kind + apsis.kind !== 1)
throw `NextLunarApsis INTERNAL ERROR: did not find alternating apogee/perigee: prev=${apsis.kind} @ ${apsis.time.toString()}, next=${next.kind} @ ${next.time.toString()}`;
return next;
}
function PlanetExtreme(body: Body, kind: number, start_time: AstroTime, dayspan: number): Apsis {
const direction = (kind === 1) ? +1.0 : -1.0;
const npoints = 10;
for (; ;) {
const interval = dayspan / (npoints - 1);
// iterate until uncertainty is less than one minute
if (interval < 1.0 / 1440.0) {
const apsis_time = start_time.AddDays(interval / 2.0);
const dist_au = HelioDistance(body, apsis_time);
return new Apsis(apsis_time, kind, dist_au);
}
let best_i = -1;
let best_dist = 0.0;
for (let i = 0; i < npoints; ++i) {
const time = start_time.AddDays(i * interval);
const dist = direction * HelioDistance(body, time);
if (i == 0 || dist > best_dist) {
best_i = i;
best_dist = dist;
}
}
/* Narrow in on the extreme point. */
start_time = start_time.AddDays((best_i - 1) * interval);
dayspan = 2.0 * interval;
}
}
function BruteSearchPlanetApsis(body: Body, startTime: AstroTime): Apsis {
/*
Neptune is a special case for two reasons:
1. Its orbit is nearly circular (low orbital eccentricity).
2. It is so distant from the Sun that the orbital period is very long.
Put together, this causes wobbling of the Sun around the Solar System Barycenter (SSB)
to be so significant that there are 3 local minima in the distance-vs-time curve
near each apsis. Therefore, unlike for other planets, we can't use an optimized
algorithm for finding dr/dt = 0.
Instead, we use a dumb, brute-force algorithm of sampling and finding min/max
heliocentric distance.
There is a similar problem in the TOP2013 model for Pluto:
Its position vector has high-frequency oscillations that confuse the
slope-based determination of apsides.
*/
/*
Rewind approximately 30 degrees in the orbit,
then search forward for 270 degrees.
This is a very cautious way to prevent missing an apsis.
Typically we will find two apsides, and we pick whichever
apsis is ealier, but after startTime.
Sample points around this orbital arc and find when the distance
is greatest and smallest.
*/
const npoints = 100;
const t1 = startTime.AddDays(Planet[body].OrbitalPeriod * (-30 / 360));
const t2 = startTime.AddDays(Planet[body].OrbitalPeriod * (+270 / 360));
let t_min = t1;
let t_max = t1;
let min_dist = -1.0;
let max_dist = -1.0;
const interval = (t2.ut - t1.ut) / (npoints - 1);
for (let i = 0; i < npoints; ++i) {
const time = t1.AddDays(i * interval);
const dist = HelioDistance(body, time);
if (i === 0) {
max_dist = min_dist = dist;
} else {
if (dist > max_dist) {
max_dist = dist;
t_max = time;
}
if (dist < min_dist) {
min_dist = dist;
t_min = time;
}
}
}
const perihelion = PlanetExtreme(body, 0, t_min.AddDays(-2 * interval), 4 * interval);
const aphelion = PlanetExtreme(body, 1, t_max.AddDays(-2 * interval), 4 * interval);
if (perihelion.time.tt >= startTime.tt) {
if (aphelion.time.tt >= startTime.tt && aphelion.time.tt < perihelion.time.tt)
return aphelion;
return perihelion;
}
if (aphelion.time.tt >= startTime.tt)
return aphelion;
throw 'Internal error: failed to find Neptune apsis.';
}
/**
* @brief Finds the next perihelion or aphelion of a planet.
*
* Finds the date and time of a planet's perihelion (closest approach to the Sun)
* or aphelion (farthest distance from the Sun) after a given time.
*
* Given a date and time to start the search in `startTime`, this function finds the
* next date and time that the center of the specified planet reaches the closest or farthest point
* in its orbit with respect to the center of the Sun, whichever comes first
* after `startTime`.
*
* The closest point is called *perihelion* and the farthest point is called *aphelion*.
* The word *apsis* refers to either event.
*
* To iterate through consecutive alternating perihelion and aphelion events,
* call `SearchPlanetApsis` once, then use the return value to call
* {@link NextPlanetApsis}. After that, keep feeding the previous return value
* from `NextPlanetApsis` into another call of `NextPlanetApsis`
* as many times as desired.
*
* @param {Body} body
* The planet for which to find the next perihelion/aphelion event.
* Not allowed to be `"Sun"` or `"Moon"`.
*
* @param {AstroTime} startTime
* The date and time at which to start searching for the next perihelion or aphelion.
*
* @returns {Apsis}
* The next perihelion or aphelion that occurs after `startTime`.
*/
export function SearchPlanetApsis(body: Body, startTime: AstroTime): Apsis {
if (body === Body.Neptune || body === Body.Pluto)
return BruteSearchPlanetApsis(body, startTime);
function positive_slope(t: AstroTime): number {
const dt = 0.001;
let t1 = t.AddDays(-dt / 2);
let t2 = t.AddDays(+dt / 2);
let r1 = HelioDistance(body, t1);
let r2 = HelioDistance(body, t2);
let m = (r2 - r1) / dt;
return m;
}
function negative_slope(t: AstroTime): number {
return -positive_slope(t);
}
const orbit_period_days = Planet[body].OrbitalPeriod;
const increment = orbit_period_days / 6.0;
let t1 = startTime;
let m1 = positive_slope(t1);
for (let iter = 0; iter * increment < 2.0 * orbit_period_days; ++iter) {
const t2 = t1.AddDays(increment);
const m2 = positive_slope(t2);
if (m1 * m2 <= 0.0) {
/* There is a change of slope polarity within the time range [t1, t2]. */
/* Therefore this time range contains an apsis. */
/* Figure out whether it is perihelion or aphelion. */
let slope_func: (t: AstroTime) => number;
let kind: number;
if (m1 < 0.0 || m2 > 0.0) {
/* We found a minimum-distance event: perihelion. */
/* Search the time range for the time when the slope goes from negative to positive. */
slope_func = positive_slope;
kind = 0; // perihelion
} else if (m1 > 0.0 || m2 < 0.0) {
/* We found a maximum-distance event: aphelion. */
/* Search the time range for the time when the slope goes from positive to negative. */
slope_func = negative_slope;
kind = 1; // aphelion
} else {
/* This should never happen. It should not be possible for both slopes to be zero. */
throw "Internal error with slopes in SearchPlanetApsis";
}
const search = Search(slope_func, t1, t2);
if (!search)
throw "Failed to find slope transition in planetary apsis search.";
const dist = HelioDistance(body, search);
return new Apsis(search, kind, dist);
}
/* We have not yet found a slope polarity change. Keep searching. */
t1 = t2;
m1 = m2;
}
throw "Internal error: should have found planetary apsis within 2 orbital periods.";
}
/**
* @brief Finds the next planetary perihelion or aphelion event in a series.
*
* This function requires an {@link Apsis} value obtained from a call
* to {@link SearchPlanetApsis} or `NextPlanetApsis`.
* Given an aphelion event, this function finds the next perihelion event, and vice versa.
* See {@link SearchPlanetApsis} for more details.
*
* @param {Body} body
* The planet for which to find the next perihelion/aphelion event.
* Not allowed to be `"Sun"` or `"Moon"`.
* Must match the body passed into the call that produced the `apsis` parameter.
*
* @param {Apsis} apsis
* An apsis event obtained from a call to {@link SearchPlanetApsis} or `NextPlanetApsis`.
*
* @returns {Apsis}
* Same as the return value for {@link SearchPlanetApsis}.
*/
export function NextPlanetApsis(body: Body, apsis: Apsis): Apsis {
if (apsis.kind !== 0 && apsis.kind !== 1)
throw `Invalid apsis kind: ${apsis.kind}`;
/* skip 1/4 of an orbit before starting search again */
const skip = 0.25 * Planet[body].OrbitalPeriod;
const time = apsis.time.AddDays(skip);
const next = SearchPlanetApsis(body, time);
/* Verify that we found the opposite apsis from the previous one. */
if (next.kind + apsis.kind !== 1)
throw `Internal error: previous apsis was ${apsis.kind}, but found ${next.kind} for next apsis.`;
return next;
}
/**
* @brief Calculates the inverse of a rotation matrix.
*
* Given a rotation matrix that performs some coordinate transform,
* this function returns the matrix that reverses that trasnform.
*
* @param {RotationMatrix} rotation
* The rotation matrix to be inverted.
*
* @returns {RotationMatrix}
* The inverse rotation matrix.
*/
export function InverseRotation(rotation: RotationMatrix): RotationMatrix {
return new RotationMatrix([
[rotation.rot[0][0], rotation.rot[1][0], rotation.rot[2][0]],
[rotation.rot[0][1], rotation.rot[1][1], rotation.rot[2][1]],
[rotation.rot[0][2], rotation.rot[1][2], rotation.rot[2][2]]
]);
}
/**
* @brief Creates a rotation based on applying one rotation followed by another.
*
* Given two rotation matrices, returns a combined rotation matrix that is
* equivalent to rotating based on the first matrix, followed by the second.
*
* @param {RotationMatrix} a
* The first rotation to apply.
*
* @param {RotationMatrix} b
* The second rotation to apply.
*
* @returns {RotationMatrix}
* The combined rotation matrix.
*/
export function CombineRotation(a: RotationMatrix, b: RotationMatrix): RotationMatrix {
/*
Use matrix multiplication: c = b*a.
We put 'b' on the left and 'a' on the right because,
just like when you use a matrix M to rotate a vector V,
you put the M on the left in the product M*V.
We can think of this as 'b' rotating all the 3 column vectors in 'a'.
*/
return new RotationMatrix([
[
b.rot[0][0] * a.rot[0][0] + b.rot[1][0] * a.rot[0][1] + b.rot[2][0] * a.rot[0][2],
b.rot[0][1] * a.rot[0][0] + b.rot[1][1] * a.rot[0][1] + b.rot[2][1] * a.rot[0][2],
b.rot[0][2] * a.rot[0][0] + b.rot[1][2] * a.rot[0][1] + b.rot[2][2] * a.rot[0][2]
],
[
b.rot[0][0] * a.rot[1][0] + b.rot[1][0] * a.rot[1][1] + b.rot[2][0] * a.rot[1][2],
b.rot[0][1] * a.rot[1][0] + b.rot[1][1] * a.rot[1][1] + b.rot[2][1] * a.rot[1][2],
b.rot[0][2] * a.rot[1][0] + b.rot[1][2] * a.rot[1][1] + b.rot[2][2] * a.rot[1][2]
],
[
b.rot[0][0] * a.rot[2][0] + b.rot[1][0] * a.rot[2][1] + b.rot[2][0] * a.rot[2][2],
b.rot[0][1] * a.rot[2][0] + b.rot[1][1] * a.rot[2][1] + b.rot[2][1] * a.rot[2][2],
b.rot[0][2] * a.rot[2][0] + b.rot[1][2] * a.rot[2][1] + b.rot[2][2] * a.rot[2][2]
]
]);
}
/**
* @brief Creates an identity rotation matrix.
*
* Returns a rotation matrix that has no effect on orientation.
* This matrix can be the starting point for other operations,
* such as using a series of calls to {@link Pivot} to
* create a custom rotation matrix.
*
* @returns {RotationMatrix}
* The identity matrix.
*/
export function IdentityMatrix(): RotationMatrix {
return new RotationMatrix([
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]
]);
}
/**
* @brief Re-orients a rotation matrix by pivoting it by an angle around one of its axes.
*
* Given a rotation matrix, a selected coordinate axis, and an angle in degrees,
* this function pivots the rotation matrix by that angle around that coordinate axis.
*
* For example, if you have rotation matrix that converts ecliptic coordinates (ECL)
* to horizontal coordinates (HOR), but you really want to convert ECL to the orientation
* of a telescope camera pointed at a given body, you can use `Astronomy_Pivot` twice:
* (1) pivot around the zenith axis by the body's azimuth, then (2) pivot around the
* western axis by the body's altitude angle. The resulting rotation matrix will then
* reorient ECL coordinates to the orientation of your telescope camera.
*
* @param {RotationMatrix} rotation
* The input rotation matrix.
*
* @param {number} axis
* An integer that selects which coordinate axis to rotate around:
* 0 = x, 1 = y, 2 = z. Any other value will cause an exception.
*
* @param {number} angle
* An angle in degrees indicating the amount of rotation around the specified axis.
* Positive angles indicate rotation counterclockwise as seen from the positive
* direction along that axis, looking towards the origin point of the orientation system.
* Any finite number of degrees is allowed, but best precision will result from
* keeping `angle` in the range [-360, +360].
*
* @returns {RotationMatrix}
* A pivoted matrix object.
*/
export function Pivot(rotation: RotationMatrix, axis: 0 | 1 | 2, angle: number): RotationMatrix {
// Check for an invalid coordinate axis.
if (axis !== 0 && axis !== 1 && axis !== 2)
throw `Invalid axis ${axis}. Must be [0, 1, 2].`;
const radians = VerifyNumber(angle) * DEG2RAD;
const c = Math.cos(radians);
const s = Math.sin(radians);
/*
We need to maintain the "right-hand" rule, no matter which
axis was selected. That means we pick (i, j, k) axis order
such that the following vector cross product is satisfied:
i x j = k
*/
const i = (axis + 1) % 3;
const j = (axis + 2) % 3;
const k = axis;
let rot = [[0, 0, 0], [0, 0, 0], [0, 0, 0]];
rot[i][i] = c * rotation.rot[i][i] - s * rotation.rot[i][j];
rot[i][j] = s * rotation.rot[i][i] + c * rotation.rot[i][j];
rot[i][k] = rotation.rot[i][k];
rot[j][i] = c * rotation.rot[j][i] - s * rotation.rot[j][j];
rot[j][j] = s * rotation.rot[j][i] + c * rotation.rot[j][j];
rot[j][k] = rotation.rot[j][k];
rot[k][i] = c * rotation.rot[k][i] - s * rotation.rot[k][j];
rot[k][j] = s * rotation.rot[k][i] + c * rotation.rot[k][j];
rot[k][k] = rotation.rot[k][k];
return new RotationMatrix(rot);
}
/**
* @brief Converts spherical coordinates to Cartesian coordinates.
*
* Given spherical coordinates and a time at which they are valid,
* returns a vector of Cartesian coordinates. The returned value
* includes the time, as required by `AstroTime`.
*
* @param {Spherical} sphere
* Spherical coordinates to be converted.
*
* @param {AstroTime} time
* The time that should be included in the returned vector.
*
* @returns {Vector}
* The vector form of the supplied spherical coordinates.
*/
export function VectorFromSphere(sphere: Spherical, time: AstroTime): Vector {
const radlat = sphere.lat * DEG2RAD;
const radlon = sphere.lon * DEG2RAD;
const rcoslat = sphere.dist * Math.cos(radlat);
return new Vector(
rcoslat * Math.cos(radlon),
rcoslat * Math.sin(radlon),
sphere.dist * Math.sin(radlat),
time
);
}
/**
* @brief Given an equatorial vector, calculates equatorial angular coordinates.
*
* @param {Vector} vec
* A vector in an equatorial coordinate system.
*
* @returns {EquatorialCoordinates}
* Angular coordinates expressed in the same equatorial system as `vec`.
*/
export function EquatorFromVector(vec: Vector): EquatorialCoordinates {
const sphere = SphereFromVector(vec);
return new EquatorialCoordinates(sphere.lon / 15, sphere.lat, sphere.dist, vec);
}
/**
* @brief Converts Cartesian coordinates to spherical coordinates.
*
* Given a Cartesian vector, returns latitude, longitude, and distance.
*
* @param {Vector} vector
* Cartesian vector to be converted to spherical coordinates.
*
* @returns {Spherical}
* Spherical coordinates that are equivalent to the given vector.
*/
export function SphereFromVector(vector: Vector): Spherical {
const xyproj = vector.x * vector.x + vector.y * vector.y;
const dist = Math.sqrt(xyproj + vector.z * vector.z);
let lat: number, lon: number;
if (xyproj === 0.0) {
if (vector.z === 0.0)
throw 'Zero-length vector not allowed.';
lon = 0.0;
lat = (vector.z < 0.0) ? -90.0 : +90.0;
} else {
lon = RAD2DEG * Math.atan2(vector.y, vector.x);
if (lon < 0.0)
lon += 360.0;
lat = RAD2DEG * Math.atan2(vector.z, Math.sqrt(xyproj));
}
return new Spherical(lat, lon, dist);
}
function ToggleAzimuthDirection(az: number): number {
az = 360.0 - az;
if (az >= 360.0)
az -= 360.0;
else if (az < 0.0)
az += 360.0;
return az;
}
/**
* @brief Converts Cartesian coordinates to horizontal coordinates.
*
* Given a horizontal Cartesian vector, returns horizontal azimuth and altitude.
*
* *IMPORTANT:* This function differs from {@link SphereFromVector} in two ways:
* - `SphereFromVector` returns a `lon` value that represents azimuth defined counterclockwise
* from north (e.g., west = +90), but this function represents a clockwise rotation
* (e.g., east = +90). The difference is because `SphereFromVector` is intended
* to preserve the vector "right-hand rule", while this function defines azimuth in a more
* traditional way as used in navigation and cartography.
* - This function optionally corrects for atmospheric refraction, while `SphereFromVector` does not.
*
* The returned object contains the azimuth in `lon`.
* It is measured in degrees clockwise from north: east = +90 degrees, west = +270 degrees.
*
* The altitude is stored in `lat`.
*
* The distance to the observed object is stored in `dist`,
* and is expressed in astronomical units (AU).
*
* @param {Vector} vector
* Cartesian vector to be converted to horizontal coordinates.
*
* @param {string} refraction
* `"normal"`: correct altitude for atmospheric refraction (recommended).
* `"jplhor"`: for JPL Horizons compatibility testing only; not recommended for normal use.
* `null`: no atmospheric refraction correction is performed.
*
* @returns {Spherical}
*/
export function HorizonFromVector(vector: Vector, refraction: string): Spherical {
const sphere = SphereFromVector(vector);
sphere.lon = ToggleAzimuthDirection(sphere.lon);
sphere.lat += Refraction(refraction, sphere.lat);
return sphere;
}
/**
* @brief Given apparent angular horizontal coordinates in `sphere`, calculate horizontal vector.
*
* @param {Spherical} sphere
* A structure that contains apparent horizontal coordinates:
* `lat` holds the refracted azimuth angle,
* `lon` holds the azimuth in degrees clockwise from north,
* and `dist` holds the distance from the observer to the object in AU.
*
* @param {AstroTime} time
* The date and time of the observation. This is needed because the returned
* vector object requires a valid time value when passed to certain other functions.
*
* @param {string} refraction
* `"normal"`: correct altitude for atmospheric refraction (recommended).
* `"jplhor"`: for JPL Horizons compatibility testing only; not recommended for normal use.
* `null`: no atmospheric refraction correction is performed.
*
* @returns {Vector}
* A vector in the horizontal system: `x` = north, `y` = west, and `z` = zenith (up).
*/
export function VectorFromHorizon(sphere: Spherical, time: AstroTime, refraction: string): Vector {
/* Convert azimuth from clockwise-from-north to counterclockwise-from-north. */
const lon = ToggleAzimuthDirection(sphere.lon);
/* Reverse any applied refraction. */
const lat = sphere.lat + InverseRefraction(refraction, sphere.lat);
const xsphere = new Spherical(lat, lon, sphere.dist);
return VectorFromSphere(xsphere, time);
}
/**
* @brief Calculates the amount of "lift" to an altitude angle caused by atmospheric refraction.
*
* Given an altitude angle and a refraction option, calculates
* the amount of "lift" caused by atmospheric refraction.
* This is the number of degrees higher in the sky an object appears
* due to the lensing of the Earth's atmosphere.
*
* @param {string} refraction
* `"normal"`: correct altitude for atmospheric refraction (recommended).
* `"jplhor"`: for JPL Horizons compatibility testing only; not recommended for normal use.
* `null`: no atmospheric refraction correction is performed.
*
* @param {number} altitude
* An altitude angle in a horizontal coordinate system. Must be a value between -90 and +90.
*
* @returns {number}
* The angular adjustment in degrees to be added to the altitude angle to correct for atmospheric lensing.
*/
export function Refraction(refraction: string, altitude: number): number {
let refr: number;
VerifyNumber(altitude);
if (altitude < -90.0 || altitude > +90.0)
return 0.0; /* no attempt to correct an invalid altitude */
if (refraction === 'normal' || refraction === 'jplhor') {
// http://extras.springer.com/1999/978-1-4471-0555-8/chap4/horizons/horizons.pdf
// JPL Horizons says it uses refraction algorithm from
// Meeus "Astronomical Algorithms", 1991, p. 101-102.
// I found the following Go implementation:
// https://github.com/soniakeys/meeus/blob/master/v3/refraction/refract.go
// This is a translation from the function "Saemundsson" there.
// I found experimentally that JPL Horizons clamps the angle to 1 degree below the horizon.
// This is important because the 'refr' formula below goes crazy near hd = -5.11.
let hd = altitude;
if (hd < -1.0)
hd = -1.0;
refr = (1.02 / Math.tan((hd + 10.3 / (hd + 5.11)) * DEG2RAD)) / 60.0;
if (refraction === 'normal' && altitude < -1.0) {
// In "normal" mode we gradually reduce refraction toward the nadir
// so that we never get an altitude angle less than -90 degrees.
// When horizon angle is -1 degrees, the factor is exactly 1.
// As altitude approaches -90 (the nadir), the fraction approaches 0 linearly.
refr *= (altitude + 90.0) / 89.0;
}
} else {
/* No refraction, or the refraction option is invalid. */
refr = 0.0;
}
return refr;
}
/**
* @brief Calculates the inverse of an atmospheric refraction angle.
*
* Given an observed altitude angle that includes atmospheric refraction,
* calculate the negative angular correction to obtain the unrefracted
* altitude. This is useful for cases where observed horizontal
* coordinates are to be converted to another orientation system,
* but refraction first must be removed from the observed position.
*
* @param {string} refraction
* `"normal"`: correct altitude for atmospheric refraction (recommended).
* `"jplhor"`: for JPL Horizons compatibility testing only; not recommended for normal use.
* `null`: no atmospheric refraction correction is performed.
*
* @param {number} bent_altitude
* The apparent altitude that includes atmospheric refraction.
*
* @returns {number}
* The angular adjustment in degrees to be added to the
* altitude angle to correct for atmospheric lensing.
* This will be less than or equal to zero.
*/
export function InverseRefraction(refraction: string, bent_altitude: number): number {
if (bent_altitude < -90.0 || bent_altitude > +90.0)
return 0.0; /* no attempt to correct an invalid altitude */
/* Find the pre-adjusted altitude whose refraction correction leads to 'altitude'. */
let altitude = bent_altitude - Refraction(refraction, bent_altitude);
for (; ;) {
/* See how close we got. */
let diff = (altitude + Refraction(refraction, altitude)) - bent_altitude;
if (Math.abs(diff) < 1.0e-14)
return altitude - bent_altitude;
altitude -= diff;
}
}
/**
* @brief Applies a rotation to a vector, yielding a rotated vector.
*
* This function transforms a vector in one orientation to a vector
* in another orientation.
*
* @param {RotationMatrix} rotation
* A rotation matrix that specifies how the orientation of the vector is to be changed.
*
* @param {Vector} vector
* The vector whose orientation is to be changed.
*
* @returns {Vector}
* A vector in the orientation specified by `rotation`.
*/
export function RotateVector(rotation: RotationMatrix, vector: Vector): Vector {
return new Vector(
rotation.rot[0][0] * vector.x + rotation.rot[1][0] * vector.y + rotation.rot[2][0] * vector.z,
rotation.rot[0][1] * vector.x + rotation.rot[1][1] * vector.y + rotation.rot[2][1] * vector.z,
rotation.rot[0][2] * vector.x + rotation.rot[1][2] * vector.y + rotation.rot[2][2] * vector.z,
vector.t
);
}
/**
* @brief Applies a rotation to a state vector, yielding a rotated vector.
*
* This function transforms a state vector in one orientation to a vector
* in another orientation.
*
* @param {RotationMatrix} rotation
* A rotation matrix that specifies how the orientation of the state vector is to be changed.
*
* @param {StateVector} state
* The state vector whose orientation is to be changed.
* Both the position and velocity components are transformed.
*
* @return {StateVector}
* A state vector in the orientation specified by `rotation`.
*/
export function RotateState(rotation: RotationMatrix, state: StateVector): StateVector {
return new StateVector(
rotation.rot[0][0] * state.x + rotation.rot[1][0] * state.y + rotation.rot[2][0] * state.z,
rotation.rot[0][1] * state.x + rotation.rot[1][1] * state.y + rotation.rot[2][1] * state.z,
rotation.rot[0][2] * state.x + rotation.rot[1][2] * state.y + rotation.rot[2][2] * state.z,
rotation.rot[0][0] * state.vx + rotation.rot[1][0] * state.vy + rotation.rot[2][0] * state.vz,
rotation.rot[0][1] * state.vx + rotation.rot[1][1] * state.vy + rotation.rot[2][1] * state.vz,
rotation.rot[0][2] * state.vx + rotation.rot[1][2] * state.vy + rotation.rot[2][2] * state.vz,
state.t
);
}
/**
* @brief Calculates a rotation matrix from equatorial J2000 (EQJ) to ecliptic J2000 (ECL).
*
* This is one of the family of functions that returns a rotation matrix
* for converting from one orientation to another.
* Source: EQJ = equatorial system, using equator at J2000 epoch.
* Target: ECL = ecliptic system, using equator at J2000 epoch.
*
* @returns {RotationMatrix}
* A rotation matrix that converts EQJ to ECL.
*/
export function Rotation_EQJ_ECL(): RotationMatrix {
/* ob = mean obliquity of the J2000 ecliptic = 0.40909260059599012 radians. */
const c = 0.9174821430670688; /* cos(ob) */
const s = 0.3977769691083922; /* sin(ob) */
return new RotationMatrix([
[1, 0, 0],
[0, +c, -s],
[0, +s, +c]
]);
}
/**
* @brief Calculates a rotation matrix from ecliptic J2000 (ECL) to equatorial J2000 (EQJ).
*
* This is one of the family of functions that returns a rotation matrix
* for converting from one orientation to another.
* Source: ECL = ecliptic system, using equator at J2000 epoch.
* Target: EQJ = equatorial system, using equator at J2000 epoch.
*
* @returns {RotationMatrix}
* A rotation matrix that converts ECL to EQJ.
*/
export function Rotation_ECL_EQJ(): RotationMatrix {
/* ob = mean obliquity of the J2000 ecliptic = 0.40909260059599012 radians. */
const c = 0.9174821430670688; /* cos(ob) */
const s = 0.3977769691083922; /* sin(ob) */
return new RotationMatrix([
[1, 0, 0],
[0, +c, +s],
[0, -s, +c]
]);
}
/**
* @brief Calculates a rotation matrix from equatorial J2000 (EQJ) to equatorial of-date (EQD).
*
* This is one of the family of functions that returns a rotation matrix
* for converting from one orientation to another.
* Source: EQJ = equatorial system, using equator at J2000 epoch.
* Target: EQD = equatorial system, using equator of the specified date/time.
*
* @param {FlexibleDateTime} time
* The date and time at which the Earth's equator defines the target orientation.
*
* @returns {RotationMatrix}
* A rotation matrix that converts EQJ to EQD at `time`.
*/
export function Rotation_EQJ_EQD(time: FlexibleDateTime): RotationMatrix {
time = MakeTime(time);
const prec = precession_rot(time, PrecessDirection.From2000);
const nut = nutation_rot(time, PrecessDirection.From2000);
return CombineRotation(prec, nut);
}
/**
* @brief Calculates a rotation matrix from equatorial of-date (EQD) to equatorial J2000 (EQJ).
*
* This is one of the family of functions that returns a rotation matrix
* for converting from one orientation to another.
* Source: EQD = equatorial system, using equator of the specified date/time.
* Target: EQJ = equatorial system, using equator at J2000 epoch.
*
* @param {FlexibleDateTime} time
* The date and time at which the Earth's equator defines the source orientation.
*
* @returns {RotationMatrix}
* A rotation matrix that converts EQD at `time` to EQJ.
*/
export function Rotation_EQD_EQJ(time: FlexibleDateTime): RotationMatrix {
time = MakeTime(time);
const nut = nutation_rot(time, PrecessDirection.Into2000);
const prec = precession_rot(time, PrecessDirection.Into2000);
return CombineRotation(nut, prec);
}
/**
* @brief Calculates a rotation matrix from equatorial of-date (EQD) to horizontal (HOR).
*
* This is one of the family of functions that returns a rotation matrix
* for converting from one orientation to another.
* Source: EQD = equatorial system, using equator of the specified date/time.
* Target: HOR = horizontal system.
*
* Use `HorizonFromVector` to convert the return value
* to a traditional altitude/azimuth pair.
*
* @param {FlexibleDateTime} time
* The date and time at which the Earth's equator applies.
*
* @param {Observer} observer
* A location near the Earth's mean sea level that defines the observer's horizon.
*
* @returns {RotationMatrix}
* A rotation matrix that converts EQD to HOR at `time` and for `observer`.
* The components of the horizontal vector are:
* x = north, y = west, z = zenith (straight up from the observer).
* These components are chosen so that the "right-hand rule" works for the vector
* and so that north represents the direction where azimuth = 0.
*/
export function Rotation_EQD_HOR(time: FlexibleDateTime, observer: Observer): RotationMatrix {
time = MakeTime(time);
const sinlat = Math.sin(observer.latitude * DEG2RAD);
const coslat = Math.cos(observer.latitude * DEG2RAD);
const sinlon = Math.sin(observer.longitude * DEG2RAD);
const coslon = Math.cos(observer.longitude * DEG2RAD);
const uze: ArrayVector = [coslat * coslon, coslat * sinlon, sinlat];
const une: ArrayVector = [-sinlat * coslon, -sinlat * sinlon, coslat];
const uwe: ArrayVector = [sinlon, -coslon, 0];
const spin_angle = -15 * sidereal_time(time);
const uz = spin(spin_angle, uze);
const un = spin(spin_angle, une);
const uw = spin(spin_angle, uwe);
return new RotationMatrix([
[un[0], uw[0], uz[0]],
[un[1], uw[1], uz[1]],
[un[2], uw[2], uz[2]],
]);
}
/**
* @brief Calculates a rotation matrix from horizontal (HOR) to equatorial of-date (EQD).
*
* This is one of the family of functions that returns a rotation matrix
* for converting from one orientation to another.
* Source: HOR = horizontal system (x=North, y=West, z=Zenith).
* Target: EQD = equatorial system, using equator of the specified date/time.
*
* @param {FlexibleDateTime} time
* The date and time at which the Earth's equator applies.
*
* @param {Observer} observer
* A location near the Earth's mean sea level that defines the observer's horizon.
*
* @returns {RotationMatrix}
* A rotation matrix that converts HOR to EQD at `time` and for `observer`.
*/
export function Rotation_HOR_EQD(time: FlexibleDateTime, observer: Observer): RotationMatrix {
const rot = Rotation_EQD_HOR(time, observer);
return InverseRotation(rot);
}
/**
* @brief Calculates a rotation matrix from horizontal (HOR) to J2000 equatorial (EQJ).
*
* This is one of the family of functions that returns a rotation matrix
* for converting from one orientation to another.
* Source: HOR = horizontal system (x=North, y=West, z=Zenith).
* Target: EQJ = equatorial system, using equator at the J2000 epoch.
*
* @param {FlexibleDateTime} time
* The date and time of the observation.
*
* @param {Observer} observer
* A location near the Earth's mean sea level that defines the observer's horizon.
*
* @returns {RotationMatrix}
* A rotation matrix that converts HOR to EQD at `time` and for `observer`.
*/
export function Rotation_HOR_EQJ(time: FlexibleDateTime, observer: Observer): RotationMatrix {
time = MakeTime(time);
const hor_eqd = Rotation_HOR_EQD(time, observer);
const eqd_eqj = Rotation_EQD_EQJ(time);
return CombineRotation(hor_eqd, eqd_eqj);
}
/**
* @brief Calculates a rotation matrix from equatorial J2000 (EQJ) to horizontal (HOR).
*
* This is one of the family of functions that returns a rotation matrix
* for converting from one orientation to another.
* Source: EQJ = equatorial system, using the equator at the J2000 epoch.
* Target: HOR = horizontal system.
*
* Use {@link HorizonFromVector} to convert the return value
* to a traditional altitude/azimuth pair.
*
* @param {FlexibleDateTime} time
* The date and time of the desired horizontal orientation.
*
* @param {Observer} observer
* A location near the Earth's mean sea level that defines the observer's horizon.
*
* @return
* A rotation matrix that converts EQJ to HOR at `time` and for `observer`.
* The components of the horizontal vector are:
* x = north, y = west, z = zenith (straight up from the observer).
* These components are chosen so that the "right-hand rule" works for the vector
* and so that north represents the direction where azimuth = 0.
*/
export function Rotation_EQJ_HOR(time: FlexibleDateTime, observer: Observer): RotationMatrix {
const rot = Rotation_HOR_EQJ(time, observer);
return InverseRotation(rot);
}
/**
* @brief Calculates a rotation matrix from equatorial of-date (EQD) to ecliptic J2000 (ECL).
*
* This is one of the family of functions that returns a rotation matrix
* for converting from one orientation to another.
* Source: EQD = equatorial system, using equator of date.
* Target: ECL = ecliptic system, using equator at J2000 epoch.
*
* @param {FlexibleDateTime} time
* The date and time of the source equator.
*
* @returns {RotationMatrix}
* A rotation matrix that converts EQD to ECL.
*/
export function Rotation_EQD_ECL(time: FlexibleDateTime): RotationMatrix {
const eqd_eqj = Rotation_EQD_EQJ(time);
const eqj_ecl = Rotation_EQJ_ECL();
return CombineRotation(eqd_eqj, eqj_ecl);
}
/**
* @brief Calculates a rotation matrix from ecliptic J2000 (ECL) to equatorial of-date (EQD).
*
* This is one of the family of functions that returns a rotation matrix
* for converting from one orientation to another.
* Source: ECL = ecliptic system, using equator at J2000 epoch.
* Target: EQD = equatorial system, using equator of date.
*
* @param {FlexibleDateTime} time
* The date and time of the desired equator.
*
* @returns {RotationMatrix}
* A rotation matrix that converts ECL to EQD.
*/
export function Rotation_ECL_EQD(time: FlexibleDateTime): RotationMatrix {
const rot = Rotation_EQD_ECL(time);
return InverseRotation(rot);
}
/**
* @brief Calculates a rotation matrix from ecliptic J2000 (ECL) to horizontal (HOR).
*
* This is one of the family of functions that returns a rotation matrix
* for converting from one orientation to another.
* Source: ECL = ecliptic system, using equator at J2000 epoch.
* Target: HOR = horizontal system.
*
* Use {@link HorizonFromVector} to convert the return value
* to a traditional altitude/azimuth pair.
*
* @param {FlexibleDateTime} time
* The date and time of the desired horizontal orientation.
*
* @param {Observer} observer
* A location near the Earth's mean sea level that defines the observer's horizon.
*
* @returns {RotationMatrix}
* A rotation matrix that converts ECL to HOR at `time` and for `observer`.
* The components of the horizontal vector are:
* x = north, y = west, z = zenith (straight up from the observer).
* These components are chosen so that the "right-hand rule" works for the vector
* and so that north represents the direction where azimuth = 0.
*/
export function Rotation_ECL_HOR(time: FlexibleDateTime, observer: Observer): RotationMatrix {
time = MakeTime(time);
const ecl_eqd = Rotation_ECL_EQD(time);
const eqd_hor = Rotation_EQD_HOR(time, observer);
return CombineRotation(ecl_eqd, eqd_hor);
}
/**
* @brief Calculates a rotation matrix from horizontal (HOR) to ecliptic J2000 (ECL).
*
* This is one of the family of functions that returns a rotation matrix
* for converting from one orientation to another.
* Source: HOR = horizontal system.
* Target: ECL = ecliptic system, using equator at J2000 epoch.
*
* @param {FlexibleDateTime} time
* The date and time of the horizontal observation.
*
* @param {Observer} observer
* The location of the horizontal observer.
*
* @returns {RotationMatrix}
* A rotation matrix that converts HOR to ECL.
*/
export function Rotation_HOR_ECL(time: FlexibleDateTime, observer: Observer): RotationMatrix {
const rot = Rotation_ECL_HOR(time, observer);
return InverseRotation(rot);
}
/**
* @brief Calculates a rotation matrix from equatorial J2000 (EQJ) to galactic (GAL).
*
* This is one of the family of functions that returns a rotation matrix
* for converting from one orientation to another.
* Source: EQJ = equatorial system, using the equator at the J2000 epoch.
* Target: GAL = galactic system (IAU 1958 definition).
*
* @returns {RotationMatrix}
* A rotation matrix that converts EQJ to GAL.
*/
export function Rotation_EQJ_GAL(): RotationMatrix {
// This rotation matrix was calculated by the following script
// in this same source code repository:
// demo/python/galeqj_matrix.py
return new RotationMatrix([
[-0.0548624779711344, +0.4941095946388765, -0.8676668813529025],
[-0.8734572784246782, -0.4447938112296831, -0.1980677870294097],
[-0.4838000529948520, +0.7470034631630423, +0.4559861124470794]
]);
}
/**
* @brief Calculates a rotation matrix from galactic (GAL) to equatorial J2000 (EQJ).
*
* This is one of the family of functions that returns a rotation matrix
* for converting from one orientation to another.
* Source: GAL = galactic system (IAU 1958 definition).
* Target: EQJ = equatorial system, using the equator at the J2000 epoch.
*
* @returns {RotationMatrix}
* A rotation matrix that converts GAL to EQJ.
*/
export function Rotation_GAL_EQJ(): RotationMatrix {
// This rotation matrix was calculated by the following script
// in this same source code repository:
// demo/python/galeqj_matrix.py
return new RotationMatrix([
[-0.0548624779711344, -0.8734572784246782, -0.4838000529948520],
[+0.4941095946388765, -0.4447938112296831, +0.7470034631630423],
[-0.8676668813529025, -0.1980677870294097, +0.4559861124470794]
]);
}
const ConstelNames = [
['And', 'Andromeda'] // 0
, ['Ant', 'Antila'] // 1
, ['Aps', 'Apus'] // 2
, ['Aql', 'Aquila'] // 3
, ['Aqr', 'Aquarius'] // 4
, ['Ara', 'Ara'] // 5
, ['Ari', 'Aries'] // 6
, ['Aur', 'Auriga'] // 7
, ['Boo', 'Bootes'] // 8
, ['Cae', 'Caelum'] // 9
, ['Cam', 'Camelopardis'] // 10
, ['Cap', 'Capricornus'] // 11
, ['Car', 'Carina'] // 12
, ['Cas', 'Cassiopeia'] // 13
, ['Cen', 'Centaurus'] // 14
, ['Cep', 'Cepheus'] // 15
, ['Cet', 'Cetus'] // 16
, ['Cha', 'Chamaeleon'] // 17
, ['Cir', 'Circinus'] // 18
, ['CMa', 'Canis Major'] // 19
, ['CMi', 'Canis Minor'] // 20
, ['Cnc', 'Cancer'] // 21
, ['Col', 'Columba'] // 22
, ['Com', 'Coma Berenices'] // 23
, ['CrA', 'Corona Australis'] // 24
, ['CrB', 'Corona Borealis'] // 25
, ['Crt', 'Crater'] // 26
, ['Cru', 'Crux'] // 27
, ['Crv', 'Corvus'] // 28
, ['CVn', 'Canes Venatici'] // 29
, ['Cyg', 'Cygnus'] // 30
, ['Del', 'Delphinus'] // 31
, ['Dor', 'Dorado'] // 32
, ['Dra', 'Draco'] // 33
, ['Equ', 'Equuleus'] // 34
, ['Eri', 'Eridanus'] // 35
, ['For', 'Fornax'] // 36
, ['Gem', 'Gemini'] // 37
, ['Gru', 'Grus'] // 38
, ['Her', 'Hercules'] // 39
, ['Hor', 'Horologium'] // 40
, ['Hya', 'Hydra'] // 41
, ['Hyi', 'Hydrus'] // 42
, ['Ind', 'Indus'] // 43
, ['Lac', 'Lacerta'] // 44
, ['Leo', 'Leo'] // 45
, ['Lep', 'Lepus'] // 46
, ['Lib', 'Libra'] // 47
, ['LMi', 'Leo Minor'] // 48
, ['Lup', 'Lupus'] // 49
, ['Lyn', 'Lynx'] // 50
, ['Lyr', 'Lyra'] // 51
, ['Men', 'Mensa'] // 52
, ['Mic', 'Microscopium'] // 53
, ['Mon', 'Monoceros'] // 54
, ['Mus', 'Musca'] // 55
, ['Nor', 'Norma'] // 56
, ['Oct', 'Octans'] // 57
, ['Oph', 'Ophiuchus'] // 58
, ['Ori', 'Orion'] // 59
, ['Pav', 'Pavo'] // 60
, ['Peg', 'Pegasus'] // 61
, ['Per', 'Perseus'] // 62
, ['Phe', 'Phoenix'] // 63
, ['Pic', 'Pictor'] // 64
, ['PsA', 'Pisces Austrinus'] // 65
, ['Psc', 'Pisces'] // 66
, ['Pup', 'Puppis'] // 67
, ['Pyx', 'Pyxis'] // 68
, ['Ret', 'Reticulum'] // 69
, ['Scl', 'Sculptor'] // 70
, ['Sco', 'Scorpius'] // 71
, ['Sct', 'Scutum'] // 72
, ['Ser', 'Serpens'] // 73
, ['Sex', 'Sextans'] // 74
, ['Sge', 'Sagitta'] // 75
, ['Sgr', 'Sagittarius'] // 76
, ['Tau', 'Taurus'] // 77
, ['Tel', 'Telescopium'] // 78
, ['TrA', 'Triangulum Australe'] // 79
, ['Tri', 'Triangulum'] // 80
, ['Tuc', 'Tucana'] // 81
, ['UMa', 'Ursa Major'] // 82
, ['UMi', 'Ursa Minor'] // 83
, ['Vel', 'Vela'] // 84
, ['Vir', 'Virgo'] // 85
, ['Vol', 'Volans'] // 86
, ['Vul', 'Vulpecula'] // 87
];
const ConstelBounds = [
[83, 0, 8640, 2112] // UMi
, [83, 2880, 5220, 2076] // UMi
, [83, 7560, 8280, 2068] // UMi
, [83, 6480, 7560, 2064] // UMi
, [15, 0, 2880, 2040] // Cep
, [10, 3300, 3840, 1968] // Cam
, [15, 0, 1800, 1920] // Cep
, [10, 3840, 5220, 1920] // Cam
, [83, 6300, 6480, 1920] // UMi
, [33, 7260, 7560, 1920] // Dra
, [15, 0, 1263, 1848] // Cep
, [10, 4140, 4890, 1848] // Cam
, [83, 5952, 6300, 1800] // UMi
, [15, 7260, 7440, 1800] // Cep
, [10, 2868, 3300, 1764] // Cam
, [33, 3300, 4080, 1764] // Dra
, [83, 4680, 5952, 1680] // UMi
, [13, 1116, 1230, 1632] // Cas
, [33, 7350, 7440, 1608] // Dra
, [33, 4080, 4320, 1596] // Dra
, [15, 0, 120, 1584] // Cep
, [83, 5040, 5640, 1584] // UMi
, [15, 8490, 8640, 1584] // Cep
, [33, 4320, 4860, 1536] // Dra
, [33, 4860, 5190, 1512] // Dra
, [15, 8340, 8490, 1512] // Cep
, [10, 2196, 2520, 1488] // Cam
, [33, 7200, 7350, 1476] // Dra
, [15, 7393.2, 7416, 1462] // Cep
, [10, 2520, 2868, 1440] // Cam
, [82, 2868, 3030, 1440] // UMa
, [33, 7116, 7200, 1428] // Dra
, [15, 7200, 7393.2, 1428] // Cep
, [15, 8232, 8340, 1418] // Cep
, [13, 0, 876, 1404] // Cas
, [33, 6990, 7116, 1392] // Dra
, [13, 612, 687, 1380] // Cas
, [13, 876, 1116, 1368] // Cas
, [10, 1116, 1140, 1368] // Cam
, [15, 8034, 8232, 1350] // Cep
, [10, 1800, 2196, 1344] // Cam
, [82, 5052, 5190, 1332] // UMa
, [33, 5190, 6990, 1332] // Dra
, [10, 1140, 1200, 1320] // Cam
, [15, 7968, 8034, 1320] // Cep
, [15, 7416, 7908, 1316] // Cep
, [13, 0, 612, 1296] // Cas
, [50, 2196, 2340, 1296] // Lyn
, [82, 4350, 4860, 1272] // UMa
, [33, 5490, 5670, 1272] // Dra
, [15, 7908, 7968, 1266] // Cep
, [10, 1200, 1800, 1260] // Cam
, [13, 8232, 8400, 1260] // Cas
, [33, 5670, 6120, 1236] // Dra
, [62, 735, 906, 1212] // Per
, [33, 6120, 6564, 1212] // Dra
, [13, 0, 492, 1200] // Cas
, [62, 492, 600, 1200] // Per
, [50, 2340, 2448, 1200] // Lyn
, [13, 8400, 8640, 1200] // Cas
, [82, 4860, 5052, 1164] // UMa
, [13, 0, 402, 1152] // Cas
, [13, 8490, 8640, 1152] // Cas
, [39, 6543, 6564, 1140] // Her
, [33, 6564, 6870, 1140] // Dra
, [30, 6870, 6900, 1140] // Cyg
, [62, 600, 735, 1128] // Per
, [82, 3030, 3300, 1128] // UMa
, [13, 60, 312, 1104] // Cas
, [82, 4320, 4350, 1080] // UMa
, [50, 2448, 2652, 1068] // Lyn
, [30, 7887, 7908, 1056] // Cyg
, [30, 7875, 7887, 1050] // Cyg
, [30, 6900, 6984, 1044] // Cyg
, [82, 3300, 3660, 1008] // UMa
, [82, 3660, 3882, 960] // UMa
, [8, 5556, 5670, 960] // Boo
, [39, 5670, 5880, 960] // Her
, [50, 3330, 3450, 954] // Lyn
, [0, 0, 906, 882] // And
, [62, 906, 924, 882] // Per
, [51, 6969, 6984, 876] // Lyr
, [62, 1620, 1689, 864] // Per
, [30, 7824, 7875, 864] // Cyg
, [44, 7875, 7920, 864] // Lac
, [7, 2352, 2652, 852] // Aur
, [50, 2652, 2790, 852] // Lyn
, [0, 0, 720, 840] // And
, [44, 7920, 8214, 840] // Lac
, [44, 8214, 8232, 828] // Lac
, [0, 8232, 8460, 828] // And
, [62, 924, 978, 816] // Per
, [82, 3882, 3960, 816] // UMa
, [29, 4320, 4440, 816] // CVn
, [50, 2790, 3330, 804] // Lyn
, [48, 3330, 3558, 804] // LMi
, [0, 258, 507, 792] // And
, [8, 5466, 5556, 792] // Boo
, [0, 8460, 8550, 770] // And
, [29, 4440, 4770, 768] // CVn
, [0, 8550, 8640, 752] // And
, [29, 5025, 5052, 738] // CVn
, [80, 870, 978, 736] // Tri
, [62, 978, 1620, 736] // Per
, [7, 1620, 1710, 720] // Aur
, [51, 6543, 6969, 720] // Lyr
, [82, 3960, 4320, 696] // UMa
, [30, 7080, 7530, 696] // Cyg
, [7, 1710, 2118, 684] // Aur
, [48, 3558, 3780, 684] // LMi
, [29, 4770, 5025, 684] // CVn
, [0, 0, 24, 672] // And
, [80, 507, 600, 672] // Tri
, [7, 2118, 2352, 672] // Aur
, [37, 2838, 2880, 672] // Gem
, [30, 7530, 7824, 672] // Cyg
, [30, 6933, 7080, 660] // Cyg
, [80, 690, 870, 654] // Tri
, [25, 5820, 5880, 648] // CrB
, [8, 5430, 5466, 624] // Boo
, [25, 5466, 5820, 624] // CrB
, [51, 6612, 6792, 624] // Lyr
, [48, 3870, 3960, 612] // LMi
, [51, 6792, 6933, 612] // Lyr
, [80, 600, 690, 600] // Tri
, [66, 258, 306, 570] // Psc
, [48, 3780, 3870, 564] // LMi
, [87, 7650, 7710, 564] // Vul
, [77, 2052, 2118, 548] // Tau
, [0, 24, 51, 528] // And
, [73, 5730, 5772, 528] // Ser
, [37, 2118, 2238, 516] // Gem
, [87, 7140, 7290, 510] // Vul
, [87, 6792, 6930, 506] // Vul
, [0, 51, 306, 504] // And
, [87, 7290, 7404, 492] // Vul
, [37, 2811, 2838, 480] // Gem
, [87, 7404, 7650, 468] // Vul
, [87, 6930, 7140, 460] // Vul
, [6, 1182, 1212, 456] // Ari
, [75, 6792, 6840, 444] // Sge
, [59, 2052, 2076, 432] // Ori
, [37, 2238, 2271, 420] // Gem
, [75, 6840, 7140, 388] // Sge
, [77, 1788, 1920, 384] // Tau
, [39, 5730, 5790, 384] // Her
, [75, 7140, 7290, 378] // Sge
, [77, 1662, 1788, 372] // Tau
, [77, 1920, 2016, 372] // Tau
, [23, 4620, 4860, 360] // Com
, [39, 6210, 6570, 344] // Her
, [23, 4272, 4620, 336] // Com
, [37, 2700, 2811, 324] // Gem
, [39, 6030, 6210, 308] // Her
, [61, 0, 51, 300] // Peg
, [77, 2016, 2076, 300] // Tau
, [37, 2520, 2700, 300] // Gem
, [61, 7602, 7680, 300] // Peg
, [37, 2271, 2496, 288] // Gem
, [39, 6570, 6792, 288] // Her
, [31, 7515, 7578, 284] // Del
, [61, 7578, 7602, 284] // Peg
, [45, 4146, 4272, 264] // Leo
, [59, 2247, 2271, 240] // Ori
, [37, 2496, 2520, 240] // Gem
, [21, 2811, 2853, 240] // Cnc
, [61, 8580, 8640, 240] // Peg
, [6, 600, 1182, 238] // Ari
, [31, 7251, 7308, 204] // Del
, [8, 4860, 5430, 192] // Boo
, [61, 8190, 8580, 180] // Peg
, [21, 2853, 3330, 168] // Cnc
, [45, 3330, 3870, 168] // Leo
, [58, 6570, 6718.4, 150] // Oph
, [3, 6718.4, 6792, 150] // Aql
, [31, 7500, 7515, 144] // Del
, [20, 2520, 2526, 132] // CMi
, [73, 6570, 6633, 108] // Ser
, [39, 5790, 6030, 96] // Her
, [58, 6570, 6633, 72] // Oph
, [61, 7728, 7800, 66] // Peg
, [66, 0, 720, 48] // Psc
, [73, 6690, 6792, 48] // Ser
, [31, 7308, 7500, 48] // Del
, [34, 7500, 7680, 48] // Equ
, [61, 7680, 7728, 48] // Peg
, [61, 7920, 8190, 48] // Peg
, [61, 7800, 7920, 42] // Peg
, [20, 2526, 2592, 36] // CMi
, [77, 1290, 1662, 0] // Tau
, [59, 1662, 1680, 0] // Ori
, [20, 2592, 2910, 0] // CMi
, [85, 5280, 5430, 0] // Vir
, [58, 6420, 6570, 0] // Oph
, [16, 954, 1182, -42] // Cet
, [77, 1182, 1290, -42] // Tau
, [73, 5430, 5856, -78] // Ser
, [59, 1680, 1830, -96] // Ori
, [59, 2100, 2247, -96] // Ori
, [73, 6420, 6468, -96] // Ser
, [73, 6570, 6690, -96] // Ser
, [3, 6690, 6792, -96] // Aql
, [66, 8190, 8580, -96] // Psc
, [45, 3870, 4146, -144] // Leo
, [85, 4146, 4260, -144] // Vir
, [66, 0, 120, -168] // Psc
, [66, 8580, 8640, -168] // Psc
, [85, 5130, 5280, -192] // Vir
, [58, 5730, 5856, -192] // Oph
, [3, 7200, 7392, -216] // Aql
, [4, 7680, 7872, -216] // Aqr
, [58, 6180, 6468, -240] // Oph
, [54, 2100, 2910, -264] // Mon
, [35, 1770, 1830, -264] // Eri
, [59, 1830, 2100, -264] // Ori
, [41, 2910, 3012, -264] // Hya
, [74, 3450, 3870, -264] // Sex
, [85, 4260, 4620, -264] // Vir
, [58, 6330, 6360, -280] // Oph
, [3, 6792, 7200, -288.8] // Aql
, [35, 1740, 1770, -348] // Eri
, [4, 7392, 7680, -360] // Aqr
, [73, 6180, 6570, -384] // Ser
, [72, 6570, 6792, -384] // Sct
, [41, 3012, 3090, -408] // Hya
, [58, 5856, 5895, -438] // Oph
, [41, 3090, 3270, -456] // Hya
, [26, 3870, 3900, -456] // Crt
, [71, 5856, 5895, -462] // Sco
, [47, 5640, 5730, -480] // Lib
, [28, 4530, 4620, -528] // Crv
, [85, 4620, 5130, -528] // Vir
, [41, 3270, 3510, -576] // Hya
, [16, 600, 954, -585.2] // Cet
, [35, 954, 1350, -585.2] // Eri
, [26, 3900, 4260, -588] // Crt
, [28, 4260, 4530, -588] // Crv
, [47, 5130, 5370, -588] // Lib
, [58, 5856, 6030, -590] // Oph
, [16, 0, 600, -612] // Cet
, [11, 7680, 7872, -612] // Cap
, [4, 7872, 8580, -612] // Aqr
, [16, 8580, 8640, -612] // Cet
, [41, 3510, 3690, -636] // Hya
, [35, 1692, 1740, -654] // Eri
, [46, 1740, 2202, -654] // Lep
, [11, 7200, 7680, -672] // Cap
, [41, 3690, 3810, -700] // Hya
, [41, 4530, 5370, -708] // Hya
, [47, 5370, 5640, -708] // Lib
, [71, 5640, 5760, -708] // Sco
, [35, 1650, 1692, -720] // Eri
, [58, 6030, 6336, -720] // Oph
, [76, 6336, 6420, -720] // Sgr
, [41, 3810, 3900, -748] // Hya
, [19, 2202, 2652, -792] // CMa
, [41, 4410, 4530, -792] // Hya
, [41, 3900, 4410, -840] // Hya
, [36, 1260, 1350, -864] // For
, [68, 3012, 3372, -882] // Pyx
, [35, 1536, 1650, -888] // Eri
, [76, 6420, 6900, -888] // Sgr
, [65, 7680, 8280, -888] // PsA
, [70, 8280, 8400, -888] // Scl
, [36, 1080, 1260, -950] // For
, [1, 3372, 3960, -954] // Ant
, [70, 0, 600, -960] // Scl
, [36, 600, 1080, -960] // For
, [35, 1392, 1536, -960] // Eri
, [70, 8400, 8640, -960] // Scl
, [14, 5100, 5370, -1008] // Cen
, [49, 5640, 5760, -1008] // Lup
, [71, 5760, 5911.5, -1008] // Sco
, [9, 1740, 1800, -1032] // Cae
, [22, 1800, 2370, -1032] // Col
, [67, 2880, 3012, -1032] // Pup
, [35, 1230, 1392, -1056] // Eri
, [71, 5911.5, 6420, -1092] // Sco
, [24, 6420, 6900, -1092] // CrA
, [76, 6900, 7320, -1092] // Sgr
, [53, 7320, 7680, -1092] // Mic
, [35, 1080, 1230, -1104] // Eri
, [9, 1620, 1740, -1116] // Cae
, [49, 5520, 5640, -1152] // Lup
, [63, 0, 840, -1156] // Phe
, [35, 960, 1080, -1176] // Eri
, [40, 1470, 1536, -1176] // Hor
, [9, 1536, 1620, -1176] // Cae
, [38, 7680, 7920, -1200] // Gru
, [67, 2160, 2880, -1218] // Pup
, [84, 2880, 2940, -1218] // Vel
, [35, 870, 960, -1224] // Eri
, [40, 1380, 1470, -1224] // Hor
, [63, 0, 660, -1236] // Phe
, [12, 2160, 2220, -1260] // Car
, [84, 2940, 3042, -1272] // Vel
, [40, 1260, 1380, -1276] // Hor
, [32, 1380, 1440, -1276] // Dor
, [63, 0, 570, -1284] // Phe
, [35, 780, 870, -1296] // Eri
, [64, 1620, 1800, -1296] // Pic
, [49, 5418, 5520, -1296] // Lup
, [84, 3042, 3180, -1308] // Vel
, [12, 2220, 2340, -1320] // Car
, [14, 4260, 4620, -1320] // Cen
, [49, 5100, 5418, -1320] // Lup
, [56, 5418, 5520, -1320] // Nor
, [32, 1440, 1560, -1356] // Dor
, [84, 3180, 3960, -1356] // Vel
, [14, 3960, 4050, -1356] // Cen
, [5, 6300, 6480, -1368] // Ara
, [78, 6480, 7320, -1368] // Tel
, [38, 7920, 8400, -1368] // Gru
, [40, 1152, 1260, -1380] // Hor
, [64, 1800, 1980, -1380] // Pic
, [12, 2340, 2460, -1392] // Car
, [63, 0, 480, -1404] // Phe
, [35, 480, 780, -1404] // Eri
, [63, 8400, 8640, -1404] // Phe
, [32, 1560, 1650, -1416] // Dor
, [56, 5520, 5911.5, -1440] // Nor
, [43, 7320, 7680, -1440] // Ind
, [64, 1980, 2160, -1464] // Pic
, [18, 5460, 5520, -1464] // Cir
, [5, 5911.5, 5970, -1464] // Ara
, [18, 5370, 5460, -1526] // Cir
, [5, 5970, 6030, -1526] // Ara
, [64, 2160, 2460, -1536] // Pic
, [12, 2460, 3252, -1536] // Car
, [14, 4050, 4260, -1536] // Cen
, [27, 4260, 4620, -1536] // Cru
, [14, 4620, 5232, -1536] // Cen
, [18, 4860, 4920, -1560] // Cir
, [5, 6030, 6060, -1560] // Ara
, [40, 780, 1152, -1620] // Hor
, [69, 1152, 1650, -1620] // Ret
, [18, 5310, 5370, -1620] // Cir
, [5, 6060, 6300, -1620] // Ara
, [60, 6300, 6480, -1620] // Pav
, [81, 7920, 8400, -1620] // Tuc
, [32, 1650, 2370, -1680] // Dor
, [18, 4920, 5310, -1680] // Cir
, [79, 5310, 6120, -1680] // TrA
, [81, 0, 480, -1800] // Tuc
, [42, 1260, 1650, -1800] // Hyi
, [86, 2370, 3252, -1800] // Vol
, [12, 3252, 4050, -1800] // Car
, [55, 4050, 4920, -1800] // Mus
, [60, 6480, 7680, -1800] // Pav
, [43, 7680, 8400, -1800] // Ind
, [81, 8400, 8640, -1800] // Tuc
, [81, 270, 480, -1824] // Tuc
, [42, 0, 1260, -1980] // Hyi
, [17, 2760, 4920, -1980] // Cha
, [2, 4920, 6480, -1980] // Aps
, [52, 1260, 2760, -2040] // Men
, [57, 0, 8640, -2160] // Oct
];
let ConstelRot: RotationMatrix;
let Epoch2000: AstroTime;
/**
* @brief Reports the constellation that a given celestial point lies within.
*
* @property {string} symbol
* 3-character mnemonic symbol for the constellation, e.g. "Ori".
*
* @property {string} name
* Full name of constellation, e.g. "Orion".
*
* @property {number} ra1875
* Right ascension expressed in B1875 coordinates.
*
* @property {number} dec1875
* Declination expressed in B1875 coordinates.
*/
export class ConstellationInfo {
constructor(
public symbol: string,
public name: string,
public ra1875: number,
public dec1875: number) {
}
}
/**
* @brief Determines the constellation that contains the given point in the sky.
*
* Given J2000 equatorial (EQJ) coordinates of a point in the sky,
* determines the constellation that contains that point.
*
* @param {number} ra
* The right ascension (RA) of a point in the sky, using the J2000 equatorial system.
*
* @param {number} dec
* The declination (DEC) of a point in the sky, using the J2000 equatorial system.
*
* @returns {ConstellationInfo}
* An object that contains the 3-letter abbreviation and full name
* of the constellation that contains the given (ra,dec), along with
* the converted B1875 (ra,dec) for that point.
*/
export function Constellation(ra: number, dec: number): ConstellationInfo {
VerifyNumber(ra);
VerifyNumber(dec);
if (dec < -90 || dec > +90)
throw 'Invalid declination angle. Must be -90..+90.';
// Clamp right ascension to [0, 24) sidereal hours.
ra %= 24.0;
if (ra < 0.0)
ra += 24.0;
// Lazy-initialize rotation matrix.
if (!ConstelRot) {
// Need to calculate the B1875 epoch. Based on this:
// https://en.wikipedia.org/wiki/Epoch_(astronomy)#Besselian_years
// B = 1900 + (JD - 2415020.31352) / 365.242198781
// I'm interested in using TT instead of JD, giving:
// B = 1900 + ((TT+2451545) - 2415020.31352) / 365.242198781
// B = 1900 + (TT + 36524.68648) / 365.242198781
// TT = 365.242198781*(B - 1900) - 36524.68648 = -45655.741449525
// But the AstroTime constructor wants UT, not TT.
// Near that date, I get a historical correction of ut-tt = 3.2 seconds.
// That gives UT = -45655.74141261017 for the B1875 epoch,
// or 1874-12-31T18:12:21.950Z.
ConstelRot = Rotation_EQJ_EQD(new AstroTime(-45655.74141261017));
Epoch2000 = new AstroTime(0);
}
// Convert coordinates from J2000 to B1875.
const sph2000 = new Spherical(dec, 15.0 * ra, 1.0);
const vec2000 = VectorFromSphere(sph2000, Epoch2000);
const vec1875 = RotateVector(ConstelRot, vec2000);
const equ1875 = EquatorFromVector(vec1875);
// Search for the constellation using the B1875 coordinates.
const fd = 10 / (4 * 60); // conversion factor from compact units to DEC degrees
const fr = fd / 15; // conversion factor from compact units to RA sidereal hours
for (let b of ConstelBounds) {
// Convert compact angular units to RA in hours, DEC in degrees.
const dec = b[3] * fd;
const ra_lo = b[1] * fr;
const ra_hi = b[2] * fr;
if (dec <= equ1875.dec && ra_lo <= equ1875.ra && equ1875.ra < ra_hi) {
const c = ConstelNames[b[0]];
return new ConstellationInfo(c[0], c[1], equ1875.ra, equ1875.dec);
}
}
// This should never happen!
throw 'Unable to find constellation for given coordinates.';
}
/**
* @brief Returns information about a lunar eclipse.
*
* Returned by {@link SearchLunarEclipse} or {@link NextLunarEclipse}
* to report information about a lunar eclipse event.
* When a lunar eclipse is found, it is classified as penumbral, partial, or total.
* Penumbral eclipses are difficult to observe, because the moon is only slightly dimmed
* by the Earth's penumbra; no part of the Moon touches the Earth's umbra.
* Partial eclipses occur when part, but not all, of the Moon touches the Earth's umbra.
* Total eclipses occur when the entire Moon passes into the Earth's umbra.
*
* The `kind` field thus holds one of the strings `"penumbral"`, `"partial"`,
* or `"total"`, depending on the kind of lunar eclipse found.
*
* Field `peak` holds the date and time of the peak of the eclipse, when it is at its peak.
*
* Fields `sd_penum`, `sd_partial`, and `sd_total` hold the semi-duration of each phase
* of the eclipse, which is half of the amount of time the eclipse spends in each
* phase (expressed in minutes), or 0 if the eclipse never reaches that phase.
* By converting from minutes to days, and subtracting/adding with `peak`, the caller
* may determine the date and time of the beginning/end of each eclipse phase.
*
* @property {string} kind
* The type of lunar eclipse found.
*
* @property {AstroTime} peak
* The time of the eclipse at its peak.
*
* @property {number} sd_penum
* The semi-duration of the penumbral phase in minutes.
*
* @property {number} sd_partial
* The semi-duration of the penumbral phase in minutes, or 0.0 if none.
*
* @property {number} sd_total
* The semi-duration of the penumbral phase in minutes, or 0.0 if none.
*
*/
export class LunarEclipseInfo {
constructor(
public kind: string,
public peak: AstroTime,
public sd_penum: number,
public sd_partial: number,
public sd_total: number) {
}
}
/**
* @ignore
*
* @brief Represents the relative alignment of the Earth and another body, and their respective shadows.
*
* This is an internal data structure used to assist calculation of
* lunar eclipses, solar eclipses, and transits of Mercury and Venus.
*
* Definitions:
*
* casting body = A body that casts a shadow of interest, possibly striking another body.
*
* receiving body = A body on which the shadow of another body might land.
*
* shadow axis = The line passing through the center of the Sun and the center of the casting body.
*
* shadow plane = The plane passing through the center of a receiving body,
* and perpendicular to the shadow axis.
*
* @property {AstroTime} time
* The time associated with the shadow calculation.
*
* @property {number} u
* The distance [au] between the center of the casting body and the shadow plane.
*
* @property {number} r
* The distance [km] between center of receiving body and the shadow axis.
*
* @property {number} k
* The umbra radius [km] at the shadow plane.
*
* @property {number} p
* The penumbra radius [km] at the shadow plane.
*
* @property {Vector} target
* The location in space where we are interested in determining how close a shadow falls.
* For example, when calculating lunar eclipses, `target` would be the center of the Moon
* expressed in geocentric coordinates. Then we can evaluate how far the center of the Earth's
* shadow cone approaches the center of the Moon.
* The vector components are expressed in [au].
*
* @property {Vector} dir
* The direction in space that the shadow points away from the center of a shadow-casting body.
* This vector lies on the shadow axis and points away from the Sun.
* In other words: the direction light from the Sun would be traveling,
* except that the center of a body (Earth, Moon, Mercury, or Venus) is blocking it.
* The distance units do not matter, because the vector will be normalized.
*/
class ShadowInfo {
constructor(
public time: AstroTime,
public u: number,
public r: number,
public k: number,
public p: number,
public target: Vector,
public dir: Vector) {
}
}
function CalcShadow(body_radius_km: number, time: AstroTime, target: Vector, dir: Vector): ShadowInfo {
const u = (dir.x * target.x + dir.y * target.y + dir.z * target.z) / (dir.x * dir.x + dir.y * dir.y + dir.z * dir.z);
const dx = (u * dir.x) - target.x;
const dy = (u * dir.y) - target.y;
const dz = (u * dir.z) - target.z;
const r = KM_PER_AU * Math.sqrt(dx * dx + dy * dy + dz * dz);
const k = +SUN_RADIUS_KM - (1.0 + u) * (SUN_RADIUS_KM - body_radius_km);
const p = -SUN_RADIUS_KM + (1.0 + u) * (SUN_RADIUS_KM + body_radius_km);
return new ShadowInfo(time, u, r, k, p, target, dir);
}
function EarthShadow(time: AstroTime): ShadowInfo {
const e = CalcVsop(vsop.Earth, time);
const m = GeoMoon(time);
return CalcShadow(EARTH_ECLIPSE_RADIUS_KM, time, m, e);
}
function MoonShadow(time: AstroTime): ShadowInfo {
// This is a variation on the logic in _EarthShadow().
// Instead of a heliocentric Earth and a geocentric Moon,
// we want a heliocentric Moon and a lunacentric Earth.
const h = CalcVsop(vsop.Earth, time); // heliocentric Earth
const m = GeoMoon(time); // geocentric Moon
// Calculate lunacentric Earth.
const e = new Vector(-m.x, -m.y, -m.z, m.t);
// Convert geocentric moon to heliocentric Moon.
m.x += h.x;
m.y += h.y;
m.z += h.z;
return CalcShadow(MOON_MEAN_RADIUS_KM, time, e, m);
}
function LocalMoonShadow(time: AstroTime, observer: Observer): ShadowInfo {
// Calculate observer's geocentric position.
// For efficiency, do this first, to populate the earth rotation parameters in 'time'.
// That way they can be recycled instead of recalculated.
const pos = geo_pos(time, observer);
const h = CalcVsop(vsop.Earth, time); // heliocentric Earth
const m = GeoMoon(time); // geocentric Moon
// Calculate lunacentric location of an observer on the Earth's surface.
const o = new Vector(pos[0] - m.x, pos[1] - m.y, pos[2] - m.z, time);
// Convert geocentric moon to heliocentric Moon.
m.x += h.x;
m.y += h.y;
m.z += h.z;
return CalcShadow(MOON_MEAN_RADIUS_KM, time, o, m);
}
function PlanetShadow(body: Body, planet_radius_km: number, time: AstroTime): ShadowInfo {
// Calculate light-travel-corrected vector from Earth to planet.
const g = GeoVector(body, time, false);
// Calculate light-travel-corrected vector from Earth to Sun.
const e = GeoVector(Body.Sun, time, false);
// Deduce light-travel-corrected vector from Sun to planet.
const p = new Vector(g.x - e.x, g.y - e.y, g.z - e.z, time);
// Calcluate Earth's position from the planet's point of view.
e.x = -g.x;
e.y = -g.y;
e.z = -g.z;
return CalcShadow(planet_radius_km, time, e, p);
}
function ShadowDistanceSlope(shadowfunc: (t: AstroTime) => ShadowInfo, time: AstroTime): number {
const dt = 1.0 / 86400.0;
const t1 = time.AddDays(-dt);
const t2 = time.AddDays(+dt);
const shadow1 = shadowfunc(t1);
const shadow2 = shadowfunc(t2);
return (shadow2.r - shadow1.r) / dt;
}
function PlanetShadowSlope(body: Body, planet_radius_km: number, time: AstroTime): number {
const dt = 1.0 / 86400.0;
const shadow1 = PlanetShadow(body, planet_radius_km, time.AddDays(-dt));
const shadow2 = PlanetShadow(body, planet_radius_km, time.AddDays(+dt));
return (shadow2.r - shadow1.r) / dt;
}
function PeakEarthShadow(search_center_time: AstroTime): ShadowInfo {
const window = 0.03; /* initial search window, in days, before/after given time */
const t1 = search_center_time.AddDays(-window);
const t2 = search_center_time.AddDays(+window);
const tx = Search((time: AstroTime) => ShadowDistanceSlope(EarthShadow, time), t1, t2);
if (!tx)
throw 'Failed to find peak Earth shadow time.';
return EarthShadow(tx);
}
function PeakMoonShadow(search_center_time: AstroTime): ShadowInfo {
const window = 0.03; /* initial search window, in days, before/after given time */
const t1 = search_center_time.AddDays(-window);
const t2 = search_center_time.AddDays(+window);
const tx = Search((time: AstroTime) => ShadowDistanceSlope(MoonShadow, time), t1, t2);
if (!tx)
throw 'Failed to find peak Moon shadow time.';
return MoonShadow(tx);
}
function PeakPlanetShadow(body: Body, planet_radius_km: number, search_center_time: AstroTime): ShadowInfo {
// Search for when the body's shadow is closest to the center of the Earth.
const window = 1.0; // days before/after inferior conjunction to search for minimum shadow distance.
const t1 = search_center_time.AddDays(-window);
const t2 = search_center_time.AddDays(+window);
const tx = Search((time: AstroTime) => PlanetShadowSlope(body, planet_radius_km, time), t1, t2);
if (!tx)
throw 'Failed to find peak planet shadow time.';
return PlanetShadow(body, planet_radius_km, tx);
}
function PeakLocalMoonShadow(search_center_time: AstroTime, observer: Observer): ShadowInfo {
// Search for the time near search_center_time that the Moon's shadow comes
// closest to the given observer.
const window = 0.2;
const t1 = search_center_time.AddDays(-window);
const t2 = search_center_time.AddDays(+window);
function shadowfunc(time: AstroTime): ShadowInfo {
return LocalMoonShadow(time, observer);
}
const time = Search((time: AstroTime) => ShadowDistanceSlope(shadowfunc, time), t1, t2);
if (!time)
throw `PeakLocalMoonShadow: search failure for search_center_time = ${search_center_time}`;
return LocalMoonShadow(time, observer);
}
function ShadowSemiDurationMinutes(center_time: AstroTime, radius_limit: number, window_minutes: number): number {
// Search backwards and forwards from the center time until shadow axis distance crosses radius limit.
const window = window_minutes / (24.0 * 60.0);
const before = center_time.AddDays(-window);
const after = center_time.AddDays(+window);
const t1 = Search((time: AstroTime) => -(EarthShadow(time).r - radius_limit), before, center_time);
const t2 = Search((time: AstroTime) => +(EarthShadow(time).r - radius_limit), center_time, after);
if (!t1 || !t2)
throw 'Failed to find shadow semiduration';
return (t2.ut - t1.ut) * ((24.0 * 60.0) / 2.0); // convert days to minutes and average the semi-durations.
}
function MoonEclipticLatitudeDegrees(time: AstroTime): number {
const moon = CalcMoon(time);
return RAD2DEG * moon.geo_eclip_lat;
}
/**
* @brief Searches for a lunar eclipse.
*
* This function finds the first lunar eclipse that occurs after `startTime`.
* A lunar eclipse may be penumbral, partial, or total.
* See {@link LunarEclipseInfo} for more information.
* To find a series of lunar eclipses, call this function once,
* then keep calling {@link NextLunarEclipse} as many times as desired,
* passing in the `peak` value returned from the previous call.
*
* @param {FlexibleDateTime} date
* The date and time for starting the search for a lunar eclipse.
*
* @returns {LunarEclipseInfo}
*/
export function SearchLunarEclipse(date: FlexibleDateTime): LunarEclipseInfo {
const PruneLatitude = 1.8; /* full Moon's ecliptic latitude above which eclipse is impossible */
let fmtime = MakeTime(date);
for (let fmcount = 0; fmcount < 12; ++fmcount) {
/* Search for the next full moon. Any eclipse will be near it. */
const fullmoon = SearchMoonPhase(180, fmtime, 40);
if (!fullmoon)
throw 'Cannot find full moon.';
/*
Pruning: if the full Moon's ecliptic latitude is too large,
a lunar eclipse is not possible. Avoid needless work searching for
the minimum moon distance.
*/
const eclip_lat = MoonEclipticLatitudeDegrees(fullmoon);
if (Math.abs(eclip_lat) < PruneLatitude) {
/* Search near the full moon for the time when the center of the Moon */
/* is closest to the line passing through the centers of the Sun and Earth. */
const shadow = PeakEarthShadow(fullmoon);
if (shadow.r < shadow.p + MOON_MEAN_RADIUS_KM) {
/* This is at least a penumbral eclipse. We will return a result. */
let kind = 'penumbral';
let sd_total = 0.0;
let sd_partial = 0.0;
let sd_penum = ShadowSemiDurationMinutes(shadow.time, shadow.p + MOON_MEAN_RADIUS_KM, 200.0);
if (shadow.r < shadow.k + MOON_MEAN_RADIUS_KM) {
/* This is at least a partial eclipse. */
kind = 'partial';
sd_partial = ShadowSemiDurationMinutes(shadow.time, shadow.k + MOON_MEAN_RADIUS_KM, sd_penum);
if (shadow.r + MOON_MEAN_RADIUS_KM < shadow.k) {
/* This is a total eclipse. */
kind = 'total';
sd_total = ShadowSemiDurationMinutes(shadow.time, shadow.k - MOON_MEAN_RADIUS_KM, sd_partial);
}
}
return new LunarEclipseInfo(kind, shadow.time, sd_penum, sd_partial, sd_total);
}
}
/* We didn't find an eclipse on this full moon, so search for the next one. */
fmtime = fullmoon.AddDays(10);
}
/* This should never happen because there are always at least 2 full moons per year. */
throw 'Failed to find lunar eclipse within 12 full moons.';
}
/**
* @brief Reports the time and geographic location of the peak of a solar eclipse.
*
* Returned by {@link SearchGlobalSolarEclipse} or {@link NextGlobalSolarEclipse}
* to report information about a solar eclipse event.
*
* Field `peak` holds the date and time of the peak of the eclipse, defined as
* the instant when the axis of the Moon's shadow cone passes closest to the Earth's center.
*
* The eclipse is classified as partial, annular, or total, depending on the
* maximum amount of the Sun's disc obscured, as seen at the peak location
* on the surface of the Earth.
*
* The `kind` field thus holds one of the strings `"partial"`, `"annular"`, or `"total"`.
* A total eclipse is when the peak observer sees the Sun completely blocked by the Moon.
* An annular eclipse is like a total eclipse, but the Moon is too far from the Earth's surface
* to completely block the Sun; instead, the Sun takes on a ring-shaped appearance.
* A partial eclipse is when the Moon blocks part of the Sun's disc, but nobody on the Earth
* observes either a total or annular eclipse.
*
* If `kind` is `"total"` or `"annular"`, the `latitude` and `longitude`
* fields give the geographic coordinates of the center of the Moon's shadow projected
* onto the daytime side of the Earth at the instant of the eclipse's peak.
* If `kind` has any other value, `latitude` and `longitude` are undefined and should
* not be used.
*
* @property {string} kind
* One of the following string values: `"partial"`, `"annular"`, `"total"`.
*
* @property {AstroTime} peak
* The date and time of the peak of the eclipse, defined as the instant
* when the axis of the Moon's shadow cone passes closest to the Earth's center.
*
* @property {number} distance
* The distance in kilometers between the axis of the Moon's shadow cone
* and the center of the Earth at the time indicated by `peak`.
*
* @property {number | undefined} latitude
* If `kind` holds `"total"`, the geographic latitude in degrees
* where the center of the Moon's shadow falls on the Earth at the
* time indicated by `peak`; otherwise, `latitude` holds `undefined`.
*
* @property {number | undefined} longitude
* If `kind` holds `"total"`, the geographic longitude in degrees
* where the center of the Moon's shadow falls on the Earth at the
* time indicated by `peak`; otherwise, `longitude` holds `undefined`.
*/
export class GlobalSolarEclipseInfo {
constructor(
public kind: string,
public peak: AstroTime,
public distance: number,
public latitude?: number,
public longitude?: number) {
}
}
function EclipseKindFromUmbra(k: number): string {
// The umbra radius tells us what kind of eclipse the observer sees.
// If the umbra radius is positive, this is a total eclipse. Otherwise, it's annular.
// HACK: I added a tiny bias (14 meters) to match Espenak test data.
return (k > 0.014) ? 'total' : 'annular';
}
function GeoidIntersect(shadow: ShadowInfo): GlobalSolarEclipseInfo {
let kind = 'partial';
let peak = shadow.time;
let distance = shadow.r;
let latitude: number | undefined; // left undefined for partial eclipses
let longitude: number | undefined; // left undefined for partial eclipses
// We want to calculate the intersection of the shadow axis with the Earth's geoid.
// First we must convert EQJ (equator of J2000) coordinates to EQD (equator of date)
// coordinates that are perfectly aligned with the Earth's equator at this
// moment in time.
const rot = Rotation_EQJ_EQD(shadow.time);
const v = RotateVector(rot, shadow.dir); // shadow-axis vector in equator-of-date coordinates
const e = RotateVector(rot, shadow.target); // lunacentric Earth in equator-of-date coordinates
// Convert all distances from AU to km.
// But dilate the z-coordinates so that the Earth becomes a perfect sphere.
// Then find the intersection of the vector with the sphere.
// See p 184 in Montenbruck & Pfleger's "Astronomy on the Personal Computer", second edition.
v.x *= KM_PER_AU;
v.y *= KM_PER_AU;
v.z *= KM_PER_AU / EARTH_FLATTENING;
e.x *= KM_PER_AU;
e.y *= KM_PER_AU;
e.z *= KM_PER_AU / EARTH_FLATTENING;
// Solve the quadratic equation that finds whether and where
// the shadow axis intersects with the Earth in the dilated coordinate system.
const R = EARTH_EQUATORIAL_RADIUS_KM;
const A = v.x * v.x + v.y * v.y + v.z * v.z;
const B = -2.0 * (v.x * e.x + v.y * e.y + v.z * e.z);
const C = (e.x * e.x + e.y * e.y + e.z * e.z) - R * R;
const radic = B * B - 4 * A * C;
if (radic > 0.0) {
// Calculate the closer of the two intersection points.
// This will be on the day side of the Earth.
const u = (-B - Math.sqrt(radic)) / (2 * A);
// Convert lunacentric dilated coordinates to geocentric coordinates.
const px = u * v.x - e.x;
const py = u * v.y - e.y;
const pz = (u * v.z - e.z) * EARTH_FLATTENING;
// Convert cartesian coordinates into geodetic latitude/longitude.
const proj = Math.sqrt(px * px + py * py) * (EARTH_FLATTENING * EARTH_FLATTENING);
if (proj == 0.0)
latitude = (pz > 0.0) ? +90.0 : -90.0;
else
latitude = RAD2DEG * Math.atan(pz / proj);
// Adjust longitude for Earth's rotation at the given UT.
const gast = sidereal_time(peak);
longitude = (RAD2DEG * Math.atan2(py, px) - (15 * gast)) % 360.0;
if (longitude <= -180.0)
longitude += 360.0;
else if (longitude > +180.0)
longitude -= 360.0;
// We want to determine whether the observer sees a total eclipse or an annular eclipse.
// We need to perform a series of vector calculations...
// Calculate the inverse rotation matrix, so we can convert EQD to EQJ.
const inv = InverseRotation(rot);
// Put the EQD geocentric coordinates of the observer into the vector 'o'.
// Also convert back from kilometers to astronomical units.
let o = new Vector(px / KM_PER_AU, py / KM_PER_AU, pz / KM_PER_AU, shadow.time);
// Rotate the observer's geocentric EQD back to the EQJ system.
o = RotateVector(inv, o);
// Convert geocentric vector to lunacentric vector.
o.x += shadow.target.x;
o.y += shadow.target.y;
o.z += shadow.target.z;
// Recalculate the shadow using a vector from the Moon's center toward the observer.
const surface = CalcShadow(MOON_POLAR_RADIUS_KM, shadow.time, o, shadow.dir);
// If we did everything right, the shadow distance should be very close to zero.
// That's because we already determined the observer 'o' is on the shadow axis!
if (surface.r > 1.0e-9 || surface.r < 0.0)
throw `Unexpected shadow distance from geoid intersection = ${surface.r}`;
kind = EclipseKindFromUmbra(surface.k);
}
return new GlobalSolarEclipseInfo(kind, peak, distance, latitude, longitude);
}
/**
* @brief Searches for the next lunar eclipse in a series.
*
* After using {@link SearchLunarEclipse} to find the first lunar eclipse
* in a series, you can call this function to find the next consecutive lunar eclipse.
* Pass in the `peak` value from the {@link LunarEclipseInfo} returned by the
* previous call to `SearchLunarEclipse` or `NextLunarEclipse`
* to find the next lunar eclipse.
*
* @param {AstroTime} prevEclipseTime
* A date and time near a full moon. Lunar eclipse search will start at the next full moon.
*
* @returns {LunarEclipseInfo}
*/
export function NextLunarEclipse(prevEclipseTime: AstroTime): LunarEclipseInfo {
const startTime = prevEclipseTime.AddDays(10);
return SearchLunarEclipse(startTime);
}
/**
* @brief Searches for a solar eclipse visible anywhere on the Earth's surface.
*
* This function finds the first solar eclipse that occurs after `startTime`.
* A solar eclipse may be partial, annular, or total.
* See {@link GlobalSolarEclipseInfo} for more information.
* To find a series of solar eclipses, call this function once,
* then keep calling {@link NextGlobalSolarEclipse} as many times as desired,
* passing in the `peak` value returned from the previous call.
*
* @param {AstroTime} startTime
* The date and time for starting the search for a solar eclipse.
*
* @returns {GlobalSolarEclipseInfo}
*/
export function SearchGlobalSolarEclipse(startTime: AstroTime): GlobalSolarEclipseInfo {
const PruneLatitude = 1.8; // Moon's ecliptic latitude beyond which eclipse is impossible
// Iterate through consecutive new moons until we find a solar eclipse visible somewhere on Earth.
let nmtime = startTime;
let nmcount: number;
for (nmcount = 0; nmcount < 12; ++nmcount) {
// Search for the next new moon. Any eclipse will be near it.
const newmoon = SearchMoonPhase(0.0, nmtime, 40.0);
if (!newmoon)
throw 'Cannot find new moon';
// Pruning: if the new moon's ecliptic latitude is too large, a solar eclipse is not possible.
const eclip_lat = MoonEclipticLatitudeDegrees(newmoon);
if (Math.abs(eclip_lat) < PruneLatitude) {
// Search near the new moon for the time when the center of the Earth
// is closest to the line passing through the centers of the Sun and Moon.
const shadow = PeakMoonShadow(newmoon);
if (shadow.r < shadow.p + EARTH_MEAN_RADIUS_KM) {
// This is at least a partial solar eclipse visible somewhere on Earth.
// Try to find an intersection between the shadow axis and the Earth's oblate geoid.
return GeoidIntersect(shadow);
}
}
// We didn't find an eclipse on this new moon, so search for the next one.
nmtime = newmoon.AddDays(10.0);
}
// Safety valve to prevent infinite loop.
// This should never happen, because at least 2 solar eclipses happen per year.
throw 'Failed to find solar eclipse within 12 full moons.';
}
/**
* @brief Searches for the next global solar eclipse in a series.
*
* After using {@link SearchGlobalSolarEclipse} to find the first solar eclipse
* in a series, you can call this function to find the next consecutive solar eclipse.
* Pass in the `peak` value from the {@link GlobalSolarEclipseInfo} returned by the
* previous call to `SearchGlobalSolarEclipse` or `NextGlobalSolarEclipse`
* to find the next solar eclipse.
*
* @param {AstroTime} prevEclipseTime
* A date and time near a new moon. Solar eclipse search will start at the next new moon.
*
* @returns {GlobalSolarEclipseInfo}
*/
export function NextGlobalSolarEclipse(prevEclipseTime: AstroTime): GlobalSolarEclipseInfo {
const startTime = prevEclipseTime.AddDays(10.0);
return SearchGlobalSolarEclipse(startTime);
}
/**
* @brief Holds a time and the observed altitude of the Sun at that time.
*
* When reporting a solar eclipse observed at a specific location on the Earth
* (a "local" solar eclipse), a series of events occur. In addition
* to the time of each event, it is important to know the altitude of the Sun,
* because each event may be invisible to the observer if the Sun is below
* the horizon (i.e. it at night).
*
* If `altitude` is negative, the event is theoretical only; it would be
* visible if the Earth were transparent, but the observer cannot actually see it.
* If `altitude` is positive but less than a few degrees, visibility will be impaired by
* atmospheric interference (sunrise or sunset conditions).
*
* @property {AstroTime} time
* The date and time of the event.
*
* @property {number} altitude
* The angular altitude of the center of the Sun above/below the horizon, at `time`,
* corrected for atmospheric refraction and expressed in degrees.
*/
export class EclipseEvent {
constructor(
public time: AstroTime,
public altitude: number) {
}
}
/**
* @brief Information about a solar eclipse as seen by an observer at a given time and geographic location.
*
* Returned by {@link SearchLocalSolarEclipse} or {@link NextLocalSolarEclipse}
* to report information about a solar eclipse as seen at a given geographic location.
*
* When a solar eclipse is found, it is classified by setting `kind`
* to `"partial"`, `"annular"`, or `"total"`.
* A partial solar eclipse is when the Moon does not line up directly enough with the Sun
* to completely block the Sun's light from reaching the observer.
* An annular eclipse occurs when the Moon's disc is completely visible against the Sun
* but the Moon is too far away to completely block the Sun's light; this leaves the
* Sun with a ring-like appearance.
* A total eclipse occurs when the Moon is close enough to the Earth and aligned with the
* Sun just right to completely block all sunlight from reaching the observer.
*
* There are 5 "event" fields, each of which contains a time and a solar altitude.
* Field `peak` holds the date and time of the center of the eclipse, when it is at its peak.
* The fields `partial_begin` and `partial_end` are always set, and indicate when
* the eclipse begins/ends. If the eclipse reaches totality or becomes annular,
* `total_begin` and `total_end` indicate when the total/annular phase begins/ends.
* When an event field is valid, the caller must also check its `altitude` field to
* see whether the Sun is above the horizon at the time indicated by the `time` field.
* See {@link EclipseEvent} for more information.
*
* @property {string} kind
* The type of solar eclipse found: `"partial"`, `"annular"`, or `"total"`.
*
* @property {EclipseEvent} partial_begin
* The time and Sun altitude at the beginning of the eclipse.
*
* @property {EclipseEvent | undefined} total_begin
* If this is an annular or a total eclipse, the time and Sun altitude when annular/total phase begins; otherwise undefined.
*
* @property {EclipseEvent} peak
* The time and Sun altitude when the eclipse reaches its peak.
*
* @property {EclipseEvent | undefined} total_end
* If this is an annular or a total eclipse, the time and Sun altitude when annular/total phase ends; otherwise undefined.
*
* @property {EclipseEvent} partial_end
* The time and Sun altitude at the end of the eclipse.
*/
export class LocalSolarEclipseInfo {
constructor(
public kind: string,
public partial_begin: EclipseEvent,
public total_begin: EclipseEvent | undefined,
public peak: EclipseEvent,
public total_end: EclipseEvent | undefined,
public partial_end: EclipseEvent) {
}
}
function local_partial_distance(shadow: ShadowInfo): number {
return shadow.p - shadow.r;
}
function local_total_distance(shadow: ShadowInfo): number {
// Must take the absolute value of the umbra radius 'k'
// because it can be negative for an annular eclipse.
return Math.abs(shadow.k) - shadow.r;
}
function LocalEclipse(shadow: ShadowInfo, observer: Observer): LocalSolarEclipseInfo {
const PARTIAL_WINDOW = 0.2;
const TOTAL_WINDOW = 0.01;
const peak = CalcEvent(observer, shadow.time);
let t1 = shadow.time.AddDays(-PARTIAL_WINDOW);
let t2 = shadow.time.AddDays(+PARTIAL_WINDOW);
const partial_begin = LocalEclipseTransition(observer, +1.0, local_partial_distance, t1, shadow.time);
const partial_end = LocalEclipseTransition(observer, -1.0, local_partial_distance, shadow.time, t2);
let total_begin: EclipseEvent | undefined;
let total_end: EclipseEvent | undefined;
let kind: string;
if (shadow.r < Math.abs(shadow.k)) { // take absolute value of 'k' to handle annular eclipses too.
t1 = shadow.time.AddDays(-TOTAL_WINDOW);
t2 = shadow.time.AddDays(+TOTAL_WINDOW);
total_begin = LocalEclipseTransition(observer, +1.0, local_total_distance, t1, shadow.time);
total_end = LocalEclipseTransition(observer, -1.0, local_total_distance, shadow.time, t2);
kind = EclipseKindFromUmbra(shadow.k);
} else {
kind = 'partial';
}
return new LocalSolarEclipseInfo(kind, partial_begin, total_begin, peak, total_end, partial_end);
}
type ShadowFunc = (shadow: ShadowInfo) => number;
function LocalEclipseTransition(observer: Observer, direction: number, func: ShadowFunc, t1: AstroTime, t2: AstroTime): EclipseEvent {
function evaluate(time: AstroTime): number {
const shadow = LocalMoonShadow(time, observer);
return direction * func(shadow);
}
const search = Search(evaluate, t1, t2);
if (!search)
throw "Local eclipse transition search failed.";
return CalcEvent(observer, search);
}
function CalcEvent(observer: Observer, time: AstroTime): EclipseEvent {
const altitude = SunAltitude(time, observer);
return new EclipseEvent(time, altitude);
}
function SunAltitude(time: AstroTime, observer: Observer): number {
const equ = Equator(Body.Sun, time, observer, true, true);
const hor = Horizon(time, observer, equ.ra, equ.dec, 'normal');
return hor.altitude;
}
/**
* @brief Searches for a solar eclipse visible at a specific location on the Earth's surface.
*
* This function finds the first solar eclipse that occurs after `startTime`.
* A solar eclipse may be partial, annular, or total.
* See {@link LocalSolarEclipseInfo} for more information.
*
* To find a series of solar eclipses, call this function once,
* then keep calling {@link NextLocalSolarEclipse} as many times as desired,
* passing in the `peak` value returned from the previous call.
*
* IMPORTANT: An eclipse reported by this function might be partly or
* completely invisible to the observer due to the time of day.
* See {@link LocalSolarEclipseInfo} for more information about this topic.
*
* @param {AstroTime} startTime
* The date and time for starting the search for a solar eclipse.
*
* @param {Observer} observer
* The geographic location of the observer.
*
* @returns {LocalSolarEclipseInfo}
*/
export function SearchLocalSolarEclipse(startTime: AstroTime, observer: Observer): LocalSolarEclipseInfo {
VerifyObserver(observer);
const PruneLatitude = 1.8; /* Moon's ecliptic latitude beyond which eclipse is impossible */
/* Iterate through consecutive new moons until we find a solar eclipse visible somewhere on Earth. */
let nmtime = startTime;
for (; ;) {
/* Search for the next new moon. Any eclipse will be near it. */
const newmoon = SearchMoonPhase(0.0, nmtime, 40.0);
if (!newmoon)
throw 'Cannot find next new moon';
/* Pruning: if the new moon's ecliptic latitude is too large, a solar eclipse is not possible. */
const eclip_lat = MoonEclipticLatitudeDegrees(newmoon);
if (Math.abs(eclip_lat) < PruneLatitude) {
/* Search near the new moon for the time when the observer */
/* is closest to the line passing through the centers of the Sun and Moon. */
const shadow = PeakLocalMoonShadow(newmoon, observer);
if (shadow.r < shadow.p) {
/* This is at least a partial solar eclipse for the observer. */
const eclipse = LocalEclipse(shadow, observer);
/* Ignore any eclipse that happens completely at night. */
/* More precisely, the center of the Sun must be above the horizon */
/* at the beginning or the end of the eclipse, or we skip the event. */
if (eclipse.partial_begin.altitude > 0.0 || eclipse.partial_end.altitude > 0.0)
return eclipse;
}
}
/* We didn't find an eclipse on this new moon, so search for the next one. */
nmtime = newmoon.AddDays(10.0);
}
}
/**
* @brief Searches for the next local solar eclipse in a series.
*
* After using {@link SearchLocalSolarEclipse} to find the first solar eclipse
* in a series, you can call this function to find the next consecutive solar eclipse.
* Pass in the `peak` value from the {@link LocalSolarEclipseInfo} returned by the
* previous call to `SearchLocalSolarEclipse` or `NextLocalSolarEclipse`
* to find the next solar eclipse.
* This function finds the first solar eclipse that occurs after `startTime`.
* A solar eclipse may be partial, annular, or total.
* See {@link LocalSolarEclipseInfo} for more information.
*
* @param {AstroTime} prevEclipseTime
* The date and time for starting the search for a solar eclipse.
*
* @param {Observer} observer
* The geographic location of the observer.
*
* @returns {LocalSolarEclipseInfo}
*/
export function NextLocalSolarEclipse(prevEclipseTime: AstroTime, observer: Observer): LocalSolarEclipseInfo {
const startTime = prevEclipseTime.AddDays(10.0);
return SearchLocalSolarEclipse(startTime, observer);
}
/**
* @brief Information about a transit of Mercury or Venus, as seen from the Earth.
*
* Returned by {@link SearchTransit} or {@link NextTransit} to report
* information about a transit of Mercury or Venus.
* A transit is when Mercury or Venus passes between the Sun and Earth so that
* the other planet is seen in silhouette against the Sun.
*
* The calculations are performed from the point of view of a geocentric observer.
*
* @property {AstroTime} start
* The date and time at the beginning of the transit.
* This is the moment the planet first becomes visible against the Sun in its background.
*
* @property {AstroTime} peak
* When the planet is most aligned with the Sun, as seen from the Earth.
*
* @property {AstroTime} finish
* The date and time at the end of the transit.
* This is the moment the planet is last seen against the Sun in its background.
*
* @property {number} separation
* The minimum angular separation, in arcminutes, between the centers of the Sun and the planet.
* This angle pertains to the time stored in `peak`.
*/
export class TransitInfo {
constructor(
public start: AstroTime,
public peak: AstroTime,
public finish: AstroTime,
public separation: number) {
}
}
function PlanetShadowBoundary(time: AstroTime, body: Body, planet_radius_km: number, direction: number): number {
const shadow = PlanetShadow(body, planet_radius_km, time);
return direction * (shadow.r - shadow.p);
}
function PlanetTransitBoundary(body: Body, planet_radius_km: number, t1: AstroTime, t2: AstroTime, direction: number): AstroTime {
// Search for the time the planet's penumbra begins/ends making contact with the center of the Earth.
const tx = Search((time: AstroTime) => PlanetShadowBoundary(time, body, planet_radius_km, direction), t1, t2);
if (!tx)
throw 'Planet transit boundary search failed';
return tx;
}
/**
* @brief Searches for the first transit of Mercury or Venus after a given date.
*
* Finds the first transit of Mercury or Venus after a specified date.
* A transit is when an inferior planet passes between the Sun and the Earth
* so that the silhouette of the planet is visible against the Sun in the background.
* To continue the search, pass the `finish` time in the returned structure to
* {@link NextTransit}.
*
* @param {Body} body
* The planet whose transit is to be found. Must be `"Mercury"` or `"Venus"`.
*
* @param {AstroTime} startTime
* The date and time for starting the search for a transit.
*
* @returns {TransitInfo}
*/
export function SearchTransit(body: Body, startTime: AstroTime) {
const threshold_angle = 0.4; // maximum angular separation to attempt transit calculation
const dt_days = 1.0;
// Validate the planet and find its mean radius.
let planet_radius_km: number;
switch (body) {
case Body.Mercury:
planet_radius_km = 2439.7;
break;
case Body.Venus:
planet_radius_km = 6051.8;
break;
default:
throw `Invalid body: ${body}`;
}
let search_time = startTime;
for (; ;) {
// Search for the next inferior conjunction of the given planet.
// This is the next time the Earth and the other planet have the same
// ecliptic longitude as seen from the Sun.
const conj = SearchRelativeLongitude(body, 0.0, search_time);
// Calculate the angular separation between the body and the Sun at this time.
const conj_separation = AngleFromSun(body, conj);
if (conj_separation < threshold_angle) {
// The planet's angular separation from the Sun is small enough
// to consider it a transit candidate.
// Search for the moment when the line passing through the Sun
// and planet are closest to the Earth's center.
const shadow = PeakPlanetShadow(body, planet_radius_km, conj);
if (shadow.r < shadow.p) { // does the planet's penumbra touch the Earth's center?
// Find the beginning and end of the penumbral contact.
const time_before = shadow.time.AddDays(-dt_days);
const start = PlanetTransitBoundary(body, planet_radius_km, time_before, shadow.time, -1.0);
const time_after = shadow.time.AddDays(+dt_days);
const finish = PlanetTransitBoundary(body, planet_radius_km, shadow.time, time_after, +1.0);
const min_separation = 60.0 * AngleFromSun(body, shadow.time);
return new TransitInfo(start, shadow.time, finish, min_separation);
}
}
// This inferior conjunction was not a transit. Try the next inferior conjunction.
search_time = conj.AddDays(10.0);
}
}
/**
* @brief Searches for the next transit of Mercury or Venus in a series.
*
* After calling {@link SearchTransit} to find a transit of Mercury or Venus,
* this function finds the next transit after that.
* Keep calling this function as many times as you want to keep finding more transits.
*
* @param {Body} body
* The planet whose transit is to be found. Must be `"Mercury"` or `"Venus"`.
*
* @param {AstroTime} prevTransitTime
* A date and time near the previous transit.
*
* @returns {TransitInfo}
*/
export function NextTransit(body: Body, prevTransitTime: AstroTime): TransitInfo {
const startTime = prevTransitTime.AddDays(100.0);
return SearchTransit(body, startTime);
} | the_stack |
* Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { AbstractClient } from "../../../common/abstract_client"
import { ClientConfig } from "../../../common/interface"
import {
DescribeFaceIdResultsRequest,
CreateSubOrganizationRequest,
Component,
CreateSealRequest,
CancelFlowResponse,
FaceIdPhoto,
VerifySubOrganizationRequest,
VerifyUserRequest,
DescribeFaceIdPhotosResponse,
CheckVerifyCodeMatchFlowIdRequest,
CheckBankCard2EVerificationRequest,
DescribeFileIdsByCustomIdsResponse,
ModifySubOrganizationInfoResponse,
DescribeCatalogApproversRequest,
CheckFaceIdentifyRequest,
CreateServerFlowSignResponse,
ModifyUserResponse,
CheckBankCard4EVerificationResponse,
DescribeFileUrlsRequest,
FlowFileInfo,
SmsTemplate,
Address,
ModifyUserDefaultSealRequest,
GenerateUserSealRequest,
CheckIdCardVerificationResponse,
DescribeFlowResponse,
CreateSubOrganizationAndSealRequest,
CheckMobileVerificationRequest,
SendFlowUrlResponse,
DescribeCatalogApproversResponse,
CustomFileIdMap,
SendFlowResponse,
CatalogApprovers,
DescribeSealsRequest,
FlowApproverInfo,
DescribeFlowFilesRequest,
DescribeCustomFlowIdsResponse,
SubOrganizationDetail,
CheckIdCardVerificationRequest,
CreateSignUrlResponse,
ModifySubOrganizationInfoRequest,
SendSignInnerVerifyCodeResponse,
DescribeFaceIdPhotosRequest,
FileUrl,
CreateUserResponse,
CheckVerifyCodeMatchFlowIdResponse,
ModifyOrganizationDefaultSealRequest,
CreateFaceIdSignResponse,
DescribeFlowApproversResponse,
CheckMobileAndNameRequest,
DeleteSealRequest,
CheckBankCardVerificationResponse,
ArchiveFlowRequest,
CreateUserAndSealResponse,
FaceIdResult,
CreateSignUrlRequest,
ComponentSeal,
DeleteSealResponse,
UploadFilesRequest,
DescribeUsersRequest,
CreateFlowByFilesRequest,
CatalogComponents,
ArchiveFlowResponse,
FlowInfo,
UserDescribe,
CheckBankCard2EVerificationResponse,
VerifySubOrganizationResponse,
DescribeSealsResponse,
DescribeFileUrlsResponse,
ModifySealRequest,
CheckBankCard3EVerificationRequest,
CheckBankCardVerificationRequest,
RejectFlowRequest,
DescribeSubOrganizationsRequest,
SignSeal,
DescribeCatalogSignComponentsRequest,
ModifyOrganizationDefaultSealResponse,
CreateFlowByFilesResponse,
ModifyUserDefaultSealResponse,
UploadFilesResponse,
CheckBankCard3EVerificationResponse,
SignFlowRequest,
CustomFlowIdMap,
DescribeCustomFlowIdsByFlowIdRequest,
UploadFile,
DescribeUsersResponse,
CreateH5FaceIdUrlRequest,
CheckMobileVerificationResponse,
DescribeFlowFilesResponse,
CreateUserRequest,
CreatePreviewSignUrlRequest,
CreateUserAndSealRequest,
CreatePreviewSignUrlResponse,
CreateFaceIdSignRequest,
DescribeCustomFlowIdsByFlowIdResponse,
SignFlowResponse,
RejectFlowResponse,
DescribeFlowRequest,
DescribeFileIdsByCustomIdsRequest,
CreateSealResponse,
GenerateOrganizationSealResponse,
DescribeSubOrganizationsResponse,
DestroyFlowFileRequest,
CheckFaceIdentifyResponse,
Seal,
SendFlowUrlRequest,
CancelFlowRequest,
CreateH5FaceIdUrlResponse,
DescribeCustomFlowIdsRequest,
DescribeFlowApproversRequest,
DescribeFaceIdResultsResponse,
CheckBankCard4EVerificationRequest,
GenerateUserSealResponse,
DescribeCatalogSignComponentsResponse,
GenerateOrganizationSealRequest,
CreateServerFlowSignRequest,
Caller,
VerifyUserResponse,
SendFlowRequest,
SendSignInnerVerifyCodeRequest,
DestroyFlowFileResponse,
CreateSubOrganizationResponse,
CreateSubOrganizationAndSealResponse,
ModifyUserRequest,
CheckMobileAndNameResponse,
ModifySealResponse,
} from "./essbasic_models"
/**
* essbasic client
* @class
*/
export class Client extends AbstractClient {
constructor(clientConfig: ClientConfig) {
super("essbasic.tencentcloudapi.com", "2020-12-22", clientConfig)
}
/**
* 该接口为第三方平台向电子签平台验证手机号三要素
*/
async CheckMobileVerification(
req: CheckMobileVerificationRequest,
cb?: (error: string, rep: CheckMobileVerificationResponse) => void
): Promise<CheckMobileVerificationResponse> {
return this.request("CheckMobileVerification", req, cb)
}
/**
* 此接口(CreateSubOrganization)用于在腾讯电子签内注册子机构。
*/
async CreateSubOrganization(
req: CreateSubOrganizationRequest,
cb?: (error: string, rep: CreateSubOrganizationResponse) => void
): Promise<CreateSubOrganizationResponse> {
return this.request("CreateSubOrganization", req, cb)
}
/**
* 此接口(CancelFlow)用于撤销正在进行中的流程。
注:已归档流程不可完成撤销动作。
*/
async CancelFlow(
req: CancelFlowRequest,
cb?: (error: string, rep: CancelFlowResponse) => void
): Promise<CancelFlowResponse> {
return this.request("CancelFlow", req, cb)
}
/**
* 此接口(DescribeFileUrls)用于获取签署文件下载的URL。
*/
async DescribeFileUrls(
req: DescribeFileUrlsRequest,
cb?: (error: string, rep: DescribeFileUrlsResponse) => void
): Promise<DescribeFileUrlsResponse> {
return this.request("DescribeFileUrls", req, cb)
}
/**
* 该接口为第三方平台向电子签平台获取慧眼H5人脸核身Url
*/
async CreateH5FaceIdUrl(
req: CreateH5FaceIdUrlRequest,
cb?: (error: string, rep: CreateH5FaceIdUrlResponse) => void
): Promise<CreateH5FaceIdUrlResponse> {
return this.request("CreateH5FaceIdUrl", req, cb)
}
/**
* 第三方应用可通过此接口(DescribeFlowApprovers)查询流程参与者信息。
*/
async DescribeFlowApprovers(
req: DescribeFlowApproversRequest,
cb?: (error: string, rep: DescribeFlowApproversResponse) => void
): Promise<DescribeFlowApproversResponse> {
return this.request("DescribeFlowApprovers", req, cb)
}
/**
* 该接口为第三方平台向电子签平台验证银行卡四要素
*/
async CheckBankCard4EVerification(
req: CheckBankCard4EVerificationRequest,
cb?: (error: string, rep: CheckBankCard4EVerificationResponse) => void
): Promise<CheckBankCard4EVerificationResponse> {
return this.request("CheckBankCard4EVerification", req, cb)
}
/**
* 此接口 (DeleteSeal) 用于删除指定ID的印章。
注意:默认印章不支持删除
*/
async DeleteSeal(
req: DeleteSealRequest,
cb?: (error: string, rep: DeleteSealResponse) => void
): Promise<DeleteSealResponse> {
return this.request("DeleteSeal", req, cb)
}
/**
* 此接口(CreateSignUrl)用于生成指定用户的签署URL。
注:调用此接口前,请确保您已提前调用了发送流程接口(SendFlow)指定相关签署方。
*/
async CreateSignUrl(
req: CreateSignUrlRequest,
cb?: (error: string, rep: CreateSignUrlResponse) => void
): Promise<CreateSignUrlResponse> {
return this.request("CreateSignUrl", req, cb)
}
/**
* 此接口(DescribeUsers)用于查询应用号下的个人用户信息。
注:此接口仅可查询您所属机构应用号创建的个人用户信息,不可跨应用/跨机构查询。
*/
async DescribeUsers(
req: DescribeUsersRequest,
cb?: (error: string, rep: DescribeUsersResponse) => void
): Promise<DescribeUsersResponse> {
return this.request("DescribeUsers", req, cb)
}
/**
* 发送流程并获取签署URL
*/
async SendFlowUrl(
req: SendFlowUrlRequest,
cb?: (error: string, rep: SendFlowUrlResponse) => void
): Promise<SendFlowUrlResponse> {
return this.request("SendFlowUrl", req, cb)
}
/**
* 此接口用于发送签署验证码
*/
async SendSignInnerVerifyCode(
req: SendSignInnerVerifyCodeRequest,
cb?: (error: string, rep: SendSignInnerVerifyCodeResponse) => void
): Promise<SendSignInnerVerifyCodeResponse> {
return this.request("SendSignInnerVerifyCode", req, cb)
}
/**
* 查询流程文件
*/
async DescribeFlowFiles(
req: DescribeFlowFilesRequest,
cb?: (error: string, rep: DescribeFlowFilesResponse) => void
): Promise<DescribeFlowFilesResponse> {
return this.request("DescribeFlowFiles", req, cb)
}
/**
* 此接口(CreateSeal)用于创建个人/企业印章。
注意:使用FileId参数指定印章,需先调用多文件上传 (UploadFiles) 上传印章图片。
*/
async CreateSeal(
req: CreateSealRequest,
cb?: (error: string, rep: CreateSealResponse) => void
): Promise<CreateSealResponse> {
return this.request("CreateSeal", req, cb)
}
/**
* 此接口 (ModifyUserDefaultSeal) 用于重新指定个人默认印章。
*/
async ModifyUserDefaultSeal(
req: ModifyUserDefaultSealRequest,
cb?: (error: string, rep: ModifyUserDefaultSealResponse) => void
): Promise<ModifyUserDefaultSealResponse> {
return this.request("ModifyUserDefaultSeal", req, cb)
}
/**
* 此接口(CreatePreviewSignUrl)用于生成生成预览签署URL。
注:调用此接口前,请确保您已提前调用了发送流程接口(SendFlow)指定相关签署方。
*/
async CreatePreviewSignUrl(
req: CreatePreviewSignUrlRequest,
cb?: (error: string, rep: CreatePreviewSignUrlResponse) => void
): Promise<CreatePreviewSignUrlResponse> {
return this.request("CreatePreviewSignUrl", req, cb)
}
/**
* 此接口用于确认验证码是否正确
*/
async CheckVerifyCodeMatchFlowId(
req: CheckVerifyCodeMatchFlowIdRequest,
cb?: (error: string, rep: CheckVerifyCodeMatchFlowIdResponse) => void
): Promise<CheckVerifyCodeMatchFlowIdResponse> {
return this.request("CheckVerifyCodeMatchFlowId", req, cb)
}
/**
* 该接口为第三方平台向电子签平台检测慧眼或腾讯电子签小程序人脸核身结果
*/
async CheckFaceIdentify(
req: CheckFaceIdentifyRequest,
cb?: (error: string, rep: CheckFaceIdentifyResponse) => void
): Promise<CheckFaceIdentifyResponse> {
return this.request("CheckFaceIdentify", req, cb)
}
/**
* 此接口(GenerateUserSeal)用于生成个人签名图片。
注意:
1. 个人签名由用户注册时预留的姓名信息生成,不支持自定义签名内容。
2. 个人用户仅支持拥有一个系统生成的电子签名。
*/
async GenerateUserSeal(
req: GenerateUserSealRequest,
cb?: (error: string, rep: GenerateUserSealResponse) => void
): Promise<GenerateUserSealResponse> {
return this.request("GenerateUserSeal", req, cb)
}
/**
* 此接口(UploadFiles)用于文件上传。
*/
async UploadFiles(
req: UploadFilesRequest,
cb?: (error: string, rep: UploadFilesResponse) => void
): Promise<UploadFilesResponse> {
return this.request("UploadFiles", req, cb)
}
/**
* 此接口(DescribeCustomFlowIds)用于通过自定义流程id来查询对应的电子签流程id
*/
async DescribeCustomFlowIds(
req: DescribeCustomFlowIdsRequest,
cb?: (error: string, rep: DescribeCustomFlowIdsResponse) => void
): Promise<DescribeCustomFlowIdsResponse> {
return this.request("DescribeCustomFlowIds", req, cb)
}
/**
* 此接口(CreateSubOrganizationAndSeal)用于注册子机构,同时系统将为该子企业自动生成一个默认电子印章图片。
注意:
1. 在后续的签署流程中,若未指定签署使用的印章ID,则默认调用自动生成的印章图片进行签署。
2. 此接口为白名单接口,如您需要使用此能力,请提前与客户经理沟通或邮件至e-contract@tencent.com与我们联系。
*/
async CreateSubOrganizationAndSeal(
req: CreateSubOrganizationAndSealRequest,
cb?: (error: string, rep: CreateSubOrganizationAndSealResponse) => void
): Promise<CreateSubOrganizationAndSealResponse> {
return this.request("CreateSubOrganizationAndSeal", req, cb)
}
/**
* 通过此接口(DescribeFlow)可查询签署流程的详细信息。
*/
async DescribeFlow(
req: DescribeFlowRequest,
cb?: (error: string, rep: DescribeFlowResponse) => void
): Promise<DescribeFlowResponse> {
return this.request("DescribeFlow", req, cb)
}
/**
* 此接口(CreateFlowByFiles)用于通过PDF文件创建签署流程。
注意:调用此接口前,请先调用多文件上传接口 (UploadFiles),提前上传合同文件。
*/
async CreateFlowByFiles(
req: CreateFlowByFilesRequest,
cb?: (error: string, rep: CreateFlowByFilesResponse) => void
): Promise<CreateFlowByFilesResponse> {
return this.request("CreateFlowByFiles", req, cb)
}
/**
* 第三方应用可通过此接口(DescribeCatalogApprovers)查询指定目录的参与者列表
*/
async DescribeCatalogApprovers(
req: DescribeCatalogApproversRequest,
cb?: (error: string, rep: DescribeCatalogApproversResponse) => void
): Promise<DescribeCatalogApproversResponse> {
return this.request("DescribeCatalogApprovers", req, cb)
}
/**
* 此接口(DescribeSubOrganizations)用于查询子机构信息。
注:此接口仅可查询您所属机构应用号创建的子机构信息,不可跨应用/跨机构查询。
*/
async DescribeSubOrganizations(
req: DescribeSubOrganizationsRequest,
cb?: (error: string, rep: DescribeSubOrganizationsResponse) => void
): Promise<DescribeSubOrganizationsResponse> {
return this.request("DescribeSubOrganizations", req, cb)
}
/**
* 该接口为第三方平台向电子签平台验证银行卡二要素
*/
async CheckBankCard2EVerification(
req: CheckBankCard2EVerificationRequest,
cb?: (error: string, rep: CheckBankCard2EVerificationResponse) => void
): Promise<CheckBankCard2EVerificationResponse> {
return this.request("CheckBankCard2EVerification", req, cb)
}
/**
* 此接口(ArchiveFlow)用于流程的归档。
注意:归档后的流程不可再进行发送、签署、拒签、撤回等一系列操作。
*/
async ArchiveFlow(
req: ArchiveFlowRequest,
cb?: (error: string, rep: ArchiveFlowResponse) => void
): Promise<ArchiveFlowResponse> {
return this.request("ArchiveFlow", req, cb)
}
/**
* 该接口为第三方平台向电子签平台验证手机号二要素
*/
async CheckMobileAndName(
req: CheckMobileAndNameRequest,
cb?: (error: string, rep: CheckMobileAndNameResponse) => void
): Promise<CheckMobileAndNameResponse> {
return this.request("CheckMobileAndName", req, cb)
}
/**
* 生成企业电子印章
*/
async GenerateOrganizationSeal(
req: GenerateOrganizationSealRequest,
cb?: (error: string, rep: GenerateOrganizationSealResponse) => void
): Promise<GenerateOrganizationSealResponse> {
return this.request("GenerateOrganizationSeal", req, cb)
}
/**
* 此接口(ModifySubOrganizationInfo)用于更新子机构信息。
注:若修改子机构名称或更新机构证件照片,需要重新通过子机构实名接口(VerifySubOrganization)进行重新实名。
*/
async ModifySubOrganizationInfo(
req: ModifySubOrganizationInfoRequest,
cb?: (error: string, rep: ModifySubOrganizationInfoResponse) => void
): Promise<ModifySubOrganizationInfoResponse> {
return this.request("ModifySubOrganizationInfo", req, cb)
}
/**
* 第三方应用可通过此接口(CreateUserAndSeal)注册腾讯电子签实名个人用户,同时系统将为该用户自动生成一个默认电子签名图片。
注意:
1. 在后续的签署流程中,若未指定签署使用的印章ID,则默认调用自动生成的签名图片进行签署。
2. 此接口为白名单接口,如您需要使用此能力,请提前与客户经理沟通或邮件至e-contract@tencent.com与我们联系。
*/
async CreateUserAndSeal(
req: CreateUserAndSealRequest,
cb?: (error: string, rep: CreateUserAndSealResponse) => void
): Promise<CreateUserAndSealResponse> {
return this.request("CreateUserAndSeal", req, cb)
}
/**
* 通过此接口(DestroyFlowFile)可删除指定流程中的合同文件。
注:调用此接口前,请确保此流程已属于归档状态。您可通过查询流程信息接口(DescribeFlow)进行查询。
*/
async DestroyFlowFile(
req: DestroyFlowFileRequest,
cb?: (error: string, rep: DestroyFlowFileResponse) => void
): Promise<DestroyFlowFileResponse> {
return this.request("DestroyFlowFile", req, cb)
}
/**
* 此接口(ModifySeal)用于修改指定印章ID的印章图片和名称。
注:印章类型暂不支持修改,如需调整,请联系客服经理或通过创建印章接口(CreateSeal)进行创建新印章。
*/
async ModifySeal(
req: ModifySealRequest,
cb?: (error: string, rep: ModifySealResponse) => void
): Promise<ModifySealResponse> {
return this.request("ModifySeal", req, cb)
}
/**
* 根据用户自定义id查询文件id
*/
async DescribeFileIdsByCustomIds(
req: DescribeFileIdsByCustomIdsRequest,
cb?: (error: string, rep: DescribeFileIdsByCustomIdsResponse) => void
): Promise<DescribeFileIdsByCustomIdsResponse> {
return this.request("DescribeFileIdsByCustomIds", req, cb)
}
/**
* 此接口(SignFlow)可用于对流程文件进行签署。
*/
async SignFlow(
req: SignFlowRequest,
cb?: (error: string, rep: SignFlowResponse) => void
): Promise<SignFlowResponse> {
return this.request("SignFlow", req, cb)
}
/**
* 该接口为第三方平台向电子签平台获取慧眼人脸核身结果
*/
async DescribeFaceIdResults(
req: DescribeFaceIdResultsRequest,
cb?: (error: string, rep: DescribeFaceIdResultsResponse) => void
): Promise<DescribeFaceIdResultsResponse> {
return this.request("DescribeFaceIdResults", req, cb)
}
/**
* 第三方应用可通过此接口(DescribeCatalogSignComponents)拉取目录签署区
*/
async DescribeCatalogSignComponents(
req: DescribeCatalogSignComponentsRequest,
cb?: (error: string, rep: DescribeCatalogSignComponentsResponse) => void
): Promise<DescribeCatalogSignComponentsResponse> {
return this.request("DescribeCatalogSignComponents", req, cb)
}
/**
* 此接口(RejectFlow)用于用户拒绝签署合同流程。
*/
async RejectFlow(
req: RejectFlowRequest,
cb?: (error: string, rep: RejectFlowResponse) => void
): Promise<RejectFlowResponse> {
return this.request("RejectFlow", req, cb)
}
/**
* 此接口(ModifyUser)用于更新个人用户信息。
注:若修改用户姓名,需要重新通过个人用户实名接口(VerifyUser)进行重新实名。
*/
async ModifyUser(
req: ModifyUserRequest,
cb?: (error: string, rep: ModifyUserResponse) => void
): Promise<ModifyUserResponse> {
return this.request("ModifyUser", req, cb)
}
/**
* 此接口(VerifySubOrganization)用于通过子机构的实名认证。
注:此接口为白名单接口,如您需要使用此能力,请提前与客户经理沟通或邮件至e-contract@tencent.com与我们联系。
*/
async VerifySubOrganization(
req: VerifySubOrganizationRequest,
cb?: (error: string, rep: VerifySubOrganizationResponse) => void
): Promise<VerifySubOrganizationResponse> {
return this.request("VerifySubOrganization", req, cb)
}
/**
* 第三方应用可通过此接口(VerifyUser)将腾讯电子签个人用户的实名认证状态设为通过。
注:此接口为白名单接口,如您需要使用此能力,请提前与客户经理沟通或邮件至e-contract@tencent.com与我们联系。
*/
async VerifyUser(
req: VerifyUserRequest,
cb?: (error: string, rep: VerifyUserResponse) => void
): Promise<VerifyUserResponse> {
return this.request("VerifyUser", req, cb)
}
/**
* 此接口(DescribeCustomFlowIdsByFlowId)用于根据流程id反查自定义流程id
*/
async DescribeCustomFlowIdsByFlowId(
req: DescribeCustomFlowIdsByFlowIdRequest,
cb?: (error: string, rep: DescribeCustomFlowIdsByFlowIdResponse) => void
): Promise<DescribeCustomFlowIdsByFlowIdResponse> {
return this.request("DescribeCustomFlowIdsByFlowId", req, cb)
}
/**
* 该接口为第三方平台向电子签平台获取慧眼人脸核身照片
*/
async DescribeFaceIdPhotos(
req: DescribeFaceIdPhotosRequest,
cb?: (error: string, rep: DescribeFaceIdPhotosResponse) => void
): Promise<DescribeFaceIdPhotosResponse> {
return this.request("DescribeFaceIdPhotos", req, cb)
}
/**
* 该接口为第三方平台向电子签平台获取慧眼慧眼API签名
*/
async CreateFaceIdSign(
req: CreateFaceIdSignRequest,
cb?: (error: string, rep: CreateFaceIdSignResponse) => void
): Promise<CreateFaceIdSignResponse> {
return this.request("CreateFaceIdSign", req, cb)
}
/**
* 该接口为第三方平台向电子签平台验证姓名和身份证信息
*/
async CheckIdCardVerification(
req: CheckIdCardVerificationRequest,
cb?: (error: string, rep: CheckIdCardVerificationResponse) => void
): Promise<CheckIdCardVerificationResponse> {
return this.request("CheckIdCardVerification", req, cb)
}
/**
* 该接口为第三方平台向电子签平台验证银行卡三要素
*/
async CheckBankCard3EVerification(
req: CheckBankCard3EVerificationRequest,
cb?: (error: string, rep: CheckBankCard3EVerificationResponse) => void
): Promise<CheckBankCard3EVerificationResponse> {
return this.request("CheckBankCard3EVerification", req, cb)
}
/**
* 此接口(SendFlow)用于指定签署者及签署内容,后续可通过生成签署接口(CreateSignUrl)获取签署url。
*/
async SendFlow(
req: SendFlowRequest,
cb?: (error: string, rep: SendFlowResponse) => void
): Promise<SendFlowResponse> {
return this.request("SendFlow", req, cb)
}
/**
* 此接口(CreateUser)用于注册腾讯电子签个人用户。
*/
async CreateUser(
req: CreateUserRequest,
cb?: (error: string, rep: CreateUserResponse) => void
): Promise<CreateUserResponse> {
return this.request("CreateUser", req, cb)
}
/**
* 此接口 (ModifyOrganizationDefaultSeal) 用于重新指定企业默认印章。
*/
async ModifyOrganizationDefaultSeal(
req: ModifyOrganizationDefaultSealRequest,
cb?: (error: string, rep: ModifyOrganizationDefaultSealResponse) => void
): Promise<ModifyOrganizationDefaultSealResponse> {
return this.request("ModifyOrganizationDefaultSeal", req, cb)
}
/**
* 此接口(DescribeSeals)用于查询指定ID的印章信息。
*/
async DescribeSeals(
req: DescribeSealsRequest,
cb?: (error: string, rep: DescribeSealsResponse) => void
): Promise<DescribeSealsResponse> {
return this.request("DescribeSeals", req, cb)
}
/**
* 该接口为第三方平台向电子签平台验证银行卡二/三/四要素
银行卡二要素(同CheckBankCard2EVerification): bank_card + name
银行卡三要素(同CheckBankCard3EVerification): bank_card + name + id_card_number
银行卡四要素(同CheckBankCard4EVerification): bank_card + name + id_card_number + mobile
*/
async CheckBankCardVerification(
req: CheckBankCardVerificationRequest,
cb?: (error: string, rep: CheckBankCardVerificationResponse) => void
): Promise<CheckBankCardVerificationResponse> {
return this.request("CheckBankCardVerification", req, cb)
}
/**
* 此接口(CreateServerFlowSign)用于静默签署文件。
注:
1、此接口为白名单接口,调用前请提前与客服经理或邮件至e-contract@tencent.com进行联系。
2、仅合同发起者可使用流程静默签署能力。
*/
async CreateServerFlowSign(
req: CreateServerFlowSignRequest,
cb?: (error: string, rep: CreateServerFlowSignResponse) => void
): Promise<CreateServerFlowSignResponse> {
return this.request("CreateServerFlowSign", req, cb)
}
} | the_stack |
import {
DirectiveTransform,
createSimpleExpression,
Node,
NodeTypes,
SimpleExpressionNode,
CompoundExpressionNode,
isText,
TextNode,
InterpolationNode,
createCompoundExpression,
TO_DISPLAY_STRING,
TransformContext
} from '@vue/compiler-dom'
import {
isNumber,
isObject,
isString,
isSymbol,
toDisplayString
} from '@intlify/shared'
import { I18n, I18nMode, Locale } from 'vue-i18n'
import {
evaluateValue,
parseVTExpression,
TranslationParams
} from './transpiler'
import { report, ReportCodes } from './report'
import { createContentBuilder, ContentBuilder } from './builder'
// TODO: should be imported from vue-i18n
type VTDirectiveValue = {
path: string
locale?: Locale
args?: { [prop: string]: unknown }
choice?: number
plural?: number
}
/**
* Transform options for `v-t` custom directive
*
* @public
*/
export interface TransformVTDirectiveOptions<
Messages = {},
DateTimeFormats = {},
NumberFormats = {},
Legacy extends boolean = true
> {
/**
* I18n instance
*
* @remarks
* If this option is specified, `v-t` custom diretive transform uses an I18n instance to pre-translate.
* The translation will use the global resources registered in the I18n instance,
* that is, `v-t` diretive transform is also a limitation that the resources of each component cannot be used.
*/
i18n?: I18n<Messages, DateTimeFormats, NumberFormats, Legacy>
/**
* I18n Mode
*
* @remarks
* Specify the API style of vue-i18n. If you use legacy API style (e.g. `$t`) at vue-i18n, you need to specify `legacy`.
*
* @default 'composition'
*/
mode?: I18nMode
}
// compatibility for this commit(v3.0.3)
// https://github.com/vuejs/vue-next/commit/90bdf59f4c84ec0af9bab402c37090d82806cfc1
const enum ConstantTypes {
NOT_CONSTANT = 0,
CAN_SKIP_PATCH,
CAN_HOIST,
CAN_STRINGIFY
}
/**
* Transform `v-t` custom directive
*
* @remarks
* Transform that `v-t` custom directive is optimized vue-i18n code by Vue compiler.
* This transform can improve the performance by pre-translating, and it does support SSR.
*
* @param options - `v-t` custom directive transform options, see {@link TransformVTDirectiveOptions}
* @returns Directive transform
*
* @example
* ```js
* import { compile } from '@vue/compiler-dom'
* import { createI18n } from 'vue-i18n'
* import { transformVTDirective } from '@intlify/vue-i18n-extensions'
*
* // create i18n instance
* const i18n = createI18n({
* locale: 'ja',
* messages: {
* en: {
* hello: 'hello'
* },
* ja: {
* hello: 'こんにちは'
* }
* }
* })
*
* // get transform from `transformVTDirective` function, with `i18n` option
* const transformVT = transformVTDirective({ i18n })
*
* const { code } = compile(`<p v-t="'hello'"></p>`, {
* mode: 'function',
* hoistStatic: true,
* prefixIdentifiers: true,
* directiveTransforms: { t: transformVT } // <- you need to specify to `directiveTransforms` option!
* })
*
* console.log(code)
* // output ->
* // const { createVNode: _createVNode, openBlock: _openBlock, createBlock: _createBlock } = Vue
* // return function render(_ctx, _cache) {
* // return (_openBlock(), _createBlock(\\"div\\", null, \\"こんにちは!\\"))
* // }
* ```
* @public
*/
export function transformVTDirective<
Messages = {},
DateTimeFormats = {},
NumberFormats = {},
Legacy extends boolean = true
>(
options: TransformVTDirectiveOptions<
Messages,
DateTimeFormats,
NumberFormats,
Legacy
> = {}
): DirectiveTransform {
const i18nInstance = options.i18n
const mode =
isString(options.mode) && ['composition', 'legacy'].includes(options.mode)
? options.mode
: 'composition'
return (dir, node, context) => {
const { exp, loc } = dir
// console.log('v-t dir', dir)
// console.log('v-t node', node)
if (!exp) {
// TODO: throw error with context.OnError
// NOTE: We need to support from @vue/compiler-core
// https://github.com/vuejs/vue-next/issues/1147
report(ReportCodes.UNEXPECTED_DIRECTIVE_EXPRESSION, {
mode: 'error',
args: [node.loc.source || ''],
loc: node.loc
})
}
if (node.children.length > 0) {
// TODO: throw error with context.OnError
// NOTE: We need to support from @vue/compiler-core
// https://github.com/vuejs/vue-next/issues/1147
report(ReportCodes.ORVERRIDE_ELEMENT_CHILDREN, {
mode: 'error',
args: [node.loc.source || ''],
loc: node.loc
})
node.children.length = 0
}
if (dir.modifiers.includes('preserve')) {
report(ReportCodes.NOT_SUPPORTED_PRESERVE, {
args: [node.loc.source || ''],
loc: node.loc
})
}
if (isSimpleExpressionNode(exp)) {
if (isConstant(exp) && i18nInstance) {
const { status, value } = evaluateValue(exp.content)
if (status === 'ng') {
report(ReportCodes.FAILED_VALUE_EVALUATION, {
args: [node.loc.source || ''],
loc: node.loc
})
return { props: [] }
}
const [parsedValue, parseStatus] = parseValue(value)
if (parseStatus !== ReportCodes.SUCCESS) {
report(parseStatus, { args: [node.loc.source || ''], loc: node.loc })
return { props: [] }
}
const global =
i18nInstance.mode === 'composition'
? (i18nInstance.global as any) // eslint-disable-line @typescript-eslint/no-explicit-any
: (i18nInstance.global as any).__composer // eslint-disable-line @typescript-eslint/no-explicit-any
const content = global.t(...makeParams(parsedValue!))
node.children.push({
type: NodeTypes.TEXT,
content
} as TextNode)
return { props: [] }
} else {
const translationParams = parseVTExpression(exp.content)
const code = generateTranslationCode(context, mode, translationParams)
context.helper(TO_DISPLAY_STRING)
node.children.push({
type: NodeTypes.INTERPOLATION,
content: createCompoundExpression([
createSimpleExpression(
code,
false,
loc,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
ConstantTypes.NOT_CONSTANT as any
)
])
} as InterpolationNode)
return { props: [] }
}
} else if (isCompoundExpressionNode(exp)) {
const content = exp.children.map(mapNodeContentHanlder).join('')
const code = generateTranslationCode(
context,
mode,
parseVTExpression(content)
)
context.helper(TO_DISPLAY_STRING)
node.children.push({
type: NodeTypes.INTERPOLATION,
content: createCompoundExpression([
createSimpleExpression(
code,
false,
loc,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
ConstantTypes.NOT_CONSTANT as any
)
])
} as InterpolationNode)
return { props: [] }
} else {
report(ReportCodes.NOT_SUPPORTED, {
args: [node.loc.source || ''],
loc: node.loc
})
return { props: [] }
}
}
}
function isSimpleExpressionNode(
node: Node | undefined
): node is SimpleExpressionNode {
return node != null && node.type === NodeTypes.SIMPLE_EXPRESSION
}
function isCompoundExpressionNode(
node: Node | undefined
): node is CompoundExpressionNode {
return node != null && node.type === NodeTypes.COMPOUND_EXPRESSION
}
function isConstant(node: SimpleExpressionNode): boolean {
if ('isConstant' in node) {
// for v3.0.3 earlier
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return (node as any).isConstant
} else if ('constType' in node) {
// for v3.0.3 or later
return (node.constType as number) <= ConstantTypes.CAN_STRINGIFY
} else {
throw Error('unexpected error')
}
}
function mapNodeContentHanlder(
value:
| string
| symbol
| SimpleExpressionNode
| CompoundExpressionNode
| TextNode
| InterpolationNode
): string {
if (isString(value)) {
return value
} else if (isSymbol(value)) {
return value.description || ''
} else if (isSimpleExpressionNode(value)) {
return value.content
} else if (isCompoundExpressionNode(value)) {
return value.children.map(mapNodeContentHanlder).join('')
} else if (isText(value)) {
if (isString(value.content)) {
return value.content
} else if (isSimpleExpressionNode(value.content)) {
return value.content.content
} else if (isCompoundExpressionNode(value.content)) {
return value.content.children.map(mapNodeContentHanlder).join('')
} else {
return ''
}
} else {
return ''
}
}
function parseValue(value: unknown): [VTDirectiveValue | null, ReportCodes] {
if (isString(value)) {
return [{ path: value }, ReportCodes.SUCCESS]
} else if (isObject(value)) {
if (!('path' in value)) {
return [null, ReportCodes.REQUIRED_PARAMETER]
}
return [value as VTDirectiveValue, ReportCodes.SUCCESS]
} else {
return [null, ReportCodes.INVALID_PARAMETER_TYPE]
}
}
function makeParams(value: VTDirectiveValue): unknown[] {
const { path, locale, args, choice, plural } = value
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const options = {} as any
const named: { [prop: string]: unknown } = args || {}
if (isString(locale)) {
options.locale = locale
}
if (isNumber(choice)) {
options.plural = choice
}
if (isNumber(plural)) {
options.plural = plural
}
return [path, named, options]
}
function generateTranslationCode(
context: TransformContext,
mode: I18nMode,
params: TranslationParams
): string {
return mode === 'composition'
? generateComposableCode(context, params)
: generateLegacyCode(context, params)
}
function generateComposableCode(
context: TransformContext,
params: TranslationParams
): string {
const baseCode = `${context.prefixIdentifiers ? '_ctx.' : ''}t`
const builder = createContentBuilder()
builder.push(`${baseCode}(`)
// generate path
builder.push(`${toDisplayString(params.path)}`)
// generate named
builder.push(`, { `)
generateNamedCode(builder, params.named)
builder.push(` }`)
// generate options
builder.push(`, { `)
if (params.options.locale) {
builder.push(`locale: ${toDisplayString(params.options.locale)}`)
}
if (params.options.plural) {
if (params.options.locale) {
builder.push(', ')
}
builder.push(`plural: ${toDisplayString(params.options.plural)}`)
}
builder.push(` }`)
builder.push(`)`)
const content = builder.content
return content
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function generateNamedCode(builder: ContentBuilder, named: any): void {
const keys = Object.keys(named)
keys.forEach(k => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const v: any = named[k]
if (isObject(v)) {
builder.push(`${k}: { `)
generateNamedCode(builder, v)
builder.push(` }`)
} else {
builder.push(`${k}: ${toDisplayString(v)}`)
}
})
}
function generateLegacyCode(
context: TransformContext,
params: TranslationParams
): string {
const mode = !params.options.plural ? 'basic' : 'plural'
const baseCode = `${context.prefixIdentifiers ? '_ctx.' : ''}${
mode === 'basic' ? '$t' : '$tc'
}`
const builder = createContentBuilder()
builder.push(`${baseCode}(`)
// generate path
builder.push(`${toDisplayString(params.path)}`)
if (mode === 'basic') {
// generate locale
if (isString(params.options.locale)) {
builder.push(`, ${toDisplayString(params.options.locale)}`)
}
// generate named
builder.push(`, { `)
generateNamedCode(builder, params.named)
builder.push(` }`)
} else {
// generaete plural
builder.push(`, ${toDisplayString(params.options.plural)}`)
if (isString(params.options.locale)) {
// generate locale
builder.push(`, ${toDisplayString(params.options.locale)}`)
} else {
// generate named
builder.push(`, { `)
generateNamedCode(builder, params.named)
builder.push(` }`)
}
}
builder.push(`)`)
const content = builder.content
return content
} | the_stack |
// eslint-disable-next-line max-len
// [...$0.children].map(el => ({ label: (el.getAttribute('aria-label')|| '').replace(/\(.*?\)(.+)/, '$1').trim(), name: el.getAttribute('data-value'), offset: +(el.getAttribute('aria-label')|| '').replace(/\(.*?(-?[0-9]{2}):([0-9]{2})\).*/, (all, one, two) => +one + (two / 60) * (one > 0 ? 1 : -1)) }))
export default [
{
label: 'Niue Time',
name: 'Pacific/Niue',
offset: -11,
},
{
label: 'Samoa Standard Time',
name: 'Pacific/Pago_Pago',
offset: -11,
},
{
label: 'Cook Islands Standard Time',
name: 'Pacific/Rarotonga',
offset: -10,
},
{
label: 'Hawaii-Aleutian Standard Time',
name: 'Pacific/Honolulu',
offset: -10,
},
{
label: 'Hawaii-Aleutian Time',
name: 'America/Adak',
offset: -10,
},
{
label: 'Tahiti Time',
name: 'Pacific/Tahiti',
offset: -10,
},
{
label: 'Marquesas Time',
name: 'Pacific/Marquesas',
offset: -9.5,
},
{
label: 'Alaska Time - Anchorage',
name: 'America/Anchorage',
offset: -9,
},
{
label: 'Alaska Time - Juneau',
name: 'America/Juneau',
offset: -9,
},
{
label: 'Alaska Time - Nome',
name: 'America/Nome',
offset: -9,
},
{
label: 'Alaska Time - Sitka',
name: 'America/Sitka',
offset: -9,
},
{
label: 'Alaska Time - Yakutat',
name: 'America/Yakutat',
offset: -9,
},
{
label: 'Gambier Time',
name: 'Pacific/Gambier',
offset: -9,
},
{
label: 'Pacific Time - Dawson',
name: 'America/Dawson',
offset: -8,
},
{
label: 'Pacific Time - Los Angeles',
name: 'America/Los_Angeles',
offset: -8,
},
{
label: 'Pacific Time - Metlakatla',
name: 'America/Metlakatla',
offset: -8,
},
{
label: 'Pacific Time - Tijuana',
name: 'America/Tijuana',
offset: -8,
},
{
label: 'Pacific Time - Vancouver',
name: 'America/Vancouver',
offset: -8,
},
{
label: 'Pacific Time - Whitehorse',
name: 'America/Whitehorse',
offset: -8,
},
{
label: 'Pitcairn Time',
name: 'Pacific/Pitcairn',
offset: -8,
},
{
label: 'Mexican Pacific Standard Time',
name: 'America/Hermosillo',
offset: -7,
},
{
label: 'Mexican Pacific Time - Chihuahua',
name: 'America/Chihuahua',
offset: -7,
},
{
label: 'Mexican Pacific Time - Mazatlan',
name: 'America/Mazatlan',
offset: -7,
},
{
label: 'Mountain Standard Time - Creston',
name: 'America/Creston',
offset: -7,
},
{
label: 'Mountain Standard Time - Dawson Creek',
name: 'America/Dawson_Creek',
offset: -7,
},
{
label: 'Mountain Standard Time - Fort Nelson',
name: 'America/Fort_Nelson',
offset: -7,
},
{
label: 'Mountain Standard Time - Phoenix',
name: 'America/Phoenix',
offset: -7,
},
{
label: 'Mountain Time - Boise',
name: 'America/Boise',
offset: -7,
},
{
label: 'Mountain Time - Cambridge Bay',
name: 'America/Cambridge_Bay',
offset: -7,
},
{
label: 'Mountain Time - Denver',
name: 'America/Denver',
offset: -7,
},
{
label: 'Mountain Time - Edmonton',
name: 'America/Edmonton',
offset: -7,
},
{
label: 'Mountain Time - Inuvik',
name: 'America/Inuvik',
offset: -7,
},
{
label: 'Mountain Time - Ojinaga',
name: 'America/Ojinaga',
offset: -7,
},
{
label: 'Mountain Time - Yellowknife',
name: 'America/Yellowknife',
offset: -7,
},
{
label: 'Central Standard Time - Belize',
name: 'America/Belize',
offset: -6,
},
{
label: 'Central Standard Time - Costa Rica',
name: 'America/Costa_Rica',
offset: -6,
},
{
label: 'Central Standard Time - El Salvador',
name: 'America/El_Salvador',
offset: -6,
},
{
label: 'Central Standard Time - Guatemala',
name: 'America/Guatemala',
offset: -6,
},
{
label: 'Central Standard Time - Managua',
name: 'America/Managua',
offset: -6,
},
{
label: 'Central Standard Time - Regina',
name: 'America/Regina',
offset: -6,
},
{
label: 'Central Standard Time - Swift Current',
name: 'America/Swift_Current',
offset: -6,
},
{
label: 'Central Standard Time - Tegucigalpa',
name: 'America/Tegucigalpa',
offset: -6,
},
{
label: 'Central Time - Bahia Banderas',
name: 'America/Bahia_Banderas',
offset: -6,
},
{
label: 'Central Time - Beulah, North Dakota',
name: 'America/North_Dakota/Beulah',
offset: -6,
},
{
label: 'Central Time - Center, North Dakota',
name: 'America/North_Dakota/Center',
offset: -6,
},
{
label: 'Central Time - Chicago',
name: 'America/Chicago',
offset: -6,
},
{
label: 'Central Time - Knox, Indiana',
name: 'America/Indiana/Knox',
offset: -6,
},
{
label: 'Central Time - Matamoros',
name: 'America/Matamoros',
offset: -6,
},
{
label: 'Central Time - Menominee',
name: 'America/Menominee',
offset: -6,
},
{
label: 'Central Time - Merida',
name: 'America/Merida',
offset: -6,
},
{
label: 'Central Time - Mexico City',
name: 'America/Mexico_City',
offset: -6,
},
{
label: 'Central Time - Monterrey',
name: 'America/Monterrey',
offset: -6,
},
{
label: 'Central Time - New Salem, North Dakota',
name: 'America/North_Dakota/New_Salem',
offset: -6,
},
{
label: 'Central Time - Rainy River',
name: 'America/Rainy_River',
offset: -6,
},
{
label: 'Central Time - Rankin Inlet',
name: 'America/Rankin_Inlet',
offset: -6,
},
{
label: 'Central Time - Resolute',
name: 'America/Resolute',
offset: -6,
},
{
label: 'Central Time - Tell City, Indiana',
name: 'America/Indiana/Tell_City',
offset: -6,
},
{
label: 'Central Time - Winnipeg',
name: 'America/Winnipeg',
offset: -6,
},
{
label: 'Galapagos Time',
name: 'Pacific/Galapagos',
offset: -6,
},
{
label: 'Acre Standard Time - Eirunepe',
name: 'America/Eirunepe',
offset: -5,
},
{
label: 'Acre Standard Time - Rio Branco',
name: 'America/Rio_Branco',
offset: -5,
},
{
label: 'Colombia Standard Time',
name: 'America/Bogota',
offset: -5,
},
{
label: 'Cuba Time',
name: 'America/Havana',
offset: -5,
},
{
label: 'Easter Island Time',
name: 'Pacific/Easter',
offset: -5,
},
{
label: 'Eastern Standard Time - Atikokan',
name: 'America/Atikokan',
offset: -5,
},
{
label: 'Eastern Standard Time - Cancun',
name: 'America/Cancun',
offset: -5,
},
{
label: 'Eastern Standard Time - Jamaica',
name: 'America/Jamaica',
offset: -5,
},
{
label: 'Eastern Standard Time - Panama',
name: 'America/Panama',
offset: -5,
},
{
label: 'Eastern Time - Detroit',
name: 'America/Detroit',
offset: -5,
},
{
label: 'Eastern Time - Grand Turk',
name: 'America/Grand_Turk',
offset: -5,
},
{
label: 'Eastern Time - Indianapolis',
name: 'America/Indiana/Indianapolis',
offset: -5,
},
{
label: 'Eastern Time - Iqaluit',
name: 'America/Iqaluit',
offset: -5,
},
{
label: 'Eastern Time - Louisville',
name: 'America/Kentucky/Louisville',
offset: -5,
},
{
label: 'Eastern Time - Marengo, Indiana',
name: 'America/Indiana/Marengo',
offset: -5,
},
{
label: 'Eastern Time - Monticello, Kentucky',
name: 'America/Kentucky/Monticello',
offset: -5,
},
{
label: 'Eastern Time - Nassau',
name: 'America/Nassau',
offset: -5,
},
{
label: 'Eastern Time - New York',
name: 'America/New_York',
offset: -5,
},
{
label: 'Eastern Time - Nipigon',
name: 'America/Nipigon',
offset: -5,
},
{
label: 'Eastern Time - Pangnirtung',
name: 'America/Pangnirtung',
offset: -5,
},
{
label: 'Eastern Time - Petersburg, Indiana',
name: 'America/Indiana/Petersburg',
offset: -5,
},
{
label: 'Eastern Time - Port-au-Prince',
name: 'America/Port-au-Prince',
offset: -5,
},
{
label: 'Eastern Time - Thunder Bay',
name: 'America/Thunder_Bay',
offset: -5,
},
{
label: 'Eastern Time - Toronto',
name: 'America/Toronto',
offset: -5,
},
{
label: 'Eastern Time - Vevay, Indiana',
name: 'America/Indiana/Vevay',
offset: -5,
},
{
label: 'Eastern Time - Vincennes, Indiana',
name: 'America/Indiana/Vincennes',
offset: -5,
},
{
label: 'Eastern Time - Winamac, Indiana',
name: 'America/Indiana/Winamac',
offset: -5,
},
{
label: 'Ecuador Time',
name: 'America/Guayaquil',
offset: -5,
},
{
label: 'Peru Standard Time',
name: 'America/Lima',
offset: -5,
},
{
label: 'Amazon Standard Time - Boa Vista',
name: 'America/Boa_Vista',
offset: -4,
},
{
label: 'Amazon Standard Time - Manaus',
name: 'America/Manaus',
offset: -4,
},
{
label: 'Amazon Standard Time - Porto Velho',
name: 'America/Porto_Velho',
offset: -4,
},
{
label: 'Atlantic Standard Time - Barbados',
name: 'America/Barbados',
offset: -4,
},
{
label: 'Atlantic Standard Time - Blanc-Sablon',
name: 'America/Blanc-Sablon',
offset: -4,
},
{
label: 'Atlantic Standard Time - Curaçao',
name: 'America/Curacao',
offset: -4,
},
{
label: 'Atlantic Standard Time - Martinique',
name: 'America/Martinique',
offset: -4,
},
{
label: 'Atlantic Standard Time - Port of Spain',
name: 'America/Port_of_Spain',
offset: -4,
},
{
label: 'Atlantic Standard Time - Puerto Rico',
name: 'America/Puerto_Rico',
offset: -4,
},
{
label: 'Atlantic Standard Time - Santo Domingo',
name: 'America/Santo_Domingo',
offset: -4,
},
{
label: 'Atlantic Time - Bermuda',
name: 'Atlantic/Bermuda',
offset: -4,
},
{
label: 'Atlantic Time - Glace Bay',
name: 'America/Glace_Bay',
offset: -4,
},
{
label: 'Atlantic Time - Goose Bay',
name: 'America/Goose_Bay',
offset: -4,
},
{
label: 'Atlantic Time - Halifax',
name: 'America/Halifax',
offset: -4,
},
{
label: 'Atlantic Time - Moncton',
name: 'America/Moncton',
offset: -4,
},
{
label: 'Atlantic Time - Thule',
name: 'America/Thule',
offset: -4,
},
{
label: 'Bolivia Time',
name: 'America/La_Paz',
offset: -4,
},
{
label: 'Guyana Time',
name: 'America/Guyana',
offset: -4,
},
{
label: 'Venezuela Time',
name: 'America/Caracas',
offset: -4,
},
{
label: 'Newfoundland Time',
name: 'America/St_Johns',
offset: -3.5,
},
{
label: 'Amazon Time (Campo Grande)',
name: 'America/Campo_Grande',
offset: -3,
},
{
label: 'Amazon Time (Cuiaba)',
name: 'America/Cuiaba',
offset: -3,
},
{
label: 'Argentina Standard Time - Buenos Aires',
name: 'America/Argentina/Buenos_Aires',
offset: -3,
},
{
label: 'Argentina Standard Time - Catamarca',
name: 'America/Argentina/Catamarca',
offset: -3,
},
{
label: 'Argentina Standard Time - Cordoba',
name: 'America/Argentina/Cordoba',
offset: -3,
},
{
label: 'Argentina Standard Time - Jujuy',
name: 'America/Argentina/Jujuy',
offset: -3,
},
{
label: 'Argentina Standard Time - La Rioja',
name: 'America/Argentina/La_Rioja',
offset: -3,
},
{
label: 'Argentina Standard Time - Mendoza',
name: 'America/Argentina/Mendoza',
offset: -3,
},
{
label: 'Argentina Standard Time - Rio Gallegos',
name: 'America/Argentina/Rio_Gallegos',
offset: -3,
},
{
label: 'Argentina Standard Time - Salta',
name: 'America/Argentina/Salta',
offset: -3,
},
{
label: 'Argentina Standard Time - San Juan',
name: 'America/Argentina/San_Juan',
offset: -3,
},
{
label: 'Argentina Standard Time - Tucuman',
name: 'America/Argentina/Tucuman',
offset: -3,
},
{
label: 'Argentina Standard Time - Ushuaia',
name: 'America/Argentina/Ushuaia',
offset: -3,
},
{
label: 'Brasilia Standard Time - Araguaina',
name: 'America/Araguaina',
offset: -3,
},
{
label: 'Brasilia Standard Time - Bahia',
name: 'America/Bahia',
offset: -3,
},
{
label: 'Brasilia Standard Time - Belem',
name: 'America/Belem',
offset: -3,
},
{
label: 'Brasilia Standard Time - Fortaleza',
name: 'America/Fortaleza',
offset: -3,
},
{
label: 'Brasilia Standard Time - Maceio',
name: 'America/Maceio',
offset: -3,
},
{
label: 'Brasilia Standard Time - Recife',
name: 'America/Recife',
offset: -3,
},
{
label: 'Brasilia Standard Time - Santarem',
name: 'America/Santarem',
offset: -3,
},
{
label: 'Chile Time',
name: 'America/Santiago',
offset: -3,
},
{
label: 'Falkland Islands Standard Time',
name: 'Atlantic/Stanley',
offset: -3,
},
{
label: 'French Guiana Time',
name: 'America/Cayenne',
offset: -3,
},
{
label: 'Palmer Time',
name: 'Antarctica/Palmer',
offset: -3,
},
{
label: 'Paraguay Time',
name: 'America/Asuncion',
offset: -3,
},
{
label: 'Punta Arenas Time',
name: 'America/Punta_Arenas',
offset: -3,
},
{
label: 'Rothera Time',
name: 'Antarctica/Rothera',
offset: -3,
},
{
label: 'St. Pierre & Miquelon Time',
name: 'America/Miquelon',
offset: -3,
},
{
label: 'Suriname Time',
name: 'America/Paramaribo',
offset: -3,
},
{
label: 'Uruguay Standard Time',
name: 'America/Montevideo',
offset: -3,
},
{
label: 'West Greenland Time',
name: 'America/Godthab',
offset: -3,
},
{
label: 'Western Argentina Standard Time',
name: 'America/Argentina/San_Luis',
offset: -3,
},
{
label: 'Brasilia Time',
name: 'America/Sao_Paulo',
offset: -3,
},
{
label: 'Fernando de Noronha Standard Time',
name: 'America/Noronha',
offset: -2,
},
{
label: 'South Georgia Time',
name: 'Atlantic/South_Georgia',
offset: -2,
},
{
label: 'Azores Time',
name: 'Atlantic/Azores',
offset: -1,
},
{
label: 'Cape Verde Standard Time',
name: 'Atlantic/Cape_Verde',
offset: -1,
},
{
label: 'East Greenland Time',
name: 'America/Scoresbysund',
offset: -1,
},
{
label: 'Coordinated Universal Time',
name: 'UTC',
offset: 0,
},
{
label: 'Greenwich Mean Time',
name: 'Etc/GMT',
offset: 0,
},
{
label: 'Greenwich Mean Time - Abidjan',
name: 'Africa/Abidjan',
offset: 0,
},
{
label: 'Greenwich Mean Time - Accra',
name: 'Africa/Accra',
offset: 0,
},
{
label: 'Greenwich Mean Time - Bissau',
name: 'Africa/Bissau',
offset: 0,
},
{
label: 'Greenwich Mean Time - Danmarkshavn',
name: 'America/Danmarkshavn',
offset: 0,
},
{
label: 'Greenwich Mean Time - Monrovia',
name: 'Africa/Monrovia',
offset: 0,
},
{
label: 'Greenwich Mean Time - Reykjavik',
name: 'Atlantic/Reykjavik',
offset: 0,
},
{
label: 'Greenwich Mean Time - São Tomé',
name: 'Africa/Sao_Tome',
offset: 0,
},
{
label: 'Ireland Time',
name: 'Europe/Dublin',
offset: 0,
},
{
label: 'Troll Time',
name: 'Antarctica/Troll',
offset: 0,
},
{
label: 'United Kingdom Time',
name: 'Europe/London',
offset: 0,
},
{
label: 'Western European Time - Canary',
name: 'Atlantic/Canary',
offset: 0,
},
{
label: 'Western European Time - Faroe',
name: 'Atlantic/Faroe',
offset: 0,
},
{
label: 'Western European Time - Lisbon',
name: 'Europe/Lisbon',
offset: 0,
},
{
label: 'Western European Time - Madeira',
name: 'Atlantic/Madeira',
offset: 0,
},
{
label: 'Central European Standard Time - Algiers',
name: 'Africa/Algiers',
offset: 1,
},
{
label: 'Central European Standard Time - Tunis',
name: 'Africa/Tunis',
offset: 1,
},
{
label: 'Central European Time - Amsterdam',
name: 'Europe/Amsterdam',
offset: 1,
},
{
label: 'Central European Time - Andorra',
name: 'Europe/Andorra',
offset: 1,
},
{
label: 'Central European Time - Belgrade',
name: 'Europe/Belgrade',
offset: 1,
},
{
label: 'Central European Time - Berlin',
name: 'Europe/Berlin',
offset: 1,
},
{
label: 'Central European Time - Brussels',
name: 'Europe/Brussels',
offset: 1,
},
{
label: 'Central European Time - Budapest',
name: 'Europe/Budapest',
offset: 1,
},
{
label: 'Central European Time - Ceuta',
name: 'Africa/Ceuta',
offset: 1,
},
{
label: 'Central European Time - Copenhagen',
name: 'Europe/Copenhagen',
offset: 1,
},
{
label: 'Central European Time - Gibraltar',
name: 'Europe/Gibraltar',
offset: 1,
},
{
label: 'Central European Time - Luxembourg',
name: 'Europe/Luxembourg',
offset: 1,
},
{
label: 'Central European Time - Madrid',
name: 'Europe/Madrid',
offset: 1,
},
{
label: 'Central European Time - Malta',
name: 'Europe/Malta',
offset: 1,
},
{
label: 'Central European Time - Monaco',
name: 'Europe/Monaco',
offset: 1,
},
{
label: 'Central European Time - Oslo',
name: 'Europe/Oslo',
offset: 1,
},
{
label: 'Central European Time - Paris',
name: 'Europe/Paris',
offset: 1,
},
{
label: 'Central European Time - Prague',
name: 'Europe/Prague',
offset: 1,
},
{
label: 'Central European Time - Rome',
name: 'Europe/Rome',
offset: 1,
},
{
label: 'Central European Time - Stockholm',
name: 'Europe/Stockholm',
offset: 1,
},
{
label: 'Central European Time - Tirane',
name: 'Europe/Tirane',
offset: 1,
},
{
label: 'Central European Time - Vienna',
name: 'Europe/Vienna',
offset: 1,
},
{
label: 'Central European Time - Warsaw',
name: 'Europe/Warsaw',
offset: 1,
},
{
label: 'Central European Time - Zurich',
name: 'Europe/Zurich',
offset: 1,
},
{
label: 'Morocco Time',
name: 'Africa/Casablanca',
offset: 1,
},
{
label: 'West Africa Standard Time - Lagos',
name: 'Africa/Lagos',
offset: 1,
},
{
label: 'West Africa Standard Time - Ndjamena',
name: 'Africa/Ndjamena',
offset: 1,
},
{
label: 'Western Sahara Time',
name: 'Africa/El_Aaiun',
offset: 1,
},
{
label: 'Central Africa Time - Khartoum',
name: 'Africa/Khartoum',
offset: 2,
},
{
label: 'Central Africa Time - Maputo',
name: 'Africa/Maputo',
offset: 2,
},
{
label: 'Central Africa Time - Windhoek',
name: 'Africa/Windhoek',
offset: 2,
},
{
label: 'Eastern European Standard Time - Cairo',
name: 'Africa/Cairo',
offset: 2,
},
{
label: 'Eastern European Standard Time - Kaliningrad',
name: 'Europe/Kaliningrad',
offset: 2,
},
{
label: 'Eastern European Standard Time - Tripoli',
name: 'Africa/Tripoli',
offset: 2,
},
{
label: 'Eastern European Time - Amman',
name: 'Asia/Amman',
offset: 2,
},
{
label: 'Eastern European Time - Athens',
name: 'Europe/Athens',
offset: 2,
},
{
label: 'Eastern European Time - Beirut',
name: 'Asia/Beirut',
offset: 2,
},
{
label: 'Eastern European Time - Bucharest',
name: 'Europe/Bucharest',
offset: 2,
},
{
label: 'Eastern European Time - Chisinau',
name: 'Europe/Chisinau',
offset: 2,
},
{
label: 'Eastern European Time - Damascus',
name: 'Asia/Damascus',
offset: 2,
},
{
label: 'Eastern European Time - Gaza',
name: 'Asia/Gaza',
offset: 2,
},
{
label: 'Eastern European Time - Hebron',
name: 'Asia/Hebron',
offset: 2,
},
{
label: 'Eastern European Time - Helsinki',
name: 'Europe/Helsinki',
offset: 2,
},
{
label: 'Eastern European Time - Kiev',
name: 'Europe/Kiev',
offset: 2,
},
{
label: 'Eastern European Time - Nicosia',
name: 'Asia/Nicosia',
offset: 2,
},
{
label: 'Eastern European Time - Riga',
name: 'Europe/Riga',
offset: 2,
},
{
label: 'Eastern European Time - Sofia',
name: 'Europe/Sofia',
offset: 2,
},
{
label: 'Eastern European Time - Tallinn',
name: 'Europe/Tallinn',
offset: 2,
},
{
label: 'Eastern European Time - Uzhhorod',
name: 'Europe/Uzhgorod',
offset: 2,
},
{
label: 'Eastern European Time - Vilnius',
name: 'Europe/Vilnius',
offset: 2,
},
{
label: 'Eastern European Time - Zaporozhye',
name: 'Europe/Zaporozhye',
offset: 2,
},
{
label: 'Famagusta Time',
name: 'Asia/Famagusta',
offset: 2,
},
{
label: 'Israel Time',
name: 'Asia/Jerusalem',
offset: 2,
},
{
label: 'South Africa Standard Time',
name: 'Africa/Johannesburg',
offset: 2,
},
{
label: 'Arabian Standard Time - Baghdad',
name: 'Asia/Baghdad',
offset: 3,
},
{
label: 'Arabian Standard Time - Qatar',
name: 'Asia/Qatar',
offset: 3,
},
{
label: 'Arabian Standard Time - Riyadh',
name: 'Asia/Riyadh',
offset: 3,
},
{
label: 'East Africa Time - Juba',
name: 'Africa/Juba',
offset: 3,
},
{
label: 'East Africa Time - Nairobi',
name: 'Africa/Nairobi',
offset: 3,
},
{
label: 'Kirov Time',
name: 'Europe/Kirov',
offset: 3,
},
{
label: 'Moscow Standard Time - Minsk',
name: 'Europe/Minsk',
offset: 3,
},
{
label: 'Moscow Standard Time - Moscow',
name: 'Europe/Moscow',
offset: 3,
},
{
label: 'Moscow Standard Time - Simferopol',
name: 'Europe/Simferopol',
offset: 3,
},
{
label: 'Syowa Time',
name: 'Antarctica/Syowa',
offset: 3,
},
{
label: 'Turkey Time',
name: 'Europe/Istanbul',
offset: 3,
},
{
label: 'Iran Time',
name: 'Asia/Tehran',
offset: 3.5,
},
{
label: 'Armenia Standard Time',
name: 'Asia/Yerevan',
offset: 4,
},
{
label: 'Astrakhan Time',
name: 'Europe/Astrakhan',
offset: 4,
},
{
label: 'Azerbaijan Standard Time',
name: 'Asia/Baku',
offset: 4,
},
{
label: 'Georgia Standard Time',
name: 'Asia/Tbilisi',
offset: 4,
},
{
label: 'Gulf Standard Time',
name: 'Asia/Dubai',
offset: 4,
},
{
label: 'Mauritius Standard Time',
name: 'Indian/Mauritius',
offset: 4,
},
{
label: 'Réunion Time',
name: 'Indian/Reunion',
offset: 4,
},
{
label: 'Samara Standard Time',
name: 'Europe/Samara',
offset: 4,
},
{
label: 'Saratov Time',
name: 'Europe/Saratov',
offset: 4,
},
{
label: 'Seychelles Time',
name: 'Indian/Mahe',
offset: 4,
},
{
label: 'Ulyanovsk Time',
name: 'Europe/Ulyanovsk',
offset: 4,
},
{
label: 'Volgograd Standard Time',
name: 'Europe/Volgograd',
offset: 4,
},
{
label: 'Afghanistan Time',
name: 'Asia/Kabul',
offset: 4.5,
},
{
label: 'French Southern & Antarctic Time',
name: 'Indian/Kerguelen',
offset: 5,
},
{
label: 'Maldives Time',
name: 'Indian/Maldives',
offset: 5,
},
{
label: 'Mawson Time',
name: 'Antarctica/Mawson',
offset: 5,
},
{
label: 'Pakistan Standard Time',
name: 'Asia/Karachi',
offset: 5,
},
{
label: 'Tajikistan Time',
name: 'Asia/Dushanbe',
offset: 5,
},
{
label: 'Turkmenistan Standard Time',
name: 'Asia/Ashgabat',
offset: 5,
},
{
label: 'Uzbekistan Standard Time - Samarkand',
name: 'Asia/Samarkand',
offset: 5,
},
{
label: 'Uzbekistan Standard Time - Tashkent',
name: 'Asia/Tashkent',
offset: 5,
},
{
label: 'West Kazakhstan Time - Aqtau',
name: 'Asia/Aqtau',
offset: 5,
},
{
label: 'West Kazakhstan Time - Aqtobe',
name: 'Asia/Aqtobe',
offset: 5,
},
{
label: 'West Kazakhstan Time - Atyrau',
name: 'Asia/Atyrau',
offset: 5,
},
{
label: 'West Kazakhstan Time - Oral',
name: 'Asia/Oral',
offset: 5,
},
{
label: 'West Kazakhstan Time - Qyzylorda',
name: 'Asia/Qyzylorda',
offset: 5,
},
{
label: 'Yekaterinburg Standard Time',
name: 'Asia/Yekaterinburg',
offset: 5,
},
{
label: 'India Standard Time - Colombo',
name: 'Asia/Colombo',
offset: 5.5,
},
{
label: 'India Standard Time - Kolkata',
name: 'Asia/Kolkata',
offset: 5.5,
},
{
label: 'Nepal Time',
name: 'Asia/Kathmandu',
offset: 5.75,
},
{
label: 'Bangladesh Standard Time',
name: 'Asia/Dhaka',
offset: 6,
},
{
label: 'Bhutan Time',
name: 'Asia/Thimphu',
offset: 6,
},
{
label: 'East Kazakhstan Time - Almaty',
name: 'Asia/Almaty',
offset: 6,
},
{
label: 'East Kazakhstan Time - Qostanay',
name: 'Asia/Qostanay',
offset: 6,
},
{
label: 'Indian Ocean Time',
name: 'Indian/Chagos',
offset: 6,
},
{
label: 'Kyrgyzstan Time',
name: 'Asia/Bishkek',
offset: 6,
},
{
label: 'Omsk Standard Time',
name: 'Asia/Omsk',
offset: 6,
},
{
label: 'Urumqi Time',
name: 'Asia/Urumqi',
offset: 6,
},
{
label: 'Vostok Time',
name: 'Antarctica/Vostok',
offset: 6,
},
{
label: 'Cocos Islands Time',
name: 'Indian/Cocos',
offset: 6.5,
},
{
label: 'Myanmar Time',
name: 'Asia/Yangon',
offset: 6.5,
},
{
label: 'Barnaul Time',
name: 'Asia/Barnaul',
offset: 7,
},
{
label: 'Christmas Island Time',
name: 'Indian/Christmas',
offset: 7,
},
{
label: 'Davis Time',
name: 'Antarctica/Davis',
offset: 7,
},
{
label: 'Hovd Standard Time',
name: 'Asia/Hovd',
offset: 7,
},
{
label: 'Indochina Time - Bangkok',
name: 'Asia/Bangkok',
offset: 7,
},
{
label: 'Indochina Time - Ho Chi Minh City',
name: 'Asia/Ho_Chi_Minh',
offset: 7,
},
{
label: 'Krasnoyarsk Standard Time - Krasnoyarsk',
name: 'Asia/Krasnoyarsk',
offset: 7,
},
{
label: 'Krasnoyarsk Standard Time - Novokuznetsk',
name: 'Asia/Novokuznetsk',
offset: 7,
},
{
label: 'Novosibirsk Standard Time',
name: 'Asia/Novosibirsk',
offset: 7,
},
{
label: 'Tomsk Time',
name: 'Asia/Tomsk',
offset: 7,
},
{
label: 'Western Indonesia Time - Jakarta',
name: 'Asia/Jakarta',
offset: 7,
},
{
label: 'Western Indonesia Time - Pontianak',
name: 'Asia/Pontianak',
offset: 7,
},
{
label: 'Australian Western Standard Time - Casey',
name: 'Antarctica/Casey',
offset: 8,
},
{
label: 'Australian Western Standard Time - Perth',
name: 'Australia/Perth',
offset: 8,
},
{
label: 'Brunei Darussalam Time',
name: 'Asia/Brunei',
offset: 8,
},
{
label: 'Central Indonesia Time',
name: 'Asia/Makassar',
offset: 8,
},
{
label: 'China Standard Time - Macau',
name: 'Asia/Macau',
offset: 8,
},
{
label: 'China Standard Time - Shanghai',
name: 'Asia/Shanghai',
offset: 8,
},
{
label: 'Choibalsan Standard Time',
name: 'Asia/Choibalsan',
offset: 8,
},
{
label: 'Hong Kong Standard Time',
name: 'Asia/Hong_Kong',
offset: 8,
},
{
label: 'Irkutsk Standard Time',
name: 'Asia/Irkutsk',
offset: 8,
},
{
label: 'Malaysia Time - Kuala Lumpur',
name: 'Asia/Kuala_Lumpur',
offset: 8,
},
{
label: 'Malaysia Time - Kuching',
name: 'Asia/Kuching',
offset: 8,
},
{
label: 'Philippine Standard Time',
name: 'Asia/Manila',
offset: 8,
},
{
label: 'Singapore Standard Time',
name: 'Asia/Singapore',
offset: 8,
},
{
label: 'Taipei Standard Time',
name: 'Asia/Taipei',
offset: 8,
},
{
label: 'Ulaanbaatar Standard Time',
name: 'Asia/Ulaanbaatar',
offset: 8,
},
{
label: 'Australian Central Western Standard Time',
name: 'Australia/Eucla',
offset: 8.75,
},
{
label: 'East Timor Time',
name: 'Asia/Dili',
offset: 9,
},
{
label: 'Eastern Indonesia Time',
name: 'Asia/Jayapura',
offset: 9,
},
{
label: 'Japan Standard Time',
name: 'Asia/Tokyo',
offset: 9,
},
{
label: 'Korean Standard Time - Pyongyang',
name: 'Asia/Pyongyang',
offset: 9,
},
{
label: 'Korean Standard Time - Seoul',
name: 'Asia/Seoul',
offset: 9,
},
{
label: 'Palau Time',
name: 'Pacific/Palau',
offset: 9,
},
{
label: 'Yakutsk Standard Time - Chita',
name: 'Asia/Chita',
offset: 9,
},
{
label: 'Yakutsk Standard Time - Khandyga',
name: 'Asia/Khandyga',
offset: 9,
},
{
label: 'Yakutsk Standard Time - Yakutsk',
name: 'Asia/Yakutsk',
offset: 9,
},
{
label: 'Australian Central Standard Time',
name: 'Australia/Darwin',
offset: 9.5,
},
{
label: 'Australian Eastern Standard Time - Brisbane',
name: 'Australia/Brisbane',
offset: 10,
},
{
label: 'Australian Eastern Standard Time - Lindeman',
name: 'Australia/Lindeman',
offset: 10,
},
{
label: 'Chamorro Standard Time',
name: 'Pacific/Guam',
offset: 10,
},
{
label: 'Chuuk Time',
name: 'Pacific/Chuuk',
offset: 10,
},
{
label: 'Dumont-d’Urville Time',
name: 'Antarctica/DumontDUrville',
offset: 10,
},
{
label: 'Papua New Guinea Time',
name: 'Pacific/Port_Moresby',
offset: 10,
},
{
label: 'Vladivostok Standard Time - Ust-Nera',
name: 'Asia/Ust-Nera',
offset: 10,
},
{
label: 'Vladivostok Standard Time - Vladivostok',
name: 'Asia/Vladivostok',
offset: 10,
},
{
label: 'Central Australia Time - Adelaide',
name: 'Australia/Adelaide',
offset: 10.5,
},
{
label: 'Central Australia Time - Broken Hill',
name: 'Australia/Broken_Hill',
offset: 10.5,
},
{
label: 'Bougainville Time',
name: 'Pacific/Bougainville',
offset: 11,
},
{
label: 'Eastern Australia Time - Currie',
name: 'Australia/Currie',
offset: 11,
},
{
label: 'Eastern Australia Time - Hobart',
name: 'Australia/Hobart',
offset: 11,
},
{
label: 'Eastern Australia Time - Melbourne',
name: 'Australia/Melbourne',
offset: 11,
},
{
label: 'Eastern Australia Time - Sydney',
name: 'Australia/Sydney',
offset: 11,
},
{
label: 'Kosrae Time',
name: 'Pacific/Kosrae',
offset: 11,
},
{
label: 'Lord Howe Time',
name: 'Australia/Lord_Howe',
offset: 11,
},
{
label: 'Macquarie Island Time',
name: 'Antarctica/Macquarie',
offset: 11,
},
{
label: 'Magadan Standard Time',
name: 'Asia/Magadan',
offset: 11,
},
{
label: 'New Caledonia Standard Time',
name: 'Pacific/Noumea',
offset: 11,
},
{
label: 'Norfolk Island Time',
name: 'Pacific/Norfolk',
offset: 11,
},
{
label: 'Ponape Time',
name: 'Pacific/Pohnpei',
offset: 11,
},
{
label: 'Sakhalin Standard Time',
name: 'Asia/Sakhalin',
offset: 11,
},
{
label: 'Solomon Islands Time',
name: 'Pacific/Guadalcanal',
offset: 11,
},
{
label: 'Srednekolymsk Time',
name: 'Asia/Srednekolymsk',
offset: 11,
},
{
label: 'Vanuatu Standard Time',
name: 'Pacific/Efate',
offset: 11,
},
{
label: 'Anadyr Standard Time',
name: 'Asia/Anadyr',
offset: 12,
},
{
label: 'Fiji Time',
name: 'Pacific/Fiji',
offset: 12,
},
{
label: 'Gilbert Islands Time',
name: 'Pacific/Tarawa',
offset: 12,
},
{
label: 'Marshall Islands Time - Kwajalein',
name: 'Pacific/Kwajalein',
offset: 12,
},
{
label: 'Marshall Islands Time - Majuro',
name: 'Pacific/Majuro',
offset: 12,
},
{
label: 'Nauru Time',
name: 'Pacific/Nauru',
offset: 12,
},
{
label: 'Petropavlovsk-Kamchatski Standard Time',
name: 'Asia/Kamchatka',
offset: 12,
},
{
label: 'Tuvalu Time',
name: 'Pacific/Funafuti',
offset: 12,
},
{
label: 'Wake Island Time',
name: 'Pacific/Wake',
offset: 12,
},
{
label: 'Wallis & Futuna Time',
name: 'Pacific/Wallis',
offset: 12,
},
{
label: 'New Zealand Time',
name: 'Pacific/Auckland',
offset: 13,
},
{
label: 'Phoenix Islands Time',
name: 'Pacific/Enderbury',
offset: 13,
},
{
label: 'Tokelau Time',
name: 'Pacific/Fakaofo',
offset: 13,
},
{
label: 'Tonga Standard Time',
name: 'Pacific/Tongatapu',
offset: 13,
},
{
label: 'Chatham Time',
name: 'Pacific/Chatham',
offset: 13.75,
},
{
label: 'Apia Time',
name: 'Pacific/Apia',
offset: 14,
},
{
label: 'Line Islands Time',
name: 'Pacific/Kiritimati',
offset: 14,
},
]; | the_stack |
import fs from 'fs';
import path from 'path';
import { CancellationToken, WorkspaceFolder } from 'vscode-languageserver';
import { URI, Utils } from 'vscode-uri';
import { ServiceRegistry } from '../service-registry';
import { LangiumSharedServices } from '../services';
import { AstNode, AstNodeDescription, AstReflection } from '../syntax-tree';
import { getDocument } from '../utils/ast-util';
import { interruptAndCheck } from '../utils/promise-util';
import { stream, Stream } from '../utils/stream';
import { ReferenceDescription } from './ast-descriptions';
import { DocumentState, LangiumDocument, LangiumDocuments } from './documents';
/**
* The index manager is responsible for keeping metadata about symbols and cross-references
* in the workspace. It is used to look up symbols in the global scope, mostly during linking
* and completion.
*/
export interface IndexManager {
/**
* Does the initial indexing of workspace folders.
* Collects information about exported and referenced AstNodes in
* each language file and stores it locally.
*
* @param folders The set of workspace folders to be indexed.
*/
initializeWorkspace(folders: WorkspaceFolder[]): Promise<void>;
/**
* Deletes the specified document uris from the index.
* Necessary when documents are deleted and not referenceable anymore.
*
* @param uris The document uris to delete.
*/
remove(uris: URI[]): void;
/**
* Updates the information about a Document inside the index.
*
* @param document document(s) to be updated
* @param cancelToken allows to cancel the current operation
* @throws `OperationCanceled` if a user action occurs during execution
*/
update(documents: LangiumDocument[], cancelToken?: CancellationToken): Promise<void>;
/**
* Returns all documents that could be affected by changes in the documents
* identified by the given URIs.
*
* @param uris The document URIs which may affect other documents.
*/
getAffectedDocuments(uris: URI[]): Stream<LangiumDocument>;
/**
* Compute a global scope, optionally filtered using a type identifier.
*
* @param nodeType The type to filter with, or `undefined` to return descriptions of all types.
* @returns a `Stream` of existing `AstNodeDescription`s filtered by their type
*/
allElements(nodeType?: string): Stream<AstNodeDescription>;
/**
* Returns all known references that are pointing to the given `targetNode`.
*
* @param targetNode the `AstNode` to look up references for
* @param astNodePath the path that points to the `targetNode` inside the document. See also `AstNodeLocator`
*
* @returns a `Stream` of references that are targeting the `targetNode`
*/
findAllReferences(targetNode: AstNode, astNodePath: string): Stream<ReferenceDescription>;
}
export class DefaultIndexManager implements IndexManager {
protected readonly serviceRegistry: ServiceRegistry;
protected readonly langiumDocuments: () => LangiumDocuments;
protected readonly astReflection: AstReflection;
protected readonly simpleIndex: Map<string, AstNodeDescription[]> = new Map<string, AstNodeDescription[]>();
protected readonly referenceIndex: Map<string, ReferenceDescription[]> = new Map<string, ReferenceDescription[]>();
protected readonly globalScopeCache = new Map<string, AstNodeDescription[]>();
constructor(services: LangiumSharedServices) {
this.serviceRegistry = services.ServiceRegistry;
this.astReflection = services.AstReflection;
this.langiumDocuments = () => services.workspace.LangiumDocuments;
}
findAllReferences(targetNode: AstNode, astNodePath: string): Stream<ReferenceDescription> {
const targetDocUri = getDocument(targetNode).uri;
const result: ReferenceDescription[] = [];
this.referenceIndex.forEach((docRefs: ReferenceDescription[]) => {
docRefs.forEach((refDescr) => {
if (refDescr.targetUri.toString() === targetDocUri.toString() && refDescr.targetPath === astNodePath) {
result.push(refDescr);
}
});
});
return stream(result);
}
allElements(nodeType = ''): Stream<AstNodeDescription> {
if (!this.globalScopeCache.has('')) {
this.globalScopeCache.set('', Array.from(this.simpleIndex.values()).flat());
}
const cached = this.globalScopeCache.get(nodeType);
if (cached) {
return stream(cached);
} else {
const elements = this.globalScopeCache.get('')!.filter(e => this.astReflection.isSubtype(e.type, nodeType));
this.globalScopeCache.set(nodeType, elements);
return stream(elements);
}
}
remove(uris: URI[]): void {
for (const uri of uris) {
const uriString = uri.toString();
this.simpleIndex.delete(uriString);
this.referenceIndex.delete(uriString);
}
}
update(documents: LangiumDocument[], cancelToken = CancellationToken.None): Promise<void> {
return this.processDocuments(documents, cancelToken);
}
getAffectedDocuments(uris: URI[]): Stream<LangiumDocument> {
return this.langiumDocuments().all.filter(e => {
if (uris.some(uri => e.uri.toString() === uri.toString())) {
return false;
}
for (const uri of uris) {
if (this.isAffected(e, uri)) {
return true;
}
}
return false;
});
}
/**
* Determine whether the given document could be affected by a change of the document
* identified by the given URI (second parameter).
*/
protected isAffected(document: LangiumDocument, changed: URI): boolean {
const changedUriString = changed.toString();
const documentUri = document.uri.toString();
// The document is affected if it contains linking errors
if (document.references.some(e => e.error)) {
return true;
}
const references = this.referenceIndex.get(documentUri);
// ...or if it contains a reference to the changed file
if (references) {
return references.filter(e => !e.local).some(e => e.targetUri.toString() === changedUriString);
}
return false;
}
async initializeWorkspace(folders: WorkspaceFolder[]): Promise<void> {
const documents: LangiumDocument[] = [];
const allFileExtensions = this.serviceRegistry.all.flatMap(e => e.LanguageMetaData.fileExtensions);
const fileFilter = (uri: URI) => allFileExtensions.includes(path.extname(uri.path));
const collector = (document: LangiumDocument) => documents.push(document);
await Promise.all(
folders.map(folder => this.getRootFolder(folder))
.map(async folderPath => this.traverseFolder(folderPath, fileFilter, collector))
);
await this.loadAdditionalDocuments(folders, collector);
await this.processDocuments(documents);
}
/**
* Load all additional documents that shall be visible in the context of the given workspace
* folders and add them to the acceptor. This can be used to include built-in libraries of
* your language, which can be either loaded from provided files or constructed in memory.
*/
protected loadAdditionalDocuments(_folders: WorkspaceFolder[], _acceptor: (document: LangiumDocument) => void): Promise<void> {
return Promise.resolve();
}
/**
* Determine the root folder of the source documents in the given workspace folder.
* The default implementation returns the URI of the workspace folder, but you can override
* this to return a subfolder like `src` instead.
*/
protected getRootFolder(folder: WorkspaceFolder): URI {
return URI.parse(folder.uri);
}
/**
* Traverse the file system folder identified by the given URI and its subFolders. All
* contained files that match the filter are added to the acceptor.
*/
protected async traverseFolder(folderPath: URI, fileFilter: (uri: URI) => boolean, acceptor: (document: LangiumDocument) => void): Promise<void> {
const fsPath = folderPath.fsPath;
if (!fs.existsSync(fsPath)) {
console.error(`File ${folderPath} doesn't exist.`);
return;
}
if (this.skipFolder(folderPath)) {
return;
}
const subFolders = await fs.promises.readdir(fsPath, { withFileTypes: true });
for (const dir of subFolders) {
const uri = URI.file(path.resolve(fsPath, dir.name));
if (dir.isDirectory()) {
await this.traverseFolder(uri, fileFilter, acceptor);
} else if (fileFilter(uri)) {
const document = this.langiumDocuments().getOrCreateDocument(uri);
acceptor(document);
}
}
}
/**
* Determine whether the folder with the given path shall be skipped while indexing the workspace.
*/
protected skipFolder(folderPath: URI): boolean {
const base = Utils.basename(folderPath);
return base.startsWith('.') || base === 'node_modules' || base === 'out';
}
protected async processDocuments(documents: LangiumDocument[], cancelToken = CancellationToken.None): Promise<void> {
this.globalScopeCache.clear();
// first: build exported object data
for (const document of documents) {
const services = this.serviceRegistry.getServices(document.uri);
const indexData: AstNodeDescription[] = await services.index.AstNodeDescriptionProvider.createDescriptions(document, cancelToken);
for (const data of indexData) {
data.node = undefined; // clear reference to the AST Node
}
this.simpleIndex.set(document.textDocument.uri, indexData);
await interruptAndCheck(cancelToken);
}
// second: create reference descriptions
for (const document of documents) {
const services = this.serviceRegistry.getServices(document.uri);
this.referenceIndex.set(document.textDocument.uri, await services.index.ReferenceDescriptionProvider.createDescriptions(document, cancelToken));
await interruptAndCheck(cancelToken);
document.state = DocumentState.Indexed;
}
}
} | the_stack |
import runTime from '@feathers-plus/graphql/lib/run-time';
import BatchLoader from '@feathers-plus/batch-loader';
import { assert } from 'chai';
import { parse } from 'graphql';
import { fgraphql } from '../../src';
const { getResultsByKey } = BatchLoader;
describe('services fgraphql', () => {
describe('using service resolver', () => {
/* eslint-disable */
const beforeJane = () => ({ type: 'before', data: { first: 'Jane', last: 'Doe' } });
const afterJane = () => ({ type: 'after', result: { first: 'Jane', last: 'Doe' } });
const decisionTable: any[] = [
// Test options
// desc, schema, resolvers, recordType, query, options, context, client, result
['schema str', s('str'), r('full'), 'User', q('obj'), o('both'), afterJane(), false, a('janeFull') ],
['schema fcn', s('fcn'), r('full'), 'User', q('obj'), o('both'), afterJane(), false, a('janeFull') ],
['schema obj', s('obj'), r('full'), 'User', q('obj'), o('both'), afterJane(), false, a('janeFull') ],
['query str', s('str'), r('full'), 'User', q('obj'), o('both'), afterJane(), false, a('janeFull') ],
['query fcn', s('str'), r('full'), 'User', q('fcn'), o('both'), afterJane(), false, a('janeFull') ],
['opt server-', s('str'), r('full'), 'User', q('obj'), o('server-'), afterJane(), false, a('janeFull-') ],
['opt client-', s('str'), r('full'), 'User', q('obj'), o('client-'), afterJane(), true, a('janeFull-') ],
['before hook', s('str'), r('full'), 'User', q('obj'), o('both'), beforeJane(), false, a('janeFull') ],
['func params', s('param'),r('params'), 'User', q('params'),o('both'), afterJane(), false, a('janeParams')],
['join names', s('str'), r('full'), 'User', q('obj'), o('join-'), afterJane(), false, a('janeJoin') ],
// Test conversion of resolver results
// desc, schema, resolvers, recordType, query, options, context, client, result
['undef->null', s('cnv0'), r('undefin'),'User', q('obj'), o('both'), beforeJane(), false, a('janeNull') ],
['undef->array',s('cnv1'), r('undefin'),'User', q('obj'), o('both'), beforeJane(), false, a('janeArray0')],
['obj->array', s('cnv1'), r('full'), 'User', q('obj'), o('both'), beforeJane(), false, a('janeArray') ],
['array->obj', s('str'), r('array1'), 'User', q('obj'), o('both'), beforeJane(), false, a('janeFull') ],
// Test error checking
// desc, schema, resolvers, recordType, query, options, context, client, result
['x schema', s('err1'), r('full'), 'User', 1, o('both'), afterJane(), false, 101 ],
['x query', s('str'), r('full'), 'User', q('err1'), o('both'), afterJane(), false, 102 ],
['x hook type', s('str'), r('full'), 'Userxxx', q('obj'), o('both'), afterJane(), false, 104 ],
['x context', s('str'), r('full'), 'User', q('obj'), o('prop-'), afterJane(), false, 105 ],
['x reso func', s('str'), r('err1'), 'User', q('obj'), o('both'), afterJane(), false, 203 ],
['x array len2',s('str'), r('array2'), 'User', q('obj'), o('both'), afterJane(), false, 204 ],
// Test features not available in GraphQL
// desc, schema, resolvers, recordType, query, options, context, client, result
['normal', s('str'), r('full'), 'User', q('obj'), o('both'), afterJane(), false, a('janeFull') ],
['chge parent', s('str'), r('parent'), 'User', q('obj'), o('both'), afterJane(), false, a('janeMess') ],
['value 1', s('str'), r('full'), 'User', q('value1'),o('both'), afterJane(), false, a('janeFull') ],
['value 0', s('str'), r('full'), 'User', q('value0'),o('both'), afterJane(), false, a('jane0') ],
['value falsey',s('str'), r('full'), 'User', q('falsey'),o('both'), afterJane(), false, a('janeFalsey')],
['incl flds 1', s('str'), r('full'), 'User', q('obj'), o('both'), afterJane(), false, a('janeFull') ],
['incl flds s', s('str'), r('full'), 'User', q('obj'), o('server-'), afterJane(), false, a('janeFull-') ],
['incl flds c', s('str'), r('full'), 'User', q('obj'), o('client-'), afterJane(), true, a('janeFull-') ],
['_none', s('str'), r('full'), 'User', q('none'), o('both'), afterJane(), false, a('janeFull-') ],
// Test join type at top level #2
// desc, schema, resolvers, recordType, query, options, context, client, result
['1 post', s('S2'), r('S2'), 'User', q('S2post'),o('both'), afterJane(), false, a('S2post') ],
['1 comment', s('S2'), r('S2'), 'User', q('S2comm'),o('both'), afterJane(), false, a('S2comm') ],
['l both', s('S2'), r('S2'), 'User', q('S2both'),o('both'), afterJane(), false, a('S2both') ],
['1 post args', s('S2'), r('S2'), 'User', q('S2parm'),o('both'), afterJane(), false, a('S2parm') ],
['1 post cont', s('S2'), r('S2'), 'User', q('S2parm'),o('prop+'), afterJane(), false, a('S2cont') ],
// Test join type at level #3
// desc, schema, resolvers, recordType, query, options, ontext, client, result
['2 all', s('S3'), r('S3'), 'User', q('S3all'), o('both'), afterJane(), false, a('S3all') ],
];
/* eslint-enable */
decisionTable.forEach(([desc, schema, resolvers, recordType, query, options, context, client, result]) => {
it(desc, async () => {
context.params = context.params || {};
if (client) {
context.params.provider = 'socketio';
}
try {
const newContext: any = await fgraphql({
parse, runTime, schema, resolvers, recordType, query, options
})(context);
if (!isObject(result)) {
assert(false, `Unexpected success. Expected ${result}.`);
} else {
// inspector('result=', result);
// inspector('actual=', newContext.data || newContext.result);
assert.deepEqual(newContext.data || newContext.result, result, 'unexpected result');
}
} catch (err: any) {
if (err.message.substr(0, 19) === 'Unexpected success.') {
throw err;
}
if (isObject(result)) {
assert(false, `unexpected fail: ${err.message}`);
return;
}
assert.strictEqual(err.code, result, `unexpected error: ${err.message}`);
}
});
});
});
describe('using batchloader', () => {
let recordType: any;
let schema: any;
let context: any;
let query: any;
let options: any;
let usersBatchLoader: any;
let usersBatchLoaderCalls: any;
let resolvers: any;
let result: any;
const usersDb: any = {
31: { _id: '31', name: 'user 31' },
32: { _id: '32', name: 'user 32' },
35: { _id: '35', name: 'user 35' },
36: { _id: '36', name: 'user 36' },
37: { _id: '37', name: 'user 37' }
};
const postsDb: any = {
11: { _id: '11', body: 'body 11', userId: '31' },
12: { _id: '12', body: 'body 12', userId: '31' },
13: { _id: '13', body: 'body 13', userId: '32' }
};
const commentsDb: any = {
21: { _id: '21', comment: 'comment 21', postId: '11', userId: '35' },
22: { _id: '22', comment: 'comment 22', postId: '12', userId: '35' },
23: { _id: '23', comment: 'comment 23', postId: '13', userId: '35' },
24: { _id: '24', comment: 'comment 24', postId: '11', userId: '36' },
25: { _id: '25', comment: 'comment 25', postId: '12', userId: '36' },
26: { _id: '26', comment: 'comment 26', postId: '13', userId: '36' },
27: { _id: '27', comment: 'comment 24', postId: '11', userId: '37' },
28: { _id: '28', comment: 'comment 25', postId: '12', userId: '37' },
29: { _id: '29', comment: 'comment 26', postId: '13', userId: '37' }
};
beforeEach(() => {
usersBatchLoaderCalls = [];
recordType = 'Post';
schema = `
type User {
_id: ID
name: String
}
type Post {
_id: ID
body: String
userId: ID,
author: User
comments: [Comment]
}
type Comment {
_id: ID
comment: String
postId: ID,
userId: ID,
post: Post
author: User
}`;
context = {
type: 'after',
params: {},
result: Object.keys(postsDb).map(key => postsDb[key])
};
query = {
body: 1,
userId: 1,
author: {
name: 1
},
comments: {
userId: 1,
author: {
name: 1
}
}
};
options = {
inclJoinedNames: false
};
usersBatchLoader = new BatchLoader(
async (keys: any) => {
usersBatchLoaderCalls.push(keys);
const result = keys.map((key: any) => usersDb[key]);
return getResultsByKey(keys, result, (rec: any) => rec._id, '!');
}
);
resolvers = () => ({
Post: {
// tests returning a Promise
author: (parent: any, _args: any, _content: any, _ast: any) => usersBatchLoader.load(parent.userId),
// tests returning a value
comments: (parent: any, _args: any, _content: any, _ast: any) => {
const x: any = [];
Object.keys(commentsDb).forEach(key => {
if (commentsDb[key].postId === parent._id) {
x.push(commentsDb[key]);
}
});
return x;
}
},
Comment: {
author: (parent: any, _args: any, _content: any, _ast: any) => usersBatchLoader.load(parent.userId)
}
});
result = [
{
body: 'body 11',
userId: '31',
comments: [
{ userId: '35', author: { _id: '35', name: 'user 35' } },
{ userId: '36', author: { _id: '36', name: 'user 36' } },
{ userId: '37', author: { _id: '37', name: 'user 37' } }
],
author: { _id: '31', name: 'user 31' }
}, {
body: 'body 12',
userId: '31',
comments: [
{ userId: '35', author: { _id: '35', name: 'user 35' } },
{ userId: '36', author: { _id: '36', name: 'user 36' } },
{ userId: '37', author: { _id: '37', name: 'user 37' } }
],
author: { _id: '31', name: 'user 31' }
}, {
body: 'body 13',
userId: '32',
comments: [
{ userId: '35', author: { _id: '35', name: 'user 35' } },
{ userId: '36', author: { _id: '36', name: 'user 36' } },
{ userId: '37', author: { _id: '37', name: 'user 37' } }
],
author: { _id: '32', name: 'user 32' }
}
];
});
it('batches calls', async () => {
try {
const newContext: any = await fgraphql({
parse, runTime, schema, resolvers, recordType, query, options
})(context);
// inspector('batchloader calls', usersBatchLoaderCalls);
// inspector('actual=', newContext.data || newContext.result);
assert.deepEqual(newContext.data || newContext.result, result, 'unexpected result');
assert.deepEqual(usersBatchLoaderCalls, [['31', '32', '35', '36', '37']], 'unexpected calls');
} catch (err) {
console.log(err);
throw err;
}
});
});
});
function isObject (obj: any) {
return typeof obj === 'object' && obj !== null;
}
// schemas
function s (typ: any) {
const SDL1 = `
type User {
_id: ID
firstName: String
lastName: String
fullName: String!
}`;
const S2 = `
type User {
_id: ID
firstName: String
lastName: String
posts: [Post]
comments: [Comment]
}
type Post {
_id: ID
body: String
}
type Comment {
_id: ID
comment: String
}`;
const S3 = `
type User {
_id: ID
firstName: String
lastName: String
posts: [Post]
comments: [Comment]
}
type Post {
_id: ID
body: String
author: User
}
type Comment {
_id: ID
comment: String
author: User
}`;
const C0 = `
type User {
_id: ID
firstName: String
lastName: String
fullName: String
}`;
const C1 = `
type User {
_id: ID
firstName: String
lastName: String
fullName: [String]
}`;
switch (typ) {
case 'str':
return SDL1;
case 'cnv0':
return C0;
case 'cnv1':
return C1;
case 'fcn':
return () => SDL1;
case 'obj':
return {
User: {
firstName: { typeof: 'String' },
lastName: { typeof: 'String' },
fullName: { nonNullTypeField: true, typeof: 'String' }
}
};
case 'param':
return {
User: {
firstName: { typeof: 'String' },
lastName: { typeof: 'String' },
fullName: { nonNullTypeField: true, typeof: 'String' },
params: { typeof: 'JSON' }
}
};
case 'err1':
return (): any => null;
case 'S2':
return S2;
case 'S3':
return S3;
default:
throw new Error(`Invalid typ ${typ} for "s" function.`);
}
}
// resolvers
function r (typ: any) {
return function resolvers (_app: any, _options: any) { // eslint-disable-line no-unused-vars
// const { convertArgsToFeathers, extractAllItems, extractFirstItem } = options; // eslint-disable-line no-unused-vars
// const convertArgs = convertArgsToFeathers([]); // eslint-disable-line no-unused-vars
// let comments = app.service('/comments');
switch (typ) {
case 'full':
return {
User: {
// fullName: String!
fullName:
(parent: any, _args: any, _content: any, _ast: any) => `${parent.first} ${parent.last}` // eslint-disable-line no-unused-vars
}
};
case 'parent':
return {
User: {
// fullName: String!
fullName:
(parent: any, _args: any, _content: any, _ast: any) => { // eslint-disable-line no-unused-vars
const returns = `${parent.first} ${parent.last}`;
parent.first = 'foo';
return returns;
}
}
};
case 'params':
return {
User: {
// fullName: String!
fullName:
(parent: any, _args: any, _content: any, _ast: any) => `${parent.first} ${parent.last}`, // eslint-disable-line no-unused-vars
params:
(_parent: any, args: any, _content: any, ast: any) => ({
args,
ast
})
}
};
case 'err1':
return { User: { fullName: 'foo' } };
case 'array2':
return {
User: {
fullName: () => [{ fullName: 'foo' }, { fullName: 'foo' }]
}
};
case 'undefin':
return {
User: {
fullName: (): any => undefined
}
};
case 'array1':
return {
User: {
fullName: (parent: any) => [`${parent.first} ${parent.last}`]
}
};
case 'S2':
return {
User: {
// posts: [Post]
posts:
(_parent: any, args: any, content: any, _ast: any) => { // eslint-disable-line no-unused-vars
return [
{ _id: '1001', body: 'foo body' },
{ _id: (args.params || content.foo || {})._id || '1002', body: 'bar body' }
];
},
// comments: [Comment]
comments:
(_parent: any, _args: any, _content: any, _ast: any) => { // eslint-disable-line no-unused-vars
return [
{ _id: '2001', comment: 'foo comment' },
{ _id: '2002', comment: 'bar comment' }
];
}
},
Post: {}
};
case 'S3':
return {
User: {
// posts: [Post]
posts:
(_parent: any, args: any, _content: any, _ast: any) => { // eslint-disable-line no-unused-vars
return [
{ _id: '1001', body: 'foo body' },
{ _id: (args.params || {})._id || '1002', body: 'bar body' }
];
},
// comments: [Comment]
comments:
(_parent: any, _args: any, _content: any, _ast: any) => { // eslint-disable-line no-unused-vars
return [
{ _id: '2001', comment: 'foo comment' },
{ _id: '2002', comment: 'bar comment' }
];
}
},
Post: {
// author: User
author:
(_parent: any, _args: any, _content: any, _ast: any) => { // eslint-disable-line no-unused-vars
return { _id: '3001', first: 'Jane', last: 'Doe' };
}
},
Comment: {
// author: User
author:
(_parent: any, _args: any, _content: any, _ast: any) => { // eslint-disable-line no-unused-vars
return { _id: '4001', first: 'Jane', last: 'Doe' };
}
}
};
default:
throw new Error(`Invalid typ ${typ} for "r" function.`);
}
};
}
// query
function q (typ: any): any {
switch (typ) {
/* eslint-disable */
case 'obj':
return { fullName: {} } ;
case 'none':
return { fullName: {}, _none: {} } ;
case 'value1':
return { fullName: 1, first: 1, last: 1 } ;
case 'value0':
return { fullName: 0, first: 1, last: 0 } ;
case 'falsey':
return { fullName: '', first: null, last: 1 } ;
case 'fcn':
return () => ({ fullName: {} } );
case 'params':
return { fullName: {}, params: {
_args: { key: 1, query: { foo: 2 }, params: { bar: 3 }, baz: 4 }
} } ;
case 'err1':
return undefined;
case 'S2post':
return { posts: {} } ;
case 'S2comm':
return { comments: {} } ;
case 'S2both':
return { posts: {}, comments: {} } ;
case 'S2parm':
return {
posts: {
_args: { params: { _id: '9999' } }
}
};
case 'S2cont':
return {
posts: {}
};
case 'S3all':
return {
posts: {
author: {}
},
comments: {
author: {}
}
};
case 'big1':
return {
fullName: {},
posts: {
_args: { query: { } }, // { key: any, query: { ... }, params: { ... }
author: {
firstName: '',
fullName: '', // {} or '' doesn't matter as no props inside would-have-been {}
posts: {
draft: '',
},
},
},
comments: {},
followed_by: {
foo: '', // non-resolver name looks like field name. forces drop of real fields
follower: {
foo: '',
fullName: {},
}
},
following: {
foo: '',
followee: {
foo: '',
fullName: {},
},
},
likes: {
author: {
firstName: '',
lastName: '',
},
comment: {
body: ''
},
},
};
default:
throw new Error(`Invalid typ ${typ} for "q" function.`);
/* eslint-enable */
}
}
// options
function o (typ: any) {
switch (typ) {
case 'both':
return {
inclAllFieldsServer: true,
inclAllFieldsClient: true
};
case 'server-':
return { inclAllFieldsServer: false };
case 'client-':
return { inclAllFieldsClient: false };
case 'loop':
return { skipHookWhen: () => false };
case 'prop-':
return {
inclAllFieldsServer: true,
inclAllFieldsClient: true,
extraAuthProps: 1
};
case 'prop+':
return {
inclAllFieldsServer: true,
inclAllFieldsClient: true,
extraAuthProps: ['foo']
};
case 'join-':
return {
inclAllFieldsServer: true,
inclAllFieldsClient: true,
inclJoinedNames: false
};
default:
throw new Error(`Invalid typ ${typ} for "o" function.`);
}
}
// results
function a (typ: any) {
switch (typ) {
/* eslint-disable */
case 'janeNull' :
return { first: 'Jane', last: 'Doe', fullName: null, _include: ['fullName'] };
case 'janeFull' :
return { first: 'Jane', last: 'Doe', fullName: 'Jane Doe', _include: ['fullName'] };
case 'janeArray' :
return { first: 'Jane', last: 'Doe', fullName: ['Jane Doe'], _include: ['fullName'] };
case 'janeArray0' :
return { first: 'Jane', last: 'Doe', fullName: [], _include: ['fullName'] };
case 'janeFull-' :
return { fullName: 'Jane Doe', _include: ['fullName'] };
case 'janeMess' :
return { first: 'foo', last: 'Doe', fullName: 'Jane Doe', _include: ['fullName'] };
case 'jane0' :
return { first: 'Jane' };
case 'janeFalsey' :
return { last: 'Doe' };
case 'janeJoin' :
return { first: 'Jane', last: 'Doe', fullName: 'Jane Doe' };
case 'janeParams' :
return { first: 'Jane', last: 'Doe', fullName: 'Jane Doe', _include: ['fullName', 'params'],
params: {
args: { key: 1, query: { foo: 2 }, params: { bar: 3 }, baz: 4 }, ast: undefined
} as any };
case 'S2post' :
return {
first: 'Jane',
last: 'Doe',
posts: [
{ _id: '1001', body: 'foo body' },
{ _id: '1002', body: 'bar body' },
],
_include: ['posts']
};
case 'S2parm' :
return {
first: 'Jane',
last: 'Doe',
posts: [
{ _id: '1001', body: 'foo body' },
{ _id: '9999', body: 'bar body' },
],
_include: ['posts']
};
case 'S2comm' :
return {
first: 'Jane',
last: 'Doe',
comments: [
{ _id: '2001', comment: 'foo comment' },
{ _id: '2002', comment: 'bar comment' },
],
_include: ['comments']
};
case 'S2cont' :
return {
first: 'Jane',
last: 'Doe',
posts: [
{ _id: '1001', body: 'foo body' },
{ _id: '9999', body: 'bar body' },
],
_include: ['posts']
};
case 'S2both' :
return {
first: 'Jane',
last: 'Doe',
posts: [
{ _id: '1001', body: 'foo body' },
{ _id: '1002', body: 'bar body' },
],
comments: [
{ _id: '2001', comment: 'foo comment' },
{ _id: '2002', comment: 'bar comment' },
],
_include: ['posts', 'comments']
};
case 'S3all' :
return {
first: 'Jane',
last: 'Doe',
posts: [
{ _id: '1001',
body: 'foo body',
author: { _id: '3001', first: 'Jane', last: 'Doe' },
_include: ['author']
},
{
_id: '1002',
body: 'bar body',
author: { _id: '3001', first: 'Jane', last: 'Doe' },
_include: ['author']
}
],
comments: [
{ _id: '2001',
comment: 'foo comment',
author: { _id: '4001', first: 'Jane', last: 'Doe' },
_include: ['author']
},
{
_id: '2002',
comment: 'bar comment',
author: { _id: '4001', first: 'Jane', last: 'Doe' },
_include: ['author']
}
],
_include: ['posts', 'comments']
}
default:
throw new Error(`Invalid typ ${typ} for "a" function.`);
}
/* eslint-enable */
}
/*
const { inspect } = require('util');
function inspector(desc, obj) {
console.log(desc);
console.log(inspect(obj, { colors: true, depth: 5 }));
}
*/ | the_stack |
import { i18nMark, withI18n, Trans } from "@lingui/react";
import classNames from "classnames";
import { Confirm, Dropdown, Modal } from "reactjs-components";
import { hashHistory } from "react-router";
import mixin from "reactjs-mixin";
import * as React from "react";
import { Icon } from "@dcos/ui-kit";
import { SystemIcons } from "@dcos/ui-kit/dist/packages/icons/dist/system-icons-enum";
import { iconSizeXs } from "@dcos/ui-kit/dist/packages/design-tokens/build/js/designTokens";
import AlertPanel from "#SRC/js/components/AlertPanel";
import AlertPanelHeader from "#SRC/js/components/AlertPanelHeader";
import CollapsingString from "#SRC/js/components/CollapsingString";
import DCOSStore from "#SRC/js/stores/DCOSStore";
import ExpandingTable from "#SRC/js/components/ExpandingTable";
import Image from "#SRC/js/components/Image";
import Loader from "#SRC/js/components/Loader";
import ModalHeading from "#SRC/js/components/modals/ModalHeading";
import ResourceTableUtil from "#SRC/js/utils/ResourceTableUtil";
import ServiceUtil from "#PLUGINS/services/src/js/utils/ServiceUtil";
import ProgressBar from "#SRC/js/components/ProgressBar";
import StoreMixin from "#SRC/js/mixins/StoreMixin";
import StringUtil from "#SRC/js/utils/StringUtil";
import TimeAgo from "#SRC/js/components/TimeAgo";
import TableUtil from "#SRC/js/utils/TableUtil";
import defaultServiceImage from "../../img/icon-service-default-small@2x.png";
import MarathonActions from "../events/MarathonActions";
const columnClasses = {
id: "deployments-table-column-id",
startTime: "deployments-table-column-start-time",
status: "deployments-table-column-status",
action: "deployments-table-column-actions",
};
const columnHeadings = ResourceTableUtil.renderHeading({
id: i18nMark("Affected Services"),
version: i18nMark("Started"),
status: i18nMark("Status"),
action: null,
});
// collapsing columns are tightly coupled to the left-align caret property;
// this wrapper allows ordinary columns to collapse.
function columnClassNameGetter(prop, sortBy, row) {
return classNames(
columnClasses[prop],
ResourceTableUtil.getClassName(prop, sortBy, row)
);
}
class DeploymentsModal extends mixin(StoreMixin) {
state = {
dcosServiceDataReceived: false,
dcosDeploymentsList: [],
};
// prettier-ignore
store_listeners = [
{ name: "dcos", events: ["change"], suppressUpdate: true },
{name: "marathon", events: ["deploymentRollbackSuccess", "deploymentRollbackError"], suppressUpdate: true}
];
onDcosStoreChange = () => {
this.setState({
dcosDeploymentsList: DCOSStore.deploymentsList.getItems(),
dcosServiceDataReceived: DCOSStore.serviceDataReceived,
});
};
onMarathonStoreDeploymentRollbackSuccess = (data) => {
const { deploymentToRollback } = this.state;
if (
deploymentToRollback != null &&
deploymentToRollback.getId() === data.originalDeploymentID
) {
this.setState({
awaitingRevertDeploymentResponse: false,
deploymentToRollback: null,
deploymentRollbackError: null,
});
}
};
onMarathonStoreDeploymentRollbackError = (data) => {
const { deploymentToRollback } = this.state;
if (
deploymentToRollback != null &&
deploymentToRollback.getId() === data.originalDeploymentID
) {
this.setState({
awaitingRevertDeploymentResponse: false,
deploymentRollbackError: data.error,
});
}
};
handleActionSelect = (deployment, action) => {
if (action.id === "rollback") {
this.handleRollbackClick(deployment);
}
};
handleRollbackClick = (deployment) => {
this.setState({ deploymentToRollback: deployment });
};
handleRollbackCancel = () => {
this.setState({
awaitingRevertDeploymentResponse: false,
deploymentToRollback: null,
deploymentRollbackError: null,
});
};
handleRollbackConfirm = () => {
const { deploymentToRollback } = this.state;
if (deploymentToRollback != null) {
this.setState({ awaitingRevertDeploymentResponse: true });
MarathonActions.revertDeployment(deploymentToRollback.getId());
}
};
getChildTableData = (deployment) => [
...deployment.getAffectedServices().map((service) => {
service.deployment = deployment;
service.isStale = false;
return service;
}),
...deployment.getStaleServiceIds().map((serviceID) => ({
deployment,
serviceID,
isStale: true,
})),
];
getColGroup() {
return (
<colgroup>
<col className={columnClasses.id} />
<col className={columnClasses.startTime} />
<col className={columnClasses.status} />
<col className={columnClasses.action} />
</colgroup>
);
}
getColumns = () => {
const sortFunction = TableUtil.getSortFunction(
"id",
(item, prop) => item[prop]
);
return [
{
className: columnClassNameGetter,
heading: columnHeadings,
prop: "id",
render: this.renderAffectedServices,
},
{
className: columnClassNameGetter,
heading: columnHeadings,
prop: "version",
render: this.renderStartTime,
sortable: true,
sortFunction,
},
{
className: columnClassNameGetter,
heading: columnHeadings,
prop: "status",
render: this.renderStatus,
},
{
className: columnClassNameGetter,
heading: columnHeadings,
prop: "action",
render: this.renderActionsMenu,
sortable: false,
},
];
};
getRollbackModalText = (deploymentToRollback) => {
const serviceNames = deploymentToRollback
.getAffectedServices()
.map((service) => StringUtil.capitalize(service.getName()));
const listOfServiceNames = StringUtil.humanizeArray(serviceNames);
const serviceCount = serviceNames.length;
// L10NTODO: Pluralize
if (deploymentToRollback.isStarting()) {
if (serviceCount === 1) {
return (
<Trans
render="p"
id="This will stop the current deployment of {listOfServiceNames} and start a new deployment to delete the affected service."
values={{ listOfServiceNames }}
/>
);
}
return (
<Trans
render="p"
id="This will stop the current deployment of {listOfServiceNames} and start a new deployment to delete the affected services."
values={{ listOfServiceNames }}
/>
);
}
// L10NTODO: Pluralize
if (serviceCount === 1) {
return (
<Trans
render="p"
id="This will stop the current deployment of {listOfServiceNames} and start a new deployment to revert the affected service to its previous version."
values={{ listOfServiceNames }}
/>
);
}
return (
<Trans
render="p"
id="This will stop the current deployment of {listOfServiceNames} and start a new deployment to revert the affected services to their previous versions."
values={{ listOfServiceNames }}
/>
);
};
getServiceDisplayPath = (service) => {
// Remove the service's name from the end of the path.
const servicePath = service
.getId()
.replace(new RegExp(`/${service.getName()}$`), "");
return (
<a
href={`#/services/overview/${encodeURIComponent(servicePath)}`}
onClick={this.props.onClose}
>
{`Services${servicePath}`}
</a>
);
};
getTableData = (deploymentsItems) => {
return deploymentsItems.map((deployment) => {
deployment.children = this.getChildTableData(deployment);
return deployment;
});
};
renderActionsMenu = (prop, deployment, rowOptions) => {
const { children = [] } = deployment;
const { i18n } = this.props;
const doesDeploymentContainSDKService = children.some((service) =>
ServiceUtil.isSDKService(service)
);
if (
!doesDeploymentContainSDKService &&
rowOptions.isParent &&
deployment != null
) {
let actionText = i18nMark("Rollback");
if (deployment.isStarting()) {
actionText = i18nMark("Rollback & Delete");
}
const dropdownItems = [
{
className: "hidden",
id: "default",
html: "",
selectedHtml: (
<Icon shape={SystemIcons.EllipsisVertical} size={iconSizeXs} />
),
},
{
id: "rollback",
html: <Trans id={actionText} render="span" className="text-danger" />,
},
];
return (
<Dropdown
anchorRight={true}
buttonClassName="button button-mini button-link"
dropdownMenuClassName="dropdown-menu"
dropdownMenuListClassName="dropdown-menu-list"
dropdownMenuListItemClassName="clickable"
wrapperClassName="dropdown flush-bottom table-cell-icon"
items={dropdownItems}
persistentID="default"
onItemSelection={this.handleActionSelect.bind(this, deployment)}
scrollContainer=".gm-scroll-view"
scrollContainerParentSelector=".gm-prevented"
title={i18n._(/*i18n*/ { id: "More actions" })}
transition={true}
transitionName="dropdown-menu"
/>
);
}
return null;
};
renderAffectedServices = (prop, item, rowOptions) => {
// item is an instance of Deployment
if (rowOptions.isParent) {
let classes = null;
if (item.children && item.children.length > 0) {
classes = classNames("expanding-table-primary-cell is-expandable", {
"is-expanded": rowOptions.isExpanded,
});
}
return (
<div className={classes} onClick={rowOptions.clickHandler}>
<CollapsingString string={item.getId()} />
</div>
);
}
if (item.isStale) {
return (
<div className="expanding-table-primary-cell-heading expanding-table-primary-cell-heading--no-nested-indicator">
<div className="table-cell-flex-box" key={`stale_${item.serviceID}`}>
<span className="icon icon-mini icon-image-container icon-app-container icon-margin-right deployment-service-icon">
<Image src={defaultServiceImage} />
</span>
<span className="table-cell-value">{item.serviceID}</span>
</div>
</div>
);
}
// item is an instance of Service
const id = encodeURIComponent(item.getId());
const image = item.getImages()["icon-small"];
return (
<div>
<div className="expanding-table-primary-cell-heading expanding-table-primary-cell-heading--no-nested-indicator">
<a
className="deployment-service-name table-cell-link-primary table-cell-flex-box clickable"
onClick={() => {
hashHistory.push(`/services/detail/${id}`);
}}
>
<span className="table-cell-icon icon icon-mini icon-image-container icon-margin-right icon-app-container deployment-service-icon">
<Image fallbackSrc={defaultServiceImage} src={image} />
</span>
<span className="table-cell-value">{item.getName()}</span>
</a>
</div>
<div className="deployment-service-path text-overflow">
{this.getServiceDisplayPath(item)}
</div>
</div>
);
};
renderEmpty() {
return (
<AlertPanel>
<AlertPanelHeader>
<Trans render="span" id="No active deployments" />
</AlertPanelHeader>
<Trans
render="p"
className="flush"
id="Active deployments will be shown here."
/>
</AlertPanel>
);
}
renderLoading() {
return <Loader />;
}
renderRollbackModal = () => {
const {
awaitingRevertDeploymentResponse,
deploymentToRollback,
deploymentRollbackError,
} = this.state;
const { i18n } = this.props;
const heading = (
<ModalHeading>
<Trans render="span" id="Are you sure?" />
</ModalHeading>
);
const rollbackActionText = awaitingRevertDeploymentResponse
? i18n._(/*i18n*/ { id: "Rolling back..." })
: i18n._(/*i18n*/ { id: "Continue Rollback" });
if (deploymentToRollback != null) {
return (
<Confirm
closeByBackdropClick={true}
disabled={awaitingRevertDeploymentResponse}
header={heading}
onClose={this.handleRollbackCancel}
leftButtonCallback={this.handleRollbackCancel}
leftButtonText={i18n._(/*i18n*/ { id: "Cancel" })}
leftButtonClassName="button button-primary-link"
rightButtonClassName="button button-danger"
rightButtonCallback={this.handleRollbackConfirm}
rightButtonText={rollbackActionText}
showHeader={true}
>
<div className="text-align-center">
{this.getRollbackModalText(deploymentToRollback)}
{this.renderRollbackError(deploymentRollbackError)}
</div>
</Confirm>
);
}
};
renderStartTime = (prop, deployment, rowOptions) => {
if (rowOptions.isParent) {
return (
<TimeAgo
className="deployment-start-time"
time={deployment.getStartTime()}
/>
);
}
return null;
};
renderStatus = (prop, item, rowOptions) => {
if (rowOptions.isParent) {
const currentStep = item.getCurrentStep();
const totalSteps = item.getTotalSteps();
return this.renderProgressBar(currentStep, totalSteps);
}
let currentActions = {};
if (
item.deployment.currentActions &&
item.deployment.currentActions.length > 0
) {
currentActions = item.deployment.currentActions.reduce((memo, action) => {
memo[action.app] = action.action;
return memo;
}, {});
}
let statusText = !item.isStale && item.getStatus ? item.getStatus() : null;
const itemId = item.isStale ? item.serviceID : item.id;
if (currentActions[itemId] != null) {
statusText = currentActions[itemId];
}
return statusText;
};
renderProgressBar = (currentStep, totalSteps) => {
const data = [
{ className: "color-4", value: currentStep - 1 },
{ className: "staged", value: 1 },
{ className: "", value: totalSteps - currentStep },
];
return <ProgressBar className="status-bar--large" data={data} />;
};
renderTable = (deploymentsItems) => {
return (
<div>
<ExpandingTable
childRowClassName="expanding-table-child"
className="deployments-table expanding-table table table-hover table-flush table-borderless-outer table-borderless-inner-columns flush-bottom"
columns={this.getColumns()}
colGroup={this.getColGroup()}
data={this.getTableData(deploymentsItems)}
expandRowsByDefault={true}
/>
{this.renderRollbackModal()}
</div>
);
};
renderRollbackError(deploymentRollbackError) {
if (typeof deploymentRollbackError === "string") {
return (
<p className="text-error-state flush-bottom">
{deploymentRollbackError}
</p>
);
}
}
render() {
let content = null;
const deployments = this.state.dcosDeploymentsList;
const { isOpen, onClose } = this.props;
const loading = !this.state.dcosServiceDataReceived;
if (loading) {
content = this.renderLoading();
} else if (deployments.length === 0) {
content = this.renderEmpty();
} else if (isOpen) {
content = this.renderTable(deployments);
}
const footer = (
<div className="text-align-center">
<button className="button button-primary-link" onClick={onClose}>
<Trans render="span" id="Close" />
</button>
</div>
);
// L10NTODO: Pluralize
const deploymentsCount = deployments.length;
const deploymentsText =
deploymentsCount === 1 ? i18nMark("Deployment") : i18nMark("Deployments");
const heading = !loading ? (
<ModalHeading>
{deploymentsCount} <Trans render="span" id="Active" />{" "}
<Trans render="span" id={deploymentsText} />
</ModalHeading>
) : null;
return (
<Modal
modalClass="modal modal-large modal--deployments"
footer={footer}
header={heading}
onClose={onClose}
open={isOpen}
showFooter={true}
showHeader={true}
>
{content}
</Modal>
);
}
}
export default withI18n()(DeploymentsModal);
export const WrappedComponent = DeploymentsModal; | the_stack |
import { Vec } from "../math/Vec";
import { Mat3 } from "../math/Mat3";
import { Mat4 } from "../math/Mat4";
import { v3, Vec3 } from "../math/Vec3";
import { Box } from "../struct/3d/Box";
import { Sphere } from "../struct/3d/Sphere";
import { BufferAttribute, Float32BufferAttribute, Uint16BufferAttribute, Uint32BufferAttribute } from "./buffer-attribute";
import { isBufferArray, TypedArray } from "./types";
import { Vec2 } from "../math/Vec2";
import { Vec4 } from "../math/Vec4";
import { verctorToNumbers } from "../alg/common";
export interface IGeometry {
position: number[];
normal?: number[];
index?: number[];
uv?: number[];
uv2?: number[];
tangent?: number[];
}
export interface IBufferGeometry {
position: Float32Array | undefined;
index?: Uint32Array | Uint16Array
normal?: Float32Array;
uv?: Float32Array;
uv2?: Float32Array;
tangent?: Float32Array;
}
var _bufferGeometryId = 1; // BufferGeometry uses odd numbers as Id
var _m1 = new Mat4();
var _offset = new Vec3();
var _box = new Box();
var _boxMorphTargets = new Box();
var _vector = new Vec3();
/**
* BufferType 几何体,用于独立计算几何体
*/
export class BufferGeometry {
name: string;
index: BufferAttribute | undefined;
morphAttributes: any;
morphTargetsRelative: boolean;
groups: { start: number; count: number; materialIndex?: number }[];
boundingBox: Box | undefined;
boundingSphere: Sphere | undefined;
drawRange: { start: number; count: number; };
attributes: { [key: string]: BufferAttribute };
parameters: any;
readonly isBufferGeometry: true = true;
uuid: string = "";
type: string = "BufferGeometry";
constructor() {
Object.defineProperty(this, 'id', { value: _bufferGeometryId += 2 });
this.name = '';
this.attributes = {};
this.morphAttributes = {};
this.morphTargetsRelative = false;
this.groups = [];
this.drawRange = { start: 0, count: Infinity };
}
/**
* 转化成BufferArray来计算
* @param geo
*/
setFromGeometry(geo: IGeometry) {
this.setAttribute('position', new Float32BufferAttribute(geo.position, 3))
if (geo.uv)
this.setAttribute('uv', new Float32BufferAttribute(geo.uv, 2));
if (geo.index)
this.setIndex(geo.index)
this.computeFaceNormals();
return this;
}
getIndex() {
return this.index;
}
setIndex(index: BufferAttribute | TypedArray | number[]) {
if (Array.isArray(index)) {
this.index = new (Vec.max(index as any) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(index, 1);
} else if (index instanceof BufferAttribute) {
this.index = index;
} else {
this.index = new (Vec.max(index as any) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(index, 1)
}
}
getAttribute(name: string) {
return this.attributes[name];
}
setAttribute(name: string, attribute: BufferAttribute) {
this.attributes[name] = attribute;
return this;
}
addAttribute(name: string, attribute: BufferAttribute | TypedArray | Array<number | Vec2 | Vec3 | Vec4>, itemSize: number = 1) {
if (Array.isArray(attribute)) {
if (attribute[0] instanceof Vec2) {
var nums = verctorToNumbers(attribute);
this.setAttribute(name, new Float32BufferAttribute(nums, 2))
} else if (attribute[0] instanceof Vec3) {
var nums = verctorToNumbers(attribute);
this.setAttribute(name, new Float32BufferAttribute(nums, 3))
} else if (attribute[0] instanceof Vec4) {
var nums = verctorToNumbers(attribute);
this.setAttribute(name, new Float32BufferAttribute(nums, 4))
} else if (!isNaN(attribute[0])) {
this.setAttribute(name, new Float32BufferAttribute(attribute, itemSize));
} else {
console.error("类型不存在");
}
}
else if (attribute instanceof BufferAttribute) {
this.attributes[name] = attribute;
} else if (isBufferArray(attribute)) {
this.setAttribute(name, new BufferAttribute(attribute as any, itemSize))
}
return this;
}
deleteAttribute(name: string) {
delete this.attributes[name];
return this;
}
addGroup(start: number, count: number, materialIndex?: number) {
this.groups.push({
start: start,
count: count,
materialIndex: materialIndex !== undefined ? materialIndex : 0
});
}
clearGroups() {
this.groups = [];
}
setDrawRange(start: number, count: number) {
this.drawRange.start = start;
this.drawRange.count = count;
}
applyMat4(matrix: Mat4) {
var position = this.attributes.position;
if (position !== undefined) {
position.applyMat4(matrix);
position.needsUpdate = true;
}
var normal = this.attributes.normal;
if (normal !== undefined) {
var normalMatrix = new Mat3().getNormalMat(matrix);
normal.applyNormalMat(normalMatrix);
normal.needsUpdate = true;
}
var tangent = this.attributes.tangent;
if (tangent !== undefined) {
tangent.transformDirection(matrix);
tangent.needsUpdate = true;
}
if (!this.boundingBox) {
this.computeBoundingBox();
}
if (!this.boundingSphere) {
this.computeBoundingSphere();
}
return this;
}
rotateX(angle: number) {
// rotate geometry around world x-axis
_m1.makeRotationX(angle);
this.applyMat4(_m1);
return this;
}
rotateY(angle: number) {
// rotate geometry around world y-axis
_m1.makeRotationY(angle);
this.applyMat4(_m1);
return this;
}
rotateZ(angle: number) {
// rotate geometry around world z-axis
_m1.makeRotationZ(angle);
this.applyMat4(_m1);
return this;
}
translate(x: number, y: number, z: number) {
// translate geometry
_m1.makeTranslation(x, y, z);
this.applyMat4(_m1);
return this;
}
scale(x: number, y: number, z: number) {
// scale geometry
_m1.makeScale(x, y, z);
this.applyMat4(_m1);
return this;
}
lookAt(vector: Vec3) {
_m1.lookAt(v3(), vector, Vec3.UnitY);
this.applyMat4(_m1);
return this;
}
center() {
this.computeBoundingBox();
this.boundingBox!.getCenter(_offset).negate();
this.translate(_offset.x, _offset.y, _offset.z);
return this;
}
setFromObject(object: any) {
// console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );
var geometry = object.geometry;
if (object.isPoints || object.isLine) {
var positions = new Float32BufferAttribute(geometry.vertices.length * 3, 3);
var colors = new Float32BufferAttribute(geometry.colors.length * 3, 3);
this.setAttribute('position', positions.copyVec3sArray(geometry.vertices));
this.setAttribute('color', colors.copyColorsArray(geometry.colors));
if (geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length) {
var lineDistances = new Float32BufferAttribute(geometry.lineDistances.length, 1);
this.setAttribute('lineDistance', lineDistances.copyArray(geometry.lineDistances));
}
if (geometry.boundingSphere !== null) {
this.boundingSphere = geometry.boundingSphere.clone();
}
if (geometry.boundingBox !== null) {
this.boundingBox = geometry.boundingBox.clone();
}
} else if (object.isMesh) {
// if (geometry && geometry.isGeometry) {
// this.fromGeometry(geometry);
// }
}
return this;
}
setFromPoints(points: Vec3[]) {
var position = [];
for (var i = 0, l = points.length; i < l; i++) {
var point = points[i];
position.push(point.x, point.y, point.z || 0);
}
this.setAttribute('position', new Float32BufferAttribute(position, 3));
return this;
}
updateFromObject(object: any) {
var geometry = object.geometry;
if (object.isMesh) {
var direct = geometry.__directGeometry;
if (geometry.elementsNeedUpdate === true) {
direct = undefined;
geometry.elementsNeedUpdate = false;
}
// if (direct === undefined) {
// return this.fromGeometry(geometry);
// }
direct.verticesNeedUpdate = geometry.verticesNeedUpdate;
direct.normalsNeedUpdate = geometry.normalsNeedUpdate;
direct.colorsNeedUpdate = geometry.colorsNeedUpdate;
direct.uvsNeedUpdate = geometry.uvsNeedUpdate;
direct.groupsNeedUpdate = geometry.groupsNeedUpdate;
geometry.verticesNeedUpdate = false;
geometry.normalsNeedUpdate = false;
geometry.colorsNeedUpdate = false;
geometry.uvsNeedUpdate = false;
geometry.groupsNeedUpdate = false;
geometry = direct;
}
var attribute;
if (geometry.verticesNeedUpdate === true) {
attribute = this.attributes.position;
if (attribute !== undefined) {
attribute.copyVec3sArray(geometry.vertices);
attribute.needsUpdate = true;
}
geometry.verticesNeedUpdate = false;
}
if (geometry.normalsNeedUpdate === true) {
attribute = this.attributes.normal;
if (attribute !== undefined) {
attribute.copyVec3sArray(geometry.normals);
attribute.needsUpdate = true;
}
geometry.normalsNeedUpdate = false;
}
if (geometry.colorsNeedUpdate === true) {
attribute = this.attributes.color;
if (attribute !== undefined) {
attribute.copyColorsArray(geometry.colors);
attribute.needsUpdate = true;
}
geometry.colorsNeedUpdate = false;
}
if (geometry.uvsNeedUpdate) {
attribute = this.attributes.uv;
if (attribute !== undefined) {
attribute.copyVec2sArray(geometry.uvs);
attribute.needsUpdate = true;
}
geometry.uvsNeedUpdate = false;
}
if (geometry.lineDistancesNeedUpdate) {
attribute = this.attributes.lineDistance;
if (attribute !== undefined) {
attribute.copyArray(geometry.lineDistances);
attribute.needsUpdate = true;
}
geometry.lineDistancesNeedUpdate = false;
}
if (geometry.groupsNeedUpdate) {
geometry.computeGroups(object.geometry);
this.groups = geometry.groups;
geometry.groupsNeedUpdate = false;
}
return this;
}
// fromGeometry(geometry: any) {
// geometry.__directGeometry = new DirectGeometry().fromGeometry(geometry);
// return this.fromDirectGeometry(geometry.__directGeometry);
// }
// fromDirectGeometry(geometry) {
// var positions = new Float32Array(geometry.vertices.length * 3);
// this.setAttribute('position', new BufferAttribute(positions, 3).copyVec3sArray(geometry.vertices));
// if (geometry.normals.length > 0) {
// var normals = new Float32Array(geometry.normals.length * 3);
// this.setAttribute('normal', new BufferAttribute(normals, 3).copyVec3sArray(geometry.normals));
// }
// if (geometry.colors.length > 0) {
// var colors = new Float32Array(geometry.colors.length * 3);
// this.setAttribute('color', new BufferAttribute(colors, 3).copyColorsArray(geometry.colors));
// }
// if (geometry.uvs.length > 0) {
// var uvs = new Float32Array(geometry.uvs.length * 2);
// this.setAttribute('uv', new BufferAttribute(uvs, 2).copyVec2sArray(geometry.uvs));
// }
// if (geometry.uvs2.length > 0) {
// var uvs2 = new Float32Array(geometry.uvs2.length * 2);
// this.setAttribute('uv2', new BufferAttribute(uvs2, 2).copyVec2sArray(geometry.uvs2));
// }
// // groups
// this.groups = geometry.groups;
// // morphs
// for (var name in geometry.morphTargets) {
// var array = [];
// var morphTargets = geometry.morphTargets[name];
// for (var i = 0, l = morphTargets.length; i < l; i++) {
// var morphTarget = morphTargets[i];
// var attribute = new Float32BufferAttribute(morphTarget.data.length * 3, 3);
// attribute.name = morphTarget.name;
// array.push(attribute.copyVec3sArray(morphTarget.data));
// }
// this.morphAttributes[name] = array;
// }
// // skinning
// if (geometry.skinIndices.length > 0) {
// var skinIndices = new Float32BufferAttribute(geometry.skinIndices.length * 4, 4);
// this.setAttribute('skinIndex', skinIndices.copyVec4sArray(geometry.skinIndices));
// }
// if (geometry.skinWeights.length > 0) {
// var skinWeights = new Float32BufferAttribute(geometry.skinWeights.length * 4, 4);
// this.setAttribute('skinWeight', skinWeights.copyVec4sArray(geometry.skinWeights));
// }
// //
// if (geometry.boundingSphere !== null) {
// this.boundingSphere = geometry.boundingSphere.clone();
// }
// if (geometry.boundingBox !== null) {
// this.boundingBox = geometry.boundingBox.clone();
// }
// return this;
// }
computeBoundingBox() {
if (!this.boundingBox) {
this.boundingBox = new Box();
}
var position = this.attributes.position;
var morphAttributesPosition = this.morphAttributes.position;
if (position) {
this.boundingBox!.setFromBufferAttribute(position);
// process morph attributes if present
if (morphAttributesPosition) {
for (var i = 0, il = morphAttributesPosition.length; i < il; i++) {
var morphAttribute = morphAttributesPosition[i];
_box.setFromBufferAttribute(morphAttribute);
if (this.morphTargetsRelative) {
_vector.addVecs(this.boundingBox.min, _box.min);
this.boundingBox.expandByPoint(_vector);
_vector.addVecs(this.boundingBox.max, _box.max);
this.boundingBox.expandByPoint(_vector);
} else {
this.boundingBox.expandByPoint(_box.min);
this.boundingBox.expandByPoint(_box.max);
}
}
}
} else {
this.boundingBox.makeEmpty();
}
if (isNaN(this.boundingBox.min.x) || isNaN(this.boundingBox.min.y) || isNaN(this.boundingBox.min.z)) {
console.error('THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this);
}
}
computeBoundingSphere() {
if (!this.boundingSphere) {
this.boundingSphere = new Sphere();
}
var position = this.attributes.position;
var morphAttributesPosition = this.morphAttributes.position;
if (position) {
// first, find the center of the bounding sphere
var center = this.boundingSphere!.center;
_box.setFromBufferAttribute(position);
// process morph attributes if present
if (morphAttributesPosition) {
for (var i = 0, il: number = morphAttributesPosition.length; i < il; i++) {
var morphAttribute = morphAttributesPosition[i];
_boxMorphTargets.setFromBufferAttribute(morphAttribute);
if (this.morphTargetsRelative) {
_vector.addVecs(_box.min, _boxMorphTargets.min);
_box.expandByPoint(_vector);
_vector.addVecs(_box.max, _boxMorphTargets.max);
_box.expandByPoint(_vector);
} else {
_box.expandByPoint(_boxMorphTargets.min);
_box.expandByPoint(_boxMorphTargets.max);
}
}
}
_box.getCenter(center);
// second, try to find a boundingSphere with a radius smaller than the
// boundingSphere of the boundingBox: sqrt(3) smaller in the best case
var maxRadiusSq = 0;
for (var i = 0, il: number = position.count; i < il; i++) {
_vector.fromBufferAttribute(position, i);
maxRadiusSq = Math.max(maxRadiusSq, center!.distanceToSquared(_vector));
}
// process morph attributes if present
if (morphAttributesPosition) {
for (var i = 0, il: number = morphAttributesPosition.length; i < il; i++) {
var morphAttribute = morphAttributesPosition[i];
var morphTargetsRelative = this.morphTargetsRelative;
for (var j = 0, jl = morphAttribute.count; j < jl; j++) {
_vector.fromBufferAttribute(morphAttribute, j);
if (morphTargetsRelative) {
_offset.fromBufferAttribute(position, j);
_vector.add(_offset);
}
maxRadiusSq = Math.max(maxRadiusSq, center!.distanceToSquared(_vector));
}
}
}
this.boundingSphere!.radius = Math.sqrt(maxRadiusSq);
if (isNaN(this.boundingSphere!.radius)) {
console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this);
}
}
}
computeFaceNormals() {
// backwards compatibility
}
computeVertexNormals() {
var index = this.index;
var attributes = this.attributes;
if (attributes.position) {
var positions = attributes.position.array;
if (attributes.normal === undefined) {
this.setAttribute('normal', new BufferAttribute(new Float32Array(positions.length), 3));
} else {
// reset existing normals to zero
var array = attributes.normal.array;
for (var i = 0, il = array.length; i < il; i++) {
array[i] = 0;
}
}
var normals = attributes.normal.array;
var vA, vB, vC;
var pA = new Vec3(), pB = new Vec3(), pC = new Vec3();
var cb = new Vec3(), ab = new Vec3();
// indexed elements
if (index) {
var indices = index.array;
for (var i = 0, il = index.count; i < il; i += 3) {
vA = indices[i + 0] * 3;
vB = indices[i + 1] * 3;
vC = indices[i + 2] * 3;
pA.fromArray(positions, vA);
pB.fromArray(positions, vB);
pC.fromArray(positions, vC);
cb.subVecs(pC, pB);
ab.subVecs(pA, pB);
cb.cross(ab);
normals[vA] += cb.x;
normals[vA + 1] += cb.y;
normals[vA + 2] += cb.z;
normals[vB] += cb.x;
normals[vB + 1] += cb.y;
normals[vB + 2] += cb.z;
normals[vC] += cb.x;
normals[vC + 1] += cb.y;
normals[vC + 2] += cb.z;
}
} else {
// non-indexed elements (unconnected triangle soup)
for (var i = 0, il = positions.length; i < il; i += 9) {
pA.fromArray(positions, i);
pB.fromArray(positions, i + 3);
pC.fromArray(positions, i + 6);
cb.subVecs(pC, pB);
ab.subVecs(pA, pB);
cb.cross(ab);
normals[i] = cb.x;
normals[i + 1] = cb.y;
normals[i + 2] = cb.z;
normals[i + 3] = cb.x;
normals[i + 4] = cb.y;
normals[i + 5] = cb.z;
normals[i + 6] = cb.x;
normals[i + 7] = cb.y;
normals[i + 8] = cb.z;
}
}
this.normalizeNormals();
attributes.normal.needsUpdate = true;
}
}
merge(geometry: BufferGeometry, offset: number) {
if (!(geometry && geometry.isBufferGeometry)) {
console.error('THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry);
return;
}
if (offset === undefined) {
offset = 0;
console.warn(
'THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. '
+ 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.'
);
}
var attributes = this.attributes;
for (var key in attributes) {
if (geometry.attributes[key] === undefined) continue;
var attribute1 = attributes[key];
var attributeArray1 = attribute1.array;
var attribute2 = geometry.attributes[key];
var attributeArray2 = attribute2.array;
var attributeOffset = attribute2.itemSize * offset;
var length = Math.min(attributeArray2.length, attributeArray1.length - attributeOffset);
for (var i = 0, j = attributeOffset; i < length; i++, j++) {
attributeArray1[j] = attributeArray2[i];
}
}
return this;
}
normalizeNormals() {
var normals = this.attributes.normal;
for (var i = 0, il = normals.count; i < il; i++) {
_vector.x = normals.getX(i);
_vector.y = normals.getY(i);
_vector.z = normals.getZ(i);
_vector.normalize();
normals.setXYZ(i, _vector.x, _vector.y, _vector.z);
}
}
toNonIndexed() {
function convertBufferAttribute(attribute: BufferAttribute, indices: ArrayLike<number>) {
var array = attribute.array;
var itemSize = attribute.itemSize;
var array2 = new (array as any).constructor(indices.length * itemSize);
var index = 0, index2 = 0;
for (var i = 0, l = indices.length; i < l; i++) {
index = indices[i] * itemSize;
for (var j = 0; j < itemSize; j++) {
array2[index2++] = array[index++];
}
}
return new BufferAttribute(array2, itemSize);
}
//
if (this.index === undefined) {
console.warn('THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.');
return this;
}
var geometry2 = new BufferGeometry();
var indices = this.index!.array;
var attributes = this.attributes;
// attributes
for (var name in attributes) {
var attribute = attributes[name];
var newAttribute = convertBufferAttribute(attribute, indices);
geometry2.setAttribute(name, newAttribute);
}
// morph attributes
var morphAttributes = this.morphAttributes;
for (name in morphAttributes) {
var morphArray = [];
var morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
for (var i = 0, il = morphAttribute.length; i < il; i++) {
var attribute: BufferAttribute = morphAttribute[i];
var newAttribute = convertBufferAttribute(attribute, indices);
morphArray.push(newAttribute);
}
geometry2.morphAttributes[name] = morphArray;
}
geometry2.morphTargetsRelative = this.morphTargetsRelative;
// groups
var groups = this.groups;
for (var i = 0, l = groups.length; i < l; i++) {
var group = groups[i];
geometry2.addGroup(group.start, group.count, group.materialIndex);
}
return geometry2;
}
toJSON() {
var data: any = {
metadata: {
version: 4.5,
type: 'BufferGeometry',
generator: 'BufferGeometry.toJSON'
}
};
// standard BufferGeometry serialization
data.uuid = this.uuid;
data.type = this.type;
if (this.name !== '') data.name = this.name;
if (Object.keys(this.userData).length > 0) data.userData = this.userData;
if (this.parameters !== undefined) {
var parameters = this.parameters;
for (var key in parameters) {
if (parameters[key] !== undefined) data[key] = parameters[key];
}
return data;
}
data.data = { attributes: {} };
var index = this.index;
if (index) {
data.data.index = {
type: index.array.constructor.name,
array: Array.prototype.slice.call(index.array)
};
}
var attributes = this.attributes;
for (var key in attributes) {
var attribute = attributes[key];
var attributeData: any = attribute.toJSON();
if (attribute.name !== '') attributeData.name = attribute.name;
data.data.attributes[key] = attributeData;
}
var morphAttributes: any = {};
var hasMorphAttributes = false;
for (var key in this.morphAttributes) {
var attributeArray = this.morphAttributes[key];
var array = [];
for (var i = 0, il = attributeArray.length; i < il; i++) {
var attribute: BufferAttribute = attributeArray[i];
var attributeData: any = attribute.toJSON();
if (attribute.name !== '') attributeData.name = attribute.name;
array.push(attributeData);
}
if (array.length > 0) {
morphAttributes[key] = array;
hasMorphAttributes = true;
}
}
if (hasMorphAttributes) {
data.data.morphAttributes = morphAttributes;
data.data.morphTargetsRelative = this.morphTargetsRelative;
}
var groups = this.groups;
if (groups.length > 0) {
data.data.groups = JSON.parse(JSON.stringify(groups));
}
var boundingSphere = this.boundingSphere;
if (boundingSphere) {
data.data.boundingSphere = {
center: boundingSphere.center.toArray(),
radius: boundingSphere.radius
};
}
return data;
}
userData(userData: any) {
throw new Error("Method not implemented.");
}
clone() {
/*
// Handle primitives
var parameters = this.parameters;
if ( parameters !== undefined ) {
var values = [];
for ( var key in parameters ) {
values.push( parameters[ key ] );
}
var geometry = Object.create( this.constructor.prototype );
this.constructor.apply( geometry, values );
return geometry;
}
return new this.constructor().copy( this );
*/
return new BufferGeometry().copy(this);
}
copy(source: BufferGeometry) {
var name, i, l;
// reset
this.attributes = {};
this.morphAttributes = {};
this.groups = [];
// name
this.name = source.name;
// index
var index = source.index;
if (index) {
this.setIndex(index.clone());
}
// attributes
var attributes = source.attributes;
for (name in attributes) {
var attribute = attributes[name];
this.setAttribute(name, attribute.clone());
}
// morph attributes
var morphAttributes = source.morphAttributes;
for (name in morphAttributes) {
var array = [];
var morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
for (i = 0, l = morphAttribute.length; i < l; i++) {
array.push(morphAttribute[i].clone());
}
this.morphAttributes[name] = array;
}
this.morphTargetsRelative = source.morphTargetsRelative;
// groups
var groups = source.groups;
for (i = 0, l = groups.length; i < l; i++) {
var group = groups[i];
this.addGroup(group.start, group.count, group.materialIndex);
}
// bounding box
var boundingBox = source.boundingBox;
if (boundingBox) {
this.boundingBox = boundingBox.clone();
}
// bounding sphere
var boundingSphere = source.boundingSphere;
if (boundingSphere) {
this.boundingSphere = boundingSphere.clone();
}
// draw range
this.drawRange.start = source.drawRange.start;
this.drawRange.count = source.drawRange.count;
// user data
this.userData = source.userData;
return this;
}
} | the_stack |
import { ContextMessageUpdate, Telegraf } from 'telegraf'
import { addRaffle, getRaffle, Raffle } from '../models'
import {
ExtraEditMessage,
ChatMember,
Message,
} from 'telegraf/typings/telegram-types'
import { shuffle, random } from 'lodash'
import { checkIfAdmin } from './checkAdmin'
import { findChat } from '../models/chat'
import { loc } from './locale'
import { InstanceType } from 'typegoose'
/**
* Starting a new raffle
* @param ctx Context of the message that started
*/
export async function startRaffle(ctx: ContextMessageUpdate) {
// Get chat
const chat = await findChat(ctx.chat.id)
// Add raffle
const raffle = await addRaffle(ctx.chat.id)
// Save raffle message if required
if (chat.raffleMessage) {
raffle.raffleMessage = chat.raffleMessage
await raffle.save()
}
if (chat.winnerMessage) {
raffle.winnerMessage = chat.winnerMessage
await raffle.save()
}
// Add buttons
const options: ExtraEditMessage = {
reply_markup: getButtons(raffle, chat.language),
parse_mode: 'HTML',
disable_web_page_preview: true,
}
// Send message
let sent: Message
if (raffle.raffleMessage) {
const raffleMessage = raffle.raffleMessage
if (raffleMessage.text) {
raffleMessage.text = raffleMessage.text.replace(
'$numberOfParticipants',
'0'
)
} else {
raffleMessage.caption = raffleMessage.caption.replace(
'$numberOfParticipants',
'0'
)
}
sent = await ctx.telegram.sendCopy(ctx.chat.id, raffleMessage, {
reply_markup: getButtons(raffle, chat.language),
parse_mode: 'HTML',
disable_web_page_preview: true,
})
} else {
sent = await ctx.replyWithHTML(
loc(
chat.number > 1 ? 'raffle_text_multiple' : 'raffle_text',
chat.language
),
options
)
}
// Save sent message id
raffle.messageId = sent.message_id
await raffle.save()
}
/**
* Setting up callback for the raffle participation button
* @param bot Bot to setup the callback
*/
export function setupCallback(bot: Telegraf<ContextMessageUpdate>) {
;(<any>bot).action(async (data: string, ctx: ContextMessageUpdate) => {
// Get raffle
const datas = data.split('~')
if (['l', 'n', 'c'].indexOf(datas[0]) > -1) return
const chatId = Number(datas[0])
let raffle = await getRaffle(chatId, datas[1])
// Get chat
const chat = await findChat(ctx.chat.id)
// Check if raffle is there
if (!raffle) {
try {
await (<any>ctx).answerCbQuery(
loc('please_retry', chat.language),
undefined,
true
)
} catch {
// do nothing
}
return
}
// Check if raffle is finished
if (raffle.winners) {
try {
await (<any>ctx).answerCbQuery(
loc('raffle_over', chat.language),
undefined,
true
)
} catch {
// do nothing
}
return
}
// Check if already in
if (raffle.participantsIds.indexOf(ctx.from.id) > -1) {
try {
await (<any>ctx).answerCbQuery(
loc('already_participating', chat.language),
undefined,
true
)
} catch {
// do nothing
}
return
}
// Check if participant subscribed
if (chat.subscribe) {
for (const subscribe of chat.subscribe.split(',')) {
try {
const member = await ctx.telegram.getChatMember(
`${!isNaN(+subscribe) ? '' : '@'}${subscribe}`,
ctx.from.id
)
if (
!member.status ||
member.status === 'left' ||
member.status === 'kicked'
) {
throw new Error()
}
} catch (err) {
try {
await (<any>ctx).answerCbQuery(
`${loc('check_subscription', chat.language)}${
!isNaN(+subscribe) ? '' : '@'
}${subscribe}`,
undefined,
true
)
} catch {
// do nothing
}
return
}
}
}
// Add participant and update number
raffle.participantsIds.push(ctx.from.id)
raffle = await raffle.save()
// Reply that they are in
try {
await (<any>ctx).answerCbQuery(
loc('participated', chat.language),
undefined,
true
)
} catch {
// do nothing
}
// Update counter of participants
try {
// Add buttons
const options: ExtraEditMessage = {
reply_markup: getButtons(raffle, chat.language),
parse_mode: 'HTML',
disable_web_page_preview: true,
}
let text: string
if (raffle.raffleMessage) {
const raffleMessage = raffle.raffleMessage
text = raffleMessage.text
? raffleMessage.text.replace(
'$numberOfParticipants',
`${raffle.participantsIds.length}`
)
: raffleMessage.caption.replace(
'$numberOfParticipants',
`${raffle.participantsIds.length}`
)
} else {
text = `${loc(
chat.number > 1 ? 'raffle_text_multiple' : 'raffle_text',
chat.language
)}\n\n${loc('participants_number', chat.language)}: ${
raffle.participantsIds.length
}`
}
if (!raffle.raffleMessage || raffle.raffleMessage.text) {
await ctx.telegram.editMessageText(
raffle.chatId,
raffle.messageId,
undefined,
text,
options
)
} else {
await ctx.telegram.editMessageCaption(
raffle.chatId,
raffle.messageId,
undefined,
text,
options as any
)
}
} catch (err) {
// Do nothing
}
})
}
/**
* Setting up listener for the raffle endings
* @param bot
*/
export function setupListener(bot: Telegraf<ContextMessageUpdate>) {
bot.use(async (ctx, next) => {
try {
const message = ctx.message || ctx.channelPost
// Check if reply to bot's message
if (
!message ||
!message.reply_to_message ||
(!message.reply_to_message.text && !message.reply_to_message.caption)
) {
throw new Error('Not checking')
}
// Check if admin replied
const isAdmin = await checkIfAdmin(ctx, false)
if (!isAdmin) {
throw new Error('No admin')
}
// Get reply message
const reply = message.reply_to_message
// Check if there is raffle to the reply message
const raffle = await getRaffle(reply.chat.id, reply.message_id)
if (!raffle) {
throw new Error('No raffle')
}
// Check if no winner yet
if (raffle.winners) {
throw new Error('No winners')
}
// Finish raffle
await finishRaffle(raffle, ctx)
} catch (err) {
// Do nothing
} finally {
// Continue
next()
}
})
}
/**
* Buttons for a raffle
* @param raffle Raffle to provide buttons to
* @param language Languageof thebuttons
* @returns buttons for a raffle
*/
function getButtons(raffle: InstanceType<Raffle>, language: string) {
return {
inline_keyboard: [
[
{
text: loc('participate_button', language),
callback_data: `${raffle.chatId}~${raffle.id}`,
},
],
],
}
}
/**
* Finishing raffle
* @param raffle Raffle to finish
* @param ctx Context of message that finished raffle
*/
async function finishRaffle(raffle: Raffle, ctx: ContextMessageUpdate) {
console.log(`Finishing raffle for chat ${raffle.chatId}`)
// Get participants ids
let ids = raffle.participantsIds
const idsOriginalLength = ids.length
// Get chat
const chat = await findChat(ctx.chat.id)
const nodelete = chat.nodelete
// Check if there were participants
if (ids.length <= 0) {
const text = loc('no_participants', chat.language)
if (!nodelete) {
if (!raffle.raffleMessage || raffle.raffleMessage.text) {
await ctx.telegram.editMessageText(
raffle.chatId,
raffle.messageId,
undefined,
text,
{ disable_web_page_preview: true, parse_mode: 'HTML' }
)
} else {
await ctx.telegram.editMessageCaption(
raffle.chatId,
raffle.messageId,
undefined,
text,
{ disable_web_page_preview: true, parse_mode: 'HTML' } as any
)
}
} else {
await ctx.telegram.sendMessage(raffle.chatId, text, {
parse_mode: 'HTML',
disable_web_page_preview: true,
})
}
return
}
// Get winners
ids = shuffle(ids)
let winners: {
name: string
winner: ChatMember
}[] = []
while (winners.length < chat.number) {
// Check if not enough participants
if (ids.length + winners.length < chat.number) {
const text = loc('not_enough_participants', chat.language)
if (!nodelete) {
if (!raffle.raffleMessage || raffle.raffleMessage.text) {
await ctx.telegram.editMessageText(
raffle.chatId,
raffle.messageId,
undefined,
text,
{ disable_web_page_preview: true, parse_mode: 'HTML' }
)
} else {
await ctx.telegram.editMessageCaption(
raffle.chatId,
raffle.messageId,
undefined,
text,
{ disable_web_page_preview: true, parse_mode: 'HTML' } as any
)
}
} else {
await ctx.telegram.sendMessage(raffle.chatId, text, {
parse_mode: 'HTML',
disable_web_page_preview: true,
})
}
return
}
const winnerIndex = random(ids.length - 1)
const winnerId = ids.splice(winnerIndex, 1)[0]
try {
const winner = await ctx.telegram.getChatMember(raffle.chatId, winnerId)
if (
!['administrator', 'creator', 'member', 'restricted'].includes(
winner.status
)
) {
continue
}
const name = winner.user.username
? `@${winner.user.username}`
: `${winner.user.first_name}${
winner.user.last_name ? ` ${winner.user.last_name}` : ''
}`
if (winners.map((w) => w.winner.user.id).indexOf(winner.user.id) < 0) {
winners.push({ name, winner })
}
} catch (err) {
// Do nothing
}
}
winners = shuffle(winners)
console.log(
`Finishing raffle for chat ${raffle.chatId}, winners length: ${winners.length}`
)
// Save winners
raffle.winners = winners.map((w) => w.winner.user.id).join(',')
await (<any>raffle).save()
// Announce winner
if (winners.length == 1) {
const winner = winners[0].winner
const name = winners[0].name.replace('<', '').replace('>', '')
let text: string
if (raffle.winnerMessage) {
text = raffle.winnerMessage.text
.replace(
'$winner',
`<a href="tg://user?id=${winner.user.id}">${name}</a>`
)
.replace('$numberOfParticipants', `${idsOriginalLength}`)
} else {
text = `🎉 ${loc('winner', chat.language)} — <a href="tg://user?id=${
winner.user.id
}">${name}</a>! ${loc('congratulations', chat.language)}!\n\n${loc(
'participants_number',
chat.language
)} — ${idsOriginalLength}.`
}
if (!nodelete) {
if (!raffle.raffleMessage || raffle.raffleMessage.text) {
await ctx.telegram.editMessageText(
raffle.chatId,
raffle.messageId,
undefined,
text,
{
parse_mode: 'HTML',
disable_web_page_preview: true,
}
)
} else {
await ctx.telegram.editMessageCaption(
raffle.chatId,
raffle.messageId,
undefined,
text,
{
parse_mode: 'HTML',
disable_web_page_preview: true,
} as any
)
}
} else {
await ctx.telegram.sendMessage(raffle.chatId, text, {
parse_mode: 'HTML',
disable_web_page_preview: true,
})
}
} else {
const names = winners.map((w) => w.name.replace('<', '').replace('>', ''))
if (names.length <= 50 || raffle.winnerMessage) {
let text: string
if (raffle.winnerMessage) {
text = raffle.winnerMessage.text
.replace(
'$winner',
names
.map(
(name, i) =>
`<a href="tg://user?id=${winners[i].winner.user.id}">${name}</a>`
)
.join(', ')
)
.replace('$numberOfParticipants', `${idsOriginalLength}`)
} else {
text = `🎉 ${loc('winners', chat.language)}:\n`
for (let i = 0; i < names.length; i++) {
text = `${text}\n${i + 1}. <a href="tg://user?id=${
winners[i].winner.user.id
}">${names[i]}</a>`
}
text = `${text}\n\n${loc('congratulations', chat.language)}!\n\n${loc(
'participants_number',
chat.language
)} — ${idsOriginalLength}.`
}
if (!nodelete) {
if (!raffle.raffleMessage || raffle.raffleMessage.text) {
await ctx.telegram.editMessageText(
raffle.chatId,
raffle.messageId,
undefined,
text,
{
parse_mode: 'HTML',
disable_web_page_preview: true,
}
)
} else {
await ctx.telegram.editMessageCaption(
raffle.chatId,
raffle.messageId,
undefined,
text,
{
parse_mode: 'HTML',
disable_web_page_preview: true,
} as any
)
}
} else {
await ctx.telegram.sendMessage(raffle.chatId, text, {
parse_mode: 'HTML',
disable_web_page_preview: true,
})
}
} else {
let commonI = 0
let text = `🎉 ${loc('winners', chat.language)}:\n`
const firstNames = names.splice(0, 50)
const firstWinners = winners.splice(0, 50)
for (let i = 0; i < firstNames.length; i++) {
commonI++
text = `${text}\n${commonI}. <a href="tg://user?id=${firstWinners[i].winner.user.id}">${firstNames[i]}</a>`
}
text = `${text}\n\n${loc('congratulations', chat.language)}!\n\n${loc(
'participants_number',
chat.language
)} — ${idsOriginalLength}.`
console.log(`Announcing winners for ${raffle.chatId}`, raffle.messageId)
if (!nodelete) {
if (!raffle.raffleMessage || raffle.raffleMessage.text) {
await ctx.telegram.editMessageText(
raffle.chatId,
raffle.messageId,
undefined,
text,
{
parse_mode: 'HTML',
disable_web_page_preview: true,
}
)
} else {
await ctx.telegram.editMessageCaption(
raffle.chatId,
raffle.messageId,
undefined,
text,
{
parse_mode: 'HTML',
disable_web_page_preview: true,
} as any
)
}
} else {
await ctx.telegram.sendMessage(raffle.chatId, text, {
parse_mode: 'HTML',
disable_web_page_preview: true,
})
}
while (names.length > 0) {
let text = ``
const nextNames = names.splice(0, 50)
const nextWinners = winners.splice(0, 50)
for (let i = 0; i < nextNames.length; i++) {
commonI++
text = `${text}\n${commonI}. <a href="tg://user?id=${nextWinners[i].winner.user.id}">${nextNames[i]}</a>`
}
await ctx.telegram.sendMessage(raffle.chatId, text, {
parse_mode: 'HTML',
disable_web_page_preview: true,
})
}
}
}
} | the_stack |
import {
Config,
getExecutable,
Launcher,
LaunchInstance,
OldLaunchInstance,
Patcher,
PatchEvents,
PatchInstance,
Queue,
Rollbacker,
State as PatcherState,
Uninstaller,
} from 'client-voodoo';
import * as fs from 'fs';
import * as path from 'path';
import Vue from 'vue';
import { Action, Mutation, namespace, State } from 'vuex-class';
import { arrayGroupBy, arrayIndexBy, arrayRemove } from '../../utils/array';
import { fuzzysearch } from '../../utils/string';
import { isErrnoException } from '../../utils/utils';
import { VuexAction, VuexGetter, VuexModule, VuexMutation, VuexStore } from '../../utils/vuex';
import { Analytics } from '../../_common/analytics/analytics.service';
import { Api } from '../../_common/api/api.service';
import { ClientUpdater } from '../../_common/client/client-updater.service';
import { Device } from '../../_common/device/device.service';
import { GameBuild } from '../../_common/game/build/build.model';
import { GameBuildLaunchOption } from '../../_common/game/build/launch-option/launch-option.model';
import { Game } from '../../_common/game/game.model';
import { GamePackage } from '../../_common/game/package/package.model';
import { GameRelease } from '../../_common/game/release/release.model';
import { Growls } from '../../_common/growls/growls.service';
import { HistoryTick } from '../../_common/history-tick/history-tick-service';
import {
SettingGameInstallDir,
SettingMaxDownloadCount,
SettingMaxExtractCount,
SettingQueueWhenPlaying,
} from '../../_common/settings/settings.service';
import { Translate } from '../../_common/translate/translate.service';
import { ClientAntiVirusModal } from '../components/client/anti-virus-modal/anti-virus-modal.service';
import { LocalDbGame } from '../components/client/local-db/game/game.model';
import { LocalDb } from '../components/client/local-db/local-db.service';
import {
LocalDbPackage,
LocalDbPackagePatchState,
LocalDbPackagePid,
LocalDbPackageProgress,
LocalDbPackageRemoveState,
LocalDbPackageRunState,
} from '../components/client/local-db/package/package.model';
export const ClientLibraryState = namespace('clientLibrary', State);
export const ClientLibraryAction = namespace('clientLibrary', Action);
export const ClientLibraryMutation = namespace('clientLibrary', Mutation);
export type ClientUpdateStatus = 'checking' | 'none' | 'fetching' | 'ready' | 'error';
// These are only the public actions/mutations.
export type Actions = {
'clientLibrary/bootstrap': undefined;
'clientLibrary/packageInstall': [
Game,
GamePackage,
GameRelease,
GameBuild,
GameBuildLaunchOption[]
];
'clientLibrary/packageStartUpdate': [LocalDbPackage, number];
'clientLibrary/packageUninstall': [
LocalDbPackage,
{ dbOnly?: boolean; notifications?: boolean }?
];
'clientLibrary/installerRetry': LocalDbPackage;
'clientLibrary/installerPause': LocalDbPackage;
'clientLibrary/installerResume': LocalDbPackage;
'clientLibrary/launcherLaunch': LocalDbPackage;
};
export type Mutations = {
'clientLibrary/checkQueueSettings': undefined;
'clientLibrary/syncInit': undefined;
'clientLibrary/syncSetInterval': NodeJS.Timer;
'clientLibrary/syncClear': undefined;
};
export type ClientVoodooOperation =
| 'launch'
| 'attach'
| 'install-begin'
| 'install-end'
| 'update-begin'
| 'update-end'
| 'patch-abort-begin'
| 'patch-abort-end'
| 'uninstall-begin'
| 'uninstall-end';
function trackClientVoodooOperation(operation: ClientVoodooOperation, success: boolean) {
Analytics.trackEvent('client-op', success ? 'success' : 'error', operation);
}
function handleClientVoodooError(
err: Error,
operation: ClientVoodooOperation,
message?: string,
title?: string
) {
if (
isErrnoException(err) &&
err.code === 'ENOENT' &&
err.path &&
path.resolve(err.path) === path.resolve(getExecutable())
) {
if (operation) {
trackClientVoodooOperation(operation, false);
}
if (message) {
ClientAntiVirusModal.show(message, title);
}
return;
}
if (message) {
Growls.error(message, title);
}
}
@VuexModule()
export class ClientLibraryStore extends VuexStore<ClientLibraryStore, Actions, Mutations> {
private _bootstrapPromise: Promise<void> | null = null;
private _bootstrapPromiseResolver: Function = null as any;
private db: LocalDb = null as any;
// Localdb variables
packages: LocalDbPackage[] = [];
games: LocalDbGame[] = [];
// Installer variables
currentlyPatching: { [packageId: number]: PatchInstance } = {};
currentlyUninstalling: { [packageId: number]: Promise<void> | undefined } = {};
// Launcher variables
isLauncherReady = false;
currentlyPlaying: LocalDbPackage[] = [];
get packagesById() {
return arrayIndexBy(this.packages, 'id');
}
get gamesById() {
return arrayIndexBy(this.games, 'id');
}
get packagesByGameId() {
return arrayGroupBy(this.packages, 'game_id');
}
get runningPackageIds() {
return this.currentlyPlaying.map(localPackage => localPackage.id);
}
get numPlaying() {
return this.currentlyPlaying.length;
}
get numPatching() {
return Object.keys(this.currentlyPatching).length;
}
get totalPatchProgress() {
if (!this.numPatching) {
return null;
}
let currentProgress = 0;
let numPatching = this.numPatching;
for (const packageId in this.currentlyPatching) {
const progress = this.packagesById[packageId].patchProgress;
// If the progress is null, we don't count that package progress as part of the total
// progress, because it means there was some unexpected error with the stored package.
if (progress === null) {
numPatching -= 1;
continue;
}
currentProgress += progress;
}
return numPatching ? currentProgress / numPatching : null;
}
@VuexAction
async bootstrap() {
if (this._bootstrapPromise) {
return;
}
this._startBootstrap();
console.log('Bootstrapping client library');
const db = await LocalDb.instance();
this._useLocalDb(db);
console.log('LocalDB ready');
const [packages, games] = [db.packages.all(), db.games.all()];
this._bootstrap({ packages, games });
if (GJ_ENVIRONMENT === 'development') {
Config.env = 'development';
}
await ClientUpdater.init();
this.installerInit();
this.launcherInit();
this.syncCheck();
setInterval(() => this.syncCheck(), 60 * 60 * 1000); // 1hr currently
this._bootstrapPromiseResolver();
}
@VuexMutation
private _startBootstrap() {
this._bootstrapPromise = new Promise(resolve => {
this._bootstrapPromiseResolver = resolve;
});
}
@VuexMutation
private _bootstrap({ packages, games }: { packages: LocalDbPackage[]; games: LocalDbGame[] }) {
this.packages = packages;
this.games = games;
}
@VuexMutation
private _useLocalDb(db: LocalDb) {
this.db = db;
}
/**
* Returns a package that is representative of this game's current state.
* For example, if a package is installing, we will return that.
* It should return a single package for a game, even if they have multiple
* installed.
*/
@VuexGetter
findActiveForGame(gameId: number) {
const localPackages = this.packagesByGameId[gameId];
if (!localPackages || !localPackages.length) {
return null;
}
for (const localPackage of localPackages) {
if (localPackage.install_state) {
return localPackage;
}
}
return localPackages[0];
}
@VuexGetter
searchInstalledGames(query: string, limit = 3) {
query = query.toLowerCase();
return this.games
.filter(i => fuzzysearch(query, i.title.toLowerCase()))
.sort((g1, g2) => g1.title.localeCompare(g2.title))
.slice(0, limit);
}
@VuexMutation
private setCurrentlyPatching([localPackage, patchInstance]: [LocalDbPackage, PatchInstance]) {
if (!this.currentlyPatching[localPackage.id]) {
Vue.set(this.currentlyPatching, localPackage.id + '', patchInstance);
}
}
@VuexMutation
private unsetCurrentlyPatching(localPackage: LocalDbPackage) {
Vue.delete(this.currentlyPatching, localPackage.id + '');
}
@VuexMutation
private setCurrentlyUninstalling([localPackage, uninstallPromise]: [
LocalDbPackage,
Promise<void>
]) {
if (this.currentlyUninstalling[localPackage.id]) {
return;
}
Vue.set(this.currentlyUninstalling, localPackage.id + '', uninstallPromise);
}
@VuexMutation
private unsetCurrentlyUninstalling(localPackage: LocalDbPackage) {
if (!this.currentlyUninstalling[localPackage.id]) {
return;
}
Vue.delete(this.currentlyUninstalling, localPackage.id + '');
}
@VuexMutation
checkQueueSettings() {
Queue.faster = {
downloads: SettingMaxDownloadCount.get(),
extractions: SettingMaxExtractCount.get(),
};
if (SettingQueueWhenPlaying.get()) {
Queue.slower = {
downloads: 0,
extractions: 0,
};
} else {
Queue.slower = Queue.faster;
}
}
@VuexAction
private installerInit() {
this.checkQueueSettings();
return this.retryAllInstallations();
}
@VuexAction
private retryAllInstallations() {
const promises = [];
// This will retry to install anything that was installing before client was closed.
for (const packageId in this.packages) {
const localPackage = this.packages[packageId];
if (localPackage.isPatching && !localPackage.isPatchPaused) {
promises.push(this.installerRetry(localPackage));
} else if (localPackage.isRemoving || localPackage.didRemoveFail) {
// Since the old client version on nwjs 0.12.3 we solved a long lived bug that prevented users from
// uninstalling packages that failed during uninstallation. The client now retries the uninstallations
// properly - which means after the update users will receive a torrent of growl messages and system notifications
// for each package that was now finally uninstalled successfully. Ungood, lets silence that.
promises.push(
this.packageUninstall([
localPackage,
{
dbOnly: false,
notifications: false,
},
])
);
}
}
return Promise.resolve(promises);
}
@VuexAction
async installerRetry(localPackage: Actions['clientLibrary/installerRetry']) {
// Reset states.
const downloadStates = [
LocalDbPackagePatchState.DOWNLOADING,
LocalDbPackagePatchState.DOWNLOAD_FAILED,
];
const unpackStates = [
LocalDbPackagePatchState.UNPACKING,
LocalDbPackagePatchState.UNPACK_FAILED,
];
if (localPackage.install_state) {
if (downloadStates.indexOf(localPackage.install_state) !== -1) {
this.setPackageInstallState([localPackage, LocalDbPackagePatchState.PATCH_PENDING]);
} else if (unpackStates.indexOf(localPackage.install_state) !== -1) {
this.setPackageInstallState([localPackage, LocalDbPackagePatchState.DOWNLOADED]);
}
} else if (localPackage.update_state) {
if (downloadStates.indexOf(localPackage.update_state || '') !== -1) {
this.setPackageUpdateState([localPackage, LocalDbPackagePatchState.PATCH_PENDING]);
} else if (unpackStates.indexOf(localPackage.update_state || '') !== -1) {
this.setPackageUpdateState([localPackage, LocalDbPackagePatchState.DOWNLOADED]);
}
}
const game = this.gamesById[localPackage.game_id];
return this.doPatch([game, localPackage]);
}
@VuexAction
private async doPatch([localGame, localPackage]: [LocalDbGame, LocalDbPackage]) {
const packageId = localPackage.id;
const authTokenGetter = () => LocalDbPackage.getAccessToken(packageId);
let authToken = '';
try {
authToken = await authTokenGetter();
} catch (err) {
console.log(`Could not get access token for package ${packageId}`);
console.warn(err);
}
const operation = localPackage.install_state ? 'install' : 'update';
let packageTitle = localPackage.title || localGame.title;
if (packageTitle !== localGame.title) {
packageTitle += ' for ' + localGame.title;
}
let patchBegun = false;
try {
// We freeze the installation directory in time.
if (!localPackage.install_dir) {
const title = (localPackage.title || 'default').replace(/[\/\?<>\\:\*\|":]/g, '');
await this.setPackageInstallDir([
localPackage,
path.join(
SettingGameInstallDir.get(),
`${localGame.slug}-${localGame.id}`,
`${title}-${packageId}`
),
]);
}
// This is a very specific edge case.
// Normally when you pause an installation/update, the joltron process hangs around.
// This allows us to resume it easily with the installerResume function that simply
// sends the existing process a resume message and continue with its existing promise chain.
// However, if the operation was paused and the client was closed, when the user boots the client
// back up again it'll attempt to retry all the installations that were in progress automatically
// by calling installerRetry, which will end up calling this method.
// Issue is that the package status will still be paused from the previous run so we need to
// flick it back to resumed before continuing.
if (localPackage.isPatchPaused) {
await this.setPackagePatchResumed(localPackage);
}
const patchInstance = await Patcher.patch(localPackage as any, authTokenGetter, {
authToken,
});
patchBegun = true;
trackClientVoodooOperation(
operation === 'install' ? 'install-begin' : 'update-begin',
true
);
const canceled = await new Promise<boolean>((resolve, reject) => {
this.setCurrentlyPatching([localPackage, patchInstance]);
const listeners: Partial<PatchEvents> = {};
const cleanupListeners = () => {
// Remove all listeners we bound to patch instance so it won't update the
// local package after the operation is done.
// This addresses a race condition where we might receive a message from joltron
// while trying to remove the package model from indexeddb. reciving a message
// will attempt to update the localdb model but since updates are basically upserts
// it might re-add a package we just removed!
for (const i_event in listeners) {
const event: keyof PatchEvents = i_event as any;
patchInstance.removeListener(event, listeners[event]!);
delete listeners[event];
}
};
patchInstance
.on(
'state',
(listeners.state = state => {
switch (state) {
case PatcherState.Downloading:
if (localPackage.install_state) {
this.setPackageInstallState([
localPackage,
LocalDbPackagePatchState.DOWNLOADING,
]);
} else if (localPackage.update_state) {
this.setPackageUpdateState([
localPackage,
LocalDbPackagePatchState.DOWNLOADING,
]);
}
break;
case PatcherState.Patching:
// No longer needed.
this.setPackageDownloadProgress([localPackage, null]);
if (localPackage.install_state) {
this.setPackageInstallState([
localPackage,
LocalDbPackagePatchState.UNPACKING,
]);
} else if (localPackage.update_state) {
this.setPackageUpdateState([
localPackage,
LocalDbPackagePatchState.UNPACKING,
]);
}
break;
}
})
)
.on(
'progress',
(listeners.progress = progress => {
const progressType = progress.type;
const newProgress: LocalDbPackageProgress = {
// Newer version of client voodoo return progress as an integer between 0-100,
// but old client-voodoo returned a float between 0-1.
// To maintain compatibility, make this function return the float always.
progress: progress.percent / 100,
timeLeft: Math.round(
(progress.total - progress.current) /
(progress.sample ? progress.sample.movingAverage : 1)
),
// divide by 1024 to convert to kbps
rate: progress.sample
? Math.round(progress.sample.movingAverage / 1024)
: 0,
};
if (progressType === 'download') {
this.setPackageDownloadProgress([localPackage, newProgress]);
} else {
this.setPackageUnpackProgress([localPackage, newProgress]);
}
})
)
.on(
'paused',
(listeners.paused = queued => {
console.log(
'Pause received in gamejolt repo. From queue: ' +
(queued ? 'yes' : 'no')
);
if (queued) {
this.setPackagePatchQueued(localPackage);
} else {
this.setPackagePatchPaused(localPackage);
}
})
)
.on(
'resumed',
(listeners.resumed = unqueued => {
console.log(
'Resume received in gamejolt repo. From queue: ' +
(unqueued ? 'yes' : 'no')
);
if (unqueued) {
this.setPackagePatchUnqueued(localPackage);
} else {
this.setPackagePatchResumed(localPackage);
}
})
)
.on(
'updateFailed',
(listeners.updateFailed = reason => {
cleanupListeners();
// If the update was canceled the 'context canceled' will be emitted as the updateFailed reason.
if (reason === 'context canceled') {
return resolve(true);
}
reject(new Error(reason));
})
)
.on(
'updateFinished',
(listeners.updateFinished = () => {
cleanupListeners();
resolve(false);
})
)
.on(
'fatal',
(listeners.fatal = err => {
cleanupListeners();
console.log(
'Received fatal error in patcher in gamejolt repo: ' + err.message
);
reject(err);
})
);
});
this.unsetCurrentlyPatching(localPackage);
// Even if our patch operation has been canceled - as far as the installation flow is concerned it was a success.
trackClientVoodooOperation(
operation === 'install' ? 'install-end' : 'update-end',
true
);
if (!canceled) {
if (localPackage.install_state) {
await this.clearPackageOperations(localPackage);
} else if (localPackage.update_state) {
await this.setPackageUpdateComplete(localPackage);
}
const action =
operation === 'install'
? 'finished installing'
: 'updated to the latest version';
const title = operation === 'install' ? 'Game Installed' : 'Game Updated';
Growls.success({ title, message: `${packageTitle} has ${action}.`, system: true });
} else {
console.log('installerInstall: Handling canceled installation');
// If we were cancelling the first installation - we have to treat the package as uninstalled.
// By this point we can assume joltron has removed it from disk.
if (operation === 'install') {
// Since the actual aborting is done by joltron for first installations we don't
// really have a hook to use for sending the patch-abort-begin/end analytics. This is a best effort.
trackClientVoodooOperation('patch-abort-begin', true);
trackClientVoodooOperation('patch-abort-end', true);
console.log(
'installerInstall: This is a first installation. Marking as uninstalled from db with packageUninstall(true)'
);
// Calling uninstall normally attempts to spawn a client voodoo uninstall instance.
// Override that because the uninstallation should be done automatically by the installation process.
await this.packageUninstall([
localPackage,
{ dbOnly: true, notifications: true },
]);
} else {
console.log(
'installerInstall: This is an update operation. Attempting to rollback with installerRollback'
);
try {
await this.installerRollback(localPackage, packageTitle);
Growls.success({
title: 'Update Aborted',
message: `${packageTitle} aborted the update.`,
system: true,
});
} catch (err) {
if (localPackage.update_state === LocalDbPackagePatchState.UNPACKING) {
await this.setPackageUpdateState([
localPackage,
LocalDbPackagePatchState.UNPACK_FAILED,
]);
} else {
await this.setPackageUpdateState([
localPackage,
LocalDbPackagePatchState.DOWNLOAD_FAILED,
]);
}
}
}
}
} catch (err) {
console.error(err);
const title =
operation === 'install'
? Translate.$gettext(`Installation Failed`)
: Translate.$gettext(`Update Failed`);
const message =
operation === 'install'
? Translate.$gettextInterpolate(`%{package} failed to install.`, {
package: packageTitle,
})
: Translate.$gettextInterpolate(`%{package} failed to update.`, {
package: packageTitle,
});
let cvOperation: ClientVoodooOperation;
if (operation === 'install') {
cvOperation = patchBegun ? 'install-end' : 'install-begin';
} else {
cvOperation = patchBegun ? 'update-end' : 'update-begin';
}
handleClientVoodooError(err, cvOperation, message, title);
if (localPackage.install_state) {
if (localPackage.install_state === LocalDbPackagePatchState.UNPACKING) {
await this.setPackageInstallState([
localPackage,
LocalDbPackagePatchState.UNPACK_FAILED,
]);
} else {
await this.setPackageInstallState([
localPackage,
LocalDbPackagePatchState.DOWNLOAD_FAILED,
]);
}
} else if (localPackage.update_state) {
if (localPackage.update_state === LocalDbPackagePatchState.UNPACKING) {
await this.setPackageUpdateState([
localPackage,
LocalDbPackagePatchState.UNPACK_FAILED,
]);
} else {
await this.setPackageUpdateState([
localPackage,
LocalDbPackagePatchState.DOWNLOAD_FAILED,
]);
}
}
this.unsetCurrentlyPatching(localPackage);
}
}
@VuexAction
installerPause(localPackage: Actions['clientLibrary/installerPause']) {
const patchInstance = this.currentlyPatching[localPackage.id];
if (!patchInstance) {
throw new Error('Package is not installing.');
}
return patchInstance.pause();
}
@VuexAction
async installerResume(localPackage: Actions['clientLibrary/installerResume']) {
const patchInstance = this.currentlyPatching[localPackage.id];
if (!patchInstance) {
return this.installerRetry(localPackage);
}
let authToken = '';
try {
authToken = await LocalDbPackage.getAccessToken(localPackage.id);
} catch (err) {
console.log(`Could not get access token for package ${localPackage.id}`);
console.error(err);
}
return patchInstance.resume({ authToken });
}
@VuexAction
private async installerCancel(localPackage: LocalDbPackage) {
console.log('installerCancel: executed for package ' + localPackage.id);
const patchInstance = this.currentlyPatching[localPackage.id];
if (!patchInstance) {
console.log('installerCancel: no currently running installation/updates for package');
return false;
}
console.log('installerCancel: found running installation/update. sending cancel');
await patchInstance.cancel(true);
console.log('installerCancel: cancel sent');
return true;
}
@VuexAction
private async installerRollback(localPackage: LocalDbPackage, packageTitle: string) {
let abortBegun = false;
try {
const rollbackInstance = await Rollbacker.rollback(localPackage as any);
abortBegun = true;
trackClientVoodooOperation('patch-abort-begin', true);
await new Promise((resolve, reject) => {
rollbackInstance
.on('rollbackFailed', (reason: string) => {
console.log(`Received rollbackFailed in gamejolt: ${reason}`);
reject(new Error(reason));
})
.on('rollbackFinished', () => {
console.log('Received rollbackFinished in gamejolt');
resolve();
})
.on('fatal', reject);
});
await this.clearPackageOperations(localPackage);
trackClientVoodooOperation('patch-abort-end', true);
} catch (err) {
const title = Translate.$gettext('Update Failed');
const message = Translate.$gettextInterpolate(
`%{ packageTitle } cannot abort at this time. Retry or uninstall it.`,
{ packageTitle }
);
handleClientVoodooError(
err,
abortBegun ? 'patch-abort-end' : 'patch-abort-begin',
message,
title
);
throw err;
}
}
@VuexAction
private async doUninstall(
localPackage: LocalDbPackage,
packageTitle: string,
withNotifications: boolean,
wasInstalling: boolean
) {
let uninstallBegun = false;
try {
const uninstallInstance = await Uninstaller.uninstall(localPackage as any);
uninstallBegun = true;
trackClientVoodooOperation('uninstall-begin', true);
await new Promise<void>((resolve, reject) => {
uninstallInstance
.on('uninstallFinished', () => resolve())
.on('uninstallFailed', reject)
.on('fatal', reject);
});
trackClientVoodooOperation('uninstall-end', true);
} catch (err) {
console.error(err);
const uninstallOp: ClientVoodooOperation = uninstallBegun
? 'uninstall-end'
: 'uninstall-begin';
if (withNotifications) {
if (wasInstalling) {
handleClientVoodooError(
err,
uninstallOp,
Translate.$gettextInterpolate(
'Could not stop the installation of %{ packageTitle }.',
{
packageTitle,
}
)
);
} else {
handleClientVoodooError(
err,
uninstallOp,
Translate.$gettextInterpolate('Could not remove %{ packageTitle }.', {
packageTitle,
}),
Translate.$gettext('Remove failed')
);
}
} else {
handleClientVoodooError(err, uninstallOp);
}
throw err;
}
}
@VuexAction
private async launcherInit() {
const pidDir = path.resolve(nw.App.dataPath, 'game-pids');
Config.setPidDir(pidDir);
try {
await Config.ensurePidDir();
// Get all running packages by looking at the old launcher's game pid directory.
// This finds games that were started outside the client as well.
const runningPackageIds = fs
.readdirSync(pidDir)
.map(filename => {
// Pid files are named after the package ids they are currently running.
try {
return parseInt(path.basename(filename), 10);
} catch (err) {
return 0;
}
})
.filter(packageId => !!packageId && !isNaN(packageId));
console.log(`Running package ids by game pid file: [${runningPackageIds.join(',')}]`);
// For all the packages that have a game pid file and aren't marked as running in the
// localdb - mark as running before attaching. This will mark them as running using the
// old client launcher's running format.
for (const runningPackageId of runningPackageIds) {
const localPackage = this.packagesById[runningPackageId];
if (localPackage && !localPackage.isRunning) {
try {
await this.setPackageRunningPid([
localPackage,
{ wrapperId: localPackage.id.toString() },
]);
} catch (e) {
console.warn(`Could not mark package as running: ${localPackage.id}`);
console.warn(e);
}
}
}
// Reattach all running games after a restart.
for (const localPackage of this.packages) {
if (localPackage.isRunning) {
try {
await this.launcherReattach(localPackage);
} catch (e) {
console.warn(e);
}
}
}
// We only mark the launcher as loaded once it at least finished reattaching to the
// currently running instances.
console.log('Launcher loaded and ready');
this.setLauncherReady(true);
} catch (err) {
console.error('Failed to initialize everything for launcher');
console.error(err);
this.setLauncherReady(true);
}
}
@VuexMutation
private setLauncherReady(ready: boolean) {
this.isLauncherReady = ready;
}
@VuexMutation
private setCurrentlyPlaying(localPackage: LocalDbPackage) {
this.currentlyPlaying.push(localPackage);
}
@VuexMutation
private unsetCurrentlyPlaying(localPackage: LocalDbPackage) {
arrayRemove(this.currentlyPlaying, i => localPackage.id === i.id);
}
@VuexAction
async launcherLaunch(localPackage: Actions['clientLibrary/launcherLaunch']) {
try {
await this.setPackageLaunching(localPackage);
let payload: any = null;
try {
payload = await Api.sendRequest(
'/web/dash/token/get-for-game?game_id=' + localPackage.game_id
);
} catch (err) {
console.log('Could not get game token to launch with - launching anyway.');
console.warn(err);
}
const credentials =
payload && payload.username && payload.token
? { username: payload.username, user_token: payload.token }
: null;
const launchInstance = await Launcher.launch(localPackage as any, credentials);
this.launcherAttach([localPackage, launchInstance]);
trackClientVoodooOperation('launch', true);
} catch (err) {
console.error(err);
handleClientVoodooError(err, 'launch', Translate.$gettext('Could not launch game.'));
this.launcherClear(localPackage);
}
}
@VuexAction
private async launcherReattach(localPackage: LocalDbPackage) {
if (!localPackage.running_pid) {
throw new Error('Package is not running');
}
try {
const launchInstance = await Launcher.attach(localPackage.running_pid);
this.launcherAttach([localPackage, launchInstance]);
trackClientVoodooOperation('attach', true);
} catch (err) {
console.log(`Could not reattach launcher instance: ${localPackage.running_pid}`);
console.error(err);
handleClientVoodooError(err, 'attach');
this.launcherClear(localPackage);
}
}
@VuexAction
private async launcherAttach([localPackage, launchInstance]: [
LocalDbPackage,
LaunchInstance | OldLaunchInstance
]) {
this.setCurrentlyPlaying(localPackage);
// Typescript for some reason can't detect that all possible types of launchInstance have a .on( 'gameOver' ), so we have to assert type.
if (launchInstance instanceof LaunchInstance) {
launchInstance.on('gameOver', () => this.launcherClear(localPackage));
} else {
launchInstance.on('gameOver', () => this.launcherClear(localPackage));
}
await this.setPackageRunningPid([localPackage, launchInstance.pid]);
}
@VuexAction
private async launcherClear(localPackage: LocalDbPackage) {
this.unsetCurrentlyPlaying(localPackage);
await this.clearPackageRunningPid(localPackage);
}
@VuexAction
private async syncCheck() {
console.log('Syncing library.');
const builds = this.packages.map(i => i.build);
const os = Device.os();
const arch = Device.arch();
const request: any = {
games: {},
builds: {},
os: os,
arch: arch,
};
// The modified_on fields are what tells us if the client has up to date info
// for each model.
for (const localGame of this.games) {
request.games[localGame.id] = localGame.modified_on || 0;
}
for (const build of builds) {
request.builds[build.id] = build.modified_on || 0;
}
type ApiResponse = {
games: any[] | undefined;
builds: any[] | undefined;
updateBuilds: any[] | undefined;
};
const response = (await Api.sendRequest('/web/client/sync', request, {
detach: true,
// If we allowed it to sanitize, it would filter out arrays in the request.
sanitizeComplexData: false,
})) as ApiResponse;
// Important! Don't the whole thing if any of these fail.
if (response.games) {
for (const gameData of response.games) {
try {
await this.syncGame([gameData.id, gameData]);
} catch (e) {
console.error(e);
}
}
}
if (response.builds) {
for (const buildData of response.builds) {
try {
await this.syncPackage([buildData.game_package_id, response]);
} catch (e) {
console.error(e);
}
}
}
if (response.updateBuilds) {
for (const data of response.updateBuilds) {
const packageId = data.packageId as number;
const newBuildId = data.newBuildId as number;
try {
const localPackage = this.packagesById[packageId];
if (!localPackage) {
throw new Error('Tried updating package not set in localdb.');
}
await this.packageStartUpdate([localPackage, newBuildId]);
} catch (e) {
console.error(e);
}
}
}
}
@VuexAction
private async syncGame([gameId, data]: [number, any]) {
const localGame = this.gamesById[gameId];
if (!localGame) {
throw new Error('Game is not set in localdb.');
}
await this.setGameData([localGame, data]);
}
@VuexAction
private async syncPackage([packageId, data]: [number, any]) {
const localPackage = this.packagesById[packageId];
if (!localPackage) {
throw new Error('Game is not set in localdb.');
}
const pkg = (data.packages as GamePackage[]).find(a => a.id === localPackage.id);
const release = (data.releases as GameRelease[]).find(
a => a.id === localPackage.release.id
);
const build = (data.builds as GameBuild[]).find(a => a.id === localPackage.build.id);
const launchOptions = (data.launchOptions as GameBuildLaunchOption[]).filter(
a => a.game_build_id === localPackage.build.id
);
// If those are not set then this package is not even valid.
if (!pkg || !release || !build) {
throw new Error(
`Package ${localPackage.id} is no longer valid. ` +
`The payload did not contain the package, it's release (${localPackage.release.id})` +
` or it's build (${localPackage.build.id})`
);
}
await this.setPackageData([
localPackage,
LocalDbPackage.fromSitePackageInfo(pkg, release, build, launchOptions),
]);
}
@VuexAction
private async setGameData([localGame, data]: [LocalDbGame, Partial<LocalDbGame>]) {
this._setGameData([localGame, data]);
this.db.games.put(localGame);
await this.db.games.save();
if (!this.gamesById[localGame.id]) {
this.games.push(localGame);
}
}
@VuexMutation
private _setGameData([localGame, data]: [LocalDbGame, Partial<LocalDbGame>]) {
localGame.set(data);
}
@VuexAction
async packageInstall([
game,
pkg,
release,
build,
launchOptions,
]: Actions['clientLibrary/packageInstall']) {
// TODO: Are these needed?
HistoryTick.sendBeacon('game-build', build.id, {
sourceResource: 'Game',
sourceResourceId: game.id,
});
HistoryTick.sendBeacon('game-build-install', build.id, {
sourceResource: 'Game',
sourceResourceId: game.id,
});
const localGame = new LocalDbGame();
const localPackage = new LocalDbPackage();
await this.setGameData([localGame, game]);
await this.setPackageData([
localPackage,
{
...LocalDbPackage.fromSitePackageInfo(pkg, release, build, launchOptions),
install_state: LocalDbPackagePatchState.PATCH_PENDING,
},
]);
return this.doPatch([localGame, localPackage]);
}
@VuexAction
async packageStartUpdate([
localPackage,
newBuildId,
]: Actions['clientLibrary/packageStartUpdate']) {
// If this package isn't installed (and at rest), we don't update.
// We also don't update if we're currently running the game. Imagine that happening!
if (!localPackage.isSettled || localPackage.isRunning) {
return false;
}
const response = await Api.sendRequest(
`/web/client/get-build-for-update/${newBuildId}`,
null,
{
detach: true,
}
);
if (!response || !response.package) {
return false;
}
// We store the new data from the site into update data so we can pull it into the localdb
// package model after the update finishes.
const updateData = new LocalDbPackage();
// Don't put into localdb. Just call set manually to set the fields.
updateData.set(
LocalDbPackage.fromSitePackageInfo(
response.package,
response.release,
response.build,
response.launchOptions
)
);
updateData.install_dir = localPackage.install_dir;
await this.setPackageUpdateData([localPackage, updateData]);
await this.setPackageUpdateState([localPackage, LocalDbPackagePatchState.PATCH_PENDING]);
const game = this.gamesById[localPackage.game_id];
this.doPatch([game, localPackage]);
return true;
}
@VuexAction
async packageUninstall([localPackage, options]: Actions['clientLibrary/packageUninstall']) {
options = options || {};
const dbOnly = typeof options.dbOnly === 'boolean' ? options.dbOnly : false;
const withNotifications =
typeof options.notifications === 'boolean' ? options.notifications : true;
// We just use this so they don't click "uninstall" twice in a row.
// No need to save to the DB.
let currentlyUninstalling = this.currentlyUninstalling[localPackage.id];
if (currentlyUninstalling) {
console.log(
'packageUninstall: already handling an uninstallation for this package. noop.'
);
return currentlyUninstalling;
}
// Optimally the entire uninstalling promise would run in a single indexeddb transaction,
// but dexie has an issue with keeping a transaction alive for the duration: http://dexie.org/docs/Dexie/Dexie.transaction().html
// Basically if there is a node tick that doesn't 'use' or 'wait on' an indexeddb transaction operation the transaction auto commits,
// so we can't do things like asyncronously waiting on filesystem. Therefore we had to split the transaction into chunks.
currentlyUninstalling = (async () => {
// Are we removing a FIRST install?
const wasInstalling = localPackage.isInstalling;
let localGame: LocalDbGame | undefined;
try {
// When canceling a first installation it will end up calling packageUninstall
// with dbOnly set to true. In this case joltron will uninstall the package on its own,
// so all we need to do here is clean the package and game if necessary from the indexeddb.
// So we only attempt to do installerCancel (which interacts with joltron) if its NOT
// a first installation cancellation (dbOnly would be false)
if (!dbOnly) {
// if no installation or update is currently in progress this will return false immediately,
// otherwise it'll await until the cancel message is SENT.
// it won't wait for the cancel to be acknowledged and processed,
// when the cancel is processed by the installerInstall promise chain,
// it'll result in a second call to packageUninstall this time with dbOnly set to true if its
// a first installation, or a rollback operation for update operations.
// Either way this means we shouldn't continue this uninstallation promise chain.
const interruptedPatch = await this.installerCancel(localPackage);
if (interruptedPatch) {
// We unset the uninstallation because otherwise the second time we call packageUninstall
// (for first installations) it'll be a noop instead of actually cleaning the package
// from localdb. In case of rollback its not really an uninstallation state either.
this.unsetCurrentlyUninstalling(localPackage);
return;
}
}
// We refetch from db because if canceling a first installation it might remove the local game from the db.
localGame = this.db.games.get(localPackage.game_id)!;
const packageTitle =
localPackage.title || (localGame ? localGame.title : 'the package');
// Make sure we're clean.
await this.clearPackageOperations(localPackage);
await this.setPackageRemoveState([
localPackage,
LocalDbPackageRemoveState.REMOVING,
]);
// Skip removing the package if we don't want to actually uninstall from disk.
if (!dbOnly) {
await this.doUninstall(
localPackage,
packageTitle,
withNotifications,
wasInstalling
);
}
// Get the number of packages in this game.
const count = this.db.packages.countInGroup('game_id', localPackage.game_id);
// Note that some times a game is removed before the package (really weird cases).
// We still want the remove to go through, so be sure to skip this situation.
// If this is the last package for the game, remove the game since we no longer need it.
if (localGame && count <= 1) {
this.db.games.delete(localGame.id);
await this.db.games.save();
}
this.db.packages.delete(localPackage.id);
await this.db.packages.save();
// Finally remove from the vuex store.
if (localGame && count <= 1) {
arrayRemove(this.games, g => g.id === localGame!.id);
}
arrayRemove(this.packages, p => p.id === localPackage.id);
if (withNotifications) {
if (!wasInstalling) {
Growls.success({
title: 'Package Removed',
message:
'Removed ' +
(localPackage.title ||
(localGame ? localGame.title : 'the package')) +
' from your computer.',
system: true,
});
} else {
Growls.success({
title: 'Installation Canceled',
message:
'Canceled installation of ' +
(localPackage.title ||
(localGame ? localGame.title : 'the package')),
system: true,
});
}
}
} catch (err) {
await this.setPackageRemoveState([
localPackage,
LocalDbPackageRemoveState.REMOVE_FAILED,
]);
} finally {
this.unsetCurrentlyUninstalling(localPackage);
}
})();
this.setCurrentlyUninstalling([localPackage, currentlyUninstalling]);
return currentlyUninstalling;
}
@VuexAction
async setPackageInstallDir([localPackage, dir]: [LocalDbPackage, string]) {
await this.setPackageData([localPackage, { install_dir: dir }]);
}
@VuexAction
async setPackageInstallState([localPackage, state]: [
LocalDbPackage,
LocalDbPackagePatchState
]) {
await this.setPackageData([localPackage, { install_state: state }]);
}
@VuexAction
async setPackagePatchPaused(localPackage: LocalDbPackage) {
await this.setPackageData([localPackage, { patch_paused: true }]);
}
@VuexAction
async setPackagePatchResumed(localPackage: LocalDbPackage) {
await this.setPackageData([localPackage, { patch_paused: false }]);
}
@VuexAction
async setPackagePatchQueued(localPackage: LocalDbPackage) {
await this.setPackageData([localPackage, { patch_queued: true }]);
}
@VuexAction
async setPackagePatchUnqueued(localPackage: LocalDbPackage) {
await this.setPackageData([localPackage, { patch_queued: false }]);
}
@VuexAction
async setPackageUpdateData([localPackage, update]: [LocalDbPackage, LocalDbPackage]) {
await this.setPackageData([localPackage, { update }]);
}
@VuexAction
async setPackageUpdateState([localPackage, state]: [LocalDbPackage, LocalDbPackagePatchState]) {
await this.setPackageData([localPackage, { update_state: state }]);
}
@VuexAction
async setPackageUpdateComplete(localPackage: LocalDbPackage) {
// The new data that we need to put on the package is in the "update" property of the local
// package.
if (!localPackage.update) {
throw new Error('Update package does not exist');
}
const update = localPackage.update;
if (!update.install_dir) {
update.install_dir = localPackage.install_dir;
}
await this.clearPackageOperations(localPackage);
await this.setPackageData([
localPackage,
{
// It's a localdb package, so it should have all the correct fields.
...update,
},
]);
}
@VuexAction
async setPackageDownloadProgress([localPackage, progress]: [
LocalDbPackage,
LocalDbPackageProgress | null
]) {
await this.setPackageData([localPackage, { download_progress: progress }]);
}
@VuexAction
async setPackageUnpackProgress([localPackage, progress]: [
LocalDbPackage,
LocalDbPackageProgress | null
]) {
await this.setPackageData([localPackage, { unpack_progress: progress }]);
}
/**
* Clears any state information contained in the package to a clean slate. Can be used after
* operations complete or fail.
*/
@VuexAction
async clearPackageOperations(localPackage: LocalDbPackage) {
await this.setPackageData([
localPackage,
{
update: null,
install_state: null,
update_state: null,
remove_state: null,
run_state: null,
download_progress: null,
unpack_progress: null,
patch_paused: null,
patch_queued: null,
running_pid: null,
},
]);
}
@VuexAction
async setPackageLaunching(localPackage: LocalDbPackage) {
await this.setPackageData([localPackage, { run_state: LocalDbPackageRunState.LAUNCHING }]);
}
@VuexAction
async setPackageRunningPid([localPackage, pid]: [LocalDbPackage, LocalDbPackagePid]) {
await this.setPackageData([
localPackage,
{
run_state: LocalDbPackageRunState.RUNNING,
running_pid: pid,
},
]);
}
@VuexAction
async clearPackageRunningPid(localPackage: LocalDbPackage) {
await this.setPackageData([
localPackage,
{
run_state: null,
running_pid: null,
},
]);
}
@VuexAction
async setPackageRemoveState([localPackage, state]: [
LocalDbPackage,
LocalDbPackageRemoveState
]) {
await this.setPackageData([localPackage, { remove_state: state }]);
}
@VuexAction
private async setPackageData([localPackage, data]: [LocalDbPackage, Partial<LocalDbPackage>]) {
this._setPackageData([localPackage, data]);
this.db.packages.put(localPackage);
await this.db.packages.save();
if (!this.packagesById[localPackage.id]) {
this.packages.push(localPackage);
}
}
@VuexMutation
private _setPackageData([localPackage, data]: [LocalDbPackage, Partial<LocalDbPackage>]) {
localPackage.set(data);
}
} | the_stack |
import * as assert from 'assert';
import { URI as uri } from 'vs/base/common/uri';
import { DebugModel, Breakpoint } from 'vs/workbench/contrib/debug/common/debugModel';
import { getExpandedBodySize, getBreakpointMessageAndIcon } from 'vs/workbench/contrib/debug/browser/breakpointsView';
import { dispose } from 'vs/base/common/lifecycle';
import { Range } from 'vs/editor/common/core/range';
import { IBreakpointData, IBreakpointUpdateData, State } from 'vs/workbench/contrib/debug/common/debug';
import { TextModel } from 'vs/editor/common/model/textModel';
import { createBreakpointDecorations } from 'vs/workbench/contrib/debug/browser/breakpointEditorContribution';
import { OverviewRulerLane } from 'vs/editor/common/model';
import { MarkdownString } from 'vs/base/common/htmlContent';
import { createTextModel } from 'vs/editor/test/common/editorTestUtils';
import { createMockSession } from 'vs/workbench/contrib/debug/test/browser/callStack.test';
import { createMockDebugModel } from 'vs/workbench/contrib/debug/test/browser/mockDebug';
function addBreakpointsAndCheckEvents(model: DebugModel, uri: uri, data: IBreakpointData[]): void {
let eventCount = 0;
const toDispose = model.onDidChangeBreakpoints(e => {
assert.strictEqual(e?.sessionOnly, false);
assert.strictEqual(e?.changed, undefined);
assert.strictEqual(e?.removed, undefined);
const added = e?.added;
assert.notStrictEqual(added, undefined);
assert.strictEqual(added!.length, data.length);
eventCount++;
dispose(toDispose);
for (let i = 0; i < data.length; i++) {
assert.strictEqual(e!.added![i] instanceof Breakpoint, true);
assert.strictEqual((e!.added![i] as Breakpoint).lineNumber, data[i].lineNumber);
}
});
model.addBreakpoints(uri, data);
assert.strictEqual(eventCount, 1);
}
suite('Debug - Breakpoints', () => {
let model: DebugModel;
setup(() => {
model = createMockDebugModel();
});
// Breakpoints
test('simple', () => {
const modelUri = uri.file('/myfolder/myfile.js');
addBreakpointsAndCheckEvents(model, modelUri, [{ lineNumber: 5, enabled: true }, { lineNumber: 10, enabled: false }]);
assert.strictEqual(model.areBreakpointsActivated(), true);
assert.strictEqual(model.getBreakpoints().length, 2);
let eventCount = 0;
const toDispose = model.onDidChangeBreakpoints(e => {
eventCount++;
assert.strictEqual(e?.added, undefined);
assert.strictEqual(e?.sessionOnly, false);
assert.strictEqual(e?.removed?.length, 2);
assert.strictEqual(e?.changed, undefined);
dispose(toDispose);
});
model.removeBreakpoints(model.getBreakpoints());
assert.strictEqual(eventCount, 1);
assert.strictEqual(model.getBreakpoints().length, 0);
});
test('toggling', () => {
const modelUri = uri.file('/myfolder/myfile.js');
addBreakpointsAndCheckEvents(model, modelUri, [{ lineNumber: 5, enabled: true }, { lineNumber: 10, enabled: false }]);
addBreakpointsAndCheckEvents(model, modelUri, [{ lineNumber: 12, enabled: true, condition: 'fake condition' }]);
assert.strictEqual(model.getBreakpoints().length, 3);
const bp = model.getBreakpoints().pop();
if (bp) {
model.removeBreakpoints([bp]);
}
assert.strictEqual(model.getBreakpoints().length, 2);
model.setBreakpointsActivated(false);
assert.strictEqual(model.areBreakpointsActivated(), false);
model.setBreakpointsActivated(true);
assert.strictEqual(model.areBreakpointsActivated(), true);
});
test('two files', () => {
const modelUri1 = uri.file('/myfolder/my file first.js');
const modelUri2 = uri.file('/secondfolder/second/second file.js');
addBreakpointsAndCheckEvents(model, modelUri1, [{ lineNumber: 5, enabled: true }, { lineNumber: 10, enabled: false }]);
assert.strictEqual(getExpandedBodySize(model, 9), 44);
addBreakpointsAndCheckEvents(model, modelUri2, [{ lineNumber: 1, enabled: true }, { lineNumber: 2, enabled: true }, { lineNumber: 3, enabled: false }]);
assert.strictEqual(getExpandedBodySize(model, 9), 110);
assert.strictEqual(model.getBreakpoints().length, 5);
assert.strictEqual(model.getBreakpoints({ uri: modelUri1 }).length, 2);
assert.strictEqual(model.getBreakpoints({ uri: modelUri2 }).length, 3);
assert.strictEqual(model.getBreakpoints({ lineNumber: 5 }).length, 1);
assert.strictEqual(model.getBreakpoints({ column: 5 }).length, 0);
const bp = model.getBreakpoints()[0];
const update = new Map<string, IBreakpointUpdateData>();
update.set(bp.getId(), { lineNumber: 100 });
let eventFired = false;
const toDispose = model.onDidChangeBreakpoints(e => {
eventFired = true;
assert.strictEqual(e?.added, undefined);
assert.strictEqual(e?.removed, undefined);
assert.strictEqual(e?.changed?.length, 1);
dispose(toDispose);
});
model.updateBreakpoints(update);
assert.strictEqual(eventFired, true);
assert.strictEqual(bp.lineNumber, 100);
assert.strictEqual(model.getBreakpoints({ enabledOnly: true }).length, 3);
model.enableOrDisableAllBreakpoints(false);
model.getBreakpoints().forEach(bp => {
assert.strictEqual(bp.enabled, false);
});
assert.strictEqual(model.getBreakpoints({ enabledOnly: true }).length, 0);
model.setEnablement(bp, true);
assert.strictEqual(bp.enabled, true);
model.removeBreakpoints(model.getBreakpoints({ uri: modelUri1 }));
assert.strictEqual(getExpandedBodySize(model, 9), 66);
assert.strictEqual(model.getBreakpoints().length, 3);
});
test('conditions', () => {
const modelUri1 = uri.file('/myfolder/my file first.js');
addBreakpointsAndCheckEvents(model, modelUri1, [{ lineNumber: 5, condition: 'i < 5', hitCondition: '17' }, { lineNumber: 10, condition: 'j < 3' }]);
const breakpoints = model.getBreakpoints();
assert.strictEqual(breakpoints[0].condition, 'i < 5');
assert.strictEqual(breakpoints[0].hitCondition, '17');
assert.strictEqual(breakpoints[1].condition, 'j < 3');
assert.strictEqual(!!breakpoints[1].hitCondition, false);
assert.strictEqual(model.getBreakpoints().length, 2);
model.removeBreakpoints(model.getBreakpoints());
assert.strictEqual(model.getBreakpoints().length, 0);
});
test('function breakpoints', () => {
model.addFunctionBreakpoint('foo', '1');
model.addFunctionBreakpoint('bar', '2');
model.updateFunctionBreakpoint('1', { name: 'fooUpdated' });
model.updateFunctionBreakpoint('2', { name: 'barUpdated' });
const functionBps = model.getFunctionBreakpoints();
assert.strictEqual(functionBps[0].name, 'fooUpdated');
assert.strictEqual(functionBps[1].name, 'barUpdated');
model.removeFunctionBreakpoints();
assert.strictEqual(model.getFunctionBreakpoints().length, 0);
});
test('multiple sessions', () => {
const modelUri = uri.file('/myfolder/myfile.js');
addBreakpointsAndCheckEvents(model, modelUri, [{ lineNumber: 5, enabled: true, condition: 'x > 5' }, { lineNumber: 10, enabled: false }]);
const breakpoints = model.getBreakpoints();
const session = createMockSession(model);
const data = new Map<string, DebugProtocol.Breakpoint>();
assert.strictEqual(breakpoints[0].lineNumber, 5);
assert.strictEqual(breakpoints[1].lineNumber, 10);
data.set(breakpoints[0].getId(), { verified: false, line: 10 });
data.set(breakpoints[1].getId(), { verified: true, line: 50 });
model.setBreakpointSessionData(session.getId(), {}, data);
assert.strictEqual(breakpoints[0].lineNumber, 5);
assert.strictEqual(breakpoints[1].lineNumber, 50);
const session2 = createMockSession(model);
const data2 = new Map<string, DebugProtocol.Breakpoint>();
data2.set(breakpoints[0].getId(), { verified: true, line: 100 });
data2.set(breakpoints[1].getId(), { verified: true, line: 500 });
model.setBreakpointSessionData(session2.getId(), {}, data2);
// Breakpoint is verified only once, show that line
assert.strictEqual(breakpoints[0].lineNumber, 100);
// Breakpoint is verified two times, show the original line
assert.strictEqual(breakpoints[1].lineNumber, 10);
model.setBreakpointSessionData(session.getId(), {}, undefined);
// No more double session verification
assert.strictEqual(breakpoints[0].lineNumber, 100);
assert.strictEqual(breakpoints[1].lineNumber, 500);
assert.strictEqual(breakpoints[0].supported, false);
const data3 = new Map<string, DebugProtocol.Breakpoint>();
data3.set(breakpoints[0].getId(), { verified: true, line: 500 });
model.setBreakpointSessionData(session2.getId(), { supportsConditionalBreakpoints: true }, data2);
assert.strictEqual(breakpoints[0].supported, true);
});
test('exception breakpoints', () => {
let eventCount = 0;
model.onDidChangeBreakpoints(() => eventCount++);
model.setExceptionBreakpoints([{ filter: 'uncaught', label: 'UNCAUGHT', default: true }]);
assert.strictEqual(eventCount, 1);
let exceptionBreakpoints = model.getExceptionBreakpoints();
assert.strictEqual(exceptionBreakpoints.length, 1);
assert.strictEqual(exceptionBreakpoints[0].filter, 'uncaught');
assert.strictEqual(exceptionBreakpoints[0].enabled, true);
model.setExceptionBreakpoints([{ filter: 'uncaught', label: 'UNCAUGHT' }, { filter: 'caught', label: 'CAUGHT' }]);
assert.strictEqual(eventCount, 2);
exceptionBreakpoints = model.getExceptionBreakpoints();
assert.strictEqual(exceptionBreakpoints.length, 2);
assert.strictEqual(exceptionBreakpoints[0].filter, 'uncaught');
assert.strictEqual(exceptionBreakpoints[0].enabled, true);
assert.strictEqual(exceptionBreakpoints[1].filter, 'caught');
assert.strictEqual(exceptionBreakpoints[1].label, 'CAUGHT');
assert.strictEqual(exceptionBreakpoints[1].enabled, false);
});
test('instruction breakpoints', () => {
let eventCount = 0;
model.onDidChangeBreakpoints(() => eventCount++);
//address: string, offset: number, condition?: string, hitCondition?: string
model.addInstructionBreakpoint('0xCCCCFFFF', 0);
assert.strictEqual(eventCount, 1);
let instructionBreakpoints = model.getInstructionBreakpoints();
assert.strictEqual(instructionBreakpoints.length, 1);
assert.strictEqual(instructionBreakpoints[0].instructionReference, '0xCCCCFFFF');
assert.strictEqual(instructionBreakpoints[0].offset, 0);
model.addInstructionBreakpoint('0xCCCCEEEE', 1);
assert.strictEqual(eventCount, 2);
instructionBreakpoints = model.getInstructionBreakpoints();
assert.strictEqual(instructionBreakpoints.length, 2);
assert.strictEqual(instructionBreakpoints[0].instructionReference, '0xCCCCFFFF');
assert.strictEqual(instructionBreakpoints[0].offset, 0);
assert.strictEqual(instructionBreakpoints[1].instructionReference, '0xCCCCEEEE');
assert.strictEqual(instructionBreakpoints[1].offset, 1);
});
test('data breakpoints', () => {
let eventCount = 0;
model.onDidChangeBreakpoints(() => eventCount++);
model.addDataBreakpoint('label', 'id', true, ['read'], 'read');
model.addDataBreakpoint('second', 'secondId', false, ['readWrite'], 'readWrite');
const dataBreakpoints = model.getDataBreakpoints();
assert.strictEqual(dataBreakpoints[0].canPersist, true);
assert.strictEqual(dataBreakpoints[0].dataId, 'id');
assert.strictEqual(dataBreakpoints[0].accessType, 'read');
assert.strictEqual(dataBreakpoints[1].canPersist, false);
assert.strictEqual(dataBreakpoints[1].description, 'second');
assert.strictEqual(dataBreakpoints[1].accessType, 'readWrite');
assert.strictEqual(eventCount, 2);
model.removeDataBreakpoints(dataBreakpoints[0].getId());
assert.strictEqual(eventCount, 3);
assert.strictEqual(model.getDataBreakpoints().length, 1);
model.removeDataBreakpoints();
assert.strictEqual(model.getDataBreakpoints().length, 0);
assert.strictEqual(eventCount, 4);
});
test('message and class name', () => {
const modelUri = uri.file('/myfolder/my file first.js');
addBreakpointsAndCheckEvents(model, modelUri, [
{ lineNumber: 5, enabled: true, condition: 'x > 5' },
{ lineNumber: 10, enabled: false },
{ lineNumber: 12, enabled: true, logMessage: 'hello' },
{ lineNumber: 15, enabled: true, hitCondition: '12' },
{ lineNumber: 500, enabled: true },
]);
const breakpoints = model.getBreakpoints();
let result = getBreakpointMessageAndIcon(State.Stopped, true, breakpoints[0]);
assert.strictEqual(result.message, 'Expression condition: x > 5');
assert.strictEqual(result.icon.id, 'debug-breakpoint-conditional');
result = getBreakpointMessageAndIcon(State.Stopped, true, breakpoints[1]);
assert.strictEqual(result.message, 'Disabled Breakpoint');
assert.strictEqual(result.icon.id, 'debug-breakpoint-disabled');
result = getBreakpointMessageAndIcon(State.Stopped, true, breakpoints[2]);
assert.strictEqual(result.message, 'Log Message: hello');
assert.strictEqual(result.icon.id, 'debug-breakpoint-log');
result = getBreakpointMessageAndIcon(State.Stopped, true, breakpoints[3]);
assert.strictEqual(result.message, 'Hit Count: 12');
assert.strictEqual(result.icon.id, 'debug-breakpoint-conditional');
result = getBreakpointMessageAndIcon(State.Stopped, true, breakpoints[4]);
assert.strictEqual(result.message, 'Breakpoint');
assert.strictEqual(result.icon.id, 'debug-breakpoint');
result = getBreakpointMessageAndIcon(State.Stopped, false, breakpoints[2]);
assert.strictEqual(result.message, 'Disabled Logpoint');
assert.strictEqual(result.icon.id, 'debug-breakpoint-log-disabled');
model.addDataBreakpoint('label', 'id', true, ['read'], 'read');
const dataBreakpoints = model.getDataBreakpoints();
result = getBreakpointMessageAndIcon(State.Stopped, true, dataBreakpoints[0]);
assert.strictEqual(result.message, 'Data Breakpoint');
assert.strictEqual(result.icon.id, 'debug-breakpoint-data');
const functionBreakpoint = model.addFunctionBreakpoint('foo', '1');
result = getBreakpointMessageAndIcon(State.Stopped, true, functionBreakpoint);
assert.strictEqual(result.message, 'Function Breakpoint');
assert.strictEqual(result.icon.id, 'debug-breakpoint-function');
const data = new Map<string, DebugProtocol.Breakpoint>();
data.set(breakpoints[0].getId(), { verified: false, line: 10 });
data.set(breakpoints[1].getId(), { verified: true, line: 50 });
data.set(breakpoints[2].getId(), { verified: true, line: 50, message: 'world' });
data.set(functionBreakpoint.getId(), { verified: true });
model.setBreakpointSessionData('mocksessionid', { supportsFunctionBreakpoints: false, supportsDataBreakpoints: true, supportsLogPoints: true }, data);
result = getBreakpointMessageAndIcon(State.Stopped, true, breakpoints[0]);
assert.strictEqual(result.message, 'Unverified Breakpoint');
assert.strictEqual(result.icon.id, 'debug-breakpoint-unverified');
result = getBreakpointMessageAndIcon(State.Stopped, true, functionBreakpoint);
assert.strictEqual(result.message, 'Function breakpoints not supported by this debug type');
assert.strictEqual(result.icon.id, 'debug-breakpoint-function-unverified');
result = getBreakpointMessageAndIcon(State.Stopped, true, breakpoints[2]);
assert.strictEqual(result.message, 'Log Message: hello, world');
assert.strictEqual(result.icon.id, 'debug-breakpoint-log');
});
test('decorations', () => {
const modelUri = uri.file('/myfolder/my file first.js');
const languageId = 'testMode';
const textModel = createTextModel(
['this is line one', 'this is line two', ' this is line three it has whitespace at start', 'this is line four', 'this is line five'].join('\n'),
TextModel.DEFAULT_CREATION_OPTIONS,
languageId
);
addBreakpointsAndCheckEvents(model, modelUri, [
{ lineNumber: 1, enabled: true, condition: 'x > 5' },
{ lineNumber: 2, column: 4, enabled: false },
{ lineNumber: 3, enabled: true, logMessage: 'hello' },
{ lineNumber: 500, enabled: true },
]);
const breakpoints = model.getBreakpoints();
let decorations = createBreakpointDecorations(textModel, breakpoints, State.Running, true, true);
assert.strictEqual(decorations.length, 3); // last breakpoint filtered out since it has a large line number
assert.deepStrictEqual(decorations[0].range, new Range(1, 1, 1, 2));
assert.deepStrictEqual(decorations[1].range, new Range(2, 4, 2, 5));
assert.deepStrictEqual(decorations[2].range, new Range(3, 5, 3, 6));
assert.strictEqual(decorations[0].options.beforeContentClassName, undefined);
assert.strictEqual(decorations[1].options.beforeContentClassName, `debug-breakpoint-placeholder`);
assert.strictEqual(decorations[0].options.overviewRuler?.position, OverviewRulerLane.Left);
const expected = new MarkdownString().appendCodeblock(languageId, 'Expression condition: x > 5');
assert.deepStrictEqual(decorations[0].options.glyphMarginHoverMessage, expected);
decorations = createBreakpointDecorations(textModel, breakpoints, State.Running, true, false);
assert.strictEqual(decorations[0].options.overviewRuler, null);
textModel.dispose();
});
}); | the_stack |
module dragonBones {
/**
* @class dragonBones.AnimationState
* @classdesc
* AnimationState 实例由 Animation 实例播放动画时产生, 可以对单个动画的播放进行最细致的调节。
* @see dragonBones.Animation
* @see dragonBones.AnimationData
*
* @example
<pre>
//获取动画数据
var skeletonData = RES.getRes("skeleton");
//获取纹理集数据
var textureData = RES.getRes("textureConfig");
//获取纹理集图片
var texture = RES.getRes("texture");
//创建一个工厂,用来创建Armature
var factory:dragonBones.EgretFactory = new dragonBones.EgretFactory();
//把动画数据添加到工厂里
factory.addSkeletonData(dragonBones.DataParser.parseDragonBonesData(skeletonData));
//把纹理集数据和图片添加到工厂里
factory.addTextureAtlas(new dragonBones.EgretTextureAtlas(texture, textureData));
//获取Armature的名字,dragonBones4.0的数据可以包含多个骨架,这里取第一个Armature
var armatureName:string = skeletonData.armature[0].name;
//从工厂里创建出Armature
var armature:dragonBones.Armature = factory.buildArmature(armatureName);
//获取装载Armature的容器
var armatureDisplay = armature.display;
armatureDisplay.x = 200;
armatureDisplay.y = 500;
//把它添加到舞台上
this.addChild(armatureDisplay);
//取得这个Armature动画列表中的第一个动画的名字
var curAnimationName:string = armature.animation.animationList[0];
//播放这个动画
armature.animation.gotoAndPlay(curAnimationName,0.3,-1,0);
//获取animationState可以对动画进行更多控制;
var animationState:dragonBones.AnimationState = armature.animation.getState(curAnimationName);
//下面的代码实现人物的脖子和头动,但是其他部位不动
animationState.addBoneMask("neck",true);
//下面的代码实现人物的身体动,但是脖子和头不动
//animationState.addBoneMask("hip",true);//“hip”是骨架的根骨骼的名字
//animationState.removeBoneMask("neck",true);
//下面的代码实现动画幅度减小的效果
//animationState.weight = 0.5;
//把Armature添加到心跳时钟里
dragonBones.WorldClock.clock.add(armature);
//心跳时钟开启
egret.Ticker.getInstance().register(function (advancedTime) {
dragonBones.WorldClock.clock.advanceTime(advancedTime / 1000);
}, this);
</pre>
*/
export class AnimationState{
private static _pool:Array<AnimationState> =[];
/** @private */
public static _borrowObject():AnimationState{
if(AnimationState._pool.length == 0){
return new AnimationState();
}
return AnimationState._pool.pop();
}
/** @private */
public static _returnObject(animationState:AnimationState):void{
animationState.clear();
if(AnimationState._pool.indexOf(animationState) < 0){
AnimationState._pool[AnimationState._pool.length] = animationState;
}
}
/** @private */
public static _clear():void{
var i:number = AnimationState._pool.length;
while(i --){
AnimationState._pool[i].clear();
}
AnimationState._pool.length = 0;
TimelineState._clear();
}
/**
* 标记是否控制display的切换。
* 设置为 true时,该 AnimationState 会控制display的切换
* 默认值:true。
* @member {boolean} dragonBones.AnimationState#displayControl
* @see dragonBones.Bone#displayController
* @see dragonBones.Bone#display
*/
public displayControl:boolean;
public additiveBlending:boolean;
/**
* 标记动画播放完毕时是否自动淡出。
* 默认值:true。
* @member {boolean} dragonBones.AnimationState#autoFadeOut
*/
public autoFadeOut:boolean;
/**
* 淡出时间。
* @member {number} dragonBones.AnimationState#fadeOutTime
*/
public fadeOutTime:number;
/**
* 动画权重(0~1)。
* 默认值:1。
* @member {number} dragonBones.AnimationState#weight
*/
public weight:number;
/**
* 是否自动补间。
* @member {boolean} dragonBones.AnimationState#autoTween
*/
public autoTween:boolean;
/**
* 动画循环播放时,从最后一帧到第一帧是否自动补间。
* 默认值:true
* @member {boolean} dragonBones.AnimationState#lastFrameAutoTween
*/
public lastFrameAutoTween:boolean;
/** @private */
public _layer:number = 0;
/** @private */
public _group:string;
private _armature:Armature;
private _timelineStateList:Array<TimelineState>;
private _slotTimelineStateList:Array<SlotTimelineState>;
private _boneMasks:Array<string>;
private _isPlaying:boolean;
private _time:number;
private _currentFrameIndex:number = 0;
private _currentFramePosition:number = 0;
private _currentFrameDuration:number = 0;
//Fadein 的时候是否先暂停
private _pausePlayheadInFade:boolean;
private _isFadeOut:boolean;
//最终的真实权重值
private _fadeTotalWeight:number;
//受fade影响的动作权重系数,在fadein阶段他的值会由0变为1,在fadeout阶段会由1变为0
private _fadeWeight:number;
private _fadeCurrentTime:number;
private _fadeBeginTime:number;
private _name:string;
private _clip:AnimationData;
private _isComplete:boolean;
private _currentPlayTimes:number = 0;
private _totalTime:number = 0;
private _currentTime:number = 0;
private _lastTime: number = 0;
//-1 beforeFade, 0 fading, 1 fadeComplete
private _fadeState:number = 0;
private _fadeTotalTime:number;
//时间缩放参数, 各帧duration数据不变的情况下,让传入时间*timeScale 实现durationScale
private _timeScale:number;
private _playTimes:number = 0;
public constructor(){
this._timelineStateList =[];
this._slotTimelineStateList=[];
this._boneMasks = [];
}
private clear():void{
this._resetTimelineStateList();
this._boneMasks.length = 0;
this._armature = null;
this._clip = null;
}
public _resetTimelineStateList():void
{
var i:number = this._timelineStateList.length;
while(i --){
TimelineState._returnObject(this._timelineStateList[i]);
}
this._timelineStateList.length = 0;
i = this._slotTimelineStateList.length;
while(i --){
SlotTimelineState._returnObject(this._slotTimelineStateList[i])
}
this._slotTimelineStateList.length = 0;
}
//骨架装配
/**
* 检查指定名称的骨头是否在遮罩中。只有在遮罩中的骨头动画才会被播放
* @param boneName {string} dragonBones.AnimationState#containsBoneMask
* @returns {boolean}
*/
public containsBoneMask(boneName:string):boolean{
return this._boneMasks.length == 0 || this._boneMasks.indexOf(boneName) >= 0;
}
/**
* 将一个骨头加入遮罩。只有加入遮罩的骨头的动画才会被播放,如果没有骨头加入遮罩,则所有骨头的动画都会播放。通过这个API可以实现只播放角色的一部分.
* @param boneName {string} 骨头名称.
* @param ifInvolveChildBones {boolean} 是否影响子骨头。默认值:true.
* @returns {AnimationState} 动画播放状态实例
*/
public addBoneMask(boneName:string, ifInvolveChildBones:boolean = true):AnimationState{
this.addBoneToBoneMask(boneName);
if(ifInvolveChildBones){
var currentBone:Bone = this._armature.getBone(boneName);
if(currentBone){
var boneList:Array<Bone> = this._armature.getBones(false);
var i:number = boneList.length;
while(i--){
var tempBone:Bone = boneList[i];
if(currentBone.contains(tempBone)){
this.addBoneToBoneMask(tempBone.name);
}
}
}
}
this._updateTimelineStates();
return this;
}
/**
* 将一个指定名称的骨头从遮罩中移除.
* @param boneName {string} 骨头名称.
* @param ifInvolveChildBones {boolean} 是否影响子骨头。默认值:true.
* @returns {AnimationState} 动画播放状态实例
*/
public removeBoneMask(boneName:string, ifInvolveChildBones:boolean = true):AnimationState{
this.removeBoneFromBoneMask(boneName);
if(ifInvolveChildBones){
var currentBone:Bone = this._armature.getBone(boneName);
if(currentBone){
var boneList:Array<Bone> = this._armature.getBones(false);
var i:number = boneList.length;
while(i--){
var tempBone:Bone = boneList[i];
if(currentBone.contains(tempBone)){
this.removeBoneFromBoneMask(tempBone.name);
}
}
}
}
this._updateTimelineStates();
return this;
}
/**
* 清空骨头遮罩.
* @returns {AnimationState} 动画播放状态实例
*/
public removeAllMixingTransform():AnimationState{
this._boneMasks.length = 0;
this._updateTimelineStates();
return this;
}
private addBoneToBoneMask(boneName:string):void{
if(this._clip.getTimeline(boneName) && this._boneMasks.indexOf(boneName)<0){
this._boneMasks.push(boneName);
}
}
private removeBoneFromBoneMask(boneName:string):void{
var index:number = this._boneMasks.indexOf(boneName);
if(index >= 0){
this._boneMasks.splice(index, 1);
}
}
/**
* @private
* Update timeline state based on mixing transforms and clip.
*/
public _updateTimelineStates():void{
var timelineState:TimelineState;
var slotTimelineState:SlotTimelineState;
var i:number = this._timelineStateList.length;
var len:number;
while(i --){
timelineState = this._timelineStateList[i];
if(!this._armature.getBone(timelineState.name)){
this.removeTimelineState(timelineState);
}
}
i = this._slotTimelineStateList.length;
while(i --){
slotTimelineState = this._slotTimelineStateList[i];
if(!this._armature.getSlot(slotTimelineState.name)){
this.removeSlotTimelineState(slotTimelineState);
}
}
if(this._boneMasks.length > 0){
i = this._timelineStateList.length;
while(i --){
timelineState = this._timelineStateList[i];
if(this._boneMasks.indexOf(timelineState.name) < 0){
this.removeTimelineState(timelineState);
}
}
for(i = 0,len = this._boneMasks.length; i < len; i++)
{
var timelineName:string = this._boneMasks[i];
this.addTimelineState(timelineName);
}
}
else{
for(i = 0,len = this._clip.timelineList.length; i < len; i++)
{
var timeline:TransformTimeline = this._clip.timelineList[i];
this.addTimelineState(timeline.name);
}
}
for(i = 0,len = this._clip.slotTimelineList.length; i < len; i++)
{
var slotTimeline:SlotTimeline = this._clip.slotTimelineList[i];
this.addSlotTimelineState(slotTimeline.name);
}
}
private addTimelineState(timelineName:string):void{
var bone:Bone = this._armature.getBone(timelineName);
if(bone){
for(var i:number = 0,len:number = this._timelineStateList.length; i < len; i++)
{
var eachState:TimelineState = this._timelineStateList[i];
if(eachState.name == timelineName){
return;
}
}
var timelineState:TimelineState = TimelineState._borrowObject();
timelineState._fadeIn(bone, this, this._clip.getTimeline(timelineName));
this._timelineStateList.push(timelineState);
}
}
private removeTimelineState(timelineState:TimelineState):void{
var index:number = this._timelineStateList.indexOf(timelineState);
this._timelineStateList.splice(index, 1);
TimelineState._returnObject(timelineState);
}
private addSlotTimelineState(timelineName:string):void{
var slot:Slot = this._armature.getSlot(timelineName);
if(slot){
for(var i:number = 0, len:number = this._slotTimelineStateList.length; i < len; i++)
{
var eachState:SlotTimelineState = this._slotTimelineStateList[i];
if(eachState.name == timelineName){
return;
}
}
var timelineState:SlotTimelineState = SlotTimelineState._borrowObject();
timelineState._fadeIn(slot, this, this._clip.getSlotTimeline(timelineName));
this._slotTimelineStateList.push(timelineState);
}
}
private removeSlotTimelineState(timelineState:SlotTimelineState):void{
var index:number = this._slotTimelineStateList.indexOf(timelineState);
this._slotTimelineStateList.splice(index, 1);
SlotTimelineState._returnObject(timelineState);
}
//动画
/**
* 播放当前动画。如果动画已经播放完毕, 将不会继续播放.
* @returns {AnimationState} 动画播放状态实例
*/
public play():AnimationState{
this._isPlaying = true;
return this;
}
/**
* 暂停当前动画的播放。
* @returns {AnimationState} 动画播放状态实例
*/
public stop():AnimationState{
this._isPlaying = false;
return this;
}
/** @private */
public _fadeIn(armature:Armature, clip:AnimationData, fadeTotalTime:number, timeScale:number, playTimes:number, pausePlayhead:boolean):AnimationState{
this._armature = armature;
this._clip = clip;
this._pausePlayheadInFade = pausePlayhead;
this._name = this._clip.name;
this._totalTime = this._clip.duration;
this.autoTween = this._clip.autoTween;
this.setTimeScale(timeScale);
this.setPlayTimes(playTimes);
//reset
this._isComplete = false;
this._currentFrameIndex = -1;
this._currentPlayTimes = -1;
if(Math.round(this._totalTime * this._clip.frameRate * 0.001) < 2 || timeScale == Infinity){
this._currentTime = this._totalTime;
}
else{
this._currentTime = -1;
}
this._time = 0;
this._boneMasks.length = 0;
//fade start
this._isFadeOut = false;
this._fadeWeight = 0;
this._fadeTotalWeight = 1;
this._fadeState = -1;
this._fadeCurrentTime = 0;
this._fadeBeginTime = this._fadeCurrentTime;
this._fadeTotalTime = fadeTotalTime * this._timeScale;
//default
this._isPlaying = true;
this.displayControl = true;
this.lastFrameAutoTween = true;
this.additiveBlending = false;
this.weight = 1;
this.fadeOutTime = fadeTotalTime;
this._updateTimelineStates();
return this;
}
/**
* 淡出当前动画
* @param fadeTotalTime {number} 淡出时间
* @param pausePlayhead {boolean} 淡出时动画是否暂停。
*/
public fadeOut(fadeTotalTime:number, pausePlayhead:boolean):AnimationState{
if(!this._armature){
return null;
}
if(isNaN(fadeTotalTime) || fadeTotalTime < 0){
fadeTotalTime = 0;
}
this._pausePlayheadInFade = pausePlayhead;
if(this._isFadeOut){
if(fadeTotalTime > this._fadeTotalTime / this._timeScale - (this._fadeCurrentTime - this._fadeBeginTime)){
//如果已经在淡出中,新的淡出需要更长的淡出时间,则忽略
//If the animation is already in fade out, the new fade out will be ignored.
return this;
}
}
else{
//第一次淡出
//The first time to fade out.
for(var i:number = 0,len:number = this._timelineStateList.length; i < len; i++)
{
var timelineState:TimelineState = this._timelineStateList[i];
timelineState._fadeOut();
}
}
//fade start
this._isFadeOut = true;
this._fadeTotalWeight = this._fadeWeight;
this._fadeState = -1;
this._fadeBeginTime = this._fadeCurrentTime;
this._fadeTotalTime = this._fadeTotalWeight >= 0?fadeTotalTime * this._timeScale:0;
//default
this.displayControl = false;
return this;
}
/** @private */
public _advanceTime(passedTime:number):boolean{
passedTime *= this._timeScale;
this.advanceFadeTime(passedTime);
if(this._fadeWeight){
this.advanceTimelinesTime(passedTime);
}
return this._isFadeOut && this._fadeState == 1;
}
private advanceFadeTime(passedTime:number):void{
var fadeStartFlg:boolean = false;
var fadeCompleteFlg:boolean = false;
if(this._fadeBeginTime >= 0){
var fadeState:number = this._fadeState;
this._fadeCurrentTime += passedTime < 0?-passedTime:passedTime;
if(this._fadeCurrentTime >= this._fadeBeginTime + this._fadeTotalTime){
//fade完全结束之后触发
//TODO 研究明白为什么要下次再触发
if(
this._fadeWeight == 1 ||
this._fadeWeight == 0
){
fadeState = 1;
if (this._pausePlayheadInFade){
this._pausePlayheadInFade = false;
this._currentTime = -1;
}
}
this._fadeWeight = this._isFadeOut?0:1;
}
else if(this._fadeCurrentTime >= this._fadeBeginTime){
//fading
fadeState = 0;
//暂时只支持线性淡入淡出
//Currently only support Linear fadein and fadeout
this._fadeWeight = (this._fadeCurrentTime - this._fadeBeginTime) / this._fadeTotalTime * this._fadeTotalWeight;
if(this._isFadeOut){
this._fadeWeight = this._fadeTotalWeight - this._fadeWeight;
}
}
else{
//before fade
fadeState = -1;
this._fadeWeight = this._isFadeOut?1:0;
}
if(this._fadeState != fadeState){
//_fadeState == -1 && (fadeState == 0 || fadeState == 1)
if(this._fadeState == -1){
fadeStartFlg = true;
}
//(_fadeState == -1 || _fadeState == 0) && fadeState == 1
if(fadeState == 1){
fadeCompleteFlg = true;
}
this._fadeState = fadeState;
}
}
var event:AnimationEvent;
if(fadeStartFlg){
if(this._isFadeOut){
if(this._armature.hasEventListener(AnimationEvent.FADE_OUT)){
event = new AnimationEvent(AnimationEvent.FADE_OUT);
event.animationState = this;
this._armature._eventList.push(event);
}
}
else{
//动画开始,先隐藏不需要的骨头
this.hideBones();
if(this._armature.hasEventListener(AnimationEvent.FADE_IN)){
event = new AnimationEvent(AnimationEvent.FADE_IN);
event.animationState = this;
this._armature._eventList.push(event);
}
}
}
if(fadeCompleteFlg){
if(this._isFadeOut){
if(this._armature.hasEventListener(AnimationEvent.FADE_OUT_COMPLETE)){
event = new AnimationEvent(AnimationEvent.FADE_OUT_COMPLETE);
event.animationState = this;
this._armature._eventList.push(event);
}
}
else{
if(this._armature.hasEventListener(AnimationEvent.FADE_IN_COMPLETE)){
event = new AnimationEvent(AnimationEvent.FADE_IN_COMPLETE);
event.animationState = this;
this._armature._eventList.push(event);
}
}
}
}
private advanceTimelinesTime(passedTime:number):void{
if(this._isPlaying && !this._pausePlayheadInFade){
this._time += passedTime;
}
var startFlg:boolean = false;
var completeFlg:boolean = false;
var loopCompleteFlg:boolean = false;
var isThisComplete:boolean = false;
var currentPlayTimes:number = 0;
var currentTime:number = this._time * 1000;
if(this._playTimes == 0){
isThisComplete = false;
currentPlayTimes = Math.ceil(Math.abs(currentTime) / this._totalTime) || 1;
if(currentTime>=0)
{
currentTime -= Math.floor(currentTime / this._totalTime) * this._totalTime;
}
else
{
currentTime -= Math.ceil(currentTime / this._totalTime) * this._totalTime;
}
if(currentTime < 0){
currentTime += this._totalTime;
}
}
else{
var totalTimes:number = this._playTimes * this._totalTime;
if(currentTime >= totalTimes){
currentTime = totalTimes;
isThisComplete = true;
}
else if(currentTime <= -totalTimes){
currentTime = -totalTimes;
isThisComplete = true;
}
else{
isThisComplete = false;
}
if(currentTime < 0){
currentTime += totalTimes;
}
currentPlayTimes = Math.ceil(currentTime / this._totalTime) || 1;
if(currentTime>=0)
{
currentTime -= Math.floor(currentTime / this._totalTime) * this._totalTime;
}
else
{
currentTime -= Math.ceil(currentTime / this._totalTime) * this._totalTime;
}
if(isThisComplete){
currentTime = this._totalTime;
}
}
//update timeline
this._isComplete = isThisComplete;
var progress:number = this._time * 1000 / this._totalTime;
var i:number = 0;
var len:number = 0;
for(i = 0,len = this._timelineStateList.length; i < len; i++) {
var timeline:TimelineState = this._timelineStateList[i];
timeline._update(progress);
this._isComplete = timeline._isComplete && this._isComplete;
}
for(i = 0,len = this._slotTimelineStateList.length; i < len; i++) {
var slotTimeline:SlotTimelineState = this._slotTimelineStateList[i];
slotTimeline._update(progress);
this._isComplete = timeline._isComplete && this._isComplete;
}
//update main timeline
if(this._currentTime != currentTime){
if(this._currentPlayTimes != currentPlayTimes) //check loop complete
{
if(this._currentPlayTimes > 0 && currentPlayTimes > 1){
loopCompleteFlg = true;
}
this._currentPlayTimes = currentPlayTimes;
}
if(this._currentTime < 0) //check start
{
startFlg = true;
}
if(this._isComplete) //check complete
{
completeFlg = true;
}
this._lastTime = this._currentTime;
this._currentTime = currentTime;
/*
if(isThisComplete)
{
currentTime = _totalTime * 0.999999;
}
//[0, _totalTime)
*/
this.updateMainTimeline(isThisComplete);
}
var event:AnimationEvent;
if(startFlg){
if(this._armature.hasEventListener(AnimationEvent.START)){
event = new AnimationEvent(AnimationEvent.START);
event.animationState = this;
this._armature._eventList.push(event);
}
}
if(completeFlg){
if(this._armature.hasEventListener(AnimationEvent.COMPLETE)){
event = new AnimationEvent(AnimationEvent.COMPLETE);
event.animationState = this;
this._armature._eventList.push(event);
}
if(this.autoFadeOut){
this.fadeOut(this.fadeOutTime, true);
}
}
else if(loopCompleteFlg){
if(this._armature.hasEventListener(AnimationEvent.LOOP_COMPLETE)){
event = new AnimationEvent(AnimationEvent.LOOP_COMPLETE);
event.animationState = this;
this._armature._eventList.push(event);
}
}
}
private updateMainTimeline(isThisComplete:boolean):void{
var frameList:Array<Frame> = this._clip.frameList;
if(frameList.length > 0){
var prevFrame:Frame;
var currentFrame:Frame;
for (var i:number = 0, l:number = this._clip.frameList.length; i < l; ++i){
if(this._currentFrameIndex < 0){
this._currentFrameIndex = 0;
}
else if(this._currentTime < this._currentFramePosition || this._currentTime >= this._currentFramePosition + this._currentFrameDuration || this._currentTime < this._lastTime){
this._currentFrameIndex ++;
this._lastTime = this._currentTime;
if(this._currentFrameIndex >= frameList.length){
if(isThisComplete){
this._currentFrameIndex --;
break;
}
else{
this._currentFrameIndex = 0;
}
}
}
else{
break;
}
currentFrame = frameList[this._currentFrameIndex];
if(prevFrame){
this._armature._arriveAtFrame(prevFrame, null, this, true);
}
this._currentFrameDuration = currentFrame.duration;
this._currentFramePosition = currentFrame.position;
prevFrame = currentFrame;
}
if(currentFrame){
this._armature._arriveAtFrame(currentFrame, null, this, false);
}
}
}
private hideBones():void{
for(var i:number = 0,len:number = this._clip.hideTimelineNameMap.length; i < len; i++)
{
var timelineName:string = this._clip.hideTimelineNameMap[i];
var bone:Bone = this._armature.getBone(timelineName);
if(bone){
bone._hideSlots();
}
}
var slotTimelineName:string;
for(i = 0,len = this._clip.hideSlotTimelineNameMap.length; i < len; i++)
{
slotTimelineName = this._clip.hideSlotTimelineNameMap[i];
var slot:Slot = this._armature.getSlot(slotTimelineName);
if (slot)
{
slot._resetToOrigin();
}
}
}
//属性访问
public setAdditiveBlending(value:boolean):AnimationState{
this.additiveBlending = value;
return this;
}
public setAutoFadeOut(value:boolean, fadeOutTime:number = -1):AnimationState{
this.autoFadeOut = value;
if(fadeOutTime >= 0){
this.fadeOutTime = fadeOutTime * this._timeScale;
}
return this;
}
public setWeight(value:number):AnimationState{
if(isNaN(value) || value < 0){
value = 1;
}
this.weight = value;
return this;
}
public setFrameTween(autoTween:boolean, lastFrameAutoTween:boolean):AnimationState{
this.autoTween = autoTween;
this.lastFrameAutoTween = lastFrameAutoTween;
return this;
}
public setCurrentTime(value:number):AnimationState{
if(value < 0 || isNaN(value)){
value = 0;
}
this._time = value;
this._currentTime = this._time * 1000;
return this;
}
public setTimeScale(value:number):AnimationState{
if(isNaN(value) || value == Infinity){
value = 1;
}
this._timeScale = value;
return this;
}
public setPlayTimes(value:number = 0):AnimationState{
//如果动画只有一帧 播放一次就可以
if(Math.round(this._totalTime * 0.001 * this._clip.frameRate) < 2){
this._playTimes = value < 0?-1:1;
}
else{
this._playTimes = value < 0?-value:value;
}
this.autoFadeOut = value < 0?true:false;
return this;
}
/**
* 动画的名字
* @member {string} dragonBones.AnimationState#name
*/
public get name():string{
return this._name;
}
/**
* 动画所在的层
* @member {number} dragonBones.AnimationState#layer
*/
public get layer():number{
return this._layer;
}
/**
* 动画所在的组
* @member {string} dragonBones.AnimationState#group
*/
public get group():string{
return this._group;
}
/**
* 动画包含的动画数据
* @member {AnimationData} dragonBones.AnimationState#clip
*/
public get clip():AnimationData{
return this._clip;
}
/**
* 是否播放完成
* @member {boolean} dragonBones.AnimationState#isComplete
*/
public get isComplete():boolean{
return this._isComplete;
}
/**
* 是否正在播放
* @member {boolean} dragonBones.AnimationState#isPlaying
*/
public get isPlaying():boolean{
return (this._isPlaying && !this._isComplete);
}
/**
* 当前播放次数
* @member {number} dragonBones.AnimationState#currentPlayTimes
*/
public get currentPlayTimes():number{
return this._currentPlayTimes < 0 ? 0 : this._currentPlayTimes;
}
/**
* 动画总时长(单位:秒)
* @member {number} dragonBones.AnimationState#totalTime
*/
public get totalTime():number{
return this._totalTime * 0.001;
}
/**
* 动画当前播放时间(单位:秒)
* @member {number} dragonBones.AnimationState#currentTime
*/
public get currentTime():number{
return this._currentTime < 0 ? 0 : this._currentTime * 0.001;
}
public get fadeWeight():number{
return this._fadeWeight;
}
public get fadeState():number{
return this._fadeState;
}
public get fadeTotalTime():number{
return this._fadeTotalTime;
}
/**
* 时间缩放系数。用于调节动画播放速度
* @member {number} dragonBones.AnimationState#timeScale
*/
public get timeScale():number{
return this._timeScale;
}
/**
* 播放次数 (0:循环播放, >0:播放次数)
* @member {number} dragonBones.AnimationState#playTimes
*/
public get playTimes():number{
return this._playTimes;
}
}
} | the_stack |
import { AccessLevelList } from "../shared/access-level";
import { PolicyStatement } from "../shared";
/**
* Statement provider for service [iotwireless](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsiotcoreforlorawan.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
export class Iotwireless extends PolicyStatement {
public servicePrefix = 'iotwireless';
/**
* Statement provider for service [iotwireless](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsiotcoreforlorawan.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);
}
/**
* Grants permission to link partner accounts with Aws account
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/iot-wireless/2020-11-22/apireference/API_AssociateAwsAccountWithPartnerAccount.html
*/
public toAssociateAwsAccountWithPartnerAccount() {
return this.to('AssociateAwsAccountWithPartnerAccount');
}
/**
* Grants permission to associate the wireless device with AWS IoT thing for a given wirelessDeviceId
*
* Access Level: Write
*
* Dependent actions:
* - iot:DescribeThing
*
* https://docs.aws.amazon.com/iot-wireless/2020-11-22/apireference/API_AssociateWirelessDeviceWithThing.html
*/
public toAssociateWirelessDeviceWithThing() {
return this.to('AssociateWirelessDeviceWithThing');
}
/**
* Grants permission to associate a WirelessGateway with the IoT Core Identity certificate
*
* Access Level: Write
*
* https://docs.aws.amazon.com/iot-wireless/2020-11-22/apireference/API_AssociateWirelessGatewayWithCertificate.html
*/
public toAssociateWirelessGatewayWithCertificate() {
return this.to('AssociateWirelessGatewayWithCertificate');
}
/**
* Grants permission to associate the wireless gateway with AWS IoT thing for a given wirelessGatewayId
*
* Access Level: Write
*
* Dependent actions:
* - iot:DescribeThing
*
* https://docs.aws.amazon.com/iot-wireless/2020-11-22/apireference/API_AssociateWirelessGatewayWithThing.html
*/
public toAssociateWirelessGatewayWithThing() {
return this.to('AssociateWirelessGatewayWithThing');
}
/**
* Grants permission to create a Destination resource
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/iot-wireless/2020-11-22/apireference/API_CreateDestination.html
*/
public toCreateDestination() {
return this.to('CreateDestination');
}
/**
* Grants permission to create a DeviceProfile resource
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/iot-wireless/2020-11-22/apireference/API_CreateDeviceProfile.html
*/
public toCreateDeviceProfile() {
return this.to('CreateDeviceProfile');
}
/**
* Grants permission to create a ServiceProfile resource
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/iot-wireless/2020-11-22/apireference/API_CreateServiceProfile.html
*/
public toCreateServiceProfile() {
return this.to('CreateServiceProfile');
}
/**
* Grants permission to create a WirelessDevice resource with given Destination
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/iot-wireless/2020-11-22/apireference/API_CreateWirelessDevice.html
*/
public toCreateWirelessDevice() {
return this.to('CreateWirelessDevice');
}
/**
* Grants permission to create a WirelessGateway resource
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/iot-wireless/2020-11-22/apireference/API_CreateWirelessGateway.html
*/
public toCreateWirelessGateway() {
return this.to('CreateWirelessGateway');
}
/**
* Grants permission to create a task for a given WirelessGateway
*
* Access Level: Write
*
* https://docs.aws.amazon.com/iot-wireless/2020-11-22/apireference/API_CreateWirelessGatewayTask.html
*/
public toCreateWirelessGatewayTask() {
return this.to('CreateWirelessGatewayTask');
}
/**
* Grants permission to create a WirelessGateway task definition
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/iot-wireless/2020-11-22/apireference/API_CreateWirelessGatewayTaskDefinition.html
*/
public toCreateWirelessGatewayTaskDefinition() {
return this.to('CreateWirelessGatewayTaskDefinition');
}
/**
* Grants permission to delete a Destination
*
* Access Level: Write
*
* https://docs.aws.amazon.com/iot-wireless/2020-11-22/apireference/API_DeleteDestination.html
*/
public toDeleteDestination() {
return this.to('DeleteDestination');
}
/**
* Grants permission to delete a DeviceProfile
*
* Access Level: Write
*
* https://docs.aws.amazon.com/iot-wireless/2020-11-22/apireference/API_DeleteDeviceProfile.html
*/
public toDeleteDeviceProfile() {
return this.to('DeleteDeviceProfile');
}
/**
* Grants permission to delete a ServiceProfile
*
* Access Level: Write
*
* https://docs.aws.amazon.com/iot-wireless/2020-11-22/apireference/API_DeleteServiceProfile.html
*/
public toDeleteServiceProfile() {
return this.to('DeleteServiceProfile');
}
/**
* Grants permission to delete a WirelessDevice
*
* Access Level: Write
*
* https://docs.aws.amazon.com/iot-wireless/2020-11-22/apireference/API_DeleteWirelessDevice.html
*/
public toDeleteWirelessDevice() {
return this.to('DeleteWirelessDevice');
}
/**
* Grants permission to delete a WirelessGateway
*
* Access Level: Write
*
* https://docs.aws.amazon.com/iot-wireless/2020-11-22/apireference/API_DeleteWirelessGateway.html
*/
public toDeleteWirelessGateway() {
return this.to('DeleteWirelessGateway');
}
/**
* Grants permission to delete task for a given WirelessGateway
*
* Access Level: Write
*
* https://docs.aws.amazon.com/iot-wireless/2020-11-22/apireference/API_DeleteWirelessGatewayTask.html
*/
public toDeleteWirelessGatewayTask() {
return this.to('DeleteWirelessGatewayTask');
}
/**
* Grants permission to delete a WirelessGateway task definition
*
* Access Level: Write
*
* https://docs.aws.amazon.com/iot-wireless/2020-11-22/apireference/API_DeleteWirelessGatewayTaskDefinition.html
*/
public toDeleteWirelessGatewayTaskDefinition() {
return this.to('DeleteWirelessGatewayTaskDefinition');
}
/**
* Grants permission to disassociate an AWS account from a partner account
*
* Access Level: Write
*
* https://docs.aws.amazon.com/iot-wireless/2020-11-22/apireference/API_DisassociateAwsAccountFromPartnerAccount.html
*/
public toDisassociateAwsAccountFromPartnerAccount() {
return this.to('DisassociateAwsAccountFromPartnerAccount');
}
/**
* Grants permission to disassociate a wireless device from a AWS IoT thing
*
* Access Level: Write
*
* Dependent actions:
* - iot:DescribeThing
*
* https://docs.aws.amazon.com/iot-wireless/2020-11-22/apireference/API_DisassociateWirelessDeviceFromThing.html
*/
public toDisassociateWirelessDeviceFromThing() {
return this.to('DisassociateWirelessDeviceFromThing');
}
/**
* Grants permission to disassociate a WirelessGateway from a IoT Core Identity certificate
*
* Access Level: Write
*
* https://docs.aws.amazon.com/iot-wireless/2020-11-22/apireference/API_DisassociateWirelessGatewayFromCertificate.html
*/
public toDisassociateWirelessGatewayFromCertificate() {
return this.to('DisassociateWirelessGatewayFromCertificate');
}
/**
* Grants permission to disassociate a WirelessGateway from a IoT Core thing
*
* Access Level: Write
*
* Dependent actions:
* - iot:DescribeThing
*
* https://docs.aws.amazon.com/iot-wireless/2020-11-22/apireference/API_DisassociateWirelessGatewayFromThing.html
*/
public toDisassociateWirelessGatewayFromThing() {
return this.to('DisassociateWirelessGatewayFromThing');
}
/**
* Grants permission to get the Destination
*
* Access Level: Read
*
* https://docs.aws.amazon.com/iot-wireless/2020-11-22/apireference/API_GetDestination.html
*/
public toGetDestination() {
return this.to('GetDestination');
}
/**
* Grants permission to get the DeviceProfile
*
* Access Level: Read
*
* https://docs.aws.amazon.com/iot-wireless/2020-11-22/apireference/API_GetDeviceProfile.html
*/
public toGetDeviceProfile() {
return this.to('GetDeviceProfile');
}
/**
* Grants permission to get log levels by resource types
*
* Access Level: Read
*
* https://docs.aws.amazon.com/iot-wireless/2020-11-22/apireference/API_GetLogLevelsByResourceTypes.html
*/
public toGetLogLevelsByResourceTypes() {
return this.to('GetLogLevelsByResourceTypes');
}
/**
* Grants permission to get the associated PartnerAccount
*
* Access Level: Read
*
* https://docs.aws.amazon.com/iot-wireless/2020-11-22/apireference/API_GetPartnerAccount.html
*/
public toGetPartnerAccount() {
return this.to('GetPartnerAccount');
}
/**
* Grants permission to get resource log level
*
* Access Level: Read
*
* https://docs.aws.amazon.com/iot-wireless/2020-11-22/apireference/API_GetResourceLogLevel.html
*/
public toGetResourceLogLevel() {
return this.to('GetResourceLogLevel');
}
/**
* Grants permission to retrieve the customer account specific endpoint for CUPS protocol connection or LoRaWAN Network Server (LNS) protocol connection, and optionally server trust certificate in PEM format
*
* Access Level: Read
*
* https://docs.aws.amazon.com/iot-wireless/2020-11-22/apireference/API_GetServiceEndpoint.html
*/
public toGetServiceEndpoint() {
return this.to('GetServiceEndpoint');
}
/**
* Grants permission to get the ServiceProfile
*
* Access Level: Read
*
* https://docs.aws.amazon.com/iot-wireless/2020-11-22/apireference/API_GetServiceProfile.html
*/
public toGetServiceProfile() {
return this.to('GetServiceProfile');
}
/**
* Grants permission to get the WirelessDevice
*
* Access Level: Read
*
* https://docs.aws.amazon.com/iot-wireless/2020-11-22/apireference/API_GetWirelessDevice.html
*/
public toGetWirelessDevice() {
return this.to('GetWirelessDevice');
}
/**
* Grants permission to get statistics info for a given WirelessDevice
*
* Access Level: Read
*
* https://docs.aws.amazon.com/iot-wireless/2020-11-22/apireference/API_GetWirelessDeviceStatistics.html
*/
public toGetWirelessDeviceStatistics() {
return this.to('GetWirelessDeviceStatistics');
}
/**
* Grants permission to get the WirelessGateway
*
* Access Level: Read
*
* https://docs.aws.amazon.com/iot-wireless/2020-11-22/apireference/API_GetWirelessGateway.html
*/
public toGetWirelessGateway() {
return this.to('GetWirelessGateway');
}
/**
* Grants permission to get the IoT Core Identity certificate id associated with the WirelessGateway
*
* Access Level: Read
*
* https://docs.aws.amazon.com/iot-wireless/2020-11-22/apireference/API_GetWirelessGatewayCertificate.html
*/
public toGetWirelessGatewayCertificate() {
return this.to('GetWirelessGatewayCertificate');
}
/**
* Grants permission to get Current firmware version and other information for the WirelessGateway
*
* Access Level: Read
*
* https://docs.aws.amazon.com/iot-wireless/2020-11-22/apireference/API_GetWirelessGatewayFirmwareInformation.html
*/
public toGetWirelessGatewayFirmwareInformation() {
return this.to('GetWirelessGatewayFirmwareInformation');
}
/**
* Grants permission to get statistics info for a given WirelessGateway
*
* Access Level: Read
*
* https://docs.aws.amazon.com/iot-wireless/2020-11-22/apireference/API_GetWirelessGatewayStatistics.html
*/
public toGetWirelessGatewayStatistics() {
return this.to('GetWirelessGatewayStatistics');
}
/**
* Grants permission to get the task for a given WirelessGateway
*
* Access Level: Read
*
* https://docs.aws.amazon.com/iot-wireless/2020-11-22/apireference/API_GetWirelessGatewayTask.html
*/
public toGetWirelessGatewayTask() {
return this.to('GetWirelessGatewayTask');
}
/**
* Grants permission to get the given WirelessGateway task definition
*
* Access Level: Read
*
* https://docs.aws.amazon.com/iot-wireless/2020-11-22/apireference/API_GetWirelessGatewayTaskDefinition.html
*/
public toGetWirelessGatewayTaskDefinition() {
return this.to('GetWirelessGatewayTaskDefinition');
}
/**
* List information of available Destinations based on the AWS account.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/iot-wireless/2020-11-22/apireference/API_ListDestinations.html
*/
public toListDestinations() {
return this.to('ListDestinations');
}
/**
* Grants permission to list information of available DeviceProfiles based on the AWS account
*
* Access Level: Read
*
* https://docs.aws.amazon.com/iot-wireless/2020-11-22/apireference/API_ListDeviceProfiles.html
*/
public toListDeviceProfiles() {
return this.to('ListDeviceProfiles');
}
/**
* Grants permission to list the available partner accounts
*
* Access Level: Read
*
* https://docs.aws.amazon.com/iot-wireless/2020-11-22/apireference/API_ListPartnerAccounts.html
*/
public toListPartnerAccounts() {
return this.to('ListPartnerAccounts');
}
/**
* Grants permission to list information of available ServiceProfiles based on the AWS account
*
* Access Level: Read
*
* https://docs.aws.amazon.com/iot-wireless/2020-11-22/apireference/API_ListServiceProfiles.html
*/
public toListServiceProfiles() {
return this.to('ListServiceProfiles');
}
/**
* Grants permission to list all tags for a given resource
*
* Access Level: Read
*
* https://docs.aws.amazon.com/iot-wireless/2020-11-22/apireference/API_ListTagsForResource.html
*/
public toListTagsForResource() {
return this.to('ListTagsForResource');
}
/**
* Grants permission to list information of available WirelessDevices based on the AWS account
*
* Access Level: Read
*
* https://docs.aws.amazon.com/iot-wireless/2020-11-22/apireference/API_ListWirelessDevices.html
*/
public toListWirelessDevices() {
return this.to('ListWirelessDevices');
}
/**
* Grants permission to list information of available WirelessGateway task definitions based on the AWS account
*
* Access Level: Read
*
* https://docs.aws.amazon.com/iot-wireless/2020-11-22/apireference/API_ListWirelessGatewayTaskDefinitions.html
*/
public toListWirelessGatewayTaskDefinitions() {
return this.to('ListWirelessGatewayTaskDefinitions');
}
/**
* Grants permission to list information of available WirelessGateways based on the AWS account
*
* Access Level: Read
*
* https://docs.aws.amazon.com/iot-wireless/2020-11-22/apireference/API_ListWirelessGateways.html
*/
public toListWirelessGateways() {
return this.to('ListWirelessGateways');
}
/**
* Grants permission to put resource log level
*
* Access Level: Write
*
* https://docs.aws.amazon.com/iot-wireless/2020-11-22/apireference/API_PutResourceLogLevel.html
*/
public toPutResourceLogLevel() {
return this.to('PutResourceLogLevel');
}
/**
* Grants permission to reset all resource log levels
*
* Access Level: Write
*
* https://docs.aws.amazon.com/iot-wireless/2020-11-22/apireference/API_ResetAllResourceLogLevels.html
*/
public toResetAllResourceLogLevels() {
return this.to('ResetAllResourceLogLevels');
}
/**
* Grants permission to reset resource log level
*
* Access Level: Write
*
* https://docs.aws.amazon.com/iot-wireless/2020-11-22/apireference/API_ResetResourceLogLevel.html
*/
public toResetResourceLogLevel() {
return this.to('ResetResourceLogLevel');
}
/**
* Grants permission to send the decrypted application data frame to the target device
*
* Access Level: Write
*
* https://docs.aws.amazon.com/iot-wireless/2020-11-22/apireference/API_SendDataToWirelessDevice.html
*/
public toSendDataToWirelessDevice() {
return this.to('SendDataToWirelessDevice');
}
/**
* Grants permission to tag a given resource
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/iot-wireless/2020-11-22/apireference/API_TagResource.html
*/
public toTagResource() {
return this.to('TagResource');
}
/**
* Grants permission to simulate a provisioned device to send an uplink data with payload of 'Hello'
*
* Access Level: Write
*
* https://docs.aws.amazon.com/iot-wireless/2020-11-22/apireference/API_TestWirelessDevice.html
*/
public toTestWirelessDevice() {
return this.to('TestWirelessDevice');
}
/**
* Grants permission to remove the given tags from the resource
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/iot-wireless/2020-11-22/apireference/API_UntagResource.html
*/
public toUntagResource() {
return this.to('UntagResource');
}
/**
* Grants permission to update a Destination resource
*
* Access Level: Write
*
* https://docs.aws.amazon.com/iot-wireless/2020-11-22/apireference/API_UpdateDestination.html
*/
public toUpdateDestination() {
return this.to('UpdateDestination');
}
/**
* Grants permission to update log levels by resource types
*
* Access Level: Write
*
* https://docs.aws.amazon.com/iot-wireless/2020-11-22/apireference/API_UpdateLogLevelsByResourceTypes.html
*/
public toUpdateLogLevelsByResourceTypes() {
return this.to('UpdateLogLevelsByResourceTypes');
}
/**
* Grants permission to update a partner account
*
* Access Level: Write
*
* https://docs.aws.amazon.com/iot-wireless/2020-11-22/apireference/API_UpdatePartnerAccount.html
*/
public toUpdatePartnerAccount() {
return this.to('UpdatePartnerAccount');
}
/**
* Grants permission to update a WirelessDevice resource
*
* Access Level: Write
*
* https://docs.aws.amazon.com/iot-wireless/2020-11-22/apireference/API_UpdateWirelessDevice.html
*/
public toUpdateWirelessDevice() {
return this.to('UpdateWirelessDevice');
}
/**
* Grants permission to update a WirelessGateway resource
*
* Access Level: Write
*
* https://docs.aws.amazon.com/iot-wireless/2020-11-22/apireference/API_UpdateWirelessGateway.html
*/
public toUpdateWirelessGateway() {
return this.to('UpdateWirelessGateway');
}
protected accessLevelList: AccessLevelList = {
"Write": [
"AssociateAwsAccountWithPartnerAccount",
"AssociateWirelessDeviceWithThing",
"AssociateWirelessGatewayWithCertificate",
"AssociateWirelessGatewayWithThing",
"CreateDestination",
"CreateDeviceProfile",
"CreateServiceProfile",
"CreateWirelessDevice",
"CreateWirelessGateway",
"CreateWirelessGatewayTask",
"CreateWirelessGatewayTaskDefinition",
"DeleteDestination",
"DeleteDeviceProfile",
"DeleteServiceProfile",
"DeleteWirelessDevice",
"DeleteWirelessGateway",
"DeleteWirelessGatewayTask",
"DeleteWirelessGatewayTaskDefinition",
"DisassociateAwsAccountFromPartnerAccount",
"DisassociateWirelessDeviceFromThing",
"DisassociateWirelessGatewayFromCertificate",
"DisassociateWirelessGatewayFromThing",
"PutResourceLogLevel",
"ResetAllResourceLogLevels",
"ResetResourceLogLevel",
"SendDataToWirelessDevice",
"TestWirelessDevice",
"UpdateDestination",
"UpdateLogLevelsByResourceTypes",
"UpdatePartnerAccount",
"UpdateWirelessDevice",
"UpdateWirelessGateway"
],
"Read": [
"GetDestination",
"GetDeviceProfile",
"GetLogLevelsByResourceTypes",
"GetPartnerAccount",
"GetResourceLogLevel",
"GetServiceEndpoint",
"GetServiceProfile",
"GetWirelessDevice",
"GetWirelessDeviceStatistics",
"GetWirelessGateway",
"GetWirelessGatewayCertificate",
"GetWirelessGatewayFirmwareInformation",
"GetWirelessGatewayStatistics",
"GetWirelessGatewayTask",
"GetWirelessGatewayTaskDefinition",
"ListDestinations",
"ListDeviceProfiles",
"ListPartnerAccounts",
"ListServiceProfiles",
"ListTagsForResource",
"ListWirelessDevices",
"ListWirelessGatewayTaskDefinitions",
"ListWirelessGateways"
],
"Tagging": [
"TagResource",
"UntagResource"
]
};
/**
* Adds a resource of type WirelessDevice to the statement
*
* https://docs.aws.amazon.com/iot-wireless/2020-11-22/apireference/API_CreateWirelessDevice.html
*
* @param wirelessDeviceId - Identifier for the wirelessDeviceId.
* @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 onWirelessDevice(wirelessDeviceId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:iotwireless:${Region}:${Account}:WirelessDevice/${WirelessDeviceId}';
arn = arn.replace('${WirelessDeviceId}', wirelessDeviceId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type WirelessGateway to the statement
*
* https://docs.aws.amazon.com/iot-wireless/2020-11-22/apireference/API_CreateWirelessGateway.html
*
* @param wirelessGatewayId - Identifier for the wirelessGatewayId.
* @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 onWirelessGateway(wirelessGatewayId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:iotwireless:${Region}:${Account}:WirelessGateway/${WirelessGatewayId}';
arn = arn.replace('${WirelessGatewayId}', wirelessGatewayId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type DeviceProfile to the statement
*
* https://docs.aws.amazon.com/iot-wireless/2020-11-22/apireference/API_CreateDeviceProfile.html
*
* @param deviceProfileId - Identifier for the deviceProfileId.
* @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 onDeviceProfile(deviceProfileId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:iotwireless:${Region}:${Account}:DeviceProfile/${DeviceProfileId}';
arn = arn.replace('${DeviceProfileId}', deviceProfileId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type ServiceProfile to the statement
*
* https://docs.aws.amazon.com/iot-wireless/2020-11-22/apireference/API_CreateServiceProfile.html
*
* @param serviceProfileId - Identifier for the serviceProfileId.
* @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 onServiceProfile(serviceProfileId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:iotwireless:${Region}:${Account}:ServiceProfile/${ServiceProfileId}';
arn = arn.replace('${ServiceProfileId}', serviceProfileId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type Destination to the statement
*
* https://docs.aws.amazon.com/iot-wireless/2020-11-22/apireference/API_CreateDestination.html
*
* @param destinationName - Identifier for the destinationName.
* @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 onDestination(destinationName: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:iotwireless:${Region}:${Account}:Destination/${DestinationName}';
arn = arn.replace('${DestinationName}', destinationName);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type SidewalkAccount to the statement
*
* https://docs.aws.amazon.com/iot-wireless/2020-11-22/apireference/API_AssociateAwsAccountWithPartnerAccount.html
*
* @param sidewalkAccountId - Identifier for the sidewalkAccountId.
* @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 onSidewalkAccount(sidewalkAccountId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:iotwireless:${Region}:${Account}:SidewalkAccount/${SidewalkAccountId}';
arn = arn.replace('${SidewalkAccountId}', sidewalkAccountId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type WirelessGatewayTaskDefinition to the statement
*
* https://docs.aws.amazon.com/iot-wireless/2020-11-22/apireference/API_CreateWirelessGatewayTaskDefinition.html
*
* @param wirelessGatewayTaskDefinitionId - Identifier for the wirelessGatewayTaskDefinitionId.
* @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 onWirelessGatewayTaskDefinition(wirelessGatewayTaskDefinitionId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:iotwireless:${Region}:${Account}:WirelessGatewayTaskDefinition/${WirelessGatewayTaskDefinitionId}';
arn = arn.replace('${WirelessGatewayTaskDefinitionId}', wirelessGatewayTaskDefinitionId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type thing to the statement
*
* https://docs.aws.amazon.com/iot/latest/developerguide/thing-registry.html
*
* @param thingName - Identifier for the thingName.
* @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`.
*/
public onThing(thingName: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:iot:${Region}:${Account}:thing/${ThingName}';
arn = arn.replace('${ThingName}', thingName);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type cert to the statement
*
* https://docs.aws.amazon.com/iot/latest/developerguide/x509-client-certs.html
*
* @param certificate - Identifier for the certificate.
* @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`.
*/
public onCert(certificate: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:iot:${Region}:${Account}:cert/${Certificate}';
arn = arn.replace('${Certificate}', certificate);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
} | the_stack |
import { ethers, upgrades, waffle } from "hardhat";
import { Overrides, Signer, BigNumberish, utils, Wallet } from "ethers";
import chai from "chai";
import { solidity } from "ethereum-waffle";
import "@openzeppelin/test-helpers";
import {
AlpacaToken,
AlpacaToken__factory,
FairLaunch,
FairLaunch__factory,
FairLaunchV2,
FairLaunchV2__factory,
MockERC20,
MockERC20__factory,
LinearRelease,
LinearRelease__factory,
} from "../../../typechain";
import * as TimeHelpers from "../../helpers/time";
chai.use(solidity);
const { expect } = chai;
describe("FairLaunchV2", () => {
const ALPACA_REWARD_PER_BLOCK = ethers.utils.parseEther("5000");
const ALPACA_BONUS_LOCK_UP_BPS = 7000;
const ADDRESS0 = "0x0000000000000000000000000000000000000000";
// Contract as Signer
let alpacaTokenAsAlice: AlpacaToken;
let alpacaTokenAsBob: AlpacaToken;
let alpacaTokenAsDev: AlpacaToken;
let stoken0AsDeployer: MockERC20;
let stoken0AsAlice: MockERC20;
let stoken0AsBob: MockERC20;
let stoken0AsDev: MockERC20;
let stoken1AsDeployer: MockERC20;
let stoken1AsAlice: MockERC20;
let stoken1AsBob: MockERC20;
let stoken1AsDev: MockERC20;
let fairLaunchAsDeployer: FairLaunch;
let fairLaunchAsAlice: FairLaunch;
let fairLaunchAsBob: FairLaunch;
let fairLaunchAsDev: FairLaunch;
let fairLaunchV2AsDeployer: FairLaunchV2;
let fairLaunchV2AsAlice: FairLaunchV2;
let fairLaunchV2AsBob: FairLaunchV2;
let fairLaunchV2AsDev: FairLaunchV2;
// Accounts
let deployer: Signer;
let alice: Signer;
let bob: Signer;
let dev: Signer;
let alpacaToken: AlpacaToken;
let fairLaunch: FairLaunch;
let fairLaunchV2: FairLaunchV2;
let fairLaunchLink: MockERC20;
let stakingTokens: MockERC20[];
async function fixture() {
[deployer, alice, bob, dev] = await ethers.getSigners();
// Setup FairLaunch contract
// Deploy ALPACAs
const AlpacaToken = (await ethers.getContractFactory("AlpacaToken", deployer)) as AlpacaToken__factory;
alpacaToken = await AlpacaToken.deploy(0, 1);
await alpacaToken.deployed();
const FairLaunch = (await ethers.getContractFactory("FairLaunch", deployer)) as FairLaunch__factory;
fairLaunch = await FairLaunch.deploy(
alpacaToken.address,
await dev.getAddress(),
ALPACA_REWARD_PER_BLOCK,
0,
ALPACA_BONUS_LOCK_UP_BPS,
0
);
await fairLaunch.deployed();
await alpacaToken.transferOwnership(fairLaunch.address);
stakingTokens = new Array();
const MockERC20 = (await ethers.getContractFactory("MockERC20", deployer)) as MockERC20__factory;
for (let i = 0; i < 4; i++) {
const mockERC20 = (await upgrades.deployProxy(MockERC20, [`STOKEN${i}`, `STOKEN${i}`, 18])) as MockERC20;
await mockERC20.deployed();
stakingTokens.push(mockERC20);
}
// Create fairLaunchLink token
fairLaunchLink = (await upgrades.deployProxy(MockERC20, ["fairLaunchLink", "fairLaunchLink", 18])) as MockERC20;
await fairLaunchLink.deployed();
// Deploy FairLaunchV2
const FairLaunchV2 = (await ethers.getContractFactory("FairLaunchV2", deployer)) as FairLaunchV2__factory;
fairLaunchV2 = await FairLaunchV2.deploy(fairLaunch.address, alpacaToken.address, 1);
await fairLaunch.deployed();
alpacaTokenAsAlice = AlpacaToken__factory.connect(alpacaToken.address, alice);
alpacaTokenAsBob = AlpacaToken__factory.connect(alpacaToken.address, bob);
alpacaTokenAsDev = AlpacaToken__factory.connect(alpacaToken.address, dev);
stoken0AsDeployer = MockERC20__factory.connect(stakingTokens[0].address, deployer);
stoken0AsAlice = MockERC20__factory.connect(stakingTokens[0].address, alice);
stoken0AsBob = MockERC20__factory.connect(stakingTokens[0].address, bob);
stoken0AsDev = MockERC20__factory.connect(stakingTokens[0].address, dev);
stoken1AsDeployer = MockERC20__factory.connect(stakingTokens[1].address, deployer);
stoken1AsAlice = MockERC20__factory.connect(stakingTokens[1].address, alice);
stoken1AsBob = MockERC20__factory.connect(stakingTokens[1].address, bob);
stoken1AsDev = MockERC20__factory.connect(stakingTokens[1].address, dev);
fairLaunchAsDeployer = FairLaunch__factory.connect(fairLaunch.address, deployer);
fairLaunchAsAlice = FairLaunch__factory.connect(fairLaunch.address, alice);
fairLaunchAsBob = FairLaunch__factory.connect(fairLaunch.address, bob);
fairLaunchAsDev = FairLaunch__factory.connect(fairLaunch.address, dev);
fairLaunchV2AsDeployer = FairLaunchV2__factory.connect(fairLaunchV2.address, deployer);
fairLaunchV2AsAlice = FairLaunchV2__factory.connect(fairLaunchV2.address, alice);
fairLaunchV2AsBob = FairLaunchV2__factory.connect(fairLaunchV2.address, bob);
fairLaunchV2AsDev = FairLaunchV2__factory.connect(fairLaunchV2.address, dev);
}
beforeEach(async () => {
await waffle.loadFixture(fixture);
});
context("when already init", async () => {
it("should work", async () => {
// add dummyToken to fairLaunchV1
await fairLaunch.addPool(0, stakingTokens[0].address, false);
await fairLaunch.addPool(1, fairLaunchLink.address, false);
// mint fairLaunchLink token for deployer
await fairLaunchLink.mint(await deployer.getAddress(), ethers.utils.parseEther("1"));
// Initialized fairLaunchV2
await fairLaunchLink.approve(fairLaunchV2.address, ethers.utils.parseEther("1"));
await fairLaunchV2.init(fairLaunchLink.address);
expect(await fairLaunchLink.balanceOf(await deployer.getAddress())).to.be.eq("0");
});
});
context("when adjust params", async () => {
it("should add new pool", async () => {
// add dummyToken to fairLaunchV1
await fairLaunch.addPool(0, stakingTokens[0].address, false);
await fairLaunch.addPool(1, fairLaunchLink.address, false);
// mint fairLaunchLink token for deployer
await fairLaunchLink.mint(await deployer.getAddress(), ethers.utils.parseEther("1"));
// Initialized fairLaunchV2
await fairLaunchLink.approve(fairLaunchV2.address, ethers.utils.parseEther("1"));
await fairLaunchV2.init(fairLaunchLink.address);
for (let i = 0; i < stakingTokens.length; i++) {
await fairLaunchV2.addPool(1, stakingTokens[i].address, ADDRESS0, 0);
}
expect(await fairLaunchV2.poolLength()).to.eq(stakingTokens.length);
});
it("should revert when the stakeToken is already added to the pool", async () => {
// add dummyToken to fairLaunchV1
await fairLaunch.addPool(0, stakingTokens[0].address, false);
await fairLaunch.addPool(1, fairLaunchLink.address, false);
// mint fairLaunchLink token for deployer
await fairLaunchLink.mint(await deployer.getAddress(), ethers.utils.parseEther("1"));
// Initialized fairLaunchV2
await fairLaunchLink.approve(fairLaunchV2.address, ethers.utils.parseEther("1"));
await fairLaunchV2.init(fairLaunchLink.address);
for (let i = 0; i < stakingTokens.length; i++) {
await fairLaunchV2.addPool(1, stakingTokens[i].address, ADDRESS0, 0);
}
expect(await fairLaunchV2.poolLength()).to.eq(stakingTokens.length);
await expect(fairLaunchV2.addPool(1, stakingTokens[0].address, ADDRESS0, 0)).to.be.revertedWith(
"FairLaunchV2::addPool:: stakeToken dup"
);
});
});
context("when use pool", async () => {
it("should revert when that pool is not existed", async () => {
// add dummyToken to fairLaunchV1
await fairLaunch.addPool(0, stakingTokens[0].address, false);
await fairLaunch.addPool(1, fairLaunchLink.address, false);
// mint fairLaunchLink token for deployer
await fairLaunchLink.mint(await deployer.getAddress(), ethers.utils.parseEther("1"));
// Initialized fairLaunchV2
await fairLaunchLink.approve(fairLaunchV2.address, ethers.utils.parseEther("1"));
await fairLaunchV2.init(fairLaunchLink.address);
await expect(
fairLaunchV2.deposit(await deployer.getAddress(), 88, ethers.utils.parseEther("100"), {
from: await deployer.getAddress(),
} as Overrides)
).to.be.reverted;
});
it("should revert when withdrawer is not a funder", async () => {
// add dummyToken to fairLaunchV1
await fairLaunch.addPool(0, stakingTokens[0].address, false);
await fairLaunch.addPool(1, fairLaunchLink.address, false);
// mint fairLaunchLink token for deployer
await fairLaunchLink.mint(await deployer.getAddress(), ethers.utils.parseEther("1"));
// Initialized fairLaunchV2
await fairLaunchLink.approve(fairLaunchV2.address, ethers.utils.parseEther("1"));
await fairLaunchV2.init(fairLaunchLink.address);
// 1. Mint STOKEN0 for staking
await stoken0AsDeployer.mint(await alice.getAddress(), ethers.utils.parseEther("400"));
// 2. Add STOKEN0 to the fairLaunch pool
await fairLaunchV2AsDeployer.addPool(1, stakingTokens[0].address, ADDRESS0, 0);
// 3. Deposit STOKEN0 to the STOKEN0 pool
await stoken0AsAlice.approve(fairLaunchV2.address, ethers.utils.parseEther("100"));
await fairLaunchV2AsAlice.deposit(await bob.getAddress(), 0, ethers.utils.parseEther("100"));
// 4. Bob try to withdraw from the pool
// Bob shuoldn't do that, he can get yield but not the underlaying
await expect(
fairLaunchV2AsBob.withdraw(await bob.getAddress(), 0, ethers.utils.parseEther("100"))
).to.be.revertedWith("FairLaunchV2::withdraw:: only funder");
});
it("should allow deposit when funder withdrew funds and owner want to stake his own token", async () => {
// add dummyToken to fairLaunchV1
await fairLaunch.addPool(0, stakingTokens[0].address, false);
await fairLaunch.addPool(1, fairLaunchLink.address, false);
// mint fairLaunchLink token for deployer
await fairLaunchLink.mint(await deployer.getAddress(), ethers.utils.parseEther("1"));
// Initialized fairLaunchV2
await fairLaunchLink.approve(fairLaunchV2.address, ethers.utils.parseEther("1"));
await fairLaunchV2.init(fairLaunchLink.address);
// 1. Mint STOKEN0 for staking
await stoken0AsDeployer.mint(await alice.getAddress(), ethers.utils.parseEther("400"));
await stoken0AsDeployer.mint(await bob.getAddress(), ethers.utils.parseEther("100"));
// 2. Add STOKEN0 to the fairLaunch pool
await fairLaunchV2AsDeployer.addPool(1, stakingTokens[0].address, ADDRESS0, 0);
// 3. Deposit STOKEN0 to the STOKEN0 pool
await stoken0AsAlice.approve(fairLaunchV2.address, ethers.utils.parseEther("100"));
await fairLaunchV2AsAlice.deposit(await bob.getAddress(), 0, ethers.utils.parseEther("100"));
// 4. Bob harvest the yield
let bobAlpacaBalanceBefore = await alpacaToken.balanceOf(await bob.getAddress());
await fairLaunchV2AsBob.harvest(0);
expect(await alpacaToken.balanceOf(await bob.getAddress())).to.be.gt(bobAlpacaBalanceBefore);
// 5. Bob try to withdraw from the pool
// Bob shuoldn't do that, he can get yield but not the underlaying
await expect(
fairLaunchV2AsBob.withdraw(await bob.getAddress(), 0, ethers.utils.parseEther("100"))
).to.be.revertedWith("FairLaunchV2::withdraw:: only funder");
// 6. Alice withdraw her STOKEN0 that staked on behalf of BOB
await fairLaunchV2AsAlice.withdraw(await bob.getAddress(), 0, ethers.utils.parseEther("100"));
// 7. Bob deposit his STOKN0 to FairLaunch
await stoken0AsBob.approve(fairLaunchV2.address, ethers.utils.parseEther("100"));
await fairLaunchV2AsBob.deposit(await bob.getAddress(), 0, ethers.utils.parseEther("100"));
});
it("should revert when funder partially withdraw the funds, then user try to withdraw funds", async () => {
// add dummyToken to fairLaunchV1
await fairLaunch.addPool(0, stakingTokens[0].address, false);
await fairLaunch.addPool(1, fairLaunchLink.address, false);
// mint fairLaunchLink token for deployer
await fairLaunchLink.mint(await deployer.getAddress(), ethers.utils.parseEther("1"));
// Initialized fairLaunchV2
await fairLaunchLink.approve(fairLaunchV2.address, ethers.utils.parseEther("1"));
await fairLaunchV2.init(fairLaunchLink.address);
// 1. Mint STOKEN0 for staking
await stoken0AsDeployer.mint(await alice.getAddress(), ethers.utils.parseEther("400"));
await stoken0AsDeployer.mint(await dev.getAddress(), ethers.utils.parseEther("100"));
// 2. Add STOKEN0 to the fairLaunch pool
await fairLaunchV2AsDeployer.addPool(1, stakingTokens[0].address, ADDRESS0, 0);
// 3. Deposit STOKEN0 to the STOKEN0 pool
await stoken0AsAlice.approve(fairLaunchV2.address, ethers.utils.parseEther("100"));
await fairLaunchV2AsAlice.deposit(await bob.getAddress(), 0, ethers.utils.parseEther("100"));
// 4. Alice withdraw some from FLV2
await fairLaunchV2AsAlice.withdraw(await bob.getAddress(), 0, ethers.utils.parseEther("50"));
// 5. Expect to be revert with Bob try to withdraw the funds
await expect(
fairLaunchV2AsBob.withdraw(await bob.getAddress(), 0, ethers.utils.parseEther("1"))
).to.be.revertedWith("FairLaunchV2::withdraw:: only funder");
});
it("should give the correct withdraw amount back to funder if funder withdraw", async () => {
// add dummyToken to fairLaunchV1
await fairLaunch.addPool(0, stakingTokens[0].address, false);
await fairLaunch.addPool(1, fairLaunchLink.address, false);
// mint fairLaunchLink token for deployer
await fairLaunchLink.mint(await deployer.getAddress(), ethers.utils.parseEther("1"));
// Initialized fairLaunchV2
await fairLaunchLink.approve(fairLaunchV2.address, ethers.utils.parseEther("1"));
await fairLaunchV2.init(fairLaunchLink.address);
// 1. Mint STOKEN0 for staking
await stoken0AsDeployer.mint(await alice.getAddress(), ethers.utils.parseEther("400"));
await stoken0AsDeployer.mint(await dev.getAddress(), ethers.utils.parseEther("100"));
// 2. Add STOKEN0 to the fairLaunch pool
await fairLaunchV2AsDeployer.addPool(1, stakingTokens[0].address, ADDRESS0, 0);
// 3. Deposit STOKEN0 to the STOKEN0 pool
await stoken0AsAlice.approve(fairLaunchV2.address, ethers.utils.parseEther("100"));
await fairLaunchV2AsAlice.deposit(await bob.getAddress(), 0, ethers.utils.parseEther("100"));
// 4. Alice withdraw some from FLV2
await fairLaunchV2AsAlice.withdraw(await bob.getAddress(), 0, ethers.utils.parseEther("50"));
// 5. Expect to Alice STOKEN0 will be 400-100+50=350
expect(await stoken0AsBob.balanceOf(await alice.getAddress())).to.be.eq(ethers.utils.parseEther("350"));
});
it("should revert when non funder try to emergencyWithdraw from FLV2", async () => {
// add dummyToken to fairLaunchV1
await fairLaunch.addPool(0, stakingTokens[0].address, false);
await fairLaunch.addPool(1, fairLaunchLink.address, false);
// mint fairLaunchLink token for deployer
await fairLaunchLink.mint(await deployer.getAddress(), ethers.utils.parseEther("1"));
// Initialized fairLaunchV2
await fairLaunchLink.approve(fairLaunchV2.address, ethers.utils.parseEther("1"));
await fairLaunchV2.init(fairLaunchLink.address);
// 1. Mint STOKEN0 for staking
await stoken0AsDeployer.mint(await alice.getAddress(), ethers.utils.parseEther("400"));
await stoken0AsDeployer.mint(await dev.getAddress(), ethers.utils.parseEther("100"));
// 2. Add STOKEN0 to the fairLaunch pool
await fairLaunchV2AsDeployer.addPool(1, stakingTokens[0].address, ADDRESS0, 0);
// 3. Deposit STOKEN0 to the STOKEN0 pool
await stoken0AsAlice.approve(fairLaunchV2.address, ethers.utils.parseEther("100"));
await fairLaunchV2AsAlice.deposit(await bob.getAddress(), 0, ethers.utils.parseEther("100"));
await expect(fairLaunchV2AsBob.emergencyWithdraw(0, await bob.getAddress())).to.be.revertedWith(
"FairLaunchV2::emergencyWithdraw:: only funder"
);
});
it("should revert when 2 accounts try to fund the same user", async () => {
// add dummyToken to fairLaunchV1
await fairLaunch.addPool(0, stakingTokens[0].address, false);
await fairLaunch.addPool(1, fairLaunchLink.address, false);
// mint fairLaunchLink token for deployer
await fairLaunchLink.mint(await deployer.getAddress(), ethers.utils.parseEther("1"));
// Initialized fairLaunchV2
await fairLaunchLink.approve(fairLaunchV2.address, ethers.utils.parseEther("1"));
await fairLaunchV2.init(fairLaunchLink.address);
// 1. Mint STOKEN0 for staking
await stoken0AsDeployer.mint(await alice.getAddress(), ethers.utils.parseEther("400"));
await stoken0AsDeployer.mint(await dev.getAddress(), ethers.utils.parseEther("100"));
// 2. Add STOKEN0 to the fairLaunch pool
await fairLaunchV2AsDeployer.addPool(1, stakingTokens[0].address, ADDRESS0, 0);
// 3. Deposit STOKEN0 to the STOKEN0 pool
await stoken0AsAlice.approve(fairLaunchV2.address, ethers.utils.parseEther("100"));
await fairLaunchV2AsAlice.deposit(await bob.getAddress(), 0, ethers.utils.parseEther("100"));
// 4. Dev try to deposit to the pool on the bahalf of Bob
// Dev should get revert tx as this will fuck up the tracking
await stoken0AsDev.approve(fairLaunchV2.address, ethers.utils.parseEther("100"));
await expect(
fairLaunchV2AsDev.deposit(await bob.getAddress(), 0, ethers.utils.parseEther("1"))
).to.be.revertedWith("FairLaunchV2::deposit:: bad sof");
});
it("should harvest yield from the position opened by funder", async () => {
// add dummyToken to fairLaunchV1
await fairLaunch.addPool(0, stakingTokens[0].address, false);
await fairLaunch.addPool(1, fairLaunchLink.address, false);
// mint fairLaunchLink token for deployer
await fairLaunchLink.mint(await deployer.getAddress(), ethers.utils.parseEther("1"));
// Initialized fairLaunchV2
await fairLaunchLink.approve(fairLaunchV2.address, ethers.utils.parseEther("1"));
await fairLaunchV2.init(fairLaunchLink.address);
// 1. Mint STOKEN0 for staking
await stoken0AsDeployer.mint(await alice.getAddress(), ethers.utils.parseEther("400"));
// 2. Add STOKEN0 to the fairLaunch pool
await fairLaunchV2AsDeployer.addPool(1, stakingTokens[0].address, ADDRESS0, 0);
// 3. Deposit STOKEN0 to the STOKEN0 pool
await stoken0AsAlice.approve(fairLaunchV2.address, ethers.utils.parseEther("100"));
await fairLaunchV2AsAlice.deposit(await bob.getAddress(), 0, ethers.utils.parseEther("100"));
// 4. Move 1 Block so there is some pending
await fairLaunchV2AsDeployer.updatePool(0);
expect(await fairLaunchV2AsBob.pendingAlpaca(0, await bob.getAddress())).to.be.eq(
ethers.utils.parseEther("5000")
);
// 5. Harvest all yield
await fairLaunchV2AsBob.harvest(0);
expect(await alpacaToken.balanceOf(await bob.getAddress())).to.be.eq(ethers.utils.parseEther("10000"));
});
it("should distribute rewards according to the alloc point", async () => {
// add dummyToken to fairLaunchV1
await fairLaunch.addPool(0, stakingTokens[0].address, false);
await fairLaunch.addPool(1, fairLaunchLink.address, false);
// mint fairLaunchLink token for deployer
await fairLaunchLink.mint(await deployer.getAddress(), ethers.utils.parseEther("1"));
// Initialized fairLaunchV2
await fairLaunchLink.approve(fairLaunchV2.address, ethers.utils.parseEther("1"));
await fairLaunchV2.init(fairLaunchLink.address);
// 1. Mint STOKEN0 and STOKEN1 for staking
await stoken0AsDeployer.mint(await alice.getAddress(), ethers.utils.parseEther("100"));
await stoken1AsDeployer.mint(await alice.getAddress(), ethers.utils.parseEther("50"));
// 2. Add STOKEN0 to the fairLaunch pool
await fairLaunchV2AsDeployer.addPool(50, stakingTokens[0].address, ADDRESS0, 0);
await fairLaunchV2AsDeployer.addPool(50, stakingTokens[1].address, ADDRESS0, 0);
// 3. Deposit STOKEN0 to the STOKEN0 pool
await stoken0AsAlice.approve(fairLaunchV2.address, ethers.utils.parseEther("100"));
await fairLaunchV2AsAlice.deposit(await alice.getAddress(), 0, ethers.utils.parseEther("100"));
// 4. Deposit STOKEN1 to the STOKEN1 pool
await stoken1AsAlice.approve(fairLaunchV2.address, ethers.utils.parseEther("50"));
await fairLaunchV2AsAlice.deposit(await alice.getAddress(), 1, ethers.utils.parseEther("50"));
// 5. Move 1 Block so there is some pending
await fairLaunchV2AsDeployer.massUpdatePools([0, 1]);
expect(await fairLaunchV2.pendingAlpaca(0, await alice.getAddress())).to.be.eq(ethers.utils.parseEther("7500"));
expect(await fairLaunchV2.pendingAlpaca(1, await alice.getAddress())).to.be.eq(ethers.utils.parseEther("2500"));
// 6. Harvest all yield of pId 0
// should get 7,500 + 2,500 = 10,000 ALPACAs from pId 0
await fairLaunchV2AsAlice.harvest(0);
expect(await alpacaToken.balanceOf(await alice.getAddress())).to.be.eq(ethers.utils.parseEther("10000"));
// 7. Harvest all yield of pId 1
// should get 2,500 + 2,500 + 2,500 = 7,500 ALPACAs from pId 1
await fairLaunchV2AsAlice.harvest(1);
expect(await alpacaToken.balanceOf(await alice.getAddress())).to.be.eq(ethers.utils.parseEther("17500"));
});
it("should work", async () => {
// add dummyToken to fairLaunchV1
await fairLaunch.addPool(0, stakingTokens[0].address, false);
await fairLaunch.addPool(1, fairLaunchLink.address, false);
// mint fairLaunchLink token for deployer
await fairLaunchLink.mint(await deployer.getAddress(), ethers.utils.parseEther("1"));
// Initialized fairLaunchV2
await fairLaunchLink.approve(fairLaunchV2.address, ethers.utils.parseEther("1"));
await fairLaunchV2.init(fairLaunchLink.address);
// 1. Mint STOKEN0 for staking
await stoken0AsDeployer.mint(await alice.getAddress(), ethers.utils.parseEther("400"));
await stoken0AsDeployer.mint(await bob.getAddress(), ethers.utils.parseEther("100"));
// 2. Add STOKEN0 to the fairLaunchV2 pool
await fairLaunchV2AsDeployer.addPool(1, stakingTokens[0].address, ADDRESS0, 0);
// 3. Deposit STOKEN0 to the STOKEN0 pool
await stoken0AsAlice.approve(fairLaunchV2.address, ethers.utils.parseEther("100"));
await fairLaunchV2AsAlice.deposit(await alice.getAddress(), 0, ethers.utils.parseEther("100"));
// 4. Trigger random update pool to make 1 more block mine
await fairLaunchV2.massUpdatePools([0]);
// 5. Check pendingAlpaca for Alice
expect(await fairLaunchV2.pendingAlpaca(0, await alice.getAddress())).to.be.eq(ethers.utils.parseEther("5000"));
// 6. Trigger random update pool to make 1 more block mine
await fairLaunchV2AsAlice.massUpdatePools([0]);
// 7. Check pendingAlpaca for Alice
expect(await fairLaunchV2.pendingAlpaca(0, await alice.getAddress())).to.be.eq(ethers.utils.parseEther("10000"));
// 8. Alice should get 15,000 ALPACAs when she harvest
// also check that dev got his tax
// PS. Dev get 4,000 as MASTER_POOL was added 8 blocks earlier
await fairLaunchV2AsAlice.harvest(0);
expect(await alpacaToken.balanceOf(await alice.getAddress())).to.be.eq(ethers.utils.parseEther("15000"));
expect(await alpacaToken.balanceOf(await dev.getAddress())).to.be.eq(ethers.utils.parseEther("4000"));
// 9. Bob come in and join the party
// 2 blocks are mined here, hence Alice should get 10,000 ALPACAs more
await stoken0AsBob.approve(fairLaunchV2.address, ethers.utils.parseEther("100"));
await fairLaunchV2AsBob.deposit(await bob.getAddress(), 0, ethers.utils.parseEther("100"));
expect(await fairLaunchV2.pendingAlpaca(0, await alice.getAddress())).to.be.eq(ethers.utils.parseEther("10000"));
expect(await alpacaToken.balanceOf(await dev.getAddress())).to.be.eq(ethers.utils.parseEther("5000"));
// 10. Trigger random update pool to make 1 more block mine
await fairLaunchV2.massUpdatePools([0]);
// 11. Check pendingAlpaca
// Reward per Block must now share amoung Bob and Alice (50-50)
// Alice should has 12,500 ALPACAs (10,000 + 2,500)
// Bob should has 2,500 ALPACAs
// Dev get 10% tax per block (5,000*0.1 = 500/block)
expect(await fairLaunchV2.pendingAlpaca(0, await alice.getAddress())).to.be.eq(ethers.utils.parseEther("12500"));
expect(await fairLaunchV2.pendingAlpaca(0, await bob.getAddress())).to.be.eq(ethers.utils.parseEther("2500"));
expect(await alpacaToken.balanceOf(await dev.getAddress())).to.be.eq(ethers.utils.parseEther("5500"));
// 12. Trigger random update pool to make 1 more block mine
await fairLaunchV2AsAlice.massUpdatePools([0]);
// 13. Check pendingAlpaca
// Reward per Block must now share amoung Bob and Alice (50-50)
// Alice should has 15,000 ALPACAs (12,500 + 2,500)
// Bob should has 5,000 ALPACAs (2,500 + 2,500)
// Dev get 10% tax per block (5,000*0.1 = 500/block)
expect(await fairLaunchV2.pendingAlpaca(0, await alice.getAddress())).to.be.eq(ethers.utils.parseEther("15000"));
expect(await fairLaunchV2.pendingAlpaca(0, await bob.getAddress())).to.be.eq(ethers.utils.parseEther("5000"));
expect(await alpacaToken.balanceOf(await dev.getAddress())).to.be.eq(ethers.utils.parseEther("6000"));
// 14. Bob harvest his yield
// Reward per Block is till (50-50) as Bob is not leaving the pool yet
// Alice should has 17,500 ALPACAs (15,000 + 2,500) in pending
// Bob should has 7,500 ALPACAs (5,000 + 2,500) in his account as he harvest it
// Dev get 10% tax per block (5,000*0.1 = 500/block)
await fairLaunchV2AsBob.harvest(0);
expect(await fairLaunchV2.pendingAlpaca(0, await alice.getAddress())).to.be.eq(ethers.utils.parseEther("17500"));
expect(await fairLaunchV2.pendingAlpaca(0, await bob.getAddress())).to.be.eq(ethers.utils.parseEther("0"));
expect(await alpacaToken.balanceOf(await bob.getAddress())).to.be.eq(ethers.utils.parseEther("7500"));
expect(await alpacaToken.balanceOf(await dev.getAddress())).to.be.eq(ethers.utils.parseEther("6500"));
// 15. Alice wants more ALPACAs so she deposit 300 STOKEN0 more
await stoken0AsAlice.approve(fairLaunchV2.address, ethers.utils.parseEther("300"));
await fairLaunchV2AsAlice.deposit(await alice.getAddress(), 0, ethers.utils.parseEther("300"));
// Alice should get 22,500 ALPACAs (17,500 + 2,500 [B1] + 2,500 [B2]) in pending Alpaca
// Bob should has (2,500 [B1] + 2,500 [B2]) = 5,000 ALPACAs in pending
expect(await fairLaunchV2.pendingAlpaca(0, await alice.getAddress())).to.be.eq(ethers.utils.parseEther("22500"));
expect(await fairLaunchV2.pendingAlpaca(0, await bob.getAddress())).to.be.eq(ethers.utils.parseEther("5000"));
expect(await alpacaToken.balanceOf(await alice.getAddress())).to.be.eq(ethers.utils.parseEther("15000"));
expect(await alpacaToken.balanceOf(await bob.getAddress())).to.be.eq(ethers.utils.parseEther("7500"));
expect(await alpacaToken.balanceOf(await dev.getAddress())).to.be.eq(ethers.utils.parseEther("7500"));
// 16. Trigger random update pool to make 1 more block mine
await fairLaunchV2AsAlice.massUpdatePools([0]);
// 1 more block is mined, now Alice shold get 80% and Bob should get 20% of rewards
// How many STOKEN0 needed to make Alice get 80%: find n from 100n/(100n+100) = 0.8
// Hence, Alice should get 22,500 + 4,000 = 26,5000 ALPACAs in pending
// Bob should get 5,000 + 1,000 = 6,000 ALPACAs in pending
expect(await fairLaunchV2.pendingAlpaca(0, await alice.getAddress())).to.be.eq(ethers.utils.parseEther("26500"));
expect(await fairLaunchV2.pendingAlpaca(0, await bob.getAddress())).to.be.eq(ethers.utils.parseEther("6000"));
expect(await alpacaToken.balanceOf(await alice.getAddress())).to.be.eq(ethers.utils.parseEther("15000"));
expect(await alpacaToken.balanceOf(await bob.getAddress())).to.be.eq(ethers.utils.parseEther("7500"));
expect(await alpacaToken.balanceOf(await dev.getAddress())).to.be.eq(ethers.utils.parseEther("8000"));
});
it("should work when there is a locker", async () => {
// add dummyToken to fairLaunchV1
await fairLaunch.addPool(0, stakingTokens[0].address, false);
await fairLaunch.addPool(1, fairLaunchLink.address, false);
// mint fairLaunchLink token for deployer
await fairLaunchLink.mint(await deployer.getAddress(), ethers.utils.parseEther("1"));
// Initialized fairLaunchV2
await fairLaunchLink.approve(fairLaunchV2.address, ethers.utils.parseEther("1"));
await fairLaunchV2.init(fairLaunchLink.address);
// 1. Mint STOKEN0 for staking
await stoken0AsDeployer.mint(await alice.getAddress(), ethers.utils.parseEther("400"));
await stoken0AsDeployer.mint(await bob.getAddress(), ethers.utils.parseEther("100"));
// 2. Deploy LinearRelease Locker
const startReleaseBlock = (await TimeHelpers.latestBlockNumber()).add(12);
const endReleaseBlock = startReleaseBlock.add(5);
const LinearRelease = (await ethers.getContractFactory("LinearRelease", deployer)) as LinearRelease__factory;
const linearRelease = (await LinearRelease.deploy(
alpacaToken.address,
"7000",
fairLaunchV2.address,
startReleaseBlock,
endReleaseBlock
)) as LinearRelease;
const linearReleaseAsAlice = LinearRelease__factory.connect(linearRelease.address, alice);
const linearReleaseAsBob = LinearRelease__factory.connect(linearRelease.address, bob);
// 3. Add STOKEN0 to the fairLaunchV2 pool
await fairLaunchV2AsDeployer.addPool(1, stakingTokens[0].address, linearRelease.address, 0);
// 4. Deposit STOKEN0 to the STOKEN0 pool
await stoken0AsAlice.approve(fairLaunchV2.address, ethers.utils.parseEther("100"));
await fairLaunchV2AsAlice.deposit(await alice.getAddress(), 0, ethers.utils.parseEther("100"));
// 5. Trigger random update pool to make 1 more block mine
await fairLaunchV2.massUpdatePools([0]);
// 6. Check pendingAlpaca for Alice
expect(await fairLaunchV2.pendingAlpaca(0, await alice.getAddress())).to.be.eq(ethers.utils.parseEther("5000"));
// 7. Trigger random update pool to make 1 more block mine
await fairLaunchV2AsAlice.massUpdatePools([0]);
// 8. Check pendingAlpaca for Alice
expect(await fairLaunchV2.pendingAlpaca(0, await alice.getAddress())).to.be.eq(ethers.utils.parseEther("10000"));
// 9. Alice should get 15,000 * (1-0.7) = 4,500 ALPACAs when she harvest
// also check that dev got his tax
// PS. Dev get 4,500 as MASTER_POOL was added 9 blocks earlier
await fairLaunchV2AsAlice.harvest(0);
expect(await alpacaToken.balanceOf(await alice.getAddress())).to.be.eq(ethers.utils.parseEther("4500"));
expect(await alpacaToken.balanceOf(await dev.getAddress())).to.be.eq(ethers.utils.parseEther("4500"));
expect(await linearRelease.lockOf(await alice.getAddress())).to.be.eq(ethers.utils.parseEther("10500"));
// 9. Bob come in and join the party
// 2 blocks are mined here, hence Alice should get 10,000 ALPACAs more
await stoken0AsBob.approve(fairLaunchV2.address, ethers.utils.parseEther("100"));
await fairLaunchV2AsBob.deposit(await bob.getAddress(), 0, ethers.utils.parseEther("100"));
expect(await fairLaunchV2.pendingAlpaca(0, await alice.getAddress())).to.be.eq(ethers.utils.parseEther("10000"));
expect(await alpacaToken.balanceOf(await dev.getAddress())).to.be.eq(ethers.utils.parseEther("5500"));
// 10. Trigger random update pool to make 1 more block mine
await fairLaunchV2.massUpdatePools([0]);
// 11. Check pendingAlpaca
// Reward per Block must now share amoung Bob and Alice (50-50)
// Alice should has 12,500 ALPACAs (10,000 + 2,500)
// Bob should has 2,500 ALPACAs
// Dev get 10% tax per block (5,000*0.1 = 500/block)
expect(await fairLaunchV2.pendingAlpaca(0, await alice.getAddress())).to.be.eq(ethers.utils.parseEther("12500"));
expect(await fairLaunchV2.pendingAlpaca(0, await bob.getAddress())).to.be.eq(ethers.utils.parseEther("2500"));
expect(await alpacaToken.balanceOf(await dev.getAddress())).to.be.eq(ethers.utils.parseEther("6000"));
// 12. Trigger random update pool to make 1 more block mine
await fairLaunchV2AsAlice.massUpdatePools([0]);
// 13. Check pendingAlpaca
// Reward per Block must now share amoung Bob and Alice (50-50)
// Alice should has 15,000 ALPACAs (12,500 + 2,500)
// Bob should has 5,000 ALPACAs (2,500 + 2,500)
// Dev get 10% tax per block (5,000*0.1 = 500/block)
expect(await fairLaunchV2.pendingAlpaca(0, await alice.getAddress())).to.be.eq(ethers.utils.parseEther("15000"));
expect(await fairLaunchV2.pendingAlpaca(0, await bob.getAddress())).to.be.eq(ethers.utils.parseEther("5000"));
expect(await alpacaToken.balanceOf(await dev.getAddress())).to.be.eq(ethers.utils.parseEther("6500"));
// 14. Bob harvest his yield
// Reward per Block is till (50-50) as Bob is not leaving the pool yet
// Alice should has 17,500 ALPACAs (15,000 + 2,500) in pending
// Bob should has 7,500 * 0.3 = 2,250 ALPACAs (5,000 + 2,500) in his account as he harvest it
// Dev get 10% tax per block (5,000*0.1 = 500/block)
await fairLaunchV2AsBob.harvest(0);
expect(await fairLaunchV2.pendingAlpaca(0, await alice.getAddress())).to.be.eq(ethers.utils.parseEther("17500"));
expect(await fairLaunchV2.pendingAlpaca(0, await bob.getAddress())).to.be.eq(ethers.utils.parseEther("0"));
expect(await alpacaToken.balanceOf(await bob.getAddress())).to.be.eq(ethers.utils.parseEther("2250"));
expect(await alpacaToken.balanceOf(await dev.getAddress())).to.be.eq(ethers.utils.parseEther("7000"));
expect(await linearRelease.lockOf(await alice.getAddress())).to.be.eq(ethers.utils.parseEther("10500"));
expect(await linearRelease.lockOf(await bob.getAddress())).to.be.eq(ethers.utils.parseEther("5250"));
// Make random event
await fairLaunchV2.massUpdatePools([0]);
const [, alicePendingRewardsT0] = await linearReleaseAsAlice.pendingTokens(await alice.getAddress());
const [, bobPendingRewardsT0] = await linearReleaseAsBob.pendingTokens(await bob.getAddress());
expect(await alpacaToken.balanceOf(await alice.getAddress())).to.be.eq(ethers.utils.parseEther("4500"));
expect(await alpacaToken.balanceOf(await bob.getAddress())).to.be.eq(ethers.utils.parseEther("2250"));
expect(alicePendingRewardsT0[0]).to.be.eq(ethers.utils.parseEther("2100"));
expect(bobPendingRewardsT0[0]).to.be.eq(ethers.utils.parseEther("1050"));
await linearReleaseAsAlice.claim();
const [, alicePendingRewardsT1] = await linearReleaseAsAlice.pendingTokens(await alice.getAddress());
const [, bobPendingRewardsT1] = await linearReleaseAsBob.pendingTokens(await bob.getAddress());
expect(await alpacaToken.balanceOf(await alice.getAddress())).to.be.eq(ethers.utils.parseEther("8700"));
expect(await alpacaToken.balanceOf(await bob.getAddress())).to.be.eq(ethers.utils.parseEther("2250"));
expect(alicePendingRewardsT1[0]).to.be.eq(ethers.utils.parseEther("0"));
expect(bobPendingRewardsT1[0]).to.be.eq(ethers.utils.parseEther("2100"));
await linearReleaseAsBob.claim();
const [, alicePendingRewardsT2] = await linearReleaseAsAlice.pendingTokens(await alice.getAddress());
const [, bobPendingRewardsT2] = await linearReleaseAsBob.pendingTokens(await bob.getAddress());
expect(await alpacaToken.balanceOf(await alice.getAddress())).to.be.eq(ethers.utils.parseEther("8700"));
expect(await alpacaToken.balanceOf(await bob.getAddress())).to.be.eq(ethers.utils.parseEther("5400"));
expect(alicePendingRewardsT2[0]).to.be.eq(ethers.utils.parseEther("2100"));
expect(bobPendingRewardsT2[0]).to.be.eq(ethers.utils.parseEther("0"));
await fairLaunchV2.massUpdatePools([0]);
await fairLaunchV2.massUpdatePools([0]);
await linearReleaseAsAlice.claim();
await linearReleaseAsBob.claim();
expect(await alpacaToken.balanceOf(await alice.getAddress())).to.be.eq(ethers.utils.parseEther("15000"));
expect(await alpacaToken.balanceOf(await bob.getAddress())).to.be.eq(ethers.utils.parseEther("7500"));
});
});
context("when migrate from FLV1 to FLV2", async () => {
it("should migrate successfully", async () => {
// 1. Mint STOKEN0 for staking
await stoken0AsDeployer.mint(await alice.getAddress(), ethers.utils.parseEther("400"));
await stoken0AsDeployer.mint(await bob.getAddress(), ethers.utils.parseEther("100"));
// 2. Add STOKEN0 to the fairLaunch pool
await fairLaunchAsDeployer.addPool(1, stakingTokens[0].address, false);
// 3. Alice deposit STOKEN0 to the STOKEN0 pool
await stoken0AsAlice.approve(fairLaunch.address, ethers.utils.parseEther("100"));
await fairLaunchAsAlice.deposit(await alice.getAddress(), 0, ethers.utils.parseEther("100"));
// 4. Trigger random update pool to make 1 more block mine
await fairLaunch.massUpdatePools();
// 5. Check pendingAlpaca for Alice
expect(await fairLaunch.pendingAlpaca(0, await alice.getAddress())).to.be.eq(ethers.utils.parseEther("5000"));
// 6. Trigger random update pool to make 1 more block mine
await fairLaunch.massUpdatePools();
// 7. Check pendingAlpaca for Alice
expect(await fairLaunch.pendingAlpaca(0, await alice.getAddress())).to.be.eq(ethers.utils.parseEther("10000"));
// 8. Alice should get 15,000 ALPACAs when she harvest
// also check that dev got his tax
// PS. Dev get 1,500 = as 10% as Alice
await fairLaunchAsAlice.harvest(0);
expect(await alpacaToken.balanceOf(await alice.getAddress())).to.be.eq(ethers.utils.parseEther("15000"));
expect(await alpacaToken.balanceOf(await dev.getAddress())).to.be.eq(ethers.utils.parseEther("1500"));
// 9. Bob come in and join the party
// 2 blocks are mined here, hence Alice should get 10,000 ALPACAs more (2x5,000)
await stoken0AsBob.approve(fairLaunch.address, ethers.utils.parseEther("100"));
await fairLaunchAsBob.deposit(await bob.getAddress(), 0, ethers.utils.parseEther("100"));
expect(await fairLaunch.pendingAlpaca(0, await alice.getAddress())).to.be.eq(ethers.utils.parseEther("10000"));
expect(await alpacaToken.balanceOf(await dev.getAddress())).to.be.eq(ethers.utils.parseEther("2500"));
// 10. Trigger random update pool to make 1 more block mine
await fairLaunch.massUpdatePools();
// 11. Start to migrate FLV1 to FLV2
// add Link pool to FLV1 first, then turn off all pools on FLV1
await fairLaunch.addPool(1, fairLaunchLink.address, false);
await fairLaunch.setPool(0, 0, false);
// 12. Alice & Bob exit FLV1
// Alice +10,000+2,500+2,500
// Bob +2,500+2,500
await fairLaunchAsAlice.withdraw(await alice.getAddress(), 0, ethers.utils.parseEther("100"));
await fairLaunchAsBob.withdraw(await bob.getAddress(), 0, ethers.utils.parseEther("100"));
expect(await alpacaToken.balanceOf(await alice.getAddress())).to.be.eq(ethers.utils.parseEther("30000"));
expect(await alpacaToken.balanceOf(await bob.getAddress())).to.be.eq(ethers.utils.parseEther("5000"));
expect(await alpacaToken.balanceOf(await dev.getAddress())).to.be.eq(ethers.utils.parseEther("3500"));
// 13. Initialized fairLaunchV2
await fairLaunchLink.mint(await deployer.getAddress(), ethers.utils.parseEther("1"));
await fairLaunchLink.approve(fairLaunchV2.address, ethers.utils.parseEther("1"));
// 14. Add STOKEN0 to the fairLaunchV2 pool
// start at blockNumber + 5 as we want to make sure that Alice & Bob have time to onboard
const startBlock = (await TimeHelpers.latestBlockNumber()).add(6);
await fairLaunchV2AsDeployer.addPool(1, stakingTokens[0].address, ADDRESS0, startBlock);
// 15. Alice & Bob deposit STOKEN0 to the STOKEN0 pool
await stoken0AsAlice.approve(fairLaunchV2.address, ethers.utils.parseEther("100"));
await fairLaunchV2AsAlice.deposit(await alice.getAddress(), 0, ethers.utils.parseEther("100"));
await stoken0AsBob.approve(fairLaunchV2.address, ethers.utils.parseEther("100"));
await fairLaunchV2AsBob.deposit(await bob.getAddress(), 0, ethers.utils.parseEther("100"));
// 16. Trigger random update pool to make 1 more block mine
await fairLaunchV2.massUpdatePools([0]);
// 17. Check pendingAlpaca for Alice & Bob. Expected to be 0 as pool has no allocPoint yet
// expect dev token to be the same amount as no alpaca has been mint
expect(await fairLaunchV2.pendingAlpaca(0, await alice.getAddress())).to.be.eq(ethers.utils.parseEther("0"));
expect(await fairLaunchV2.pendingAlpaca(0, await alice.getAddress())).to.be.eq(ethers.utils.parseEther("0"));
expect(await alpacaToken.balanceOf(await dev.getAddress())).to.be.eq(ethers.utils.parseEther("3500"));
await fairLaunchV2.init(fairLaunchLink.address);
// 18. Set allocPoint to 1 to continue mintting ALPACAs
// Rewards kick-in here
await fairLaunch.setPool(1, 1, false);
// 19. Trigger random update pool to make 1 more block mine
await fairLaunchV2AsAlice.massUpdatePools([0]);
// 20. Now Alice and Bob should get some ALPACAs
// Check pendingAlpaca for Alice & Bob
expect(await fairLaunchV2.pendingAlpaca(0, await alice.getAddress())).to.be.eq(ethers.utils.parseEther("7500"));
expect(await fairLaunchV2.pendingAlpaca(0, await alice.getAddress())).to.be.eq(ethers.utils.parseEther("7500"));
expect(await alpacaToken.balanceOf(await dev.getAddress())).to.be.eq(ethers.utils.parseEther("4500"));
// 21. Alice should get 10,000 ALPACAs when she harvest
// also check that dev got his tax
// PS. Dev get 5,000 as mining continue 2 blocks earlier
await fairLaunchV2AsAlice.harvest(0);
expect(await alpacaToken.balanceOf(await alice.getAddress())).to.be.eq(ethers.utils.parseEther("40000"));
expect(await alpacaToken.balanceOf(await dev.getAddress())).to.be.eq(ethers.utils.parseEther("5000"));
});
});
}); | the_stack |
import * as vscode from 'vscode';
import { Plugin } from '../plugin';
import { ThemeConfig, getConfigValue, CSS_LEFT, CSS_TOP } from '../config/config';
export type ExplosionOrder = 'random' | 'sequential' | number;
export type BackgroundMode = 'mask' | 'image';
export type GifMode = 'continue' | 'restart';
export interface ExplosionConfig {
enableExplosions: boolean;
maxExplosions: number;
explosionSize: number;
explosionFrequency: number;
explosionOffset: number;
explosionDuration: number;
customExplosions: string[];
explosionOrder: ExplosionOrder;
backgroundMode: BackgroundMode;
gifMode: GifMode
customCss?: {[key: string]: string};
}
export class CursorExploder implements Plugin {
private config: ExplosionConfig = {} as ExplosionConfig;
private activeDecorations: vscode.TextEditorDecorationType[] = [];
private keystrokeCounter = -1;
private explosionIndex = -1;
private counterTimeout: NodeJS.Timer;
constructor(public themeConfig: ThemeConfig) {}
onThemeChanged = (theme: ThemeConfig) => {
this.themeConfig = theme;
this.initialize();
}
activate = () => {
// Do nothing
this.initialize();
}
dispose = () => {
this.onPowermodeStop();
}
public onPowermodeStart = (combo?: number) => {
// Do nothing
}
public onPowermodeStop = (combo?: number) => {
// Dispose all explosions
while(this.activeDecorations.length > 0) {
this.activeDecorations.shift().dispose();
}
}
public onDidChangeTextDocument = (combo: number, powermode: boolean, event: vscode.TextDocumentChangeEvent) => {
if (!this.config.enableExplosions || !powermode) {
return;
}
// If the content change is empty then it was likely a delete
// This means there may not be text after the cursor, so do the
// explosion before instead.
const changes = event.contentChanges[0];
const left = changes && changes.text.length === 0;
this.explode(left);
}
public onDidChangeConfiguration = (config: vscode.WorkspaceConfiguration) => {
const newConfig: ExplosionConfig = {
customExplosions: getConfigValue<string[]>('customExplosions', config, this.themeConfig),
enableExplosions: getConfigValue<boolean>('enableExplosions', config, this.themeConfig),
maxExplosions: getConfigValue<number>('maxExplosions', config, this.themeConfig),
explosionSize: getConfigValue<number>('explosionSize', config, this.themeConfig),
explosionFrequency: getConfigValue<number>('explosionFrequency', config, this.themeConfig),
explosionOffset: getConfigValue<number>('explosionOffset', config, this.themeConfig),
explosionOrder: getConfigValue<ExplosionOrder>('explosionOrder', config, this.themeConfig),
explosionDuration: getConfigValue<number>('explosionDuration', config, this.themeConfig),
backgroundMode: getConfigValue<BackgroundMode>('backgroundMode', config, this.themeConfig),
gifMode: getConfigValue<GifMode>('gifMode', config, this.themeConfig),
customCss: getConfigValue<any>('customCss', config, this.themeConfig),
}
let changed = false;
Object.keys(newConfig).forEach(key => {
if (this.config[key] !== newConfig[key]) {
changed = true;
}
});
if (!changed) {
return;
}
this.config = newConfig;
this.initialize();
}
public initialize = () => {
this.dispose();
if (!this.config.enableExplosions) {
return;
}
this.explosionIndex = -1;
this.keystrokeCounter = -1;
}
private getExplosionDecoration = (position: vscode.Position): vscode.TextEditorDecorationType => {
let explosions = this.config.customExplosions;
const explosion = this.pickExplosion(explosions);
if (!explosion) {
return null;
}
return this.createExplosionDecorationType(explosion, position);
}
private pickExplosion(explosions: string[]): string {
if (!explosions) {
return null;
}
switch (typeof this.config.explosionOrder) {
case 'string':
switch (this.config.explosionOrder) {
case 'random':
this.explosionIndex = getRandomInt(0, explosions.length);
break;
case 'sequential':
this.explosionIndex = (this.explosionIndex + 1) % explosions.length;
break;
default:
this.explosionIndex = 0;
}
break;
case 'number':
this.explosionIndex = Math.min(explosions.length - 1, Math.floor(Math.abs(this.config.explosionOrder as number)));
default:
break;
}
return explosions[this.explosionIndex];
}
/**
* @returns an decoration type with the configured background image
*/
private createExplosionDecorationType = (explosion: string, editorPosition: vscode.Position ): vscode.TextEditorDecorationType => {
// subtract 1 ch to account for the character and divide by two to make it centered
// Use Math.floor to skew to the right which especially helps when deleting chars
const leftValue = Math.floor((this.config.explosionSize - 1) / 2);
// By default, the top of the gif will be at the top of the text.
// Setting the top to a negative value will raise it up.
// The default gifs are "tall" and the bottom halves are empty.
// Lowering them makes them appear in a more natural position,
// but limiting the top to the line number keeps it from going
// off the top of the editor
const topValue = this.config.explosionSize * this.config.explosionOffset;
const explosionUrl = this.getExplosionUrl(explosion);
const backgroundCss = this.config.backgroundMode === 'mask' ?
this.getMaskCssSettings(explosionUrl) :
this.getBackgroundCssSettings(explosionUrl);
const defaultCss = {
position: 'absolute',
[CSS_LEFT] : `-${leftValue}ch`,
[CSS_TOP]: `-${topValue}rem`,
width: `${this.config.explosionSize}ch`,
height: `${this.config.explosionSize}rem`,
display: `inline-block`,
['z-index']: 1,
['pointer-events']: 'none',
};
const backgroundCssString = this.objectToCssString(backgroundCss);
const defaultCssString = this.objectToCssString(defaultCss);
const customCssString = this.objectToCssString(this.config.customCss || {});
return vscode.window.createTextEditorDecorationType(<vscode.DecorationRenderOptions>{
before: {
contentText: '',
textDecoration: `none; ${defaultCssString} ${backgroundCssString} ${customCssString}`,
},
textDecoration: `none; position: relative;`,
rangeBehavior: vscode.DecorationRangeBehavior.ClosedClosed,
});
}
private getExplosionUrl(explosion: string): string {
if (this.config.gifMode !== 'restart') {
return explosion;
}
if (this.isUrl(explosion)) {
return `${explosion}?timestamp=${Date.now()}`;
} else {
// https://tools.ietf.org/html/rfc2397
return explosion.replace('base64,', `timestamp=${Date.now()};base64,`);
}
}
private isUrl(value: string): boolean {
return value.indexOf('https') === 0;
}
private getBackgroundCssSettings(explosion: string) {
return {
'background-repeat': 'no-repeat',
'background-size': 'contain',
'background-image': `url("${explosion}")`,
}
}
private getMaskCssSettings(explosion: string): any {
return {
'background-color': 'currentColor',
'-webkit-mask-repeat': 'no-repeat',
'-webkit-mask-size': 'contain',
'-webkit-mask-image': `url("${explosion}")`,
filter: 'saturate(150%)',
}
}
private objectToCssString(settings: any): string {
let value = '';
const cssString = Object.keys(settings).map(setting => {
value = settings[setting];
if (typeof value === 'string' || typeof value === 'number') {
return `${setting}: ${value};`
}
}).join(' ');
return cssString;
}
/**
* "Explodes" where the cursor is by setting a text decoration
* that contains a base64 encoded gif as the background image.
* The gif is then removed 1 second later
*
* @param {boolean} [left=false] place the decoration to
* the left or the right of the cursor
*/
private explode = (left = false) => {
// To give the explosions space, only explode every X strokes
// Where X is the configured explosion frequency
// This counter resets if the user does not type for 1 second.
clearTimeout(this.counterTimeout);
this.counterTimeout = setTimeout(() => {
this.keystrokeCounter = -1;
}, 1000);
if (++this.keystrokeCounter % this.config.explosionFrequency !== 0) {
return;
}
const activeEditor = vscode.window.activeTextEditor;
const cursorPosition = vscode.window.activeTextEditor.selection.active;
// The delta is greater to the left than to the right because otherwise the gif doesn't appear
const delta = left ? -2 : 1;
const newRange = new vscode.Range(
cursorPosition.with(cursorPosition.line, cursorPosition.character),
// Value can't be negative
cursorPosition.with(cursorPosition.line, Math.max(0, cursorPosition.character + delta))
);
// Dispose excess explosions
while(this.activeDecorations.length >= this.config.maxExplosions) {
this.activeDecorations.shift().dispose();
}
// A new decoration is used each time because otherwise adjacent
// gifs will all be identical. This helps them be at least a little
// offset.
const decoration = this.getExplosionDecoration(newRange.start);
if (!decoration) {
return;
}
this.activeDecorations.push(decoration);
if (this.config.explosionDuration !== 0) {
setTimeout(() => {
decoration.dispose();
}, this.config.explosionDuration);
}
activeEditor.setDecorations(decoration, [newRange]);
}
}
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive
} | the_stack |
import { useColorMode } from "@docusaurus/theme-common";
import Box from "@mui/material/Box";
import Button from "@mui/material/Button";
import Checkbox from "@mui/material/Checkbox";
import Container from "@mui/material/Container";
import FormControl from "@mui/material/FormControl";
import FormControlLabel from "@mui/material/FormControlLabel";
import FormGroup from "@mui/material/FormGroup";
import FormLabel from "@mui/material/FormLabel";
import Grid from "@mui/material/Grid";
import Paper from "@mui/material/Paper";
import Radio from "@mui/material/Radio";
import RadioGroup from "@mui/material/RadioGroup";
import { ThemeProvider, createTheme } from "@mui/material/styles";
import TextField from "@mui/material/TextField";
import Typography from "@mui/material/Typography";
import LogoDark from "@site/static/img/Logo-dark.svg";
import Logo from "@site/static/img/Logo.svg";
import Layout from "@theme/Layout";
import { useMemo, useState } from "react";
import { Controller, useForm, Control } from "react-hook-form";
import { FunctionlessHighlighter } from "../components/highlighter";
// https://legacydocs.hubspot.com/docs/methods/forms/submit_form
interface HubSpotFormSubmission {
// This millisecond timestamp is optional. Update the value from "1517927174000" to avoid an INVALID_TIMESTAMP error
submittedAt?: string;
fields: {
objectTypeId: string;
name: string;
value: string;
}[];
context?: {
// include this parameter and set it to the hubspotutk cookie value to enable cookie tracking on your submission
hutk?: string;
pageUri?: string;
pageName?: string;
};
legalConsentOptions?: {
consent: {
// Include this object when GDPR options are enabled
consentToProcess: boolean;
text: string;
communications: {
value: boolean;
subscriptionTypeId: number;
text: string;
}[];
};
};
}
enum HubSpotTypeId {
SingleLineText = "0-1",
}
const submit = async (formData: FormData) => {
// field names that match the hub spot form field names
const { email, company } = formData;
const fields = {
email,
company,
firstname: formData.firstName,
lastname: formData.lastName,
company_size: formData.companySize,
jobtitle: formData.role,
// https://legacydocs.hubspot.com/docs/faq/how-do-i-set-multiple-values-for-checkbox-properties
iac_experience: (formData.iac ?? []).join(";"),
iac_other: formData.iacOther,
};
await fetch(
"https://api.hsforms.com/submissions/v3/integration/submit/22084824/9e8475ef-7968-4cdf-ab9d-cf1377216fef",
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
fields: Object.entries(fields)
.filter(([_, value]) => typeof value !== "undefined")
.map(([key, value]) => ({
name: key,
value,
objectTypeId: HubSpotTypeId.SingleLineText,
})),
context: {
pageName: "Sign Up",
pageUri: location.href,
},
} as HubSpotFormSubmission),
}
);
};
export default function FormPage() {
return (
<Layout>
<Themed />
</Layout>
);
}
function Themed() {
const { colorMode } = useColorMode();
const theme = useMemo(
() =>
createTheme({
palette: {
mode: colorMode,
},
}),
[colorMode]
);
return (
<ThemeProvider theme={theme}>
<Form />
</ThemeProvider>
);
}
const InitialForm = (props: { control: Control<FormData, any> }) => {
return (
<>
<Grid container spacing={2}>
<Grid item xs={12} sm={6}>
<Controller
name="firstName"
control={props.control}
render={({ field }) => (
<TextField
{...field}
autoComplete="given-name"
required
fullWidth
label="First Name"
autoFocus
/>
)}
/>
</Grid>
<Grid item xs={12} sm={6}>
<Controller
name="lastName"
control={props.control}
render={({ field }) => (
<TextField
{...field}
required
fullWidth
label="Last Name"
autoComplete="family-name"
/>
)}
/>
</Grid>
<Grid item xs={12}>
<Controller
name="email"
control={props.control}
render={({ field }) => (
<TextField
{...field}
required
fullWidth
label="Email Address"
autoComplete="email"
/>
)}
/>
</Grid>
</Grid>
<Button type="submit" fullWidth variant="contained" sx={{ mt: 3, mb: 2 }}>
Submit
</Button>
</>
);
};
const SecondForm = (props: { control: Control<FormData, any> }) => {
const [iacOtherSelected, setIacOtherSelected] = useState<boolean>(false);
return (
<>
<Grid container spacing={2}>
<Grid item xs={12} sm={6}>
<Controller
name="company"
control={props.control}
render={({ field }) => (
<TextField {...field} fullWidth label="Company name" autoFocus />
)}
/>
</Grid>
<Grid item xs={12} sm={6}>
<Controller
name="role"
control={props.control}
render={({ field }) => (
<TextField {...field} fullWidth label="Job Title" />
)}
/>
</Grid>
<Grid item xs={12}>
<FormControl>
<FormLabel id="demo-radio-buttons-group-label">
Company Size
</FormLabel>
<Controller
name="companySize"
control={props.control}
render={({ field }) => (
<RadioGroup {...field}>
{Object.entries(CompanySizes).map(([key, label]) => (
<FormControlLabel
value={key}
control={<Radio />}
label={label}
/>
))}
</RadioGroup>
)}
/>
</FormControl>
</Grid>
<Grid item xs={12}>
<FormGroup>
<Controller
name="iac"
control={props.control}
render={({ field }) => (
<>
{Object.entries(IaCOptions).map(([key, label]) => (
<FormControlLabel
{...field}
key={key}
label={label}
control={
<Checkbox
onChange={() => {
const items = !field?.value?.includes(key as any)
? [...(field.value ?? []), key]
: field.value.filter((topic) => topic !== key);
setIacOtherSelected(
items.includes("Something Else")
);
field.onChange(items);
}}
/>
}
/>
))}
</>
)}
/>{" "}
</FormGroup>
{iacOtherSelected ? (
<Controller
name="iacOther"
control={props.control}
render={({ field }) => (
<TextField {...field} fullWidth label="Other IaC" />
)}
/>
) : undefined}
</Grid>
</Grid>
<Button type="submit" fullWidth variant="contained" sx={{ mt: 3, mb: 2 }}>
Submit
</Button>
</>
);
};
const Confirmation = () => {
return (
<Paper elevation={2} sx={{ padding: 3 }}>
Thank you for your interest in Functionless. Expect updates soon.
</Paper>
);
};
interface InitialFormData {
firstName: string;
lastName: string;
email: string;
}
// Hubspot internal value -> label
const IaCOptions = {
"Azure Resource Manager": "Azure Resource Manager",
"CDK (Cloud Development Kit)": "CDK (Cloud Development Kit)",
CloudFormation: "CloudFormation",
Pulumi: "Pulumi",
"Serverless Stack": "Serverless Stack",
Terraform: "Terraform",
"Terraform CDK": "Terraform CDK",
None: "None",
"Something Else": "Other",
} as const;
type IaC = keyof typeof IaCOptions;
// Hubspot internal value -> label
const CompanySizes = {
"1": "1",
"2": "2-5",
"6": "6-30",
"31": "31-99",
"100": "100+",
} as const;
type CompanySize = keyof typeof CompanySizes;
interface FormData extends InitialFormData {
company?: string;
companySize?: CompanySize;
iac?: IaC[];
role?: string;
iacOther?: string;
}
const Form = () => {
const [formState, setFormState] = useState<"initial" | "second" | "complete">(
"initial"
);
const [initialFormData, setFormData] = useState<
InitialFormData | undefined
>();
const { control, handleSubmit } = useForm<FormData>();
const innerSubmit = (
formData: FormData,
event?: React.BaseSyntheticEvent
) => {
event?.preventDefault();
if (formState === "initial") {
submit(formData).catch(() => {});
setFormData(formData);
setFormState("second");
} else if (formState === "second") {
submit({
...formData,
...initialFormData!,
}).catch(() => {});
setFormState("complete");
}
};
const { colorMode } = useColorMode();
return (
<Container component="main" maxWidth="xl">
<Box
sx={{
alignItems: "center",
marginTop: 2,
display: "flex",
flexDirection: "column",
}}
></Box>
<Grid container>
<Grid container>
<Grid item md={4} xs={12}>
<Box
sx={{
alignItems: "center",
marginTop: { md: 9, xs: 1 },
margin: { md: 4, xs: 1 },
display: "flex",
flexDirection: "column",
}}
>
<Typography component="h1" variant="h5">
Receive updates on Functionless.
</Typography>
</Box>
</Grid>
<Grid item md={6} sx={{ display: { xs: "none", md: "block" } }}>
<Box
sx={{
alignItems: "center",
marginTop: 8,
margin: 4,
display: "flex",
flexDirection: "column",
}}
>
<Typography component="h1" variant="h5">
Write your application and infrastructure code together with
Functionless
</Typography>
</Box>
</Grid>
<Grid item md={2} sx={{ display: { xs: "none", md: "block" } }}>
{colorMode === "dark" ? <LogoDark /> : <Logo />}
</Grid>
</Grid>
<Grid item md={4} xs={12}>
<Box
sx={{
display: "flex",
flexDirection: "column",
alignItems: "center",
}}
>
<Box
component="form"
noValidate
onSubmit={handleSubmit(innerSubmit)}
sx={{ mt: 4 }}
>
{formState === "initial" ? (
<InitialForm control={control} />
) : formState === "second" ? (
<SecondForm control={control} />
) : (
<Confirmation />
)}
</Box>
</Box>
</Grid>
<Grid item md={8} sx={{ display: { xs: "none", md: "block" } }}>
<Box
sx={{
alignItems: "left",
margin: 4,
display: "flex",
flexDirection: "column",
}}
>
<FunctionlessHighlighter>
{`const bus = new EventBus<Event<{ name: string }>>(this, 'bus');
const validateName = new Function<string, boolean>(this, 'validateName', async (name) => {
const result = await fetch(\`http://my.domain.com/validate/\${name}\`);
return result.status === 200;
});
const sfn = new StepFunction(this, 'sfn', (props: {name: string}) => {
// if name is valid
if(validateName(name)) {
// send a notification to the event bus.
bus.putEvents({
source: 'magicApplication',
'detail-type': 'form-submit',
detail: {
name
}
});
}
});
sfn.onFailed('failedRule').pipe(new Function(this, 'failedWorkflows', async (event) => {
console.log(event);
});
`}
</FunctionlessHighlighter>
</Box>
</Grid>
</Grid>
</Container>
);
}; | the_stack |
import quip from "quip-apps-api";
import React from "react";
import {connect} from "react-redux";
import classNames from "classnames";
import chunk from "lodash.chunk";
import throttle from "lodash.throttle";
import startOfWeek from "date-fns/startOfWeek";
import endOfWeek from "date-fns/endOfWeek";
import eachDayOfInterval from "date-fns/eachDayOfInterval";
import Styles from "./Calendar.less";
import StylesCalendarEvent from "./CalendarEvent.less";
import {EventRecord, RootRecord} from "../model";
import {formatDate} from "../util";
import {
refreshEvents,
setDebugProp,
setIsSmallScreen,
setFocusedEvent,
setResizingEvent,
setMouseCoordinates,
setMovingEvent,
setMovingEventOrder,
setMovingEventRectMap,
setSelectedEvent,
} from "../actions";
import {
areDateRangesEqual,
isSameDay,
dateAtPoint,
getCalendarMonth,
getIsSmallScreen,
getMovingEventDateRange,
getMovingEventRectMap,
getResizingEventDateRange,
isElAtPoint,
} from "../util";
import agendaForWeek from "../agendaForWeek";
import CalendarNavHeader from "./CalendarNavHeader";
import CalendarWeek from "./CalendarWeek";
import EventLegend from "./EventLegend";
import {
MouseCoordinates,
MouseStartCoordinates,
MovingEventOrder,
} from "../types";
const {CONTAINER_SIZE_UPDATE, ELEMENT_BLUR} = quip.apps.EventType;
const BUTTON_RIGHT_CLICK = 2;
const BACKSPACE_KEY = 8;
const DELETE_KEY = 46;
const isClickOnCalendarEvent = (xy: MouseCoordinates) =>
isElAtPoint(xy, StylesCalendarEvent.event);
type Props = {
DEBUG_ORDER: boolean;
displayMonth: Date;
events: Array<EventRecord>;
focusedEvent: EventRecord;
isMobileApp: boolean;
isSmallScreen: boolean;
menuOpenRecord: EventRecord;
mouseCoordinates: MouseCoordinates;
mouseStartCoordinates: MouseStartCoordinates;
movingEvent: EventRecord | undefined | null;
movingEventOrder: MovingEventOrder | undefined | null;
refreshEvents: Function;
resizingEvent: EventRecord | undefined | null;
rootRecord: RootRecord;
selectedEvent: EventRecord;
setDebugProp: Function;
setFocusedEvent: Function;
setMouseCoordinates: Function;
setMovingEvent: Function;
setMovingEventOrder: Function;
setMovingEventRectMap: Function;
setIsSmallScreen: Function;
setResizingEvent: Function;
setSelectedEvent: Function;
};
class Calendar extends React.Component<Props, null> {
componentWillMount() {
quip.apps.addEventListener(
CONTAINER_SIZE_UPDATE,
this.handleContainerResize);
quip.apps.addEventListener(ELEMENT_BLUR, this.onElementBlur);
window.addEventListener("keydown", this.onKeyDown);
window.document.body.addEventListener("mouseout", this.onBodyMouseOut);
}
componentDidMount() {
this.props.rootRecord.listen(this.refresh);
}
componentWillUnmount() {
quip.apps.removeEventListener(
CONTAINER_SIZE_UPDATE,
this.handleContainerResize);
quip.apps.removeEventListener(ELEMENT_BLUR, this.onElementBlur);
window.removeEventListener("keydown", this.onKeyDown);
window.document.body.removeEventListener(
"mouseout",
this.onBodyMouseOut);
this.props.rootRecord.unlisten(this.refresh);
}
refresh = () => {
this.props.refreshEvents(this.props.rootRecord);
};
onElementBlur = () => {
this.props.setFocusedEvent(null);
this.props.setSelectedEvent(null);
};
handleContainerResize = () => {
this.props.setIsSmallScreen(getIsSmallScreen());
};
onBodyMouseOut = e => {
if (e.relatedTarget === window.document.querySelector("html")) {
this.onMouseUp(e);
}
};
onMouseDown = e => {
const {
isSmallScreen,
menuOpenRecord,
movingEvent,
resizingEvent,
rootRecord,
selectedEvent,
focusedEvent,
} = this.props;
if (e.button === BUTTON_RIGHT_CLICK) {
return;
}
console.log(
"Calendar onMouseDown",
"resizing",
resizingEvent,
"moving",
movingEvent,
"selected",
selectedEvent,
"focused",
focusedEvent,
e.button,
isSmallScreen);
const mouseCoordinates = {
x: e.pageX,
y: e.pageY,
};
const dateUnderMouse = dateAtPoint(mouseCoordinates);
const isClickOnEvent = isClickOnCalendarEvent(mouseCoordinates);
if (dateUnderMouse && !menuOpenRecord && !isClickOnEvent) {
if (selectedEvent || focusedEvent) {
console.log(
"NOT CALLING addEvent b/c selectedEvent",
selectedEvent,
" || focusedEvent",
focusedEvent);
} else {
const newEvent = rootRecord.addEvent(
dateUnderMouse,
dateUnderMouse);
console.log(
"^^^^^^ addEvent dateUnderMouse",
dateUnderMouse,
newEvent);
this.props.setFocusedEvent(newEvent);
this.refresh();
}
} else if (!isSmallScreen && !isClickOnEvent) {
this.props.setFocusedEvent(null);
}
this.props.setSelectedEvent(null);
};
updateEventFromMouseCoordinates = throttle(
mouseCoordinates => {
const {
mouseStartCoordinates,
movingEvent,
resizingEvent,
setMouseCoordinates,
setMovingEventOrder,
setMovingEventRectMap,
} = this.props;
let draggingEventDateRange;
if (resizingEvent) {
draggingEventDateRange = getResizingEventDateRange(
resizingEvent,
mouseCoordinates);
} else if (movingEvent) {
draggingEventDateRange = getMovingEventDateRange(
movingEvent,
mouseCoordinates,
mouseStartCoordinates);
const rectMap = getMovingEventRectMap(
movingEvent,
mouseStartCoordinates,
mouseCoordinates);
setMovingEventRectMap(rectMap);
// To figure out the new order position we use the start datetime
const movingEventRect =
rectMap[
startOfWeek(movingEvent.getDateRange().start).getTime()
];
const newOrder = this.getMovingEventOrder(
movingEvent,
movingEventRect,
draggingEventDateRange);
setMovingEventOrder(newOrder);
}
setMouseCoordinates(mouseCoordinates, draggingEventDateRange);
},
20,
{
trailing: true,
});
getMovingEventOrder(
movingEvent,
movingEventRect,
draggingEventDateRange
): MovingEventOrder {
const {rootRecord} = this.props;
const movingEventId = movingEvent.id();
const events = rootRecord
.getEventsByStartDate(draggingEventDateRange.start)
.filter(event => event.id() !== movingEventId);
const isReOrderOnSameDay = isSameDay(
movingEvent.getDateRange().start,
draggingEventDateRange.start);
const curIndex = movingEvent.getIndex();
if (!events.length) {
const index = isReOrderOnSameDay
? curIndex
: rootRecord.getNextIndexForStartDate(
draggingEventDateRange.start,
movingEvent);
return {
closestEvent: null,
index,
};
}
let closestEvent;
let isBefore = false;
let distance;
// This is the middle of the moving el
const yMoving = movingEventRect.top + movingEventRect.height / 2;
events.forEach(event => {
const rect = event.getDomEvent().getBoundingClientRect();
const yMid = rect.top + rect.height / 2;
const yDistance = Math.abs(yMoving - yMid);
if (!distance || yDistance < distance) {
distance = yDistance;
isBefore = yMoving <= yMid;
closestEvent = event;
/*
console.log(
"!winner!",
closestEvent.getTitleText(),
"yMoving",
yMoving,
"mid",
yMid,
"isBefore?",
isBefore,
);
*/
}
});
let index = curIndex;
if (closestEvent) {
index = closestEvent.getIndex();
if (index > curIndex) {
index--;
}
if (!isBefore) {
index++;
}
}
return {
closestEvent,
index,
// We need to preserve this info because we may have
// mutated the index to account for the same day case.
isBefore,
};
}
onMouseMove = e => {
const {movingEvent, resizingEvent} = this.props;
if (!(resizingEvent || movingEvent)) {
return;
}
let mouseCoordinates = {
x: e.pageX,
y: e.pageY,
};
this.updateEventFromMouseCoordinates(mouseCoordinates);
};
onMouseUp = e => {
const {
focusedEvent,
mouseCoordinates,
mouseStartCoordinates,
movingEvent,
movingEventOrder,
resizingEvent,
selectedEvent,
} = this.props;
if (e.button === BUTTON_RIGHT_CLICK) {
return;
}
console.log(
"Calendar onMouseUp",
"mouseCoordinates",
mouseCoordinates,
"resizing",
resizingEvent,
"moving",
!!movingEvent,
"movingEventOrder",
movingEventOrder,
"selected",
!!selectedEvent,
"focused",
!!focusedEvent);
if (mouseCoordinates) {
if (resizingEvent) {
const newRange = getResizingEventDateRange(
resizingEvent,
mouseCoordinates);
const curRange = resizingEvent.getDateRange();
if (!areDateRangesEqual(curRange, newRange)) {
resizingEvent.setDateRange(newRange.start, newRange.end);
console.log(
"^^^^ set resizingEvent to newRange",
newRange,
"from",
curRange);
} else {
console.log("^^^^ no change for resizingEvent range");
}
this.props.setResizingEvent(null);
} else if (movingEvent) {
const curRange = movingEvent.getDateRange();
const newRange = getMovingEventDateRange(
movingEvent,
mouseCoordinates,
mouseStartCoordinates);
if (!areDateRangesEqual(curRange, newRange)) {
movingEvent.setDateRange(newRange.start, newRange.end);
console.log("^^^^ set movingEvent to newRange", newRange);
} else {
console.log("^^^^ no range change for movingEvent");
}
if (movingEventOrder) {
console.log(
"^^^^ setIndex for movingEvent",
movingEventOrder);
movingEvent.setIndex(movingEventOrder.index);
}
this.props.setMovingEvent(null);
this.props.setSelectedEvent(null);
}
} else {
this.props.setMovingEvent(null);
}
this.props.setMouseCoordinates(null);
};
onKeyDown = e => {
if (e.ctrlKey && e.shiftKey && e.key === "D") {
this.props.setDebugProp({
DEBUG_ORDER: !this.props.DEBUG_ORDER,
});
return;
}
const {isSmallScreen, selectedEvent} = this.props;
if (!selectedEvent || isSmallScreen) {
return;
}
switch (e.keyCode) {
case BACKSPACE_KEY:
case DELETE_KEY:
e.preventDefault();
selectedEvent.delete();
this.props.setSelectedEvent(null);
}
};
render() {
const {
displayMonth,
events,
isSmallScreen,
movingEvent,
resizingEvent,
} = this.props;
const weekDays = eachDayOfInterval({
start: startOfWeek(new Date()),
end: endOfWeek(new Date()),
}).map(date => formatDate(date, isSmallScreen ? "EEEEE" : "EEE"));
const weeks = chunk(getCalendarMonth(displayMonth), 7);
return <div
onMouseUp={this.onMouseUp}
onMouseMove={this.onMouseMove}
onMouseDown={this.onMouseDown}
className={classNames(Styles.Calendar, {
[Styles.moving]: !!movingEvent,
[Styles.resizing]: !!resizingEvent,
})}>
<CalendarNavHeader/>
<div className={Styles.weekHeader}>
{weekDays.map((title, i) => <div
key={`${title}-${i}`}
className={Styles.cell}>
{title}
</div>)}
</div>
<div
className={classNames(Styles.grid, {
[Styles.moving]: !!movingEvent,
[Styles.resizing]: !!resizingEvent,
})}>
{weeks.map((week, i) => <CalendarWeek
key={i}
agenda={agendaForWeek(week, events)}
week={week}/>)}
</div>
{isSmallScreen && <EventLegend/>}
</div>;
}
}
const mapStateToProps = state => ({
DEBUG_ORDER: state.DEBUG_ORDER,
displayMonth: state.displayMonth,
events: state.events,
focusedEvent: state.focusedEvent,
isMobileApp: state.isMobileApp,
isSmallScreen: state.isSmallScreen,
menuOpenRecord: state.menuOpenRecord,
mouseCoordinates: state.mouseCoordinates,
mouseStartCoordinates: state.mouseStartCoordinates,
movingEvent: state.movingEvent,
movingEventOrder: state.movingEventOrder,
resizingEvent: state.resizingEvent,
rootRecord: state.rootRecord,
selectedEvent: state.selectedEvent,
});
export default connect(mapStateToProps, {
refreshEvents,
setDebugProp,
setFocusedEvent,
setIsSmallScreen,
setMouseCoordinates,
setMovingEvent,
setMovingEventOrder,
setMovingEventRectMap,
setResizingEvent,
setSelectedEvent,
})(Calendar); | the_stack |
import * as vscode from 'vscode';
import SqlToolsServiceClient from '../languageservice/serviceclient';
import { NotificationType, RequestType } from 'vscode-languageclient';
import { TaskExecutionMode } from 'vscode-mssql';
import { Deferred } from '../protocol';
import * as utils from '../models/utils';
import * as localizedConstants from '../constants/localizedConstants';
import UntitledSqlDocumentService from '../controllers/untitledSqlDocumentService';
export enum TaskStatus {
NotStarted = 0,
InProgress = 1,
Succeeded = 2,
SucceededWithWarning = 3,
Failed = 4,
Canceled = 5,
Canceling = 6
}
// tslint:disable: interface-name
export interface TaskProgressInfo {
taskId: string;
status: TaskStatus;
message: string;
script?: string | undefined;
}
export interface TaskInfo {
taskId: string;
status: TaskStatus;
taskExecutionMode: TaskExecutionMode;
serverName: string;
databaseName: string;
name: string;
description: string;
providerName: string;
isCancelable: boolean;
}
namespace TaskStatusChangedNotification {
export const type = new NotificationType<TaskProgressInfo, void>('tasks/statuschanged');
}
namespace TaskCreatedNotification {
export const type = new NotificationType<TaskInfo, void>('tasks/newtaskcreated');
}
interface CancelTaskParams {
taskId: string;
}
namespace CancelTaskRequest {
export const type = new RequestType<CancelTaskParams, boolean, void, void>('tasks/canceltask');
}
type ActiveTaskInfo = {
taskInfo: TaskInfo,
progressCallback: ProgressCallback,
completionPromise: Deferred<void>,
lastMessage?: string
};
type ProgressCallback = (value: { message?: string; increment?: number }) => void;
/**
* A simple service that hooks into the SQL Task Service feature provided by SQL Tools Service. This handles detecting when
* new tasks are started and displaying a progress notification for those tasks while they're running.
*/
export class SqlTasksService {
private _activeTasks = new Map<string, ActiveTaskInfo>();
constructor(private _client: SqlToolsServiceClient, private _untitledSqlDocumentService: UntitledSqlDocumentService) {
this._client.onNotification(TaskCreatedNotification.type, taskInfo => this.handleTaskCreatedNotification(taskInfo));
this._client.onNotification(TaskStatusChangedNotification.type, taskProgressInfo => this.handleTaskChangedNotification(taskProgressInfo));
}
private cancelTask(taskId: string): Thenable<boolean> {
const params: CancelTaskParams = {
taskId
};
return this._client.sendRequest(CancelTaskRequest.type, params);
}
/**
* Handles a new task being created. This will start up a progress notification toast for the task and set up
* callbacks to update the status of that task as it runs.
* @param taskInfo The info for the new task that was created
*/
private handleTaskCreatedNotification(taskInfo: TaskInfo): void {
// Default to no-op for the progressCallback since we don't have the progress callback from the notification yet. There's
// potential here for a race condition in which the first update comes in before this callback is updated - if that starts
// happening then we'd want to look into keeping track of the latest update message to display as soon as the progress
// callback is set such that we update the notification correctly.
const newTaskInfo: ActiveTaskInfo = {
taskInfo,
progressCallback: () => { return; },
completionPromise: new Deferred<void>()
};
vscode.window.withProgress(
{
location: vscode.ProgressLocation.Notification,
title: taskInfo.name,
cancellable: taskInfo.isCancelable
},
async (progress, token): Promise<void> => {
newTaskInfo.progressCallback = value => progress.report(value);
token.onCancellationRequested(() => {
this.cancelTask(taskInfo.taskId);
});
await newTaskInfo.completionPromise;
}
);
this._activeTasks.set(taskInfo.taskId, newTaskInfo);
}
/**
* Handles an update to an existing task, updating the current progress notification as needed with any new
* status/messages. If the task is completed then completes the progress notification and displays a final toast
* informing the user that the task was completed.
* @param taskProgressInfo The progress info for the task
*/
private async handleTaskChangedNotification(taskProgressInfo: TaskProgressInfo): Promise<void> {
const taskInfo = this._activeTasks.get(taskProgressInfo.taskId);
if (!taskInfo) {
console.warn(`Status update for unknown task ${taskProgressInfo.taskId}`!);
return;
}
const taskStatusString = toTaskStatusDisplayString(taskProgressInfo.status);
if (taskProgressInfo.message && (taskProgressInfo.message.toLowerCase() !== taskStatusString.toLowerCase())) {
taskInfo.lastMessage = taskProgressInfo.message;
}
if (isTaskCompleted(taskProgressInfo.status)) {
// Task is completed, complete the progress notification and display a final toast informing the
// user of the final status.
this._activeTasks.delete(taskProgressInfo.taskId);
if (taskProgressInfo.status === TaskStatus.Canceled) {
taskInfo.completionPromise.reject(new Error('Task cancelled'));
} else {
taskInfo.completionPromise.resolve();
}
// Get the message to display, if the last status doesn't have a valid message then get the last valid one
const lastMessage = (taskProgressInfo.message && taskProgressInfo.message.toLowerCase() !== taskStatusString.toLowerCase()) ?? taskInfo.lastMessage;
// Only include the message if it isn't the same as the task status string we already have - some (but not all) task status
// notifications include this string as the message
const taskMessage = lastMessage ?
utils.formatString(localizedConstants.taskStatusWithNameAndMessage, taskInfo.taskInfo.name, taskStatusString, lastMessage) :
utils.formatString(localizedConstants.taskStatusWithName, taskInfo.taskInfo.name, taskStatusString);
showCompletionMessage(taskProgressInfo.status, taskMessage);
if (taskInfo.taskInfo.taskExecutionMode === TaskExecutionMode.script && taskProgressInfo.script) {
await this._untitledSqlDocumentService.newQuery(taskProgressInfo.script);
}
} else {
// Task is still ongoing so just update the progress notification with the latest status
// The progress notification already has the name, so we just need to update the message with the latest status info.
// Only include the message if it isn't the same as the task status string we already have - some (but not all) task status
// notifications include this string as the message
const taskMessage = taskProgressInfo.message && taskProgressInfo.message.toLowerCase() !== taskStatusString.toLowerCase() ?
utils.formatString(localizedConstants.taskStatusWithMessage, taskInfo.taskInfo.name, taskStatusString, taskProgressInfo.message) :
taskStatusString;
taskInfo.progressCallback({ message: taskMessage });
}
}
}
/**
* Determines whether a particular TaskStatus indicates that the task is completed.
* @param taskStatus The task status to check
* @returns true if the task is considered completed, false if not
*/
function isTaskCompleted(taskStatus: TaskStatus): boolean {
return taskStatus === TaskStatus.Canceled ||
taskStatus === TaskStatus.Failed ||
taskStatus === TaskStatus.Succeeded ||
taskStatus === TaskStatus.SucceededWithWarning;
}
/**
* Shows a message for a task with a different type of toast notification being used for
* different status types.
* Failed - Error notification
* Canceled or SucceededWithWarning - Warning notification
* All others - Information notification
* @param taskStatus The status of the task we're showing the message for
* @param message The message to show
*/
function showCompletionMessage(taskStatus: TaskStatus, message: string): void {
if (taskStatus === TaskStatus.Failed) {
vscode.window.showErrorMessage(message);
} else if (taskStatus === TaskStatus.Canceled || taskStatus === TaskStatus.SucceededWithWarning) {
vscode.window.showWarningMessage(message);
} else {
vscode.window.showInformationMessage(message);
}
}
/**
* Gets the string to display for the specified task status
* @param taskStatus The task status to get the display string for
* @returns The display string for the task status, or the task status directly as a string if we don't have a mapping
*/
function toTaskStatusDisplayString(taskStatus: TaskStatus): string {
switch (taskStatus) {
case TaskStatus.Canceled:
return localizedConstants.canceled;
case TaskStatus.Failed:
return localizedConstants.failed;
case TaskStatus.Succeeded:
return localizedConstants.succeeded;
case TaskStatus.SucceededWithWarning:
return localizedConstants.succeededWithWarning;
case TaskStatus.InProgress:
return localizedConstants.inProgress;
case TaskStatus.Canceling:
return localizedConstants.canceling;
case TaskStatus.NotStarted:
return localizedConstants.notStarted;
default:
console.warn(`Don't have display string for task status ${taskStatus}`);
return (<any>taskStatus).toString(); // Typescript warns that we can never get here because we've used all the enum values so cast to any
}
} | the_stack |
import type * as BalenaSdk from '..';
import type { AnyObject } from '../typings/utils';
import { Compute, Equals, EqualsTrue } from './utils';
const sdk: BalenaSdk.BalenaSDK = {} as any;
const strictPine = sdk.pine as BalenaSdk.PineStrict;
let aAny: any;
let aNumber: number;
let aNumberOrUndefined: number | undefined;
let aString: string;
// This file is in .prettierignore, since otherwise
// the @ts-expect-error comments would move to the wrong place
// AnyObject pine queries
(async () => {
const result = await sdk.pine.get<AnyObject>({
resource: 'device',
options: {
$select: ['device_name', 'uuid'],
$expand: {
belongs_to__application: {},
device_tag: {},
},
},
});
const test: Equals<typeof result, AnyObject[]> = EqualsTrue;
})();
(async () => {
const result = await sdk.pine.get<AnyObject>({
resource: 'device',
id: 1,
options: {
$select: ['device_name', 'uuid'],
$expand: {
belongs_to__application: {},
device_tag: {},
},
},
});
const test: Equals<typeof result, AnyObject | undefined> = EqualsTrue;
})();
// Object level typed result
(async () => {
const result = await sdk.pine.get<BalenaSdk.Device>({
resource: 'device',
options: {
$select: ['device_name', 'uuid'],
$expand: {
belongs_to__application: {},
device_tag: {},
},
},
});
const test: Equals<typeof result, BalenaSdk.Device[]> = EqualsTrue;
})();
(async () => {
const result = await sdk.pine.get<BalenaSdk.Device>({
resource: 'device',
id: 1,
options: {
$select: ['device_name', 'uuid'],
$expand: {
belongs_to__application: {},
device_tag: {},
},
},
});
const test: Equals<typeof result, BalenaSdk.Device | undefined> = EqualsTrue;
})();
(async () => {
const fleetSlug = 'fleetSlug';
const maybeRelease: string | null = '1.2.3';
const maybeService: string | null = 'main';
const result = await sdk.pine.get<BalenaSdk.Image>({
resource: 'image',
options: {
$top: 1,
$select: 'is_stored_at__image_location',
$filter: {
status: 'success',
release_image: {
$any: {
$alias: 'ri',
$expr: {
ri: {
is_part_of__release: {
$any: {
$alias: 'ipor',
$expr: {
ipor: {
status: 'success' as const,
belongs_to__application: {
$any: {
$alias: 'bta',
$expr: {
bta: {
slug: fleetSlug,
},
},
},
},
...(maybeRelease == null && {
should_be_running_on__application: {
$any: {
$alias: 'sbroa',
$expr: {
sbroa: {
slug: fleetSlug,
},
},
},
},
}),
},
$or: [
{ ipor: { commit: maybeRelease } },
{ ipor: { semver: maybeRelease, is_final: true } },
{
ipor: { raw_version: maybeRelease, is_final: false },
},
],
},
},
},
},
},
},
},
...(maybeService != null && {
is_a_build_of__service: {
$any: {
$alias: 'iabos',
$expr: {
iabos: {
service_name: maybeService,
},
},
},
},
}),
},
},
});
const test: Equals<typeof result, BalenaSdk.Image[]> = EqualsTrue;
})();
// Explicitly providing the result type
(async () => {
const result = await sdk.pine.get<BalenaSdk.Device, number>({
resource: 'device/$count',
options: {
$filter: {
device_tag: {
$any: {
$alias: 'dt',
$expr: {
1: 1,
},
},
},
},
},
});
const test: Equals<typeof result, number> = EqualsTrue;
})();
(async () => {
const result = await sdk.pine.get<BalenaSdk.Device, number>({
resource: 'device/$count',
id: 1,
options: {
$filter: {
device_tag: {
$any: {
$alias: 'dt',
$expr: {
1: 1,
},
},
},
},
},
});
const test: Equals<typeof result, number> = EqualsTrue;
})();
// Fully Typed - auto-inferring result
(async () => {
const [result] = await sdk.pine.get({
resource: 'device',
});
aNumber = result.id;
aString = result.device_name;
aNumber = result.belongs_to__application.__id;
aNumberOrUndefined = result.should_be_running__release?.__id;
// @ts-expect-error
aNumber = result.should_be_running__release.__id;
// @ts-expect-error
aAny = result.device_tag;
})();
(async () => {
const result = await sdk.pine.get({
resource: 'device',
id: 1,
});
const checkUndefined: typeof result = undefined;
if (result === undefined) {
throw new Error('Can be undefined');
}
aNumber = result.id;
aString = result.device_name;
aNumber = result.belongs_to__application.__id;
aNumberOrUndefined = result.should_be_running__release?.__id;
// @ts-expect-error
aNumber = result.should_be_running__release.__id;
// @ts-expect-error
aAny = result.device_tag;
})();
(async () => {
const result = await sdk.pine.get({
resource: 'device',
id: 1,
options: {
$select: ['id', 'device_name'],
},
});
const checkUndefined: typeof result = undefined;
if (result === undefined) {
throw new Error('Can be undefined');
}
aNumber = result.id;
aString = result.device_name;
// @ts-expect-error
aString = result.os_version;
// @ts-expect-error
aAny = result.belongs_to__application;
// @ts-expect-error
aAny = result.device_tag;
})();
(async () => {
const [result] = await sdk.pine.get({
resource: 'device',
options: {
$select: ['id', 'device_name', 'belongs_to__application'],
$expand: {
should_be_running__release: {},
},
},
});
aNumber = result.id;
aString = result.device_name;
aNumber = result.belongs_to__application.__id;
aNumberOrUndefined = result.should_be_running__release[0]?.id;
// @ts-expect-error
aString = result.os_version;
// @ts-expect-error
aNumber = result.should_be_running__release.__id;
// @ts-expect-error
aAny = result.device_tag;
})();
// $count
(async () => {
const result = await sdk.pine.get({
resource: 'device',
options: {
$count: {},
},
});
aNumber = result;
})();
(async () => {
const [result] = await sdk.pine.get({
resource: 'device',
options: {
$select: ['id', 'device_name', 'belongs_to__application'],
$expand: {
should_be_running__release: {
$count: {},
},
device_tag: {},
},
},
});
aNumber = result.id;
aString = result.device_name;
aNumber = result.belongs_to__application.__id;
aNumber = result.should_be_running__release;
aNumber = result.device_tag[0]?.id;
// @ts-expect-error
aString = result.os_version;
// @ts-expect-error
aNumber = result.is_on__release.__id;
})();
(async () => {
const [result] = await sdk.pine.get({
resource: 'device',
options: {
$select: ['id', 'device_name', 'belongs_to__application'],
$expand: {
should_be_running__release: {},
device_tag: {
$count: {},
},
},
},
});
aNumber = result.id;
aString = result.device_name;
aNumber = result.belongs_to__application.__id;
aNumberOrUndefined = result.should_be_running__release[0]?.id;
aNumber = result.device_tag;
// @ts-expect-error
aString = result.os_version;
// @ts-expect-error
aNumber = result.is_on__release.__id;
})();
// Exceeding properties
(async () => {
const result = await sdk.pine.get({
resource: 'device',
// @ts-expect-error
missplaced$filter: {},
options: {
$select: ['id', 'device_name', 'belongs_to__application'],
},
});
})();
(async () => {
const result = await sdk.pine.get({
resource: 'device',
options: {
$select: ['id', 'device_name', 'belongs_to__application'],
// @ts-expect-error
$asdf: {},
},
});
})();
// Incorrect properties
(async () => {
const result = await sdk.pine.get({
resource: 'device',
options: {
$select: ['id', 'device_name', 'belongs_to__application', 'asdf'],
},
});
const test: Equals<
Compute<typeof result[number]>,
{
id: any;
device_name: any;
belongs_to__application: any;
asdf: any;
}
> = EqualsTrue;
// @ts-expect-error - TODO: This should either be never[] or even better the pine.get should error
const testTodo: Equals<typeof result, never[]> = EqualsTrue;
})();
(async () => {
const result = await sdk.pine.get({
resource: 'device',
options: {
$select: ['id', 'device_name', 'belongs_to__application'],
$expand: {
// @ts-expect-error
should_be_running__release: {},
asdf: {},
device_tag: {
$count: {},
},
},
},
});
})();
(async () => {
const result = await sdk.pine.get({
resource: 'device',
options: {
$select: 'device_name',
$filter: {
device_tag: {
$any: {
$alias: 'dt',
$expr: {
dt: { tag_key: 'test' },
},
},
},
},
},
});
const test: Equals<
Compute<typeof result[number]>,
{
device_name: string;
}
> = EqualsTrue;
})();
(async () => {
const result = await sdk.pine.get({
resource: 'device',
options: {
$select: 'device_name',
$filter: {
device_tag: {
$any: {
$alias: 'dt',
$expr: {
1: 1,
},
},
},
},
},
});
const test: Equals<
Compute<typeof result[number]>,
{
device_name: string;
}
> = EqualsTrue;
})();
(async () => {
const fleetSlug = 'fleetSlug';
const maybeRelease: string | null = '1.2.3';
const result = await sdk.pine.get({
resource: 'image',
options: {
$top: 1,
$select: 'is_stored_at__image_location',
$filter: {
status: 'success',
release_image: {
$any: {
$alias: 'ri',
$expr: {
ri: {
is_part_of__release: {
$any: {
$alias: 'ipor',
$expr: {
ipor: {
status: 'success' as const,
belongs_to__application: {
$any: {
$alias: 'bta',
$expr: {
bta: {
slug: fleetSlug,
},
},
},
},
...(maybeRelease == null && {
should_be_running_on__application: {
$any: {
$alias: 'sbroa',
$expr: {
sbroa: {
slug: fleetSlug,
},
},
},
},
}),
},
$or: [
{ ipor: { commit: maybeRelease } },
{ ipor: { semver: maybeRelease, is_final: true } },
{
ipor: { raw_version: maybeRelease, is_final: false },
},
],
},
},
},
},
},
},
},
},
},
});
const test: Equals<
Compute<typeof result[number]>,
{
is_stored_at__image_location: string;
}
> = EqualsTrue;
})();
(async () => {
const fleetSlug = 'string';
const maybeRelease: string | null = '1.2.3';
const maybeService: string | null = 'main';
const result = await sdk.pine.get({
resource: 'image',
options: {
$top: 1,
$select: 'is_stored_at__image_location',
$filter: {
status: 'success',
release_image: {
$any: {
$alias: 'ri',
$expr: {
ri: {
is_part_of__release: {
$any: {
$alias: 'ipor',
$expr: {
ipor: {
status: 'success' as const,
belongs_to__application: {
$any: {
$alias: 'bta',
$expr: {
bta: {
slug: fleetSlug,
},
},
},
},
...(maybeRelease == null && {
should_be_running_on__application: {
$any: {
$alias: 'sbroa',
$expr: {
sbroa: {
slug: fleetSlug,
},
},
},
},
}),
},
...(maybeRelease != null && {
$or: [
{ ipor: { commit: maybeRelease } },
{ ipor: { semver: maybeRelease, is_final: true } },
{
ipor: {
raw_version: maybeRelease,
is_final: false,
},
},
],
}),
},
},
},
},
},
},
},
},
...(maybeService != null && {
is_a_build_of__service: {
$any: {
$alias: 'iabos',
$expr: {
iabos: {
service_name: maybeService,
},
},
},
},
}),
},
});
const test: Equals<
Compute<typeof result[number]>,
{
is_stored_at__image_location: string;
}
> = EqualsTrue;
})();
// strictPine
(async () => {
const result = await strictPine.get({
resource: 'device',
options: {
// @ts-expect-error
$select: ['id', 'device_name', 'belongs_to__application', 'asdf'],
},
});
})();
(async () => {
const result = await strictPine.get({
resource: 'device',
options: {
// @ts-expect-error b/c the expand doesn't have a $select, bad placing though.
$select: ['id', 'device_name', 'belongs_to__application'],
$expand: {
should_be_running__release: {},
device_tag: {
$count: {},
},
},
},
});
})();
(async () => {
const result = await strictPine.get({
resource: 'device',
options: {
// @ts-expect-error b/c asdf is not an expandable prop, bad placing though.
$select: ['id', 'device_name', 'belongs_to__application'],
$expand: {
should_be_running__release: {
$select: 'id',
},
asdf: {
$select: 'id',
},
device_tag: {
$count: {},
},
},
},
});
})();
(async () => {
const [result] = await strictPine.get({
resource: 'device',
options: {
$select: ['id', 'device_name', 'belongs_to__application'],
$expand: {
should_be_running__release: {
$select: 'id',
},
device_tag: {
$count: {},
},
},
},
});
aNumber = result.id;
aString = result.device_name;
aNumber = result.belongs_to__application.__id;
aNumberOrUndefined = result.should_be_running__release[0]?.id;
aNumber = result.device_tag;
// @ts-expect-error
aString = result.os_version;
// @ts-expect-error
aNumber = result.is_on__release.__id;
})();
(async () => {
const result = await strictPine.get({
resource: 'device',
id: 5,
options: {
$select: ['id', 'device_name', 'belongs_to__application'],
$expand: {
should_be_running__release: {
$select: 'id',
},
device_tag: {
$count: {},
},
},
},
});
const checkUndefined: typeof result = undefined;
if (result === undefined) {
throw new Error('Can be undefined');
}
aNumber = result.id;
aString = result.device_name;
aNumber = result.belongs_to__application.__id;
aNumberOrUndefined = result.should_be_running__release[0]?.id;
aNumber = result.device_tag;
// @ts-expect-error
aString = result.os_version;
// @ts-expect-error
aNumber = result.is_on__release.__id;
})();
(async () => {
const result = await strictPine.get({
resource: 'device',
id: 5,
options: {
$count: {
$filter: {
// TODO: this should error
asdf: 4,
belongs_to__application: {
organization: 1,
application_type: 2,
depends_on__application: null,
},
},
},
},
});
aNumber = result;
})();
(async () => {
const result = await strictPine.get({
resource: 'device',
id: 5,
options: {
$count: {
$filter: {
belongs_to__application: {
organization: 1,
application_type: 2,
depends_on__application: null,
},
},
},
},
});
aNumber = result;
})(); | the_stack |
import AstNode from './base';
import type * as Values from './values';
import type * as BK from './control_commands';
import type * as CD from './class_def';
import type { FunctionDef, ArgumentDef } from './function_def';
import type * as Prog from './program';
import type * as Stmt from './statement';
import type * as Perm from './permissions';
import type * as Inv from './invocation';
import type * as BE from './boolean_expression';
import type * as Exp2 from './expression';
import type * as Prim from './legacy';
import type * as D from './dialogues';
/**
* Base class (interface) for traversing the AST using the visitor
* pattern.
*
* During the traversal, each node will call the {@link Ast.NodeVisitor.enter}
* method when visiting the node.
*
* After that, the the node will call the appropriate visit
* method based on the node type. If the visit method returns true,
* (which is the default for non-overridden methods), traversal continues
* with children.
*
* After children have been visited, the node will call {@link Ast.NodeVisitor.exit} before
* returning to the parent. {@link Ast.NodeVisitor.exit} is called regardless of the return value
* of visit, so {@link Ast.NodeVisitor.enter} and {@link Ast.NodeVisitor.exit} are always paired.
*
* Expected usage:
* ```javascript
* const visitor = new class extends Ast.NodeVisitor {
* visitMonitorStream(node) {
* // do something with it
* return true;
* }
* };
* program.visit(visitor);
* ```
*
*/
export default abstract class NodeVisitor {
/**
* Begin visiting a node.
*
* This is called for all nodes before calling the corresponding
* visit method.
*
* @param node - the node being entered
*/
enter(node : AstNode) : void {}
/**
* End visiting a node.
*
* This is called for all nodes after calling the corresponding
* visit method and visiting all children.
*
* This method is not called if {@link Ast.NodeVisitor.enter} or
* visit throws an exception.
*
* @param node - the node being exited
*/
exit(node : AstNode) : void {}
// values
visitValue(node : Values.Value) : boolean {
return true;
}
/* istanbul ignore next */
visitArrayValue(node : Values.ArrayValue) : boolean {
return true;
}
/* istanbul ignore next */
visitVarRefValue(node : Values.VarRefValue) : boolean {
return true;
}
/* istanbul ignore next */
visitArrayFieldValue(node : Values.ArrayFieldValue) : boolean {
return true;
}
/* istanbul ignore next */
visitComputationValue(node : Values.ComputationValue) : boolean {
return true;
}
/* istanbul ignore next */
visitFilterValue(node : Values.FilterValue) : boolean {
return true;
}
/* istanbul ignore next */
visitUndefinedValue(node : Values.UndefinedValue) : boolean {
return true;
}
/* istanbul ignore next */
visitContextRefValue(node : Values.ContextRefValue) : boolean {
return true;
}
/* istanbul ignore next */
visitBooleanValue(node : Values.BooleanValue) : boolean {
return true;
}
/* istanbul ignore next */
visitStringValue(node : Values.StringValue) : boolean {
return true;
}
/* istanbul ignore next */
visitNumberValue(node : Values.NumberValue) : boolean {
return true;
}
/* istanbul ignore next */
visitMeasureValue(node : Values.MeasureValue) : boolean {
return true;
}
/* istanbul ignore next */
visitCurrencyValue(node : Values.CurrencyValue) : boolean {
return true;
}
/* istanbul ignore next */
visitLocationValue(node : Values.LocationValue) : boolean {
return true;
}
/* istanbul ignore next */
visitDateValue(node : Values.DateValue) : boolean {
return true;
}
/* istanbul ignore next */
visitTimeValue(node : Values.TimeValue) : boolean {
return true;
}
/* istanbul ignore next */
visitEntityValue(node : Values.EntityValue) : boolean {
return true;
}
/* istanbul ignore next */
visitEnumValue(node : Values.EnumValue) : boolean {
return true;
}
/* istanbul ignore next */
visitEventValue(node : Values.EventValue) : boolean {
return true;
}
/* istanbul ignore next */
visitArgMapValue(node : Values.ArgMapValue) : boolean {
return true;
}
/* istanbul ignore next */
visitObjectValue(node : Values.ObjectValue) : boolean {
return true;
}
/* istanbul ignore next */
visitRecurrentTimeSpecificationValue(node : Values.RecurrentTimeSpecificationValue) : boolean {
return true;
}
/* istanbul ignore next */
visitRecurrentTimeRule(node : Values.RecurrentTimeRule) : boolean {
return true;
}
// bookkeeping
/* istanbul ignore next */
visitControlCommand(node : BK.ControlCommand) : boolean {
return true;
}
/* istanbul ignore next */
visitSpecialControlIntent(node : BK.SpecialControlIntent) : boolean {
return true;
}
/* istanbul ignore next */
visitChoiceControlIntent(node : BK.ChoiceControlIntent) : boolean {
return true;
}
/* istanbul ignore next */
visitAnswerControlIntent(node : BK.AnswerControlIntent) : boolean {
return true;
}
// classes
/* istanbul ignore next */
visitClassDef(node : CD.ClassDef) : boolean {
return true;
}
/* istanbul ignore next */
visitFunctionDef(node : FunctionDef) : boolean {
return true;
}
/* istanbul ignore next */
visitArgumentDef(node : ArgumentDef) : boolean {
return true;
}
/* istanbul ignore next */
visitMixinImportStmt(node : CD.MixinImportStmt) : boolean {
return true;
}
/* istanbul ignore next */
visitEntityDef(node : CD.EntityDef) : boolean {
return true;
}
// expressions
/* istanbul ignore next */
visitDeviceSelector(node : Inv.DeviceSelector) : boolean {
return true;
}
/* istanbul ignore next */
visitInputParam(node : Inv.InputParam) : boolean {
return true;
}
/* istanbul ignore next */
visitInvocation(node : Inv.Invocation) : boolean {
return true;
}
/* istanbul ignore next */
visitTrueBooleanExpression(node : BE.TrueBooleanExpression) : boolean {
return true;
}
/* istanbul ignore next */
visitFalseBooleanExpression(node : BE.FalseBooleanExpression) : boolean {
return true;
}
/* istanbul ignore next */
visitAndBooleanExpression(node : BE.AndBooleanExpression) : boolean {
return true;
}
/* istanbul ignore next */
visitOrBooleanExpression(node : BE.OrBooleanExpression) : boolean {
return true;
}
/* istanbul ignore next */
visitNotBooleanExpression(node : BE.NotBooleanExpression) : boolean {
return true;
}
/* istanbul ignore next */
visitAtomBooleanExpression(node : BE.AtomBooleanExpression) : boolean {
return true;
}
/* istanbul ignore next */
visitExternalBooleanExpression(node : BE.ExternalBooleanExpression) : boolean {
return true;
}
/* istanbul ignore next */
visitDontCareBooleanExpression(node : BE.DontCareBooleanExpression) : boolean {
return true;
}
/* istanbul ignore next */
visitComputeBooleanExpression(node : BE.ComputeBooleanExpression) : boolean {
return true;
}
/* istanbul ignore next */
visitComparisonSubqueryBooleanExpression(node : BE.ComparisonSubqueryBooleanExpression) : boolean {
return true;
}
/* istanbul ignore next */
visitExistentialSubqueryBooleanExpression(node : BE.ExistentialSubqueryBooleanExpression) : boolean {
return true;
}
// streams, tables, actions
/* istanbul ignore next */
visitVarRefTable(node : Prim.VarRefTable) : boolean {
return true;
}
/* istanbul ignore next */
visitInvocationTable(node : Prim.InvocationTable) : boolean {
return true;
}
/* istanbul ignore next */
visitFilteredTable(node : Prim.FilteredTable) : boolean {
return true;
}
/* istanbul ignore next */
visitProjectionTable(node : Prim.ProjectionTable) : boolean {
return true;
}
/* istanbul ignore next */
visitComputeTable(node : Prim.ComputeTable) : boolean {
return true;
}
/* istanbul ignore next */
visitAliasTable(node : Prim.AliasTable) : boolean {
return true;
}
/* istanbul ignore next */
visitAggregationTable(node : Prim.AggregationTable) : boolean {
return true;
}
/* istanbul ignore next */
visitSortedTable(node : Prim.SortedTable) : boolean {
return true;
}
/* istanbul ignore next */
visitIndexTable(node : Prim.IndexTable) : boolean {
return true;
}
/* istanbul ignore next */
visitSlicedTable(node : Prim.SlicedTable) : boolean {
return true;
}
/* istanbul ignore next */
visitJoinTable(node : Prim.JoinTable) : boolean {
return true;
}
/* istanbul ignore next */
visitVarRefStream(node : Prim.VarRefStream) : boolean {
return true;
}
/* istanbul ignore next */
visitTimerStream(node : Prim.TimerStream) : boolean {
return true;
}
/* istanbul ignore next */
visitAtTimerStream(node : Prim.AtTimerStream) : boolean {
return true;
}
/* istanbul ignore next */
visitMonitorStream(node : Prim.MonitorStream) : boolean {
return true;
}
/* istanbul ignore next */
visitEdgeNewStream(node : Prim.EdgeNewStream) : boolean {
return true;
}
/* istanbul ignore next */
visitEdgeFilterStream(node : Prim.EdgeFilterStream) : boolean {
return true;
}
/* istanbul ignore next */
visitFilteredStream(node : Prim.FilteredStream) : boolean {
return true;
}
/* istanbul ignore next */
visitProjectionStream(node : Prim.ProjectionStream) : boolean {
return true;
}
/* istanbul ignore next */
visitComputeStream(node : Prim.ComputeStream) : boolean {
return true;
}
/* istanbul ignore next */
visitAliasStream(node : Prim.AliasStream) : boolean {
return true;
}
/* istanbul ignore next */
visitJoinStream(node : Prim.JoinStream) : boolean {
return true;
}
/* istanbul ignore next */
visitVarRefAction(node : Prim.VarRefAction) : boolean {
return true;
}
/* istanbul ignore next */
visitInvocationAction(node : Prim.InvocationAction) : boolean {
return true;
}
/* istanbul ignore next */
visitNotifyAction(node : Prim.NotifyAction) : boolean {
return true;
}
/* istanbul ignore next */
visitSpecifiedPermissionFunction(node : Perm.SpecifiedPermissionFunction) : boolean {
return true;
}
/* istanbul ignore next */
visitBuiltinPermissionFunction(node : Perm.BuiltinPermissionFunction) : boolean {
return true;
}
/* istanbul ignore next */
visitClassStarPermissionFunction(node : Perm.ClassStarPermissionFunction) : boolean {
return true;
}
/* istanbul ignore next */
visitStarPermissionFunction(node : Perm.StarPermissionFunction) : boolean {
return true;
}
// new-style expressions
/* istanbul ignore next */
visitFunctionCallExpression(node : Exp2.FunctionCallExpression) : boolean {
return true;
}
/* istanbul ignore next */
visitInvocationExpression(node : Exp2.InvocationExpression) : boolean {
return true;
}
/* istanbul ignore next */
visitMonitorExpression(node : Exp2.MonitorExpression) : boolean {
return true;
}
/* istanbul ignore next */
visitFilterExpression(node : Exp2.FilterExpression) : boolean {
return true;
}
/* istanbul ignore next */
visitProjectionExpression(node : Exp2.ProjectionExpression) : boolean {
return true;
}
/* istanbul ignore next */
visitBooleanQuestionExpression(node : Exp2.BooleanQuestionExpression) : boolean {
return true;
}
/* istanbul ignore next */
visitAliasExpression(node : Exp2.AliasExpression) : boolean {
return true;
}
/* istanbul ignore next */
visitAggregationExpression(node : Exp2.AggregationExpression) : boolean {
return true;
}
/* istanbul ignore next */
visitSortExpression(node : Exp2.SortExpression) : boolean {
return true;
}
/* istanbul ignore next */
visitIndexExpression(node : Exp2.IndexExpression) : boolean {
return true;
}
/* istanbul ignore next */
visitSliceExpression(node : Exp2.SliceExpression) : boolean {
return true;
}
/* istanbul ignore next */
visitChainExpression(node : Exp2.ChainExpression) : boolean {
return true;
}
/* istanbul ignore next */
visitJoinExpression(node : Exp2.JoinExpression) : boolean {
return true;
}
// statements and inputs
/* istanbul ignore next */
visitFunctionDeclaration(node : Stmt.FunctionDeclaration) : boolean {
return true;
}
/* istanbul ignore next */
visitAssignment(node : Stmt.Assignment) : boolean {
return true;
}
/* istanbul ignore next */
visitRule(node : Stmt.Rule) : boolean {
return true;
}
/* istanbul ignore next */
visitCommand(node : Stmt.Command) : boolean {
return true;
}
/* istanbul ignore next */
visitExpressionStatement(node : Stmt.ExpressionStatement) : boolean {
return true;
}
/* istanbul ignore next */
visitReturnStatement(node : Stmt.ReturnStatement) : boolean {
return true;
}
/* istanbul ignore next */
visitDataset(node : Stmt.Dataset) : boolean {
return true;
}
/* istanbul ignore next */
visitExample(node : Stmt.Example) : boolean {
return true;
}
/* istanbul ignore next */
visitProgram(node : Prog.Program) : boolean {
return true;
}
/* istanbul ignore next */
visitPermissionRule(node : Prog.PermissionRule) : boolean {
return true;
}
/* istanbul ignore next */
visitLibrary(node : Prog.Library) : boolean {
return true;
}
// dialogue states
visitDialogueState(node : D.DialogueState) : boolean {
return true;
}
visitDialogueHistoryItem(node : D.DialogueHistoryItem) : boolean {
return true;
}
visitDialogueHistoryResultList(node : D.DialogueHistoryResultList) : boolean {
return true;
}
visitDialogueHistoryResultItem(node : D.DialogueHistoryResultItem) : boolean {
return true;
}
} | the_stack |
import { DatePart, DatePartInfo } from '../../directives/date-time-editor/date-time-editor.common';
import { formatDate, FormatWidth, getLocaleDateFormat } from '@angular/common';
import { ValidationErrors } from '@angular/forms';
import { isDate } from '../../core/utils';
/** @hidden */
const enum FormatDesc {
Numeric = 'numeric',
TwoDigits = '2-digit'
}
const DATE_CHARS = ['h', 'H', 'm', 's', 'S', 't', 'T'];
const TIME_CHARS = ['d', 'D', 'M', 'y', 'Y'];
/** @hidden */
const enum DateParts {
Day = 'day',
Month = 'month',
Year = 'year'
}
/** @hidden */
export abstract class DateTimeUtil {
public static readonly DEFAULT_INPUT_FORMAT = 'MM/dd/yyyy';
public static readonly DEFAULT_TIME_INPUT_FORMAT = 'hh:mm tt';
private static readonly SEPARATOR = 'literal';
private static readonly DEFAULT_LOCALE = 'en';
/**
* Parse a Date value from masked string input based on determined date parts
*
* @param inputData masked value to parse
* @param dateTimeParts Date parts array for the mask
*/
public static parseValueFromMask(inputData: string, dateTimeParts: DatePartInfo[], promptChar?: string): Date | null {
const parts: { [key in DatePart]: number } = {} as any;
dateTimeParts.forEach(dp => {
let value = parseInt(DateTimeUtil.getCleanVal(inputData, dp, promptChar), 10);
if (!value) {
value = dp.type === DatePart.Date || dp.type === DatePart.Month ? 1 : 0;
}
parts[dp.type] = value;
});
parts[DatePart.Month] -= 1;
if (parts[DatePart.Month] < 0 || 11 < parts[DatePart.Month]) {
return null;
}
// TODO: Century threshold
if (parts[DatePart.Year] < 50) {
parts[DatePart.Year] += 2000;
}
if (parts[DatePart.Date] > DateTimeUtil.daysInMonth(parts[DatePart.Year], parts[DatePart.Month])) {
return null;
}
if (parts[DatePart.Hours] > 23 || parts[DatePart.Minutes] > 59 || parts[DatePart.Seconds] > 59) {
return null;
}
const amPm = dateTimeParts.find(p => p.type === DatePart.AmPm);
if (amPm) {
parts[DatePart.Hours] %= 12;
}
if (amPm && DateTimeUtil.getCleanVal(inputData, amPm, promptChar).toLowerCase() === 'pm') {
parts[DatePart.Hours] += 12;
}
return new Date(
parts[DatePart.Year] || 2000,
parts[DatePart.Month] || 0,
parts[DatePart.Date] || 1,
parts[DatePart.Hours] || 0,
parts[DatePart.Minutes] || 0,
parts[DatePart.Seconds] || 0
);
}
/** Parse the mask into date/time and literal parts */
public static parseDateTimeFormat(mask: string, locale?: string): DatePartInfo[] {
const format = mask || DateTimeUtil.getDefaultInputFormat(locale);
const dateTimeParts: DatePartInfo[] = [];
const formatArray = Array.from(format);
let currentPart: DatePartInfo = null;
let position = 0;
for (let i = 0; i < formatArray.length; i++, position++) {
const type = DateTimeUtil.determineDatePart(formatArray[i]);
if (currentPart) {
if (currentPart.type === type) {
currentPart.format += formatArray[i];
if (i < formatArray.length - 1) {
continue;
}
}
DateTimeUtil.addCurrentPart(currentPart, dateTimeParts);
position = currentPart.end;
}
currentPart = {
start: position,
end: position + formatArray[i].length,
type,
format: formatArray[i]
};
}
// make sure the last member of a format like H:m:s is not omitted
if (!dateTimeParts.filter(p => p.format.includes(currentPart.format)).length) {
DateTimeUtil.addCurrentPart(currentPart, dateTimeParts);
}
// formats like "y" or "yyy" are treated like "yyyy" while editing
const yearPart = dateTimeParts.filter(p => p.type === DatePart.Year)[0];
if (yearPart && yearPart.format !== 'yy') {
yearPart.end += 4 - yearPart.format.length;
yearPart.format = 'yyyy';
}
return dateTimeParts;
}
public static getPartValue(value: Date, datePartInfo: DatePartInfo, partLength: number): string {
let maskedValue;
const datePart = datePartInfo.type;
switch (datePart) {
case DatePart.Date:
maskedValue = value.getDate();
break;
case DatePart.Month:
// months are zero based
maskedValue = value.getMonth() + 1;
break;
case DatePart.Year:
if (partLength === 2) {
maskedValue = this.prependValue(
parseInt(value.getFullYear().toString().slice(-2), 10), partLength, '0');
} else {
maskedValue = value.getFullYear();
}
break;
case DatePart.Hours:
if (datePartInfo.format.indexOf('h') !== -1) {
maskedValue = this.prependValue(
this.toTwelveHourFormat(value.getHours().toString()), partLength, '0');
} else {
maskedValue = value.getHours();
}
break;
case DatePart.Minutes:
maskedValue = value.getMinutes();
break;
case DatePart.Seconds:
maskedValue = value.getSeconds();
break;
case DatePart.AmPm:
maskedValue = value.getHours() >= 12 ? 'PM' : 'AM';
break;
}
if (datePartInfo.type !== DatePart.AmPm) {
return this.prependValue(maskedValue, partLength, '0');
}
return maskedValue;
}
/** Builds a date-time editor's default input format based on provided locale settings. */
public static getDefaultInputFormat(locale: string): string {
locale = locale || DateTimeUtil.DEFAULT_LOCALE;
if (!Intl || !Intl.DateTimeFormat || !Intl.DateTimeFormat.prototype.formatToParts) {
// TODO: fallback with Intl.format for IE?
return DateTimeUtil.DEFAULT_INPUT_FORMAT;
}
const parts = DateTimeUtil.getDefaultLocaleMask(locale);
parts.forEach(p => {
if (p.type !== DatePart.Year && p.type !== DateTimeUtil.SEPARATOR) {
p.formatType = FormatDesc.TwoDigits;
}
});
return DateTimeUtil.getMask(parts);
}
/** Tries to format a date using Angular's DatePipe. Fallbacks to `Intl` if no locale settings have been loaded. */
public static formatDate(value: number | Date, format: string, locale: string, timezone?: string): string {
let formattedDate: string;
try {
formattedDate = formatDate(value, format, locale, timezone);
} catch {
DateTimeUtil.logMissingLocaleSettings(locale);
const formatter = new Intl.DateTimeFormat(locale);
formattedDate = formatter.format(value);
}
return formattedDate;
}
/**
* Returns the date format based on a provided locale.
* Supports Angular's DatePipe format options such as `shortDate`, `longDate`.
*/
public static getLocaleDateFormat(locale: string, displayFormat?: string): string {
const formatKeys = Object.keys(FormatWidth) as (keyof FormatWidth)[];
const targetKey = formatKeys.find(k => k.toLowerCase() === displayFormat?.toLowerCase().replace('date', ''));
if (!targetKey) {
// if displayFormat is not shortDate, longDate, etc.
// or if it is not set by the user
return displayFormat;
}
let format: string;
try {
format = getLocaleDateFormat(locale, FormatWidth[targetKey]);
} catch {
DateTimeUtil.logMissingLocaleSettings(locale);
format = DateTimeUtil.getDefaultInputFormat(locale);
}
return format;
}
/** Determines if a given character is `d/M/y` or `h/m/s`. */
public static isDateOrTimeChar(char: string): boolean {
return DATE_CHARS.indexOf(char) !== -1 || TIME_CHARS.indexOf(char) !== -1;
}
/** Spins the date portion in a date-time editor. */
public static spinDate(delta: number, newDate: Date, spinLoop: boolean): void {
const maxDate = DateTimeUtil.daysInMonth(newDate.getFullYear(), newDate.getMonth());
let date = newDate.getDate() + delta;
if (date > maxDate) {
date = spinLoop ? date % maxDate : maxDate;
} else if (date < 1) {
date = spinLoop ? maxDate + (date % maxDate) : 1;
}
newDate.setDate(date);
}
/** Spins the month portion in a date-time editor. */
public static spinMonth(delta: number, newDate: Date, spinLoop: boolean): void {
const maxDate = DateTimeUtil.daysInMonth(newDate.getFullYear(), newDate.getMonth() + delta);
if (newDate.getDate() > maxDate) {
newDate.setDate(maxDate);
}
const maxMonth = 11;
const minMonth = 0;
let month = newDate.getMonth() + delta;
if (month > maxMonth) {
month = spinLoop ? (month % maxMonth) - 1 : maxMonth;
} else if (month < minMonth) {
month = spinLoop ? maxMonth + (month % maxMonth) + 1 : minMonth;
}
newDate.setMonth(month);
}
/** Spins the year portion in a date-time editor. */
public static spinYear(delta: number, newDate: Date): void {
const maxDate = DateTimeUtil.daysInMonth(newDate.getFullYear() + delta, newDate.getMonth());
if (newDate.getDate() > maxDate) {
// clip to max to avoid leap year change shifting the entire value
newDate.setDate(maxDate);
}
newDate.setFullYear(newDate.getFullYear() + delta);
}
/** Spins the hours portion in a date-time editor. */
public static spinHours(delta: number, newDate: Date, spinLoop: boolean): void {
const maxHour = 23;
const minHour = 0;
let hours = newDate.getHours() + delta;
if (hours > maxHour) {
hours = spinLoop ? hours % maxHour - 1 : maxHour;
} else if (hours < minHour) {
hours = spinLoop ? maxHour + (hours % maxHour) + 1 : minHour;
}
newDate.setHours(hours);
}
/** Spins the minutes portion in a date-time editor. */
public static spinMinutes(delta: number, newDate: Date, spinLoop: boolean): void {
const maxMinutes = 59;
const minMinutes = 0;
let minutes = newDate.getMinutes() + delta;
if (minutes > maxMinutes) {
minutes = spinLoop ? minutes % maxMinutes - 1 : maxMinutes;
} else if (minutes < minMinutes) {
minutes = spinLoop ? maxMinutes + (minutes % maxMinutes) + 1 : minMinutes;
}
newDate.setMinutes(minutes);
}
/** Spins the seconds portion in a date-time editor. */
public static spinSeconds(delta: number, newDate: Date, spinLoop: boolean): void {
const maxSeconds = 59;
const minSeconds = 0;
let seconds = newDate.getSeconds() + delta;
if (seconds > maxSeconds) {
seconds = spinLoop ? seconds % maxSeconds - 1 : maxSeconds;
} else if (seconds < minSeconds) {
seconds = spinLoop ? maxSeconds + (seconds % maxSeconds) + 1 : minSeconds;
}
newDate.setSeconds(seconds);
}
/** Spins the AM/PM portion in a date-time editor. */
public static spinAmPm(newDate: Date, currentDate: Date, amPmFromMask: string): Date {
switch (amPmFromMask) {
case 'AM':
newDate = new Date(newDate.setHours(newDate.getHours() + 12));
break;
case 'PM':
newDate = new Date(newDate.setHours(newDate.getHours() - 12));
break;
}
if (newDate.getDate() !== currentDate.getDate()) {
return currentDate;
}
return newDate;
}
/**
* Determines whether the provided value is greater than the provided max value.
*
* @param includeTime set to false if you want to exclude time portion of the two dates
* @param includeDate set to false if you want to exclude the date portion of the two dates
* @returns true if provided value is greater than provided maxValue
*/
public static greaterThanMaxValue(value: Date, maxValue: Date, includeTime = true, includeDate = true): boolean {
if (includeTime && includeDate) {
return value.getTime() > maxValue.getTime();
}
const _value = new Date(value.getTime());
const _maxValue = new Date(maxValue.getTime());
if (!includeTime) {
_value.setHours(0, 0, 0, 0);
_maxValue.setHours(0, 0, 0, 0);
}
if (!includeDate) {
_value.setFullYear(0, 0, 0);
_maxValue.setFullYear(0, 0, 0);
}
return _value.getTime() > _maxValue.getTime();
}
/**
* Determines whether the provided value is less than the provided min value.
*
* @param includeTime set to false if you want to exclude time portion of the two dates
* @param includeDate set to false if you want to exclude the date portion of the two dates
* @returns true if provided value is less than provided minValue
*/
public static lessThanMinValue(value: Date, minValue: Date, includeTime = true, includeDate = true): boolean {
if (includeTime && includeDate) {
return value.getTime() < minValue.getTime();
}
const _value = new Date(value.getTime());
const _minValue = new Date(minValue.getTime());
if (!includeTime) {
_value.setHours(0, 0, 0, 0);
_minValue.setHours(0, 0, 0, 0);
}
if (!includeDate) {
_value.setFullYear(0, 0, 0);
_minValue.setFullYear(0, 0, 0);
}
return _value.getTime() < _minValue.getTime();
}
/**
* Validates a value within a given min and max value range.
*
* @param value The value to validate
* @param minValue The lowest possible value that `value` can take
* @param maxValue The largest possible value that `value` can take
*/
public static validateMinMax(value: Date, minValue: Date | string, maxValue: Date | string,
includeTime = true, includeDate = true): ValidationErrors {
if (!value) {
return null;
}
const errors = {};
const min = DateTimeUtil.isValidDate(minValue) ? minValue : DateTimeUtil.parseIsoDate(minValue);
const max = DateTimeUtil.isValidDate(maxValue) ? maxValue : DateTimeUtil.parseIsoDate(maxValue);
if (min && value && DateTimeUtil.lessThanMinValue(value, min, includeTime, includeDate)) {
Object.assign(errors, { minValue: true });
}
if (max && value && DateTimeUtil.greaterThanMaxValue(value, max, includeTime, includeDate)) {
Object.assign(errors, { maxValue: true });
}
return errors;
}
/** Parse an ISO string to a Date */
public static parseIsoDate(value: string): Date | null {
let regex = /^\d{4}/g;
const timeLiteral = 'T';
if (regex.test(value)) {
return new Date(value + `${value.indexOf(timeLiteral) === -1 ? 'T00:00:00' : ''}`);
}
regex = /^\d{2}/g;
if (regex.test(value)) {
const dateNow = new Date().toISOString();
// eslint-disable-next-line prefer-const
let [datePart, _timePart] = dateNow.split(timeLiteral);
return new Date(`${datePart}T${value}`);
}
return null;
}
/**
* Returns whether the input is valid date
*
* @param value input to check
* @returns true if provided input is a valid date
*/
public static isValidDate(value: any): value is Date {
if (isDate(value)) {
return !isNaN(value.getTime());
}
return false;
}
private static addCurrentPart(currentPart: DatePartInfo, dateTimeParts: DatePartInfo[]): void {
DateTimeUtil.ensureLeadingZero(currentPart);
currentPart.end = currentPart.start + currentPart.format.length;
dateTimeParts.push(currentPart);
}
private static daysInMonth(fullYear: number, month: number): number {
return new Date(fullYear, month + 1, 0).getDate();
}
private static trimEmptyPlaceholders(value: string, promptChar?: string): string {
const result = value.replace(new RegExp(promptChar || '_', 'g'), '');
return result;
}
private static getMask(dateStruct: any[]): string {
const mask = [];
for (const part of dateStruct) {
switch (part.formatType) {
case FormatDesc.Numeric: {
if (part.type === DateParts.Day) {
mask.push('d');
} else if (part.type === DateParts.Month) {
mask.push('M');
} else {
mask.push('yyyy');
}
break;
}
case FormatDesc.TwoDigits: {
if (part.type === DateParts.Day) {
mask.push('dd');
} else if (part.type === DateParts.Month) {
mask.push('MM');
} else {
mask.push('yy');
}
}
}
if (part.type === DateTimeUtil.SEPARATOR) {
mask.push(part.value);
}
}
return mask.join('');
}
private static logMissingLocaleSettings(locale: string): void {
console.warn(`Missing locale data for the locale ${locale}. Please refer to https://angular.io/guide/i18n#i18n-pipes`);
console.warn('Using default browser locale settings.');
}
private static prependValue(value: number, partLength: number, prependChar: string): string {
return (prependChar + value.toString()).slice(-partLength);
}
private static toTwelveHourFormat(value: string, promptChar = '_'): number {
let hour = parseInt(value.replace(new RegExp(promptChar, 'g'), '0'), 10);
if (hour > 12) {
hour -= 12;
} else if (hour === 0) {
hour = 12;
}
return hour;
}
private static ensureLeadingZero(part: DatePartInfo) {
switch (part.type) {
case DatePart.Date:
case DatePart.Month:
case DatePart.Hours:
case DatePart.Minutes:
case DatePart.Seconds:
if (part.format.length === 1) {
part.format = part.format.repeat(2);
}
break;
}
}
private static getCleanVal(inputData: string, datePart: DatePartInfo, promptChar?: string): string {
return DateTimeUtil.trimEmptyPlaceholders(inputData.substring(datePart.start, datePart.end), promptChar);
}
private static determineDatePart(char: string): DatePart {
switch (char) {
case 'd':
case 'D':
return DatePart.Date;
case 'M':
return DatePart.Month;
case 'y':
case 'Y':
return DatePart.Year;
case 'h':
case 'H':
return DatePart.Hours;
case 'm':
return DatePart.Minutes;
case 's':
case 'S':
return DatePart.Seconds;
case 't':
case 'T':
return DatePart.AmPm;
default:
return DatePart.Literal;
}
}
private static getDefaultLocaleMask(locale: string) {
const dateStruct = [];
const formatter = new Intl.DateTimeFormat(locale);
const formatToParts = formatter.formatToParts(new Date());
for (const part of formatToParts) {
if (part.type === DateTimeUtil.SEPARATOR) {
dateStruct.push({
type: DateTimeUtil.SEPARATOR,
value: part.value
});
} else {
dateStruct.push({
type: part.type
});
}
}
const formatterOptions = formatter.resolvedOptions();
for (const part of dateStruct) {
switch (part.type) {
case DateParts.Day: {
part.formatType = formatterOptions.day;
break;
}
case DateParts.Month: {
part.formatType = formatterOptions.month;
break;
}
case DateParts.Year: {
part.formatType = formatterOptions.year;
break;
}
}
}
DateTimeUtil.fillDatePartsPositions(dateStruct);
return dateStruct;
}
private static fillDatePartsPositions(dateArray: any[]): void {
let currentPos = 0;
for (const part of dateArray) {
// Day|Month part positions
if (part.type === DateParts.Day || part.type === DateParts.Month) {
// Offset 2 positions for number
part.position = [currentPos, currentPos + 2];
currentPos += 2;
} else if (part.type === DateParts.Year) {
// Year part positions
switch (part.formatType) {
case FormatDesc.Numeric: {
// Offset 4 positions for full year
part.position = [currentPos, currentPos + 4];
currentPos += 4;
break;
}
case FormatDesc.TwoDigits: {
// Offset 2 positions for short year
part.position = [currentPos, currentPos + 2];
currentPos += 2;
break;
}
}
} else if (part.type === DateTimeUtil.SEPARATOR) {
// Separator positions
part.position = [currentPos, currentPos + 1];
currentPos++;
}
}
}
} | the_stack |
import { AbstractClassType, ClassType, getClassName } from '@deepkit/core';
export type ClassDecoratorFn = (classType: AbstractClassType, property?: string, parameterIndexOrDescriptor?: any) => void;
export type PropertyDecoratorFn = (prototype: object, property?: string, parameterIndexOrDescriptor?: any) => void;
export type FluidDecorator<T, D extends Function> = {
[name in keyof T]: T[name] extends (...args: infer K) => any ? (...args: K) => D & FluidDecorator<T, D>
: D & FluidDecorator<T, D>
};
export function createFluidDecorator<API extends APIClass<any> | APIProperty<any>, D extends Function>
(
api: API,
modifier: { name: string, args?: any }[],
collapse: (modifier: { name: string, args?: any }[], target: any, property?: string, parameterIndexOrDescriptor?: any) => void,
returnCollapse: boolean = false,
fluidFunctionSymbol?: symbol
): FluidDecorator<ExtractClass<API>, D> {
const fn = function (target: object, property?: string, parameterIndexOrDescriptor?: any) {
const res = collapse(modifier, target, property, parameterIndexOrDescriptor);
if (returnCollapse) return res;
};
Object.defineProperty(fn, 'name', { value: undefined });
const methods: string[] = [];
Object.defineProperty(fn, '_methods', { value: methods });
if (fluidFunctionSymbol) Object.defineProperty(fn, fluidFunctionSymbol, { value: true });
let current = api;
while (current.prototype) {
let proto = current.prototype;
for (const name of Object.getOwnPropertyNames(proto)) {
if (name === 'constructor') continue;
if (name === 'onDecorator') continue;
const descriptor = Object.getOwnPropertyDescriptor(proto, name);
methods.push(name);
if (descriptor && descriptor.get) {
//its a magic shizzle
Object.defineProperty(fn, name, {
configurable: true,
enumerable: false,
get: () => {
return createFluidDecorator(api, [...modifier, { name }], collapse, returnCollapse, fluidFunctionSymbol);
}
});
} else {
//regular method
Object.defineProperty(fn, name, {
configurable: true,
enumerable: false,
value: (...args: any[]) => {
return createFluidDecorator(api, [...modifier, { name, args }], collapse, returnCollapse, fluidFunctionSymbol);
}
});
}
}
//resolve parent
current = Object.getPrototypeOf(current);
}
return fn as any;
}
export type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;
export type Merge<U> = { [K in keyof U]: U[K] extends ((...a: infer A) => infer R) ? R extends DualDecorator ? (...a: A) => PropertyDecoratorFn & R & U : (...a: A) => R : never };
/**
* A dual decorator is a decorator that can be used on a class and class property.
*/
export type DualDecorator = void & { __DualDecorator?: true };
export function mergeDecorator<T extends any[]>(...args: T): Merge<Omit<UnionToIntersection<T[number]>, '_fetch' | 't'>> {
const res: any = {};
//dual decorator are decorators that share the same name for class decorators and class property decorator
//and need a special runtime check when collapsed.
const tracked: string[] = [];
const dualDecorator: string[] = [];
for (const arg of args) {
for (const method of arg._methods) {
if (tracked.includes(method)) {
if (!dualDecorator.includes(method)) dualDecorator.push(method);
continue;
}
tracked.push(method);
}
}
for (const arg of args) {
for (const method of arg._methods) {
if (!dualDecorator.includes(method)) {
Object.defineProperty(res, method, {
get() {
return arg[method];
}
});
}
}
}
function fluid(
modifier: { name: string, args?: any }[],
collapse: (modifier: { name: string, args?: any }[], target: any, property?: string, parameterIndexOrDescriptor?: any) => void,
): any {
const fn = function (target: object, property?: string, parameterIndexOrDescriptor?: any) {
collapse(modifier, target, property, parameterIndexOrDescriptor);
};
Object.defineProperty(fn, 'name', { value: undefined });
for (const name of tracked) {
const decorator = args.find(v => v[name]);
if (!decorator) continue;
const descriptor = Object.getOwnPropertyDescriptor(decorator, name);
if (descriptor && descriptor.get) {
//its a magic shizzle
Object.defineProperty(fn, name, {
configurable: true,
enumerable: false,
get: () => {
return fluid([...modifier, { name }], collapse);
}
});
} else {
//regular method
Object.defineProperty(fn, name, {
configurable: true,
enumerable: false,
get: () => {
return (...args: any[]) => {
return fluid([...modifier, { name, args }], collapse);
};
}
});
}
}
return fn;
}
function collapse(modifier: { name: string, args?: any }[], target: object, property?: string, parameterIndexOrDescriptor?: any) {
if (property) {
loop:
for (const mod of modifier) {
for (const decorator of args) {
if (decorator._type === 'propertyDecorator' && decorator[mod.name]) {
if (mod.args) {
decorator[mod.name](...mod.args)(target, property, parameterIndexOrDescriptor);
} else {
decorator[mod.name](target, property, parameterIndexOrDescriptor);
}
continue loop;
}
}
throw new Error(`Decorator '${mod.name}' can not be used on class property ${getClassName(target)}.${property}`);
}
} else {
loop:
for (const mod of modifier) {
for (const decorator of args) {
if (decorator._type === 'classDecorator' && decorator[mod.name]) {
if (mod.args) {
decorator[mod.name](...mod.args)(target);
} else {
decorator[mod.name](target);
}
continue loop;
}
}
throw new Error(`Decorator '${mod.name}' can not be used on class ${getClassName(target)}`);
}
}
}
return fluid([], collapse);
}
export interface ClassApiTypeInterface<T> {
t: T,
onDecorator?: (classType: ClassType, property?: string, parameterIndexOrDescriptor?: any) => void
}
export type APIClass<T> = ClassType<ClassApiTypeInterface<T>>;
export type ExtractClass<T> = T extends AbstractClassType<infer K> ? K : never;
export type ExtractApiDataType<T> = T extends AbstractClassType<infer K> ? K extends { t: infer P } ? P : never : (T extends { t: infer P } ? P : never);
export type ClassDecoratorResult<API extends APIClass<any>> =
FluidDecorator<ExtractClass<API>, ClassDecoratorFn>
& { (classType: AbstractClassType): void }
& { _fetch: (classType: ClassType) => ExtractApiDataType<API> | undefined };
export function createClassDecoratorContext<API extends APIClass<any>, T = ExtractApiDataType<API>>(
apiType: API
): ClassDecoratorResult<API> {
const map = new Map<object, ClassApiTypeInterface<any>>();
function collapse(modifier: { name: string, args?: any }[], target: ClassType) {
const api: ClassApiTypeInterface<any> = map.get(target) ?? new apiType(target);
for (const fn of modifier) {
if (fn.args) {
(api as any)[fn.name].bind(api)(...fn.args);
} else {
//just call the getter
(api as any)[fn.name];
}
}
if (api.onDecorator) api.onDecorator(target);
map.set(target, api);
}
const fn = createFluidDecorator(apiType, [], collapse);
Object.defineProperty(fn, '_fetch', {
configurable: true,
enumerable: false,
get: () => {
return (target: object) => {
const api = map.get(target);
return api ? api.t : undefined;
};
}
});
(fn as any)._type = 'classDecorator';
return fn as any;
}
export interface PropertyApiTypeInterface<T> {
t: T,
onDecorator?: (target: ClassType, property: string, parameterIndexOrDescriptor?: any) => void
}
export type APIProperty<T> = ClassType<PropertyApiTypeInterface<T>>;
export type PropertyDecoratorResult<API extends APIProperty<any>> =
FluidDecorator<ExtractClass<API>, PropertyDecoratorFn>
& { (prototype: object, property: string, parameterIndexOrDescriptor?: any): void }
& { _fetch: (classType: ClassType, property: string, parameterIndexOrDescriptor?: any) => ExtractApiDataType<API> | undefined };
export function createPropertyDecoratorContext<API extends APIProperty<any>, T = ExtractApiDataType<API>>(
apiType: API
): PropertyDecoratorResult<API> {
const targetMap = new Map<object, Map<any, PropertyApiTypeInterface<any>>>();
function collapse(modifier: { name: string, args?: any }[], target: object, property?: string, parameterIndexOrDescriptor?: any) {
if (!property) throw new Error('Property decorators can only be used on class properties');
target = (target as any)['constructor']; //property decorators get the prototype instead of the class.
let map = targetMap.get(target);
if (!map) {
map = new Map();
targetMap.set(target, map);
}
const secondIndex = ('number' === typeof parameterIndexOrDescriptor ? parameterIndexOrDescriptor : '');
const index = property + '$$' + secondIndex;
const api: PropertyApiTypeInterface<any> = map.get(index) ?? new apiType(target, property);
for (const fn of modifier) {
if (fn.args) {
(api as any)[fn.name].bind(api)(...fn.args);
} else {
//just call the getter
(api as any)[fn.name];
}
}
if (api.onDecorator) api.onDecorator(target as ClassType, property, ('number' === typeof parameterIndexOrDescriptor ? parameterIndexOrDescriptor : undefined));
map.set(index, api);
}
const fn = createFluidDecorator(apiType, [], collapse);
Object.defineProperty(fn, '_fetch', {
configurable: true,
enumerable: false,
get: () => {
return (target: object, property?: string, parameterIndexOrDescriptor?: any) => {
const map = targetMap.get(target);
const secondIndex = ('number' === typeof parameterIndexOrDescriptor ? parameterIndexOrDescriptor : '');
const index = property + '$$' + secondIndex;
const api = map ? map.get(index) : undefined;
return api ? api.t : undefined;
};
}
});
(fn as any)._type = 'propertyDecorator';
return fn as any;
}
export type FreeDecoratorFn<API> = { (): ExtractApiDataType<API> };
export type FreeFluidDecorator<API> = {
[name in keyof ExtractClass<API>]: ExtractClass<API>[name] extends (...args: infer K) => any
? (...args: K) => FreeFluidDecorator<API>
: FreeFluidDecorator<API>
} & FreeDecoratorFn<API>;
export type FreeDecoratorResult<API extends APIClass<any>> = FreeFluidDecorator<API> & { _fluidFunctionSymbol: symbol };
export function createFreeDecoratorContext<API extends APIClass<any>, T = ExtractApiDataType<API>>(
apiType: API
): FreeDecoratorResult<API> {
function collapse(modifier: { name: string, args?: any }[]) {
const api = new apiType;
for (const fn of modifier) {
if (fn.args) {
(api as any)[fn.name].bind(api)(...fn.args);
} else {
//just call the getter
(api as any)[fn.name];
}
}
return api.t;
}
const fluidFunctionSymbol = Symbol('fluidFunctionSymbol');
const fn = createFluidDecorator(apiType, [], collapse, true, fluidFunctionSymbol);
Object.defineProperty(fn, '_fluidFunctionSymbol', {
configurable: true,
enumerable: false,
value: fluidFunctionSymbol
});
return fn as any;
}
export function isDecoratorContext<API extends APIClass<any>>(context: FreeDecoratorResult<API>, fn: Function): fn is FreeFluidDecorator<API> {
const symbol = context._fluidFunctionSymbol;
if (Object.getOwnPropertyDescriptor(fn, symbol)) return true;
return false;
} | the_stack |
import express from 'express'
import index from '../controllers/client/index' // 主页
import user from '../controllers/client/user/user' // 注册
import personalCenter from '../controllers/client/user/personalCenter' // 用户个人中心
import article from '../controllers/client/article/article' // 文章内容页
import articleBlog from '../controllers/client/article/articleBlog' // 文章评论
import articleComment from '../controllers/client/article/articleComment' // 文章评论
import subscribe from '../controllers/client/subscribe' // 订阅
import upload from '../controllers/client/upload' // 上传
import website from '../controllers/client/website' // 上传
import dynamic from '../controllers/client/dynamic/dynamic' // 动态
import dynamicComment from '../controllers/client/dynamic/dynamicComment' // 动态评论
import books from '../controllers/client/books/books' // 小书
import book from '../controllers/client/books/book' // 小书章节
import booksComment from '../controllers/client/books/booksComment' // 小书评价
import bookComment from '../controllers/client/books/bookComment' // 小书章节评论
import like from '../controllers/client/like' // 喜欢
import attention from '../controllers/client/attention' // 关注
import thumb from '../controllers/client/thumb' // 赞
import collect from '../controllers/client/collect' // 收藏
import virtual from '../controllers/client/virtual' // 虚拟币
import shop from '../controllers/client/shop' // 购物
import experience from '../controllers/client/experience' // 经验
import uploadUse from '../utils/upload/index'
import multerUse from '../utils/upload/multer'
const tokens = require('../utils/tokens') // 登录tokens
const verifyAuthority = require('../utils/verifyAuthority') // 权限验证
const router = express.Router()
/**
* 获取标签列表操作
* @param {String} TYPE 当前router 作用类型 AJAX:ajax传递数据 RENDER:render渲染页面或者 post form提交数据
*/
/* AJAX */
/* 登录类 注册类 */
router.post('/sign-in', user.userSignIn) // 登录数据 post TYPE:RENDER
router.post('/sign-up', user.userSignUp) // 注册数据 post TYPE:AJAX post
router.post('/sign-up-code', user.userSignUpCode) // 注册数据 发送注册 验证码 post TYPE:AJAX post
router.post('/reset-password-code', user.sendResetPasswordCode) // 重置密码验证码发送 TYPE:AJAX post
router.post('/reset-password', user.userResetPassword) // 重置密码 TYPE:AJAX post
router.post(
'/upload-file',
tokens.ClientVerifyToken,
multerUse('client').single('file'),
uploadUse,
upload.uploadFile
) // 用户修改头像 post
/**
* 个人信息类
*/
router.post('/personal/info', tokens.ClientVerifyToken, user.userPersonalInfo)
router.post(
'/personal/create-article-blog',
tokens.ClientVerifyToken,
articleBlog.createUserArticleBlog
) // 用户文章专题 TYPE:AJAX post
router.post(
'/personal/update-article-blog',
tokens.ClientVerifyToken,
articleBlog.updateUserArticleBlog
) // 更新用户所有文章专题 TYPE:AJAX get
router.post(
'/personal/delete-article-blog',
tokens.ClientVerifyToken,
articleBlog.deleteUserArticleBlog
) // 删除用户所有文章专题 TYPE:AJAX get
router.get(
'/personal/message-list',
tokens.ClientVerifyToken,
user.getUserMessageList
) // 用户消息 TYPE:AJAX get
router.delete(
'/personal/message-delete',
tokens.ClientVerifyToken,
user.deleteUserMessage
) // 删除用户消息 TYPE:AJAX post
router.post(
'/personal/upload-avatar',
tokens.ClientVerifyToken,
upload.uploadUserAvatar
) // 用户修改头像 post
router.put(
'/personal/update-info',
tokens.ClientVerifyToken,
user.updateUserInfo
) // 根据uid 更新用户相应信息 post
router.put(
'/personal/update-password',
tokens.ClientVerifyToken,
user.updateUserPassword
) // 根据uid 更新用户登录密码
/**
* 用户信息类
*/
router.get('/user/info', user.getUserInfo) // 根据uid 获取用户相应信息 get
router.get('/user/blog-all', articleBlog.getUserArticleBlogAll) // 获取用户所有文章专题 TYPE:AJAX get
router.get('/user/attention-list', personalCenter.getUserAttentionList) // 获取用户个人中心关注列表
router.get('/user/my-article', personalCenter.userMyArticle) // 用户个人中心专题页
router.get('/user/role-all', user.getUserRoleAll) // 获取所有用户角色标签
/**
* 文章相关的接口
*/
router.get('/article', tokens.ClientVerifyTokenInfo, article.getArticle) // 根据aid获取文章 get
router.get(
'/article-annex',
tokens.ClientVerifyTokenInfo,
article.getArticleAnnex
) // 根据aid获取文章 get
router.get('/user-article', tokens.ClientVerifyToken, article.getUserArticle) // 根据aid uid获取用户自己的某一篇文章 get
router.post(
'/article/create',
tokens.ClientVerifyToken,
verifyAuthority.ClientCheck,
article.createArticle
) // 编写文章post TYPE:AJAX post
router.get('/article/index', index.getIndexArticle) // 首页文章 get
router.get('/article/index-column', index.getColumnArticle) // 首页专栏文章 get
router.put('/article/update', tokens.ClientVerifyToken, article.updateArticle) // 更新文章
router.delete(
'/article/delete',
tokens.ClientVerifyToken,
article.deleteArticle
) // 删除文章 delete
router.get('/article/search', article.searchArticle) // 搜索
/**
* 文章专栏相关的接口
*/
router.get('/article/column', article.getArticleColumn) // 获取文章专栏
router.get('/article/column-all', article.getArticleColumnAll) // 获取文章专栏
router.get('/article-column/list', article.getArticleColumnList) // 获取文章专栏列表
/**
* 文章标签相关的接口
*/
router.get('/article-tag', article.getArticleTag) // 文章标签
router.get('/article-tag/all', article.getArticleTagAll) // 获取文章标签 获取全部的
router.get('/article-tag/list', subscribe.getArticleTagList) // 获取用户订阅标签列表 根据搜索和分页获取
router.get('/article-tag/popular-list', article.getPopularArticleTag) // 获取热门文章标签
router.get(
'/article-tag/list-my',
tokens.ClientVerifyToken,
subscribe.getArticleTagListMy
) // 获取用户已订阅的
router.get(
'/subscribe/tag-my',
tokens.ClientVerifyToken,
subscribe.getSubscribeTagMyAll
) // 获取文章标签 获取全部的
/**
* 个人专栏相关
*/
router.get('/article-blog/info', articleBlog.getArticleBlogView) // 个人专栏详细信息
router.get('/article-blog/article-list', articleBlog.getArticleBlogArticleList) // 当前个人专栏文章列表
/**
* 文章评论相关
*/
router.get('/article/comment-list', articleComment.getArticleComment) // 获取用户发表的评论列表 TYPE:AJAX get
router.post(
'/article/comment-create',
tokens.ClientVerifyToken,
verifyAuthority.ClientCheck,
articleComment.createArticleComment
) // 用户发表评论 TYPE:AJAX post
router.post(
'/article/comment-delete',
tokens.ClientVerifyToken,
articleComment.deleteArticleComment
) // 删除评论 TYPE:AJAX post
/**
* 网站配置相关信息
*/
router.post(
'/dynamic/create',
tokens.ClientVerifyToken,
verifyAuthority.ClientCheck,
dynamic.createDynamic
) // 创建动态
router.get('/dynamic/list', dynamic.getDynamicList) // 获取动态列表
router.get('/dynamic/recommend-list', dynamic.recommendDynamicList) // 获取推荐动态列表
router.get(
'/dynamic/list-my',
tokens.ClientVerifyToken,
dynamic.getDynamicListMe
) // 获取我的动态或者关注列表
router.get('/dynamic/view', dynamic.getDynamicView) // 获取动态详情
router.delete(
'/dynamic/delete',
tokens.ClientVerifyToken,
dynamic.deleteDynamic
) // 删除动态 TYPE:AJAX post
router.get('/website/info', website.getWebsiteInfo) // 网站配置相关信息 TYPE:AJAX get
router.get('/dynamic-topic/index', dynamic.dynamicTopicIndex) // 获取首页专题 TYPE:AJAX post
router.get('/dynamic-topic/list', dynamic.dynamicTopicList) // 获取专题页专题
/**
* 动态评论相关
*/
router.get('/dynamic-comment/list', dynamicComment.getDynamicCommentList) // 获取用户发表的动态评论列表 TYPE:AJAX get
router.get('/dynamic-comment/all', dynamicComment.getDynamicCommentAll) // 获取用户发表的动态评论全部 TYPE:AJAX get
router.post(
'/dynamic-comment/create',
tokens.ClientVerifyToken,
verifyAuthority.ClientCheck,
dynamicComment.createDynamicComment
) // 用户发表动态评论 TYPE:AJAX post
router.post(
'/dynamic-comment/delete',
tokens.ClientVerifyToken,
dynamicComment.deleteDynamicComment
) // 删除动态评论 TYPE:AJAX post
router.get('/personal/dynamic-list', personalCenter.getDynamicListMe) // 个人中心获取列表
router.get('/dynamic-topic/info', dynamic.getDynamicTopicInfo) // 获取动态话题的信息
router.get('/personal/article-blog-list', personalCenter.userArticleBlogList) // 用户自己的个人专栏列表
// 小书创建
router.post(
'/books/create',
tokens.ClientVerifyToken,
verifyAuthority.ClientCheck,
books.createBooks
)
router.get('/personal/books-list', personalCenter.userBooksList) // 获取用户个人小书的列表
router.get('/user-books/info', tokens.ClientVerifyToken, books.getUserBooksInfo) // 获取用户自己的小书信息
router.get('/books/info', tokens.ClientVerifyTokenInfo, books.getBooksInfo) // 获取小书信息
router.get(
'/books/book-all',
tokens.ClientVerifyTokenInfo,
books.getBooksBookAll
) // 获取小书章节列表
router.post('/books/update', tokens.ClientVerifyToken, books.updateBooks) // 更新用户自己的小书
router.post('/books/delete', tokens.ClientVerifyToken, books.deleteBooks) // 删除用户自己的小书
router.get('/books/list', books.getBooksList) // 首页小书的列表
router.post(
'/book/create',
tokens.ClientVerifyToken,
verifyAuthority.ClientCheck,
book.createBook
) // 创建小书的章节
router.post('/book/update', tokens.ClientVerifyToken, book.updateBook) // 编辑小书的章节
router.get('/user-book/info', tokens.ClientVerifyToken, book.getUserBookInfo) // 获取用户自己的小书章节信息
router.get('/book/info', tokens.ClientVerifyTokenInfo, book.getBookInfo) // 获取小书章节信息
router.post('/book/next-prev', book.getNextPrevBook) // 获取小书上一页,下一页
router.post('/book/delete', tokens.ClientVerifyToken, book.deleteBook) // 删除用户自己的小书章节
// 小书评论
router.get('/books-comment/list', booksComment.getBooksCommentList) // 获取用户发表小书评论的评论列表 TYPE:AJAX get
router.post(
'/books-comment/create',
tokens.ClientVerifyToken,
verifyAuthority.ClientCheck,
booksComment.createBooksComment
) // 用户小书发表评论 TYPE:AJAX post
router.post(
'/books-comment/delete',
tokens.ClientVerifyToken,
booksComment.deleteBooksComment
) // 删除小书评论 TYPE:AJAX post
// 小书章节评论
router.get('/book-comment/list', bookComment.getBookCommentList) // 获取用户发表小书章节评论的评论列表 TYPE:AJAX get
router.post(
'/book-comment/create',
tokens.ClientVerifyToken,
verifyAuthority.ClientCheck,
bookComment.createBookComment
) // 用户小书章节评论发表评论 TYPE:AJAX post
router.post(
'/book-comment/delete',
tokens.ClientVerifyToken,
bookComment.deleteBookComment
) // 删除小书章节评论 TYPE:AJAX post
// 用户虚拟币开始 2019.11.4 0:19
// 签到
router.post('/virtual/check-in', tokens.ClientVerifyToken, virtual.checkIn)
// 虚拟币动态记录
router.get('/virtual/list', tokens.ClientVerifyToken, virtual.getVirtualList)
// 购买
router.post('/shop/buy', tokens.ClientVerifyToken, shop.Buy)
// 订单列表
router.get('/shop/list', tokens.ClientVerifyToken, shop.orderList)
// 获取用户关联信息
router.get(
'/user/associate-info',
tokens.ClientVerifyTokenInfo,
user.getUserAssociateinfo
)
// 关注类
router.post(
'/common/attention',
tokens.ClientVerifyToken,
attention.setAttention
)
router.post('/common/like', tokens.ClientVerifyToken, like.setLike) // like TYPE:AJAX post
router.post('/common/collect', tokens.ClientVerifyToken, collect.setCollect) // 收藏
router.get('/collect/list', tokens.ClientVerifyToken, collect.getCollectList) // 收藏列表
router.post('/common/thumb', tokens.ClientVerifyToken, thumb.setThumb) // 用户点赞动态TYPE:AJAX post
router.get(
'/experience/list',
tokens.ClientVerifyToken,
experience.getExperienceList
) // 获取经验列表
module.exports = router | the_stack |
import { camelCase, cloneDeep, forEachRight, compact, clone } from "lodash-es";
import { Codex, Weapon } from "./codex";
import { i18n } from "@/i18n";
import { NormalMod, NormalModDatabase } from "./codex/mod";
import { hAccSum } from "./util";
import { Buff, BuffList } from "./codex/buff";
import { base62, debase62 } from "./lib/base62";
import { HH } from "@/var";
import { Companion, CompanionDataBase } from "./codex/companion";
import { CommonBuild } from "./commonbuild";
import { MeleeModBuild } from "./meleemodbuild";
// TODO
export enum CompanionCompareMode {
EffectiveHealth, // 有效血量
Health, // 血量
Armor, // 护甲
Shield, // 护盾
Attack, // 攻击
}
export interface CompanionBuildOptions {
compareMode?: CompanionCompareMode;
healthLinkRef?: number;
shieldLinkRef?: number;
armorLinkRef?: number;
}
export class CompanionBuild implements CommonBuild {
data: Companion;
protected _rawmods: NormalMod[] = [];
protected _mods: NormalMod[] = [];
protected _buffs: Buff[] = [];
/** 所有适用的MOD */
protected avaliableMods: NormalMod[] = [];
/** 原型MOD列表 */
get rawMods() {
return this._rawmods;
}
/** MOD列表 */
get mods() {
return cloneDeep(this._mods);
}
set mods(value) {
this._rawmods = cloneDeep(value);
this._mods = this.mapRankUpMods(value);
this.calcMods();
this.recalcPolarizations();
}
/** 加成列表 */
get buffs() {
return cloneDeep(this._buffs);
}
set buffs(value) {
this._buffs = cloneDeep(value);
this.calcMods();
}
/** ID */
get id() {
return this.data.id;
}
/** 本地化名称 */
get name() {
return i18n.t(`messages.${camelCase(this.data.id)}`);
}
/** 类型 */
get type() {
return "Companion";
}
/** 基础ID */
get baseId() {
return this.data.className || this.data.id;
}
/** 属性标记 */
get tags() {
return this.data.tags.concat(["Companion", this.baseId]);
}
protected _healthMul: number;
protected _healthAdd: number;
protected _shieldMul: number;
protected _armorMul: number;
protected _armorAdd: number;
protected _shieldRecharge: number;
protected _enemyRadarAdd: number;
protected _lootRadarAdd: number;
protected _damageResistance: number;
/** 链接 */
protected _healthLink: number;
protected _shieldLink: number;
protected _armorLink: number;
// ### 参数 ###
compareMode = CompanionCompareMode.EffectiveHealth;
healthLinkRef = 740;
shieldLinkRef = 300;
armorLinkRef = 150;
// ### 基础属性 ###
/** 生命 */
get health() {
return (this.data.health * this._healthMul) / 100 + this._healthAdd + (this.healthLinkRef * this._healthLink) / 100;
}
/** 护盾 */
get shield() {
return (this.data.shield * this._shieldMul) / 100 + (this.shieldLinkRef * this._shieldLink) / 100;
}
/** 护甲 */
get armor() {
return (this.data.armor * this._armorMul) / 100 + this._armorAdd + (this.armorLinkRef * this._armorLink) / 100;
}
/** 敌人雷达 */
get enemyRadar() {
return this._enemyRadarAdd / 100;
}
/** 物品雷达 */
get lootRadar() {
return this._lootRadarAdd / 100;
}
/** 伤害减免 */
get damageResistance() {
return this._damageResistance / 100;
}
/** 有效生命 */
get effectiveHealth() {
return (this.shield + this.health * (1 + this.armor / 300)) / (1 - this.damageResistance);
}
/** 对比参数 */
get compareValue() {
switch (this.compareMode) {
default:
case CompanionCompareMode.EffectiveHealth:
return this.effectiveHealth;
case CompanionCompareMode.Health:
return this.health;
case CompanionCompareMode.Armor:
return this.armor;
case CompanionCompareMode.Shield:
return this.shield;
case CompanionCompareMode.Attack:
return this.attackBuild.normalDamage;
}
}
constructor(data: Companion | string, options: CompanionBuildOptions = null) {
if (typeof data === "string") data = CompanionDataBase.getCompanionById(data);
if (!data) return;
if ((this.data = data)) {
this.avaliableMods = NormalModDatabase.filter(v => this.tags.includes(v.type));
}
if (options) {
this.options = options;
}
// 狗里藏刀
if (this.data.damage) {
this.attackBuild = new MeleeModBuild(
new Weapon({
name: this.id,
tags: ["Companion"],
modes: [
{
damage: data.damage,
critChance: data.critChance / 100,
critMul: data.critMul,
procChance: data.procChance / 100,
fireRate: 60,
},
],
}),
null,
null,
true
);
this.attackBuild.compareMode = 0;
}
this.reset();
}
set options(options: CompanionBuildOptions) {
this.compareMode = typeof options.compareMode !== "undefined" ? options.compareMode : this.compareMode;
this.healthLinkRef = typeof options.healthLinkRef !== "undefined" ? options.healthLinkRef : this.healthLinkRef;
this.shieldLinkRef = typeof options.shieldLinkRef !== "undefined" ? options.shieldLinkRef : this.shieldLinkRef;
this.armorLinkRef = typeof options.armorLinkRef !== "undefined" ? options.armorLinkRef : this.armorLinkRef;
}
get options(): CompanionBuildOptions {
return {
compareMode: this.compareMode,
healthLinkRef: this.healthLinkRef,
shieldLinkRef: this.shieldLinkRef,
armorLinkRef: this.armorLinkRef,
};
}
/** 重置属性 */
reset() {
this._healthMul = 100;
this._healthAdd = 0;
this._shieldMul = 100;
this._armorMul = 100;
this._armorAdd = 0;
this._shieldRecharge = 100;
this._enemyRadarAdd = 0;
this._lootRadarAdd = 0;
this._damageResistance = 0;
this._healthLink = 0;
this._shieldLink = 0;
this._armorLink = 0;
this.recalcPolarizations();
if (this.attackBuild) {
this.attackBuild.reset();
}
}
/**
* 应用通用属性
*
* @param {(NormalMod)} mod MOD
* @param {string} pName 属性id或名称
* @param {number} pValue 属性值
* @memberof companionBuild
*/
applyProp(mod: NormalMod, pName: string, pValue: number = 0) {
switch (pName) {
/** Health */ case "h":
this._healthMul = hAccSum(this._healthMul, pValue);
break;
/** Health Link */ case "hl":
this._healthLink = hAccSum(this._healthLink, pValue);
break;
/** extra Health */ case "eh":
this._healthAdd = hAccSum(this._healthAdd, pValue);
break;
/** Shield */ case "s":
this._shieldMul = hAccSum(this._shieldMul, pValue);
break;
/** Shield Link */ case "sl":
this._shieldLink = hAccSum(this._shieldLink, pValue);
break;
/** Amror */ case "a":
this._armorMul = hAccSum(this._armorMul, pValue);
break;
/** Amror Link */ case "al":
this._armorLink = hAccSum(this._armorLink, pValue);
break;
/** AmrorAdd */ case "ea":
this._armorAdd = hAccSum(this._armorAdd, pValue);
break;
/** ShieldRecharge */ case "r":
this._shieldRecharge = hAccSum(this._shieldRecharge, pValue);
break;
/** EnemyRadar */ case "er":
this._enemyRadarAdd = hAccSum(this._enemyRadarAdd, pValue);
break;
/** LootRadar */ case "lr":
this._lootRadarAdd = hAccSum(this._lootRadarAdd, pValue);
break;
/** Damage Resistance */ case "res":
this._damageResistance = 100 - ((100 - this._damageResistance) * (100 - pValue)) / 100;
break;
}
}
/**
* 应用MOD
*
* @param {NormalMod} mod MOD
* @returns
* @memberof companionBuild
*/
applyMod(mod: NormalMod) {
this._mods.push(mod);
this.calcMods();
return this;
}
/**
* 应用加成
*
* @param {Buff} buff
* @returns
* @memberof companionBuild
*/
applyBuff(buff: Buff) {
this._buffs.push(buff);
this.calcMods();
return this;
}
/**
* 将Mod属性写入到增幅上
*
* @memberof companionBuild
*/
calcMods() {
this.reset();
this._mods.forEach(mod => {
mod && forEachRight(mod.props, prop => this.applyProp(mod, prop[0], prop[1]));
});
// 加载Buff
this._buffs.forEach(buff => {
buff && buff.props.forEach(prop => this.applyProp(null, prop[0], prop[1]));
});
if (this.attackBuild) {
this.attackBuild.mods = this.mods;
this.attackBuild.buffs = this.buffs;
}
}
/**
* 清除所有MOD并重置属性增幅器
*
* @memberof companionBuild
*/
clear() {
this._mods = [];
this.reset();
}
/**
* 检测当前MOD是否可用
*
* @param {NormalMod} mod MOD
* @returns {boolean}
* @memberof companionBuild
*/
isValidMod(mod: NormalMod): boolean {
let mods = compact(this._mods);
// 如果相应的P卡已经存在则不使用
if (mods.some(v => v.id === mod.primed || v.primed === mod.id || (v.primed && v.primed === mod.primed))) return false;
return true;
}
/**
* [纯函数] 映射组合MOD加成
*
* @param {NormalMod[]} mods
* @returns {NormalMod[]}
* @memberof companionBuild
*/
mapRankUpMods(mods: NormalMod[]): NormalMod[] {
return mods;
}
/**
* 返回MOD价值收益
* @param index 也可以是mod.id
* @return MOD价值收益 (-∞ ~ +∞ 小数)
*/
modValue(index: number | string) {
if (typeof index === "string") index = this._mods.findIndex(v => v && v.id === index);
if (!this._mods[index]) return 0;
let nb = new (this.constructor as any)(this.data);
nb._mods = this.mods;
nb._buffs = this.buffs;
nb.compareMode = this.compareMode;
nb._mods.splice(index, 1);
let oldVal = this.compareValue;
nb.calcMods();
let newVal = nb.compareValue;
return oldVal / newVal - 1;
}
/**
* 返回BUFF价值收益
* @param index 也可以是buff.id
* @return MOD价值收益 (-∞ ~ +∞ 小数)
*/
buffValue(index: number | string) {
if (typeof index === "string") index = this._buffs.findIndex(v => v.data.id === index);
if (!this._buffs[index]) return 0;
let nb = new (this.constructor as any)(this.data);
nb._mods = this.mods;
nb._buffs = this.buffs;
nb.compareMode = this.compareMode;
nb._buffs.splice(index, 1);
let oldVal = this.compareValue;
nb.calcMods();
let newVal = nb.compareValue;
return oldVal / newVal - 1;
}
/**
* 自动填充MOD
* @param slots 可用的插槽数
* @param useRiven 是否使用紫卡 0 = 不用 1 = 自动选择 2 = 必须用
*/
fill(slots = 10, useRiven = 0) {
// 初始化
this.clear();
this.fillEmpty(slots, useRiven);
}
/**
* MOD自动填充V1
*
* @description 根据所需的属性计算最大化或最小化以填充空白
* @memberof companionBuild
*/
fillEmpty(slots = 10, useRiven = 0, lib = this.avaliableMods, rivenLimit = 0) {
let mods = (this._mods = compact(this._mods));
let othermods = lib.filter(v => !mods.some(k => v.id === k.id || v.id === k.primed || v.primed === k.id));
let sortableMods = othermods.map(v => [v, this.testMod(v)] as [NormalMod, number]).filter(v => v[1] > 0);
console.log(sortableMods, mods.length, sortableMods.length, slots - mods.length);
while (mods.length < slots && sortableMods.length > 0) {
// 2. 计算收益
// console.log("开始计算收益: ", this._mods.length)
sortableMods.forEach(v => {
v[1] = this.testMod(v[0]);
});
// 3. 把所有卡按收益排序
sortableMods.sort((a, b) => (b[1] == a[1] ? b[0].name.localeCompare(a[0].name) : b[1] - a[1]));
if (sortableMods.length > 0) {
// console.log("计算收益最高值: ", sortableMods[0][0].name, "的收益是", sortableMods[0][1]);
// 4. 将收益最高的一项插入并移出数组
let expMod = sortableMods.shift();
// 跳过负收益 (可能是被过滤的)
if (expMod[1] < 0) break;
this.applyMod(expMod[0]);
// 5. 重复以上步骤直到卡槽充满
}
}
this._mods.length = 10;
this.recalcPolarizations();
}
/**
* 返回MOD增幅数值
* @param mod NormalMod
* @return MOD增幅数值
*/
testMod(mod: NormalMod) {
// MOD查重
if (!this.isValidMod(mod)) return -1;
// 效率优化
if (mod.props.length == 1) {
let oriDmg: [string, number];
switch (mod.props[0][0]) {
}
}
// 通用方法
let oldVal = this.compareValue;
this._mods.push(mod);
this.calcMods();
let newVal = this.compareValue;
this._mods.pop();
this.calcMods();
return newVal / oldVal - 1;
}
// === 计算属性 ===
/**
* 序列化支持
* 20位 普通MOD序列 如00001A1B000000000000
* 等级修饰符@0-A 如00001A@01B000000000000
* 不定长buff序列 ![id]: [base62 encoded power]: [layer]
* @type {string}
* @memberof companionBuild
*/
get miniCode(): string {
let mods = this.mods;
while (mods.length < 10) mods.push(null);
let normal = mods.map(v => (v && v.key + (v.level !== v.maxLevel ? "@" + base62(v.level) : "")) || "00").join("");
let buffseq = this.buffs.map(v => `_${v.data.id}:${v.powerEnable && v.power ? base62(v.power * 10) : ""}${v.layerEnable ? ":" + v.layer : ""}`).join("");
if (normal === "00000000000000000000") return buffseq;
else return normal + buffseq;
}
set miniCode(code: string) {
if (code.startsWith("!") || code.startsWith("_")) code = "00000000000000000000" + code;
let normal = code.match(/..(?:@.)?/g).slice(0, 10);
let subPart = code.substr(normal.join("").length);
let buffIdx = subPart.indexOf("_");
if (buffIdx < 0) buffIdx = subPart.indexOf("!");
let buffseq = subPart.substr(buffIdx + 1);
let bufflist = [];
buffseq.split(/[!_]/g).forEach(buff => {
let w = buff.split(":");
let bdata = BuffList.find(v => v.id === w[0]);
if (bdata) {
let newBuff = new Buff(bdata);
if (w[1]) newBuff.power = debase62(w[1]) / 10;
if (w[2]) newBuff.layer = +w[2];
bufflist.push(newBuff);
}
});
let mods = normal.map(v => {
let key = v.substr(0, 2),
level = v.substr(3, 4);
let mod = cloneDeep(Codex.getNormalMod(key));
if (level) mod.level = debase62(level);
return mod;
});
this._buffs = bufflist;
this.mods = mods;
}
get miniCodeURL() {
return this.miniCode ? `https://${HH}/companion/${this.data.url}/${this.miniCode}` : `https://${HH}/companion/${this.data.url}`;
}
get maxHealth() {
return 1;
}
get maxShield() {
return 1;
}
get maxArmor() {
return 1;
}
// 容量计算与极化
protected _polarizations: string[] = Array(10);
get polarizations() {
return this._polarizations;
}
/** 容量 */
get totalCost() {
let total = this.mods.reduce((a, _, i) => (a += this.getCost(i)), 0);
return total;
}
/** 获取指定位置MOD的容量 */
getCost(modIndex: number) {
let mod = this.mods[modIndex];
if (mod) return mod.calcCost(this.polarizations[modIndex]);
return 0;
}
/** 最大容量 */
get maxCost() {
return 60;
}
_formaCount = 0;
_umbraCount = 0;
/** 极化次数 */
get formaCount() {
return this._formaCount;
}
/** 暗影极化次数 */
get umbraCount() {
return this._umbraCount;
}
/** 重新计算极化次数 */
recalcPolarizations(allowedUmbra = 0) {
// 自带的极性
let defaultPolarities = this.data.polarities.slice();
this._polarizations = Array(10).fill(null);
this._formaCount = 0;
this._umbraCount = 0;
// 匹配自带槽位
// - 正面极性
const deltaSeq = this._mods.map((v, i) => [i, v ? v.delta : 0]).sort((a, b) => b[1] - a[1]);
// - 负面极性
const thetaSeq = this._mods.map((v, i) => [i, v ? v.theta : 0]).sort((a, b) => a[1] - b[1]);
deltaSeq.forEach(([i]) => {
if (this._mods[i]) {
let matched = defaultPolarities.indexOf(this._mods[i].polarity);
if (matched >= 0) {
defaultPolarities.splice(matched, 1);
this._polarizations[i] = this._mods[i].polarity;
}
}
});
// 负面极性位
let thetaMod = [];
let remainUmbra = allowedUmbra;
// 强制使用自带槽位
while (defaultPolarities.length > 0) {
const pol = defaultPolarities.pop();
let mod = thetaSeq.pop();
if (mod) {
// 跳过已经极化的槽位
if (!this._polarizations[mod[0]]) {
this._polarizations[mod[0]] = pol;
thetaMod.push(mod[0]);
}
} else {
this._polarizations.some((v, i) => {
if (!v) {
this._polarizations[i] = pol;
return true;
}
return false;
});
}
}
// 按容量需求量排序
const mods = this.mods;
enum polSeq {
r,
"-",
d,
"=",
"w",
}
const delta = mods
.map((v, i) => [i, v ? v.delta : 0])
.sort((a, b) => {
const costD = b[1] - a[1];
if (costD) return costD;
if (mods[b[0]] && mods[a[0]]) return polSeq[mods[a[0]].polarity] - polSeq[mods[b[0]].polarity] || a[0] - b[0]; // 先极化常用槽
return a[0] - b[0]; // 点数相同优先极化前面
});
// 最多极化10次
for (let i = 0; this.totalCost > this.maxCost && i < delta.length && mods[delta[i][0]]; ++i) {
const [modIndex] = delta[i];
const pol = mods[modIndex].polarity;
if (remainUmbra || pol !== "w") {
// console.log(`set pol [[${this._polarizations}]] ${modIndex - 2}: ${this._polarizations[modIndex - 2]} to ${pol}`)
if (this._polarizations[modIndex] !== pol) {
this._polarizations[modIndex] = pol;
if (pol === "w") {
--remainUmbra;
++this._umbraCount;
} else {
++this._formaCount;
}
}
} else if (thetaMod.includes(modIndex)) {
// console.log(`set null [[${this._polarizations}]] ${modIndex - 2}: ${this._polarizations[modIndex - 2]} to null`)
this._polarizations[modIndex] = "";
thetaMod = thetaMod.filter(v => v != modIndex);
}
}
// 如果还是负的 测试U福马数量
if (this.totalCost > this.maxCost) {
for (let i = 0; this.totalCost > this.maxCost && i < delta.length && mods[delta[i][0]]; ++i) {
const [modIndex] = delta[i];
const pol = mods[modIndex].polarity;
if (pol === "w") {
if (this._polarizations[modIndex] !== pol) {
this._polarizations[modIndex] = pol;
++this._umbraCount;
}
}
}
}
// console.log(this.allMods, this.allPolarizations)
return this.polarizations;
}
// 野兽类同伴的攻击计算
attackBuild: MeleeModBuild;
get weapon() {
return this.attackBuild && this.attackBuild.weapon;
}
}
export * from "./codex/companion"; | the_stack |
import {
IconCommonClose,
IconCommonDataAsset,
IconCommonDbt,
IconCommonEdit,
IconCommonLock,
IconCommonSmartQuery,
IconCommonSqlQuery
} from '@app/assets/icons'
import { useBlockSuspense } from '@app/hooks/api'
import { useBlockTranscations } from '@app/hooks/useBlockTranscation'
import { ThemingVariables } from '@app/styles'
import { Editor } from '@app/types'
import { DEFAULT_TITLE } from '@app/utils'
import { css } from '@emotion/css'
import React, { useCallback, useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import PerfectScrollbar from 'react-perfect-scrollbar'
import { Tab, TabList, TabPanel, useTabState } from 'reakit/Tab'
import { useSideBarQuestionEditor, useSideBarRightState } from '../hooks/useSideBarQuestionEditor'
import { ContentEditablePureText, EditableSimpleRef } from './editor/BlockBase/ContentEditablePureText'
import IconButton from './kit/IconButton'
import { SideBarDataAssets } from './SideBarDataAssets'
import SideBarModeling from './SideBarModeling'
import SideBarSmartQuery from './SideBarSmartQuery'
import SideBarVisualization from './SideBarVisualization'
import { SideBarTabHeader } from './v11n/components/Tab'
import { VariableSettingsSection } from './VariableSettingsSection'
export const DefaultSideBar: React.FC<{ storyId: string }> = ({ storyId }) => {
const tab = useTabState()
const { t } = useTranslation()
return (
<div
className={css`
height: 100%;
display: flex;
background-color: #fff;
flex-direction: column;
`}
>
<TabList
{...tab}
className={css`
border-bottom: solid 1px ${ThemingVariables.colors.gray[1]};
overflow-x: auto;
white-space: nowrap;
padding-right: 16px;
flex-shrink: 0;
`}
>
<Tab as={SideBarTabHeader} {...tab} id="Data Assets" selected={tab.selectedId === 'Data Assets'}>
{t`Data Assets`}
</Tab>
</TabList>
<TabPanel
{...tab}
className={css`
flex: 1;
overflow: hidden;
`}
>
<React.Suspense fallback={<></>}>
<SideBarDataAssets storyId={storyId} />
</React.Suspense>
</TabPanel>
</div>
)
}
const BLOCKTYPE_ICON = {
[Editor.BlockType.QueryBuilder]: IconCommonDataAsset,
[Editor.BlockType.SnapshotBlock]: IconCommonLock,
[Editor.BlockType.SmartQuery]: IconCommonSmartQuery,
[Editor.BlockType.DBT]: IconCommonDbt,
[Editor.BlockType.SQL]: IconCommonSqlQuery
}
export const QuestionTitleEditor: React.FC<{ blockId: string; storyId: string }> = ({ blockId, storyId }) => {
const queryBlock = useBlockSuspense(blockId)
const blockTranscation = useBlockTranscations()
const setTitle = useCallback(
(title: Editor.Token[]) => {
blockTranscation.updateBlockProps(storyId, blockId, ['content', 'title'], title)
},
[blockId, blockTranscation, storyId]
)
const [titleEditing, setTitleEditing] = useState(false)
const contentEditableRef = useRef<EditableSimpleRef | null>(null)
const sideBarQuestionEditor = useSideBarQuestionEditor(storyId)
const Icon = BLOCKTYPE_ICON[queryBlock.type as keyof typeof BLOCKTYPE_ICON]
return (
<div
className={css`
display: flex;
min-height: 40px;
padding: 0 10px;
align-items: center;
justify-content: flex-start;
background-color: ${ThemingVariables.colors.gray[3]};
`}
>
<div
className={css`
margin-right: 10px;
`}
>
{Icon ? <Icon color={ThemingVariables.colors.text[0]} /> : null}
</div>
<ContentEditablePureText
tokens={queryBlock?.content?.title}
onChange={(tokens) => {
setTitle(tokens)
}}
ref={contentEditableRef}
disableEnter
// readonly={!titleEditing}
placeHolderStrategy="always"
placeHolderText={DEFAULT_TITLE}
textAlign="left"
onConfirm={() => {
setTitleEditing(false)
}}
onClick={() => {
setTitleEditing(true)
}}
onBlur={() => {
setTitleEditing(false)
}}
onFocus={() => {
setTitleEditing(true)
}}
className={css`
background: transparent;
cursor: text;
background: transparent;
font-size: 20px;
text-align: center;
font-weight: 500;
font-size: 14px;
line-height: 24px;
/* white-space: nowrap; */
overflow-x: auto;
max-width: 100%;
color: ${ThemingVariables.colors.text[0]};
`}
/>
{!titleEditing && (
<IconButton
icon={IconCommonEdit}
size={14}
color={ThemingVariables.colors.gray[0]}
onClick={() => {
setTitleEditing(true)
setTimeout(() => {
contentEditableRef.current?.focus()
}, 0)
}}
className={css`
margin-left: 4px;
`}
/>
)}
<IconButton
icon={IconCommonClose}
color={ThemingVariables.colors.gray[0]}
onClick={() => {
sideBarQuestionEditor.close()
}}
className={css`
margin-left: auto;
cursor: pointer;
`}
/>
</div>
)
}
export const VariableSideBar: React.FC<{ storyId: string; blockId: string }> = ({ storyId, blockId }) => {
const tab = useTabState()
const { t } = useTranslation()
const [sideBarEditorState, setSideBarEditorState] = useSideBarRightState(storyId)
useEffect(() => {
if (sideBarEditorState?.data?.activeTab) {
tab.setSelectedId(sideBarEditorState.data?.activeTab)
}
}, [sideBarEditorState, tab])
const changeTab = useCallback(
(tab: 'Variable' | 'Help') => {
setSideBarEditorState((value) => {
if (value) {
return { ...value, data: { ...value.data, activeTab: tab } }
}
return value
})
},
[setSideBarEditorState]
)
return (
<div
className={css`
height: 100%;
display: flex;
background-color: #fff;
flex-direction: column;
`}
>
<TabList
{...tab}
className={css`
border-bottom: solid 1px ${ThemingVariables.colors.gray[1]};
overflow-x: auto;
white-space: nowrap;
padding-right: 16px;
`}
>
<Tab
as={SideBarTabHeader}
{...tab}
id="Variable"
selected={tab.selectedId === 'Variable'}
onClick={() => {
changeTab('Variable')
}}
>
{t`Variable`}
</Tab>
{/* <Tab
as={SideBarTabHeader}
{...tab}
id="Help"
selected={tab.selectedId === 'Help'}
onClick={() => {
changeTab('Help')
}}
>
{t`Help`}
</Tab> */}
</TabList>
<TabPanel {...tab}>
<React.Suspense fallback={<></>}>
<VariableSettingsSection storyId={storyId} blockId={blockId} />
</React.Suspense>
</TabPanel>
{/* <TabPanel {...tab}>
<React.Suspense fallback={<></>}>
<SideBarVisualization storyId={storyId} blockId={blockId} key={blockId} />
</React.Suspense>
</TabPanel> */}
</div>
)
}
export const QuestionEditorSideBar: React.FC<{ storyId: string; blockId: string }> = ({ storyId, blockId }) => {
const tab = useTabState()
const { t } = useTranslation()
const block = useBlockSuspense<Editor.VisualizationBlock>(blockId)
const queryBlock = useBlockSuspense(block.content?.queryId || blockId)
const [sideBarEditorState, setSideBarEditorState] = useSideBarRightState(storyId)
useEffect(() => {
if (sideBarEditorState?.data?.activeTab) {
tab.setSelectedId(sideBarEditorState.data?.activeTab)
}
}, [sideBarEditorState, tab])
const changeTab = useCallback(
(tab: 'Visualization' | 'Modeling' | 'Query') => {
setSideBarEditorState((value) => {
if (value) {
return { ...value, data: { ...value.data, activeTab: tab } }
}
return value
})
},
[setSideBarEditorState]
)
return (
<div
className={css`
height: 100%;
display: flex;
background-color: #fff;
flex-direction: column;
`}
>
<QuestionTitleEditor blockId={queryBlock.id} storyId={storyId} key={blockId} />
<TabList
{...tab}
className={css`
border-bottom: solid 1px ${ThemingVariables.colors.gray[1]};
overflow-x: auto;
white-space: nowrap;
padding-right: 16px;
`}
>
{queryBlock.type === Editor.BlockType.SmartQuery ? (
<Tab
as={SideBarTabHeader}
{...tab}
id="Query"
selected={tab.selectedId === 'Query'}
onClick={() => {
changeTab('Query')
}}
>
{t`Query`}
</Tab>
) : null}
<Tab
as={SideBarTabHeader}
{...tab}
id="Visualization"
selected={tab.selectedId === 'Visualization'}
onClick={() => {
changeTab('Visualization')
}}
>
{t`Visualization`}
</Tab>
{queryBlock.type !== Editor.BlockType.SmartQuery ? (
<Tab
as={SideBarTabHeader}
{...tab}
id="Modeling"
selected={tab.selectedId === 'Modeling'}
onClick={() => {
changeTab('Modeling')
}}
>
{t`Modeling`}
</Tab>
) : null}
</TabList>
<PerfectScrollbar
options={{ suppressScrollX: true }}
className={css`
flex: 1;
`}
>
{queryBlock.type === Editor.BlockType.SmartQuery ? (
<TabPanel {...tab}>
<React.Suspense fallback={<></>}>
<SideBarSmartQuery storyId={storyId} blockId={blockId} />
</React.Suspense>
</TabPanel>
) : null}
<TabPanel {...tab}>
<React.Suspense fallback={<></>}>
<SideBarVisualization storyId={storyId} blockId={blockId} key={blockId} />
</React.Suspense>
</TabPanel>
{queryBlock.type !== Editor.BlockType.SmartQuery ? (
<TabPanel {...tab}>
<React.Suspense fallback={<></>}>
<SideBarModeling storyId={storyId} blockId={blockId} />
</React.Suspense>
</TabPanel>
) : null}
</PerfectScrollbar>
</div>
)
}
export const SideBarRight: React.FC<{ storyId: string }> = ({ storyId }) => {
const [sideBarEditorState] = useSideBarRightState(storyId)
if (sideBarEditorState?.type === 'Variable' && sideBarEditorState.data?.blockId) {
return <VariableSideBar storyId={storyId} blockId={sideBarEditorState.data.blockId} />
}
if (sideBarEditorState?.type === 'Question' && sideBarEditorState.data?.blockId) {
return <QuestionEditorSideBar storyId={storyId} blockId={sideBarEditorState.data.blockId} />
}
return <DefaultSideBar storyId={storyId} />
} | the_stack |
import * as T from "../../../Effect"
import * as E from "../../../Either"
import type { FiberID } from "../../../Fiber"
import type { Journal } from "../Journal/index"
export const STMTypeId = Symbol()
export type STMTypeId = typeof STMTypeId
/**
* `STM<R, E, A>` represents an effect that can be performed transactionally,
* resulting in a failure `E` or a value `A` that may require an environment
* `R` to execute.
*
* Software Transactional Memory is a technique which allows composition of arbitrary atomic operations. It is
* the software analog of transactions in database systems.
*
* The API is lifted directly from the Haskell package Control.Concurrent.STM although the implementation does not
* resemble the Haskell one at all.
* [[http://hackage.haskell.org/package/stm-2.5.0.0/docs/Control-Concurrent-STM.html]]
*
* STM in Haskell was introduced in:
* Composable memory transactions, by Tim Harris, Simon Marlow, Simon Peyton Jones, and Maurice Herlihy, in ACM
* Conference on Principles and Practice of Parallel Programming 2005.
* [[https://www.microsoft.com/en-us/research/publication/composable-memory-transactions/]]
*
* See also:
* Lock Free Data Structures using STMs in Haskell, by Anthony Discolo, Tim Harris, Simon Marlow, Simon Peyton Jones,
* Satnam Singh) FLOPS 2006: Eighth International Symposium on Functional and Logic Programming, Fuji Susono, JAPAN,
* April 2006
* [[https://www.microsoft.com/en-us/research/publication/lock-free-data-structures-using-stms-in-haskell/]]
*
* The implemtation is based on the ZIO STM module, while JS environments have no race conditions from multiple threads
* STM provides greater benefits for syncronisation of Fibers and transactional data-types can be quite useful.
*/
export abstract class STM<R, E, A> {
readonly [STMTypeId]: STMTypeId = STMTypeId;
readonly [T._R]!: (_: R) => void;
readonly [T._E]!: () => E;
readonly [T._A]!: () => A
}
export const STMEffectTypeId = Symbol()
export type STMEffectTypeId = typeof STMEffectTypeId
export class STMEffect<R, E, A> extends STM<R, E, A> {
readonly _typeId: STMEffectTypeId = STMEffectTypeId
constructor(readonly f: (journal: Journal, fiberId: FiberID, r: R) => A) {
super()
}
}
export const STMOnFailureTypeId = Symbol()
export type STMOnFailureTypeId = typeof STMOnFailureTypeId
export class STMOnFailure<R, E, E1, A> extends STM<R, E1, A> {
readonly _typeId: STMOnFailureTypeId = STMOnFailureTypeId
constructor(readonly stm: STM<R, E, A>, readonly onFailure: (e: E) => STM<R, E1, A>) {
super()
}
apply(a: A): STM<R, E, A> {
return new STMSucceedNow(a)
}
}
export const STMOnRetryTypeId = Symbol()
export type STMOnRetryTypeId = typeof STMOnRetryTypeId
export class STMOnRetry<R, E, A> extends STM<R, E, A> {
readonly _typeId: STMOnRetryTypeId = STMOnRetryTypeId
constructor(readonly stm: STM<R, E, A>, readonly onRetry: STM<R, E, A>) {
super()
}
apply(a: A): STM<R, E, A> {
return new STMSucceedNow(a)
}
}
export const STMOnSuccessTypeId = Symbol()
export type STMOnSuccessTypeId = typeof STMOnSuccessTypeId
export class STMOnSuccess<R, E, A, B> extends STM<R, E, B> {
readonly _typeId: STMOnSuccessTypeId = STMOnSuccessTypeId
constructor(readonly stm: STM<R, E, A>, readonly apply: (a: A) => STM<R, E, B>) {
super()
}
}
export const STMSucceedTypeId = Symbol()
export type STMSucceedTypeId = typeof STMSucceedTypeId
export class STMSucceed<R, E, A> extends STM<R, E, A> {
readonly _typeId: STMSucceedTypeId = STMSucceedTypeId
constructor(readonly a: () => A) {
super()
}
}
export const STMSucceedNowTypeId = Symbol()
export type STMSucceedNowTypeId = typeof STMSucceedNowTypeId
export class STMSucceedNow<R, E, A> extends STM<R, E, A> {
readonly _typeId: STMSucceedNowTypeId = STMSucceedNowTypeId
constructor(readonly a: A) {
super()
}
}
export const STMProvideSomeTypeId = Symbol()
export type STMProvideSomeTypeId = typeof STMProvideSomeTypeId
export class STMProvideSome<R0, R, E, A> extends STM<R, E, A> {
readonly _typeId: STMProvideSomeTypeId = STMProvideSomeTypeId
constructor(readonly stm: STM<R0, E, A>, readonly f: (r: R) => R0) {
super()
}
}
/**
* @ets_optimize remove
*/
export function concreteSTM<R, E, A>(
_: STM<R, E, A>
): asserts _ is
| STMEffect<R, E, A>
| STMOnFailure<R, unknown, E, A>
| STMOnSuccess<R, E, unknown, A>
| STMOnRetry<R, E, A>
| STMSucceed<R, E, A>
| STMSucceedNow<R, E, A>
| STMProvideSome<unknown, R, E, A> {
//
}
export const FailExceptionTypeId = Symbol()
export type FailExceptionTypeId = typeof FailExceptionTypeId
export class STMFailException<E> {
readonly _typeId: FailExceptionTypeId = FailExceptionTypeId
constructor(readonly e: E) {}
}
export function isFailException(u: unknown): u is STMFailException<unknown> {
return (
typeof u === "object" &&
u != null &&
"_typeId" in u &&
u["_typeId"] === FailExceptionTypeId
)
}
export const DieExceptionTypeId = Symbol()
export type DieExceptionTypeId = typeof DieExceptionTypeId
export class STMDieException<E> {
readonly _typeId: DieExceptionTypeId = DieExceptionTypeId
constructor(readonly e: E) {}
}
export function isDieException(u: unknown): u is STMDieException<unknown> {
return (
typeof u === "object" &&
u != null &&
"_typeId" in u &&
u["_typeId"] === DieExceptionTypeId
)
}
export const RetryExceptionTypeId = Symbol()
export type RetryExceptionTypeId = typeof RetryExceptionTypeId
export class STMRetryException {
readonly _typeId: RetryExceptionTypeId = RetryExceptionTypeId
}
export function isRetryException(u: unknown): u is STMRetryException {
return (
typeof u === "object" &&
u != null &&
"_typeId" in u &&
u["_typeId"] === RetryExceptionTypeId
)
}
//
// primitive ops
//
/**
* Returns an `STM` effect that succeeds with the specified value.
*/
export function succeed<A>(a: A): STM<unknown, never, A> {
return new STMSucceedNow(a)
}
/**
* Returns an `STM` effect that succeeds with the specified value.
*/
export function succeedWith<A>(a: () => A): STM<unknown, never, A> {
return new STMSucceed(a)
}
/**
* Returns a value that models failure in the transaction.
*/
export function fail<E>(e: E): STM<unknown, E, never> {
return new STMEffect(() => {
throw new STMFailException(e)
})
}
/**
* Returns a value that models failure in the transaction.
*/
export function failWith<E>(e: () => E): STM<unknown, E, never> {
return new STMEffect(() => {
throw new STMFailException(e())
})
}
/**
* Kills the fiber running the effect.
*/
export function die(u: unknown): STM<unknown, never, never> {
return new STMEffect(() => {
throw new STMDieException(u)
})
}
/**
* Kills the fiber running the effect.
*/
export function dieWith(u: () => unknown): STM<unknown, never, never> {
return new STMEffect(() => {
throw new STMDieException(u())
})
}
/**
* Maps the value produced by the effect.
*/
export function map_<R, E, A, B>(self: STM<R, E, A>, f: (a: A) => B): STM<R, E, B> {
return chain_(self, (a) => succeed(f(a)))
}
/**
* Maps the value produced by the effect.
*
* @ets_data_first map_
*/
export function map<A, B>(f: (a: A) => B): <R, E>(self: STM<R, E, A>) => STM<R, E, B> {
return (self) => map_(self, f)
}
/**
* Feeds the value produced by this effect to the specified function,
* and then runs the returned effect as well to produce its results.
*/
export function chain_<R, E, A, R1, E1, B>(
self: STM<R, E, A>,
f: (a: A) => STM<R1, E1, B>
): STM<R1 & R, E | E1, B> {
return new STMOnSuccess<R1 & R, E | E1, A, B>(self, f)
}
/**
* Feeds the value produced by this effect to the specified function,
* and then runs the returned effect as well to produce its results.
*
* @ets_data_first chain_
*/
export function chain<A, R1, E1, B>(
f: (a: A) => STM<R1, E1, B>
): <R, E>(self: STM<R, E, A>) => STM<R1 & R, E | E1, B> {
return (self) => chain_(self, f)
}
/**
* Recovers from all errors.
*/
export function catchAll_<R, E, A, R1, E1, B>(
self: STM<R, E, A>,
f: (e: E) => STM<R1, E1, B>
): STM<R1 & R, E1, A | B> {
return new STMOnFailure<R1 & R, E, E1, A | B>(self, f)
}
/**
* Recovers from all errors.
*
* @ets_data_first catchAll_
*/
export function catchAll<E, R1, E1, B>(
f: (e: E) => STM<R1, E1, B>
): <R, A>(self: STM<R, E, A>) => STM<R1 & R, E1, A | B> {
return (self) => catchAll_(self, f)
}
/**
* Effectfully folds over the `STM` effect, handling both failure and
* success.
*/
export function foldM_<R, E, A, R1, E1, B, R2, E2, C>(
self: STM<R, E, A>,
g: (e: E) => STM<R2, E2, C>,
f: (a: A) => STM<R1, E1, B>
): STM<R1 & R2 & R, E1 | E2, B | C> {
return chain_<R2 & R, E2, E.Either<C, A>, R1, E1, B | C>(
catchAll_(map_(self, E.right), (e) => map_(g(e), E.left)),
E.fold(succeed, f)
)
}
/**
* Effectfully folds over the `STM` effect, handling both failure and
* success.
*
* @ets_data_first foldM_
*/
export function foldM<E, A, R1, E1, B, R2, E2, C>(
g: (e: E) => STM<R2, E2, C>,
f: (a: A) => STM<R1, E1, B>
): <R>(self: STM<R, E, A>) => STM<R1 & R2 & R, E1 | E2, B | C> {
return (self) => foldM_(self, g, f)
}
/**
* Executes the specified finalization transaction whether or
* not this effect succeeds. Note that as with all STM transactions,
* if the full transaction fails, everything will be rolled back.
*/
export function ensuring_<R, E, A, R1, B>(
self: STM<R, E, A>,
finalizer: STM<R1, never, B>
): STM<R & R1, E, A> {
return foldM_(
self,
(e) => chain_(finalizer, () => fail(e)),
(a) => chain_(finalizer, () => succeed(a))
)
}
/**
* Executes the specified finalization transaction whether or
* not this effect succeeds. Note that as with all STM transactions,
* if the full transaction fails, everything will be rolled back.
*
* @ets_data_first ensuring_
*/
export function ensuring<R1, B>(
finalizer: STM<R1, never, B>
): <R, E, A>(self: STM<R, E, A>) => STM<R & R1, E, A> {
return (self) => ensuring_(self, finalizer)
}
/**
* Abort and retry the whole transaction when any of the underlying
* transactional variables have changed.
*/
export const retry: STM<unknown, never, never> = new STMEffect(() => {
throw new STMRetryException()
})
/**
* Returns an `STM` effect that succeeds with `Unit`.
*/
export const unit = succeed<void>(undefined)
/**
* Provides some of the environment required to run this effect,
* leaving the remainder `R0`.
*/
export function provideSome_<R, E, A, R0>(
self: STM<R, E, A>,
f: (r: R0) => R
): STM<R0, E, A> {
return new STMProvideSome(self, f)
}
/**
* Provides some of the environment required to run this effect,
* leaving the remainder `R0`.
*
* @ets_data_first provideSome_
*/
export function provideSome<R, R0>(
f: (r: R0) => R
): <E, A>(self: STM<R, E, A>) => STM<R0, E, A> {
return (self) => provideSome_(self, f)
} | the_stack |
import test from 'ava';
import {Conversation} from '../conversation';
import * as Api from '../../api/v2';
import {
BasicCard,
Button,
Suggestions,
SimpleResponse,
Carousel,
Permission,
Image,
List,
RichResponse,
MediaObject,
Table,
BrowseCarousel,
MediaResponse,
OrderUpdate,
LinkOutSuggestion,
} from '..';
import {clone} from '../../../../common';
const CONVERSATION_ID = '1234';
const USER_ID = 'abcd';
function buildRequest(
convType: string,
intent: string,
data?: {}
): Api.GoogleActionsV2AppRequest {
const appRequest = {
conversation: {
conversationId: CONVERSATION_ID,
type: convType,
conversationToken: data,
},
user: {
userId: USER_ID,
locale: 'en_US',
},
inputs: [
{
intent,
rawInputs: [
{
inputType: 'KEYBOARD',
query: 'Talk to my test app',
},
],
},
],
surface: {
capabilities: [
{
name: 'actions.capability.SCREEN_OUTPUT',
},
{
name: 'actions.capability.MEDIA_RESPONSE_AUDIO',
},
{
name: 'actions.capability.WEB_BROWSER',
},
{
name: 'actions.capability.AUDIO_OUTPUT',
},
],
},
availableSurfaces: [
{
capabilities: [
{
name: 'actions.capability.SCREEN_OUTPUT',
},
{
name: 'actions.capability.AUDIO_OUTPUT',
},
],
},
],
} as Api.GoogleActionsV2AppRequest;
return appRequest;
}
test('conv.screen is true when screen capability exists', t => {
const conv = new Conversation({
request: {
surface: {
capabilities: [
{
name: 'actions.capability.SCREEN_OUTPUT',
},
],
},
},
});
t.true(conv.screen);
});
test('conv.screen is false when screen capability does not exist', t => {
const conv = new Conversation({
request: {
surface: {
capabilities: [],
},
},
});
t.false(conv.screen);
});
test('ask with simple text', t => {
const appRequest = buildRequest('ACTIVE', 'example.foo');
const conv = new Conversation({
request: appRequest,
});
conv.ask('hello');
t.true(conv.expectUserResponse);
t.is(conv.responses.length, 1);
t.false(conv.digested);
t.true(conv._responded);
});
test('ask with multiple responses', t => {
const appRequest = buildRequest('ACTIVE', 'example.foo');
const conv = new Conversation({
request: appRequest,
});
conv.ask('hello', 'world', '<speak>hello world</speak>');
t.true(conv.expectUserResponse);
t.is(conv.responses.length, 3);
t.false(conv.digested);
t.true(conv._responded);
});
test('close with multiple responses', t => {
const appRequest = buildRequest('ACTIVE', 'example.foo');
const conv = new Conversation({
request: appRequest,
});
conv.close('hello', 'world', '<speak>hello world</speak>');
t.false(conv.expectUserResponse);
t.is(conv.responses.length, 3);
t.false(conv.digested);
t.true(conv._responded);
});
test('basic conversation response', t => {
const appRequest = buildRequest('ACTIVE', 'example.foo');
const conv = new Conversation({
request: appRequest,
});
conv.ask('hello', '<speak>world</speak>');
const response = conv.response();
t.is(response.richResponse.items!.length, 2);
t.deepEqual(
response.richResponse.items![0].simpleResponse!.textToSpeech,
'hello'
);
t.deepEqual(
response.richResponse.items![1].simpleResponse!.textToSpeech,
'<speak>world</speak>'
);
t.true(response.expectUserResponse);
t.true(conv.digested);
t.true(conv._responded);
});
test('basic card with suggestions conversation response', t => {
const appRequest = buildRequest('ACTIVE', 'example.foo');
const conv = new Conversation({
request: appRequest,
});
conv.ask(
'hello',
new BasicCard({
title: 'Title',
subtitle: 'This is a subtitle',
text: 'This is a sample text',
image: {
url: 'http://url/to/image',
height: 200,
width: 300,
},
buttons: new Button({
title: 'Learn more',
url: 'http://url/to/open',
}),
}),
new Suggestions('suggestion one', 'suggestion two')
);
const response = conv.response();
t.is(response.richResponse.items!.length, 2);
t.deepEqual(
response.richResponse.items![1].basicCard!.formattedText,
'This is a sample text'
);
t.deepEqual(response.richResponse.suggestions![0].title, 'suggestion one');
t.true(response.expectUserResponse);
t.true(conv.digested);
t.true(conv._responded);
});
test('basic conversation response with reprompts', t => {
const appRequest = buildRequest('ACTIVE', 'example.foo');
const conv = new Conversation({
request: appRequest,
});
conv.ask('hello');
conv.noInputs = ['reprompt1', new SimpleResponse('reprompt2')];
const response = conv.response();
t.is(response.richResponse.items!.length, 1);
t.deepEqual(
response.richResponse.items![0].simpleResponse!.textToSpeech,
'hello'
);
t.deepEqual(response.noInputPrompts![0].textToSpeech, 'reprompt1');
t.deepEqual(response.noInputPrompts![1].textToSpeech, 'reprompt2');
t.true(response.expectUserResponse);
t.true(conv.digested);
t.true(conv._responded);
});
test('conv parses a valid user storage', t => {
const data = {
a: '1',
b: '2',
c: {
d: '3',
e: '4',
},
};
const conv = new Conversation({
request: {
user: {
userStorage: JSON.stringify({data}),
},
},
});
t.deepEqual(conv.user.storage, data);
});
test('conv generate an empty user storage as empty string', t => {
const response = "What's up?";
const conv = new Conversation();
t.deepEqual(conv.user.storage, {});
conv.ask(response);
t.deepEqual(clone(conv.response()), {
expectUserResponse: true,
richResponse: {
items: [
{
simpleResponse: {
textToSpeech: response,
},
},
],
},
userStorage: '',
});
});
test('conv generates first user storage replaced correctly', t => {
const response = "What's up?";
const data = {
a: '1',
b: '2',
c: {
d: '3',
e: '4',
},
};
const conv = new Conversation();
conv.ask(response);
conv.user.storage = data;
t.deepEqual(clone(conv.response()), {
expectUserResponse: true,
richResponse: {
items: [
{
simpleResponse: {
textToSpeech: response,
},
},
],
},
userStorage: JSON.stringify({data}),
});
});
test('conv generates first user storage mutated correctly', t => {
const response = "What's up?";
const conv = new Conversation<{a: string}>();
conv.ask(response);
const a = '1';
conv.user.storage.a = a;
t.deepEqual(clone(conv.response()), {
expectUserResponse: true,
richResponse: {
items: [
{
simpleResponse: {
textToSpeech: response,
},
},
],
},
userStorage: JSON.stringify({data: {a}}),
});
});
test('conv generates different user storage correctly', t => {
const response = "What's up?";
const data = {
a: '1',
b: '2',
c: {
d: '3',
e: '4',
},
};
const e = '6';
const conv = new Conversation<typeof data>({
request: {
user: {
userStorage: JSON.stringify({data}),
},
},
});
t.deepEqual(conv.user.storage, data);
conv.ask(response);
conv.user.storage.c.e = e;
t.deepEqual(clone(conv.response()), {
expectUserResponse: true,
richResponse: {
items: [
{
simpleResponse: {
textToSpeech: response,
},
},
],
},
userStorage: JSON.stringify({
data: {
a: '1',
b: '2',
c: {
d: '3',
e,
},
},
}),
});
});
test('conv generates same user storage as empty string', t => {
const response = "What's up?";
const data = {
a: '1',
b: '2',
c: {
d: '3',
e: '4',
},
};
const conv = new Conversation({
request: {
user: {
userStorage: JSON.stringify({data}),
},
},
});
t.deepEqual(conv.user.storage, data);
conv.ask(response);
t.deepEqual(clone(conv.response()), {
expectUserResponse: true,
richResponse: {
items: [
{
simpleResponse: {
textToSpeech: response,
},
},
],
},
userStorage: '',
});
});
test('conv.response throws error when no response has been set', t => {
const conv = new Conversation();
t.throws(() => conv.response(), {
message:
'No response has been set. ' +
'Is this being used in an async call that was not ' +
'returned as a promise to the intent handler?',
});
});
test('conv.response throws error when response has been digested twice', t => {
const conv = new Conversation();
conv.ask("What's up?");
conv.response();
t.throws(() => conv.response(), {
message: 'Response has already been digested',
});
});
test('conv.response throws error when only one helper has been sent', t => {
const conv = new Conversation();
conv.ask(
new Carousel({
items: [],
})
);
t.throws(() => conv.response(), {
message:
'A simple response is required in addition to this type of response',
});
});
test('conv.response does not throws error when only one SoloHelper has been sent', t => {
const conv = new Conversation();
conv.ask(
new Permission({
permissions: 'NAME',
})
);
t.deepEqual(clone(conv.response()), {
expectUserResponse: true,
expectedIntent: {
intent: 'actions.intent.PERMISSION',
inputValueData: {
'@type': 'type.googleapis.com/google.actions.v2.PermissionValueSpec',
permissions: ['NAME'],
},
},
richResponse: {
items: [],
},
userStorage: '',
});
});
test('conv.response throws error when only one rich response has been sent', t => {
const conv = new Conversation();
conv.ask(
new Image({
url: 'url',
alt: 'alt',
})
);
t.throws(() => conv.response(), {
message:
'A simple response is required in addition to this type of response',
});
});
test('conv sends speechBiasingHints when set', t => {
const response = 'What is your favorite color out of red, blue, and green?';
const biasing = ['red', 'blue', 'green'];
const conv = new Conversation();
conv.speechBiasing = biasing;
conv.ask(response);
t.deepEqual(clone(conv.response()), {
expectUserResponse: true,
richResponse: {
items: [
{
simpleResponse: {
textToSpeech: response,
},
},
],
},
userStorage: '',
speechBiasingHints: biasing,
});
});
test('conv throws error when conv.add is used after response already been sent', t => {
const conv = new Conversation();
conv.ask('hello');
t.is(typeof conv.response(), 'object');
t.throws(() => conv.add('test'), {
message:
'Response has already been sent. ' +
'Is this being used in an async call that was not ' +
'returned as a promise to the intent handler?',
});
});
test('conv enforces simple response for non SoloHelper Helper classes', t => {
const conv = new Conversation();
conv.ask(new List({items: []}));
t.throws(() => conv.response(), {
message:
'A simple response is required in addition to this type of response',
});
});
test('conv does not enforce simple response for SoloHelper classes', t => {
const conv = new Conversation();
conv.ask(new Permission({permissions: 'NAME'}));
t.is(typeof conv.response(), 'object');
});
test('conv does not enforce simple response for a raw RichResponse input', t => {
const conv = new Conversation();
conv.ask(new RichResponse());
t.is(typeof conv.response(), 'object');
});
test('conv enforces simple response for Suggestions', t => {
const conv = new Conversation();
conv.ask(new Suggestions());
t.throws(() => conv.response(), {
message:
'A simple response is required in addition to this type of response',
});
});
test('conv enforces simple response for Image', t => {
const conv = new Conversation();
conv.ask(new Image({url: '', alt: ''}));
t.throws(() => conv.response(), {
message:
'A simple response is required in addition to this type of response',
});
});
test('conv enforces simple response for MediaObject', t => {
const conv = new Conversation();
conv.ask(new MediaObject({url: ''}));
t.throws(() => conv.response(), {
message:
'A simple response is required in addition to this type of response',
});
});
test('conv enforces simple response for BasicCard', t => {
const conv = new Conversation();
conv.ask(new BasicCard({}));
t.throws(() => conv.response(), {
message:
'A simple response is required in addition to this type of response',
});
});
test('conv enforces simple response for Table', t => {
const conv = new Conversation();
conv.ask(new Table({rows: []}));
t.throws(() => conv.response(), {
message:
'A simple response is required in addition to this type of response',
});
});
test('conv enforces simple response for BrowseCarousel', t => {
const conv = new Conversation();
conv.ask(new BrowseCarousel());
t.throws(() => conv.response(), {
message:
'A simple response is required in addition to this type of response',
});
});
test('conv enforces simple response for MediaResponse', t => {
const conv = new Conversation();
conv.ask(new MediaResponse());
t.throws(() => conv.response(), {
message:
'A simple response is required in addition to this type of response',
});
});
test('conv enforces simple response for OrderUpdate', t => {
const conv = new Conversation();
conv.ask(new OrderUpdate({}));
t.throws(() => conv.response(), {
message:
'A simple response is required in addition to this type of response',
});
});
test('conv enforces simple response for LinkOutSuggestion', t => {
const conv = new Conversation();
conv.ask(new LinkOutSuggestion({openUrlAction: {url: ''}, name: ''}));
t.throws(() => conv.response(), {
message:
'A simple response is required in addition to this type of response',
});
});
test('conv does not enforce simple response for raw RichResponse item', t => {
const conv = new Conversation();
conv.ask({basicCard: {}});
t.is(typeof conv.response(), 'object');
});
test('surface capability shortcut works', t => {
const conv = new Conversation({
request: {
surface: {
capabilities: [
{
name: 'actions.capability.SCREEN_OUTPUT',
},
{
name: 'actions.capability.MEDIA_RESPONSE_AUDIO',
},
{
name: 'actions.capability.AUDIO_OUTPUT',
},
],
},
},
});
t.true(conv.surface.has('actions.capability.AUDIO_OUTPUT'));
t.false(conv.surface.has('actions.capability.WEB_BROWSER'));
});
test('available surface capability shortcut works', t => {
const conv = new Conversation({
request: {
availableSurfaces: [
{
capabilities: [
{
name: 'actions.capability.SCREEN_OUTPUT',
},
{
name: 'actions.capability.MEDIA_RESPONSE_AUDIO',
},
],
},
{
capabilities: [
{
name: 'actions.capability.AUDIO_OUTPUT',
},
],
},
],
},
});
t.true(conv.available.surfaces.has('actions.capability.AUDIO_OUTPUT'));
t.false(conv.available.surfaces.has('actions.capability.WEB_BROWSER'));
}); | the_stack |
import { Subject } from 'rxjs';
import { CoreLogger } from '@singletons/logger';
import { CoreSite, CoreSiteInfoResponse, CoreSitePublicConfigResponse } from '@classes/site';
import { CoreFilepoolComponentFileEventData } from '@services/filepool';
import { CoreNavigationOptions } from '@services/navigator';
import { CoreCourseModuleCompletionData } from '@features/course/services/course-helper';
/**
* Observer instance to stop listening to an event.
*/
export interface CoreEventObserver {
/**
* Stop the observer.
*/
off: () => void;
}
/**
* Event payloads.
*/
export interface CoreEventsData {
[CoreEvents.SITE_UPDATED]: CoreEventSiteUpdatedData;
[CoreEvents.SITE_ADDED]: CoreEventSiteAddedData;
[CoreEvents.SITE_DELETED]: CoreSite;
[CoreEvents.SESSION_EXPIRED]: CoreEventSessionExpiredData;
[CoreEvents.CORE_LOADING_CHANGED]: CoreEventLoadingChangedData;
[CoreEvents.COURSE_STATUS_CHANGED]: CoreEventCourseStatusChanged;
[CoreEvents.PACKAGE_STATUS_CHANGED]: CoreEventPackageStatusChanged;
[CoreEvents.USER_DELETED]: CoreEventUserDeletedData;
[CoreEvents.FORM_ACTION]: CoreEventFormActionData;
[CoreEvents.NOTIFICATION_SOUND_CHANGED]: CoreEventNotificationSoundChangedData;
[CoreEvents.SELECT_COURSE_TAB]: CoreEventSelectCourseTabData;
[CoreEvents.COMPLETION_MODULE_VIEWED]: CoreEventCompletionModuleViewedData;
[CoreEvents.MANUAL_COMPLETION_CHANGED]: CoreEventManualCompletionChangedData;
[CoreEvents.SECTION_STATUS_CHANGED]: CoreEventSectionStatusChangedData;
[CoreEvents.ACTIVITY_DATA_SENT]: CoreEventActivityDataSentData;
[CoreEvents.IAB_LOAD_START]: InAppBrowserEvent;
[CoreEvents.LOGIN_SITE_CHECKED]: CoreEventLoginSiteCheckedData;
[CoreEvents.SEND_ON_ENTER_CHANGED]: CoreEventSendOnEnterChangedData;
[CoreEvents.COMPONENT_FILE_ACTION]: CoreFilepoolComponentFileEventData;
[CoreEvents.FILE_SHARED]: CoreEventFileSharedData;
[CoreEvents.APP_LAUNCHED_URL]: CoreEventAppLaunchedData;
}
/*
* Service to send and listen to events.
*/
export class CoreEvents {
static readonly SESSION_EXPIRED = 'session_expired';
static readonly PASSWORD_CHANGE_FORCED = 'password_change_forced';
static readonly USER_NOT_FULLY_SETUP = 'user_not_fully_setup';
static readonly SITE_POLICY_NOT_AGREED = 'site_policy_not_agreed';
static readonly LOGIN = 'login';
static readonly LOGOUT = 'logout';
static readonly LANGUAGE_CHANGED = 'language_changed';
static readonly NOTIFICATION_SOUND_CHANGED = 'notification_sound_changed';
static readonly SITE_ADDED = 'site_added';
static readonly SITE_UPDATED = 'site_updated';
static readonly SITE_DELETED = 'site_deleted';
static readonly COMPLETION_MODULE_VIEWED = 'completion_module_viewed';
static readonly MANUAL_COMPLETION_CHANGED = 'manual_completion_changed';
static readonly USER_DELETED = 'user_deleted';
static readonly PACKAGE_STATUS_CHANGED = 'package_status_changed';
static readonly COURSE_STATUS_CHANGED = 'course_status_changed';
static readonly SECTION_STATUS_CHANGED = 'section_status_changed';
static readonly COMPONENT_FILE_ACTION = 'component_file_action';
static readonly SITE_PLUGINS_LOADED = 'site_plugins_loaded';
static readonly SITE_PLUGINS_COURSE_RESTRICT_UPDATED = 'site_plugins_course_restrict_updated';
static readonly LOGIN_SITE_CHECKED = 'login_site_checked';
static readonly LOGIN_SITE_UNCHECKED = 'login_site_unchecked';
static readonly IAB_LOAD_START = 'inappbrowser_load_start';
static readonly IAB_EXIT = 'inappbrowser_exit';
static readonly APP_LAUNCHED_URL = 'app_launched_url'; // App opened with a certain URL (custom URL scheme).
static readonly FILE_SHARED = 'file_shared';
static readonly KEYBOARD_CHANGE = 'keyboard_change';
static readonly CORE_LOADING_CHANGED = 'core_loading_changed';
static readonly ORIENTATION_CHANGE = 'orientation_change';
static readonly SEND_ON_ENTER_CHANGED = 'send_on_enter_changed';
static readonly SELECT_COURSE_TAB = 'select_course_tab';
static readonly WS_CACHE_INVALIDATED = 'ws_cache_invalidated';
static readonly SITE_STORAGE_DELETED = 'site_storage_deleted';
static readonly FORM_ACTION = 'form_action';
static readonly ACTIVITY_DATA_SENT = 'activity_data_sent';
static readonly DEVICE_REGISTERED_IN_MOODLE = 'device_registered_in_moodle';
protected static logger = CoreLogger.getInstance('CoreEvents');
protected static observables: { [eventName: string]: Subject<unknown> } = {};
protected static uniqueEvents: { [eventName: string]: {data: unknown} } = {};
/**
* Listen for a certain event. To stop listening to the event:
* let observer = eventsProvider.on('something', myCallBack);
* ...
* observer.off();
*
* @param eventName Name of the event to listen to.
* @param callBack Function to call when the event is triggered.
* @param siteId Site where to trigger the event. Undefined won't check the site.
* @return Observer to stop listening.
*/
static on<Fallback = unknown, Event extends string = string>(
eventName: Event,
callBack: (value: CoreEventData<Event, Fallback> & CoreEventSiteData) => void,
siteId?: string,
): CoreEventObserver {
// If it's a unique event and has been triggered already, call the callBack.
// We don't need to create an observer because the event won't be triggered again.
if (this.uniqueEvents[eventName]) {
callBack(this.uniqueEvents[eventName].data as CoreEventData<Event, Fallback> & CoreEventSiteData);
// Return a fake observer to prevent errors.
return {
off: (): void => {
// Nothing to do.
},
};
}
this.logger.debug(`New observer listening to event '${eventName}'`);
if (typeof this.observables[eventName] == 'undefined') {
// No observable for this event, create a new one.
this.observables[eventName] = new Subject();
}
const subscription = this.observables[eventName].subscribe(
(value: CoreEventData<Event, Fallback> & CoreEventSiteData) => {
if (!siteId || value.siteId == siteId) {
callBack(value);
}
},
);
// Create and return a CoreEventObserver.
return {
off: (): void => {
this.logger.debug(`Stop listening to event '${eventName}'`);
subscription.unsubscribe();
},
};
}
/**
* Listen for several events. To stop listening to the events:
* let observer = eventsProvider.onMultiple(['something', 'another'], myCallBack);
* ...
* observer.off();
*
* @param eventNames Names of the events to listen to.
* @param callBack Function to call when any of the events is triggered.
* @param siteId Site where to trigger the event. Undefined won't check the site.
* @return Observer to stop listening.
*/
static onMultiple<T = unknown>(eventNames: string[], callBack: (value: T) => void, siteId?: string): CoreEventObserver {
const observers = eventNames.map((name) => this.on<T>(name, callBack, siteId));
// Create and return a CoreEventObserver.
return {
off: (): void => {
observers.forEach((observer) => {
observer.off();
});
},
};
}
/**
* Triggers an event, notifying all the observers.
*
* @param event Name of the event to trigger.
* @param data Data to pass to the observers.
* @param siteId Site where to trigger the event. Undefined means no Site.
*/
static trigger<Fallback = unknown, Event extends string = string>(
eventName: Event,
data?: CoreEventData<Event, Fallback>,
siteId?: string,
): void {
this.logger.debug(`Event '${eventName}' triggered.`);
if (this.observables[eventName]) {
if (siteId) {
Object.assign(data || {}, { siteId });
}
this.observables[eventName].next(data);
}
}
/**
* Triggers a unique event, notifying all the observers. If the event has already been triggered, don't do anything.
*
* @param event Name of the event to trigger.
* @param data Data to pass to the observers.
* @param siteId Site where to trigger the event. Undefined means no Site.
*/
static triggerUnique<Fallback = unknown, Event extends string = string>(
eventName: Event,
data: CoreEventData<Event, Fallback>,
siteId?: string,
): void {
if (this.uniqueEvents[eventName]) {
this.logger.debug(`Unique event '${eventName}' ignored because it was already triggered.`);
} else {
this.logger.debug(`Unique event '${eventName}' triggered.`);
if (siteId) {
Object.assign(data || {}, { siteId });
}
// Store the data so it can be passed to observers that register from now on.
this.uniqueEvents[eventName] = {
data,
};
// Now pass the data to observers.
if (this.observables[eventName]) {
this.observables[eventName].next(data);
}
}
}
}
/**
* Resolve payload type for a given event.
*/
export type CoreEventData<Event, Fallback> = Event extends keyof CoreEventsData ? CoreEventsData[Event] : Fallback;
/**
* Some events contains siteId added by the trigger function. This type is intended to be combined with others.
*/
export type CoreEventSiteData = {
siteId?: string;
};
/**
* Data passed to SITE_UPDATED event.
*/
export type CoreEventSiteUpdatedData = CoreSiteInfoResponse;
/**
* Data passed to SITE_ADDED event.
*/
export type CoreEventSiteAddedData = CoreSiteInfoResponse;
/**
* Data passed to SESSION_EXPIRED event.
*/
export type CoreEventSessionExpiredData = {
pageName?: string;
options?: CoreNavigationOptions;
};
/**
* Data passed to CORE_LOADING_CHANGED event.
*/
export type CoreEventLoadingChangedData = {
loaded: boolean;
uniqueId: string;
};
/**
* Data passed to COURSE_STATUS_CHANGED event.
*/
export type CoreEventCourseStatusChanged = {
courseId: number; // Course Id.
status: string;
};
/**
* Data passed to PACKAGE_STATUS_CHANGED event.
*/
export type CoreEventPackageStatusChanged = {
component: string;
componentId: string | number;
status: string;
};
/**
* Data passed to USER_DELETED event.
*/
export type CoreEventUserDeletedData = {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
params: any; // Params sent to the WS that failed.
};
export enum CoreEventFormAction {
CANCEL = 'cancel',
SUBMIT = 'submit',
}
/**
* Data passed to FORM_ACTION event.
*/
export type CoreEventFormActionData = {
action: CoreEventFormAction; // Action performed.
form: HTMLElement; // Form element.
online?: boolean; // Whether the data was sent to server or not. Only when submitting.
};
/**
* Data passed to NOTIFICATION_SOUND_CHANGED event.
*/
export type CoreEventNotificationSoundChangedData = {
enabled: boolean;
};
/**
* Data passed to SELECT_COURSE_TAB event.
*/
export type CoreEventSelectCourseTabData = {
name?: string; // Name of the tab's handler. If not set, load course contents.
sectionId?: number;
sectionNumber?: number;
};
/**
* Data passed to COMPLETION_MODULE_VIEWED event.
*/
export type CoreEventCompletionModuleViewedData = {
courseId: number;
cmId?: number;
};
/**
* Data passed to MANUAL_COMPLETION_CHANGED event.
*/
export type CoreEventManualCompletionChangedData = {
completion: CoreCourseModuleCompletionData;
};
/**
* Data passed to SECTION_STATUS_CHANGED event.
*/
export type CoreEventSectionStatusChangedData = {
courseId: number;
sectionId?: number;
};
/**
* Data passed to ACTIVITY_DATA_SENT event.
*/
export type CoreEventActivityDataSentData = {
module: string;
};
/**
* Data passed to LOGIN_SITE_CHECKED event.
*/
export type CoreEventLoginSiteCheckedData = {
config: CoreSitePublicConfigResponse;
};
/**
* Data passed to SEND_ON_ENTER_CHANGED event.
*/
export type CoreEventSendOnEnterChangedData = {
sendOnEnter: boolean;
};
/**
* Data passed to FILE_SHARED event.
*/
export type CoreEventFileSharedData = {
name: string;
siteId: string;
};
/**
* Data passed to APP_LAUNCHED_URL event.
*/
export type CoreEventAppLaunchedData = {
url: string;
}; | the_stack |
export type FindImgParam = {
path: string
when?: Function
option?: {
region?: RegionType
threshold?: number
}
index?: number
useCache?: {
key?: string,
offset?: number
}
eachTime?: number
nextTime?: number
once?: boolean
take?: number
doIfNotFound?: Function
image?: Image,
valid?: number
isPausable?: boolean
center?: boolean
}
import { cap, getPrototype, height, pausable, scale, width, cap$ } from '@auto.pro/core'
import { defer, Observable, of, throwError, timer } from 'rxjs'
import { exhaustMap, filter, finalize, map, take, tap, throttleTime } from 'rxjs/operators'
const cache: Record<string, any> = {}
export function clearCache(cacheName: string) {
delete cache[cacheName]
}
/**
* 将坐标转换成region类型,即[x1, y1, x2, y2] -> [x, y, w, h],并做好边界处理
* @param param
*/
function region(param: any) {
if (param.length == 4) {
const x = Math.max(0, param[0])
const y = Math.max(0, param[1])
let w = param[2] - x
let h = param[3] - y
w = x + w >= width ? width - x : w
h = y + h >= height ? height - y : h
return [x, y, w, h]
} else if (param.length == 2) {
return [
Math.min(Math.max(0, param[0]), width),
Math.min(Math.max(0, param[1]), height)
]
} else {
return param
}
}
/**
* 获取指定路径的Image对象,若已是Image则不重复获取
* @param {string | Image} imgPath 图片路径
* @param {number | undefined} mode 获取模式,若为0则返回灰度图像
* @returns {Image | null}
*/
export function readImg(imgPath: Image | string, mode?: number) {
if (!imgPath) {
throw `图片${imgPath}不存在`
}
let result
if (getPrototype(imgPath) != 'String') {
result = imgPath
} else {
result = images.read(imgPath as string)
}
if (mode === 0) {
result = images.grayscale(result)
}
return result as Image
}
/**
* 找图函数,此函数为异步函数!
* @param {string} path 待查图片路径
* @param {Function} when 传递一个函数作为filter,仅当函数返回值为真时进行找图
* @param {object} option 查询参数
* @param {number} index 取范围内的第几个结果,值从1开始。默认为1,设置为null、fale时返回所有结果
* @param {object} useCache 缓存配置
* @param {number} eachTime 找图定时器的间隔,默认为100(ms)
* @param {number} nextTime 匹配到图片后,下一次匹配的间隔,默认为0(ms)
* @param {boolean} once 是否只找一次,该值为true时直接返回本次匹配结果
* @param {number} take 期望匹配到几次结果,默认为1
* @param {function} doIfNotFound 本次未匹配到图片时将执行的函数
* @param {Image} image 提供预截图,设置此值后,将只查询1次并返回匹配结果
* @param {number} valid 当valid大于0时,启用颜色匹配验证,消除匹配误差,默认为30
* @param {boolean} isPausable 是否受暂停状态影响,默认为true,受影响
* @param {boolean} center 是否将返回坐标处理成图片中心
* @returns {Observable<[[number, number] | [number, number] | null]>}
*/
export function findImg(param: FindImgParam): Observable<any> {
return defer(() => {
const path = param.path || ''
const option = param.option || {}
const index = param.index === undefined ? 1 : param.index
const useCache = param.useCache
const cachePath = useCache && (path + useCache.key || '__CACHE__') || null
const cacheOffset = useCache && useCache.offset || 2
const eachTime = param.eachTime || 100
const nextTime = param.nextTime || 0
const DO_IF_NOT_FOUND = param.doIfNotFound
const image = param.image || null
const valid = param.valid == null ? 30 : ~~param.valid
const isPausable = param.isPausable === false ? false : true
// 是否只找一次,无论是否找到都返回结果,默认false
// 如果提供了截图cap,则只找一次
const ONCE = image ? true : param.once
const TAKE_NUM = ONCE ? 1 : param.take === undefined ? 1 : param.take || 99999999
let template = readImg(path)
if (!template) {
return throwError(`template path ${path} is null`)
}
if (scale !== 1) {
template = images.scale(template, scale, scale)
}
let queryOption = { ...option }
queryOption.threshold = queryOption.threshold || 0.8
// 如果确认使用缓存,且缓存里已经设置有region的话,直接赋值
if (cachePath && cache[cachePath]) {
queryOption.region = cache[cachePath]
} else if (queryOption.region) {
let region = queryOption.region
if (region[0] < 0) {
region[0] = 0
}
if (region[1] < 0) {
region[1] = 0
}
if (region.length == 4) {
let x = region[0] + region[2]
let y = region[1] + region[3]
if (x > width) {
region[2] = width - region[0]
}
if (y > height) {
region[3] = height - region[1]
}
}
queryOption.region = region
}
let when = param.when || (() => true)
let isPass = true
let t: any
return cap$.pipe(
pausable(isPausable, false),
filter(cap => cap.isRecycled() === false),
throttleTime(eachTime),
filter(() => isPass && when()),
exhaustMap(cap => {
const src = image || cap
let matches = images.matchTemplate(src, template, queryOption).matches
if (valid > 0) {
matches = matches.filter(match => {
return images.findColorInRegion(src, images.pixel(template, 0, 0), match.point.x, match.point.y, 10, 10, valid)
})
}
if (matches.length == 0 && DO_IF_NOT_FOUND) {
DO_IF_NOT_FOUND()
}
return of(matches)
}),
take(ONCE ? 1 : 99999999),
filter(v => ONCE ? true : v.length > 0),
take(TAKE_NUM),
// TODO 使用MatchingResult自带的排序
map(res => {
let result = res.map(p => {
return [
Math.floor(p.point['x']),
Math.floor(p.point['y'])
]
}).sort((a, b) => {
let absY = Math.abs(a[1] - b[1])
let absX = Math.abs(a[0] - b[0])
if (absY > 4 && a[1] > b[1]) {
return -1
}
else if (absY < 4) {
return (absX > 4 && a[0] > b[0]) ? -1 : 1
} else {
return 1
}
})
// 如果设置了取第几个
if (index != undefined) {
// 如果从缓存里找,则只判断索引0
if (cachePath && cache[cachePath]) {
result = result.length > 0 ? [result[0]] : []
} else {
// 如果还未设置缓存,则取第index-1个,没有则返回空数组
result = result.length >= index ? [result[index - 1]] : []
}
}
return result
}),
tap(res => {
// 如果有结果,且确认要缓存
if (res && res.length > 0 && useCache && cachePath && !cache[cachePath]) {
const xArray = res.map(e => e[0])
const yArray = res.map(e => e[1])
cache[cachePath] = region([
Math.min(...xArray) - cacheOffset,
Math.min(...yArray) - cacheOffset,
Math.max(...xArray) + template.width + cacheOffset * 2,
Math.max(...yArray) + template.height + cacheOffset * 2
])
queryOption.region = cache[cachePath]
}
}),
map(res => {
let result
// 如果设置了取第几个,则对最后结果进行处理,有结果则直接返回索引0的值,无结果则返回null
if (index != undefined) {
result = res.length > 0 ? res[0] : null
} else {
result = res
}
if (param.center) {
result = result && result.map(pt => [pt[0] + template.width / 2, pt[1] + template.height / 2])
}
return result
}),
// 如果没有设置ONCE,且设置了index,则对最终结果进行过滤
filter(v => {
if (!ONCE && index != undefined) {
return v
} else {
return true
}
}),
tap(v => {
if (v && nextTime && isPass) {
isPass = false
t = setTimeout(function () {
isPass = true
}, nextTime)
}
}),
finalize(() => {
if (t) {
clearTimeout(t)
}
template.recycle()
})
)
})
}
/**
* (精确查找)
* 判断区域内是否不含有colors中的任意一个,不含有则返回true,含有则返回false
*
* @param {string | Image} image 图源,若为字符串则自动回收内存
* @param {Array} region 查找范围
* @param {Array<Color>} colors 待查颜色数组
*/
export function noAnyColors(image: Image, region: RegionType = [0, 0], colors: [] = []) {
let src = readImg(image)
let result = !colors.some(c => {
if (images.findColorEquals(src, c, ...region)) {
return true
} else {
return false
}
})
if (getPrototype(image) === 'String') {
src.recycle()
}
return result
}
/**
* (精确查找)
* 区域内含有colors中的全部颜色时,返回true,否则返回false
*
* @param {string | Image} image 图源,若为字符串则自动回收内存
* @param {Array} region 范围
* @param {Array<Color>} colors 待查颜色数组
*/
export function hasMulColors(image: Image | string, region: RegionType = [0, 0], colors: [] = []) {
let src = readImg(image)
let result = colors.every(c => {
if (images.findColorEquals(src, c, ...region)) {
return true
} else {
return false
}
})
if (getPrototype(image) === 'String') {
src.recycle()
}
return result
}
/**
* 存在任意颜色,则返回颜色坐标,否则返回false
*
* @param {string | Image} image 图源,若为字符串则自动回收内存
* @param {Array<Color>} colors 待查颜色数组
* @param {{
* threshold: 10,
* region: []
* }} option 查找参数
* @returns {[number, number] | false}
*/
export function hasAnyColors(image: Image | string, colors: [] = [], option = {
threshold: 10
}): ([number, number] | false) {
let result: [number, number] | false = false
let src = readImg(image)
colors.some(c => {
let has = images.findColor(src, c, option)
if (has) {
result = [has['x'], has['y']]
return true
} else {
return false
}
})
if (getPrototype(image) === 'String') {
src.recycle()
}
return result
} | the_stack |
import bind from "bind-decorator"
import classNames from "classnames"
import React, { MouseEvent } from "react"
import { dapps, links, quotes, snippet } from "../../data"
import { images, styles, videos } from "./styles"
export interface Props {
linked: boolean
onClickDisconnect: () => void
}
export class RootPage extends React.PureComponent<Props> {
public video = React.createRef<HTMLVideoElement>()
public render() {
const { linked } = this.props
return (
<div className={styles.main}>
<style>
@import
url('https://fonts.googleapis.com/css?family=Overpass|Roboto|Roboto+Mono&display=swap');
</style>
<header className={classNames(styles.section._, styles.header._)}>
<div
className={classNames(
styles.section.container._,
styles.header.content
)}
>
<h1>
<a href="/">WalletLink</a>
</h1>
<div className={styles.header.buttons}>
<a
className={classNames(
styles.roundedButton._,
styles.roundedButton.filled
)}
href={links.githubJsRepo}
>
Get started
</a>
{linked && (
<button
className={classNames(styles.roundedButton._)}
onClick={this.handleClickDisconnect}
>
Disconnect
</button>
)}
</div>
</div>
</header>
<section className={styles.section._}>
<div
className={classNames(
styles.section.container._,
styles.section.container.right
)}
>
<div
className={classNames(
styles.section.content._,
styles.section.content.half
)}
>
<video
className={styles.hero.video}
ref={this.video}
onClick={this.handleClickVideo}
autoPlay
loop
>
<source src={videos.webm} type="video/webm" />
<source src={videos.mp4} type="video/mp4" />
</video>
</div>
<div
className={classNames(
styles.section.content._,
styles.hero.content
)}
>
<h2>Link your DApp to mobile wallets</h2>
<p>
WalletLink is an open protocol that lets users connect their
mobile crypto wallets to your DApp.
</p>
<a className={styles.roundedButton._} href={links.githubJsRepo}>
Get started
</a>
</div>
</div>
</section>
<section className={classNames(styles.section._, styles.features._)}>
<div className={styles.section.container._}>
<ul>
<li>
<img src={images.browser} alt="" />
<h3>Bring your own browser</h3>
<p>
Users can now use your DApp in any browser without installing
an extension
</p>
</li>
<li>
<img src={images.key} alt="" />
<h3>Protected private keys</h3>
<p>
Private keys never leave mobile wallets, keeping user funds
safe
</p>
</li>
<li>
<img src={images.lock} alt="" />
<h3>Encrypted</h3>
<p>
End-to-end encryption using client-side generated keys keeps
all user activity private.
</p>
</li>
</ul>
</div>
<div className={styles.features.bg} />
</section>
<section
className={classNames(styles.section._, styles.section.alternate)}
>
<div
className={classNames(
styles.section.container._,
styles.section.container.right
)}
>
<div
className={classNames(
styles.section.content._,
styles.section.content.half
)}
>
<h2>5 minutes to integrate</h2>
<p>
No server deployments, no new library to learn. To integrate
with WalletLink, all you need to do is drop these few lines to
initialize a web3 object. WalletLink takes care of the rest.
WalletLink is open-source and uses minimal dependencies for
maximum security and no code bloat.
</p>
<a
className={classNames(
styles.roundedButton._,
styles.roundedButton.secondary
)}
href={links.githubJsRepo}
>
See WalletLink on GitHub
</a>
</div>
<div className={styles.integrate.snippet.box}>
<div className={styles.integrate.snippet.titlebar}>
<div />
<div />
<div />
</div>
<pre dangerouslySetInnerHTML={{ __html: snippet }} />
</div>
</div>
</section>
<section
className={classNames(styles.section._, styles.section.centered)}
>
<div className={styles.section.container._}>
<div
className={classNames(
styles.section.content._,
styles.supportedDApps.content
)}
>
<h2>Supported DApps on WalletLink</h2>
<ul className={styles.supportedDApps.list}>
{dapps.map(([name, logoUrl, url], i) => (
<SupportedDApp
key={i}
name={name}
logoUrl={logoUrl}
url={url}
/>
))}
</ul>
</div>
</div>
</section>
<section
className={classNames(styles.section._, styles.section.tertiary)}
>
<div className={classNames(styles.section.container._)}>
<ul className={styles.inspiringQuote.list}>
{quotes.map(
(
[quote, photoUrl, name, company, personalUrl, companyUrl],
i
) => (
<InspiringQuote
key={i}
quote={quote}
photoUrl={photoUrl}
name={name}
company={company}
personalUrl={personalUrl}
companyUrl={companyUrl}
right={i % 2 > 0}
/>
)
)}
</ul>
</div>
</section>
<section
className={classNames(
styles.section._,
styles.supportedWallets.section
)}
>
<div
className={classNames(
styles.section.container._,
styles.section.container.left
)}
>
<div className={styles.supportedWallets.whiteBg} />
<div
className={classNames(
styles.section.content._,
styles.section.content.half,
styles.supportedWallets.content
)}
>
<h2>Supported wallets</h2>
<p>
WalletLink is an open protocol aimed at creating a better DApp
experience for both users and developers. The WalletLink Mobile
SDK will soon be available for wallet developers to add support
for the WalletLink protocol to enable users to connect to
WalletLink-enabled DApps on desktop browsers.
</p>
<a
className={classNames(styles.roundedButton._)}
href={links.githubMobileRepo}
>
See Mobile Wallet SDK on GitHub
</a>
</div>
<div
className={classNames(
styles.section.content._,
styles.section.content.half,
styles.supportedWallets.wallets
)}
>
<div className={styles.supportedWallets.walletLogos}>
<div
className={classNames(
styles.supportedWallets.walletLogo._,
styles.supportedWallets.coinbaseWallet
)}
/>
<div
className={classNames(
styles.supportedWallets.walletLogo._,
styles.supportedWallets.walletLogo.behind
)}
/>
<div
className={classNames(
styles.supportedWallets.walletLogo._,
styles.supportedWallets.walletLogo.behind2
)}
/>
</div>
<h4>
<a href={links.coinbaseWallet}>Coinbase Wallet</a>
</h4>
<p>More wallets coming soon</p>
</div>
</div>
</section>
<section
className={classNames(styles.section._, styles.section.alternate)}
>
<div className={styles.section.container._}>
<div
className={classNames(styles.section.content._, styles.lastCTA)}
>
<h2>Get started with WalletLink today</h2>
<a
className={classNames(
styles.roundedButton._,
styles.roundedButton.secondary
)}
href={links.githubJsRepo}
>
Get started
</a>
</div>
</div>
</section>
<footer className={classNames(styles.section._, styles.footer._)}>
<div
className={classNames(
styles.section.container._,
styles.footer.content
)}
>
<ul>
<li>
<a href={links.githubOrg}>GitHub</a>
</li>
<li>
<a href={links.npm}>NPM</a>
</li>
</ul>
<h4>
<a href="/">WalletLink.org</a>
</h4>
</div>
</footer>
</div>
)
}
@bind
public handleClickVideo(e: MouseEvent): void {
e.preventDefault()
const video = this.video.current
if (video) {
video.play()
}
}
@bind
public handleClickDisconnect(e: MouseEvent): void {
e.preventDefault()
this.props.onClickDisconnect()
}
}
const SupportedDApp = (props: {
name: string
logoUrl: string
url: string
}) => (
<li className={styles.supportedDApps.item}>
<a href={props.url || "#"} target="_blank" rel="noopener noreferrer">
<div className={styles.supportedDApps.logo}>
<img src={props.logoUrl} alt="" />
</div>
{props.name}
</a>
</li>
)
const InspiringQuote = (props: {
quote: string
photoUrl: string
name: string
company: string
personalUrl: string
companyUrl: string
right?: boolean
}) => (
<li
className={classNames(
styles.inspiringQuote.item._,
props.right && styles.inspiringQuote.item.right
)}
>
<blockquote>“{props.quote}”</blockquote>
<div
className={classNames(
styles.inspiringQuote.person._,
props.right && styles.inspiringQuote.person.right
)}
>
<img src={props.photoUrl} alt="" />
<div>
<p>
<a href={props.personalUrl} target="_blank" rel="noopener noreferrer">
{props.name}
</a>
</p>
<p>
<a href={props.companyUrl} target="_blank" rel="noopener noreferrer">
{props.company}
</a>
</p>
</div>
</div>
</li>
) | the_stack |
import "./helpers/dotenv_helper";
import { getTestId, dispatch, getState } from "./helpers/test_helper";
import { testExport } from "./helpers/export_helper";
import * as R from "ramda";
import { createBlock } from "./helpers/blocks_helper";
import { registerWithEmail } from "./helpers/auth_helper";
import { createApp } from "./helpers/apps_helper";
import { inviteAdminUser, acceptInvite } from "./helpers/invites_helper";
import {
updateEnvs,
updateLocals,
fetchEnvs,
fetchChangesets,
fetchEnvsWithChangesets,
revertEnvironment,
getEnvironments,
} from "./helpers/envs_helper";
import { Api, Model, Client } from "@core/types";
import { graphTypes } from "@core/lib/graph";
import {
getPendingEnvWithMeta,
getEnvWithMeta,
getEnvironmentPendingConflicts,
getEarliestEnvUpdatePendingAt,
} from "@core/lib/client";
import { envkeyFetch } from "./helpers/fetch_helper";
import { log } from "@core/lib/utils/logger";
describe("envs", () => {
let email: string, ownerId: string, appId: string, blockId: string;
beforeEach(async () => {
email = `success+${getTestId()}@simulator.amazonses.com`;
({ userId: ownerId } = await registerWithEmail(email));
[{ id: appId }, { id: blockId }] = [
await createApp(ownerId),
await createBlock(ownerId),
];
});
for (let envParentType of [<const>"app", <const>"block"]) {
let envParentId: string;
beforeEach(async () => {
envParentId = envParentType == "app" ? appId : blockId;
});
describe(`update ${envParentType} envs`, () => {
test("with single user", async () => {
await updateEnvs(ownerId, envParentId);
await updateLocals(ownerId, envParentId);
});
});
describe(`fetch ${envParentType} envs`, () => {
beforeEach(async () => {
await updateEnvs(ownerId, envParentId);
await updateLocals(ownerId, envParentId);
});
test("fetch envs", async () => {
await fetchEnvs(ownerId, envParentId);
});
test("fetch changesets", async () => {
await fetchChangesets(ownerId, envParentId);
});
test("fetch envs with changesets", async () => {
await fetchEnvsWithChangesets(ownerId, envParentId);
});
});
describe(`revert ${envParentType} environment`, () => {
beforeEach(async () => {
await updateEnvs(ownerId, envParentId);
await updateLocals(ownerId, envParentId);
});
test("revert environment", async () => {
await fetchEnvsWithChangesets(ownerId, envParentId);
await revertEnvironment(ownerId, envParentId);
});
});
}
describe("create environment", () => {
beforeEach(async () => {
await updateEnvs(ownerId, appId);
});
test("sub environment", async () => {
let state = getState(ownerId);
const productionRole = R.indexBy(
R.prop("name"),
graphTypes(state.graph).environmentRoles
)["Production"],
[_, __, production] = getEnvironments(ownerId, appId);
const createPromise = dispatch(
{
type: Api.ActionType.CREATE_ENVIRONMENT,
payload: {
envParentId: appId,
environmentRoleId: productionRole.id,
isSub: true,
parentEnvironmentId: production.id,
subName: "prod-sub",
},
},
ownerId
);
state = getState(ownerId);
expect(Object.keys(state.isCreatingEnvironment)).toEqual([appId]);
expect(Object.values(state.isCreatingEnvironment[appId]).length).toBe(1);
const res = await createPromise;
expect(res.success).toBeTrue();
state = getState(ownerId);
expect(state.isCreatingEnvironment).toEqual({});
const newEnvironment = R.last(
R.sortBy(R.prop("createdAt"), graphTypes(state.graph).environments)
) as Model.Environment;
dispatch(
{
type: Client.ActionType.IMPORT_ENVIRONMENT,
payload: {
envParentId: appId,
environmentId: newEnvironment.id,
parsed: {
IMPORTED_KEY1: "imported-val",
IMPORTED_KEY2: "imported-val",
},
},
},
ownerId
);
dispatch(
{
type: Client.ActionType.CREATE_ENTRY_ROW,
payload: {
envParentId: appId,
entryKey: "NEW_ENVIRONMENT_KEY",
vals: {
[newEnvironment.id]: {
val: "new-environment-val",
},
},
},
},
ownerId
);
state = getState(ownerId);
expect(
getPendingEnvWithMeta(state, {
envParentId: appId,
environmentId: newEnvironment.id,
})
).toEqual({
inherits: {},
variables: {
NEW_ENVIRONMENT_KEY: {
val: "new-environment-val",
},
IMPORTED_KEY1: { val: "imported-val" },
IMPORTED_KEY2: { val: "imported-val" },
},
});
await dispatch(
{
type: Client.ActionType.COMMIT_ENVS,
payload: { message: "commit message" },
},
ownerId
);
await dispatch(
{
type: Client.ActionType.GET_SESSION,
},
ownerId
);
await dispatch(
{
type: Client.ActionType.FETCH_ENVS,
payload: {
byEnvParentId: {
[appId]: { envs: true, changesets: true },
},
},
},
ownerId
);
state = getState(ownerId);
expect(
getEnvWithMeta(state, {
envParentId: appId,
environmentId: newEnvironment.id,
})
).toEqual({
inherits: {},
variables: {
NEW_ENVIRONMENT_KEY: {
val: "new-environment-val",
},
IMPORTED_KEY1: { val: "imported-val" },
IMPORTED_KEY2: { val: "imported-val" },
},
});
expect(state.changesets[newEnvironment.id]).toEqual(
expect.objectContaining({
key: expect.toBeString(),
changesets: expect.arrayContaining([
expect.objectContaining({
message: "commit message",
actions: expect.arrayContaining([
expect.objectContaining({
type: expect.toBeString(),
payload: expect.toBeObject(),
meta: expect.toBeObject(),
}),
]),
}),
]),
})
);
const serverRes = await dispatch<
Client.Action.ClientActions["CreateServer"]
>(
{
type: Client.ActionType.CREATE_SERVER,
payload: {
appId,
name: "New Environment Server",
environmentId: newEnvironment.id,
},
},
ownerId
);
expect(serverRes.success).toBeTrue();
state = getState(ownerId);
const { envkeyIdPart, encryptionKey } = Object.values(
state.generatedEnvkeys
)[0],
envkeyFetchRes = await envkeyFetch(envkeyIdPart, encryptionKey);
expect(envkeyFetchRes).toEqual({
KEY2: "val3",
KEY3: "key3-val",
NEW_ENVIRONMENT_KEY: "new-environment-val",
IMPORTED_KEY1: "imported-val",
IMPORTED_KEY2: "imported-val",
});
await testExport(
ownerId,
{
envParentId: appId,
environmentId: newEnvironment.id,
},
{
NEW_ENVIRONMENT_KEY: "new-environment-val",
IMPORTED_KEY1: "imported-val",
IMPORTED_KEY2: "imported-val",
}
);
await testExport(
ownerId,
{
envParentId: appId,
environmentId: newEnvironment.id,
includeAncestors: true,
},
{
KEY2: "val3",
KEY3: "key3-val",
NEW_ENVIRONMENT_KEY: "new-environment-val",
IMPORTED_KEY1: "imported-val",
IMPORTED_KEY2: "imported-val",
}
);
});
});
describe("pending changes and conflicts", () => {
let development: Model.Environment,
staging: Model.Environment,
production: Model.Environment;
beforeEach(async () => {
// make updates to a couple environments
[development, staging, production] = getEnvironments(ownerId, appId);
dispatch(
{
type: Client.ActionType.IMPORT_ENVIRONMENT,
payload: {
envParentId: appId,
environmentId: development.id,
parsed: {
IMPORTED_KEY1: "imported-val",
IMPORTED_KEY2: "imported-val",
},
},
},
ownerId
);
dispatch(
{
type: Client.ActionType.CREATE_ENTRY_ROW,
payload: {
envParentId: appId,
entryKey: "KEY1",
vals: {
[development.id]: { val: "val1" },
[staging.id]: { val: "val2" },
[production.id]: {
inheritsEnvironmentId: development.id,
},
},
},
},
ownerId
);
dispatch(
{
type: Client.ActionType.CREATE_ENTRY_ROW,
payload: {
envParentId: appId,
entryKey: "KEY2",
vals: {
[development.id]: { isUndefined: true },
[staging.id]: { isEmpty: true, val: "" },
[production.id]: { val: "val3" },
},
},
},
ownerId
);
dispatch(
{
type: Client.ActionType.CREATE_ENTRY,
payload: {
envParentId: appId,
environmentId: [appId, ownerId].join("|"),
entryKey: "LOCALS_KEY",
val: { val: "val" },
},
},
ownerId
);
let state = getState(ownerId);
// ensure pending envs are what we expect them to be
expect(
getPendingEnvWithMeta(state, {
envParentId: appId,
environmentId: development.id,
})
).toEqual({
inherits: {},
variables: {
IMPORTED_KEY1: { val: "imported-val" },
IMPORTED_KEY2: { val: "imported-val" },
KEY1: { val: "val1" },
KEY2: { isUndefined: true },
},
});
expect(
getPendingEnvWithMeta(state, {
envParentId: appId,
environmentId: staging.id,
})
).toEqual({
inherits: {},
variables: {
KEY1: { val: "val2" },
KEY2: { isEmpty: true, val: "" },
},
});
expect(
getPendingEnvWithMeta(state, {
envParentId: appId,
environmentId: production.id,
})
).toEqual({
inherits: {
[development.id]: ["KEY1"],
},
variables: {
KEY1: { inheritsEnvironmentId: development.id },
KEY2: { val: "val3" },
},
});
expect(
getPendingEnvWithMeta(state, {
envParentId: appId,
environmentId: [appId, ownerId].join("|"),
})
).toEqual({
inherits: {},
variables: {
LOCALS_KEY: { val: "val" },
},
});
state = getState(ownerId);
expect(getEarliestEnvUpdatePendingAt(state, appId)).toBeNumber();
});
describe("reset pending changes", () => {
test("single environment", () => {
dispatch(
{
type: Client.ActionType.RESET_ENVS,
payload: {
pendingEnvironmentIds: [development.id],
},
},
ownerId
);
let state = getState(ownerId);
// development should reset
expect(
getPendingEnvWithMeta(state, {
envParentId: appId,
environmentId: development.id,
})
).toEqual({
inherits: {},
variables: {},
});
// staging and production should stay the same
expect(
getPendingEnvWithMeta(state, {
envParentId: appId,
environmentId: staging.id,
})
).toEqual({
inherits: {},
variables: {
KEY1: { val: "val2" },
KEY2: { isEmpty: true, val: "" },
},
});
expect(
getPendingEnvWithMeta(state, {
envParentId: appId,
environmentId: production.id,
})
).toEqual({
inherits: {
[development.id]: ["KEY1"],
},
variables: {
KEY1: { inheritsEnvironmentId: development.id },
KEY2: { val: "val3" },
},
});
// locals should stay the same
expect(
getPendingEnvWithMeta(state, {
envParentId: appId,
environmentId: [appId, ownerId].join("|"),
})
).toEqual({
inherits: {},
variables: {
LOCALS_KEY: { val: "val" },
},
});
});
test("local overrides", () => {
dispatch(
{
type: Client.ActionType.RESET_ENVS,
payload: {
pendingEnvironmentIds: [[appId, ownerId].join("|")],
},
},
ownerId
);
let state = getState(ownerId);
// locals should reset
expect(
getPendingEnvWithMeta(state, {
envParentId: appId,
environmentId: [appId, ownerId].join("|"),
})
).toEqual({
inherits: {},
variables: {},
});
// development, staging, and production should stay the same
expect(
getPendingEnvWithMeta(state, {
envParentId: appId,
environmentId: development.id,
})
).toEqual({
inherits: {},
variables: {
IMPORTED_KEY1: { val: "imported-val" },
IMPORTED_KEY2: { val: "imported-val" },
KEY1: { val: "val1" },
KEY2: { isUndefined: true },
},
});
expect(
getPendingEnvWithMeta(state, {
envParentId: appId,
environmentId: staging.id,
})
).toEqual({
inherits: {},
variables: {
KEY1: { val: "val2" },
KEY2: { isEmpty: true, val: "" },
},
});
expect(
getPendingEnvWithMeta(state, {
envParentId: appId,
environmentId: production.id,
})
).toEqual({
inherits: {
[development.id]: ["KEY1"],
},
variables: {
KEY1: { inheritsEnvironmentId: development.id },
KEY2: { val: "val3" },
},
});
});
test("multiple environments", () => {
dispatch(
{
type: Client.ActionType.RESET_ENVS,
payload: {
pendingEnvironmentIds: [development.id, staging.id],
},
},
ownerId
);
let state = getState(ownerId);
// development and staging should reset
expect(
getPendingEnvWithMeta(state, {
envParentId: appId,
environmentId: development.id,
})
).toEqual({
inherits: {},
variables: {},
});
expect(
getPendingEnvWithMeta(state, {
envParentId: appId,
environmentId: staging.id,
})
).toEqual({
inherits: {},
variables: {},
});
// production should stay the same
expect(
getPendingEnvWithMeta(state, {
envParentId: appId,
environmentId: production.id,
})
).toEqual({
inherits: {
[development.id]: ["KEY1"],
},
variables: {
KEY1: { inheritsEnvironmentId: development.id },
KEY2: { val: "val3" },
},
});
// locals should stay the same
expect(
getPendingEnvWithMeta(state, {
envParentId: appId,
environmentId: [appId, ownerId].join("|"),
})
).toEqual({
inherits: {},
variables: {
LOCALS_KEY: { val: "val" },
},
});
});
test("all environments", () => {
dispatch(
{
type: Client.ActionType.RESET_ENVS,
payload: {},
},
ownerId
);
let state = getState(ownerId);
// all environments should reset
expect(
getPendingEnvWithMeta(state, {
envParentId: appId,
environmentId: development.id,
})
).toEqual({
inherits: {},
variables: {},
});
expect(
getPendingEnvWithMeta(state, {
envParentId: appId,
environmentId: staging.id,
})
).toEqual({
inherits: {},
variables: {},
});
expect(
getPendingEnvWithMeta(state, {
envParentId: appId,
environmentId: production.id,
})
).toEqual({
inherits: {},
variables: {},
});
expect(
getPendingEnvWithMeta(state, {
envParentId: appId,
environmentId: [appId, ownerId].join("|"),
})
).toEqual({
inherits: {},
variables: {},
});
});
test("single environment, specific entry keys", () => {
dispatch(
{
type: Client.ActionType.RESET_ENVS,
payload: {
pendingEnvironmentIds: [development.id],
entryKeys: ["IMPORTED_KEY1", "KEY2"],
},
},
ownerId
);
let state = getState(ownerId);
// development should reset specified keys only
expect(
getPendingEnvWithMeta(state, {
envParentId: appId,
environmentId: development.id,
})
).toEqual({
inherits: {},
variables: {
IMPORTED_KEY2: { val: "imported-val" },
KEY1: { val: "val1" },
},
});
// staging and production should stay the same
expect(
getPendingEnvWithMeta(state, {
envParentId: appId,
environmentId: staging.id,
})
).toEqual({
inherits: {},
variables: {
KEY1: { val: "val2" },
KEY2: { isEmpty: true, val: "" },
},
});
expect(
getPendingEnvWithMeta(state, {
envParentId: appId,
environmentId: production.id,
})
).toEqual({
inherits: {
[development.id]: ["KEY1"],
},
variables: {
KEY1: { inheritsEnvironmentId: development.id },
KEY2: { val: "val3" },
},
});
});
test("multiple environments, specific entry keys", () => {
dispatch(
{
type: Client.ActionType.RESET_ENVS,
payload: {
pendingEnvironmentIds: [development.id, staging.id],
entryKeys: ["IMPORTED_KEY1", "KEY2"],
},
},
ownerId
);
let state = getState(ownerId);
// development and staging should reset specified keys only
expect(
getPendingEnvWithMeta(state, {
envParentId: appId,
environmentId: development.id,
})
).toEqual({
inherits: {},
variables: {
IMPORTED_KEY2: { val: "imported-val" },
KEY1: { val: "val1" },
},
});
expect(
getPendingEnvWithMeta(state, {
envParentId: appId,
environmentId: staging.id,
})
).toEqual({
inherits: {},
variables: {
KEY1: { val: "val2" },
},
});
// production should stay the same
expect(
getPendingEnvWithMeta(state, {
envParentId: appId,
environmentId: production.id,
})
).toEqual({
inherits: {
[development.id]: ["KEY1"],
},
variables: {
KEY1: { inheritsEnvironmentId: development.id },
KEY2: { val: "val3" },
},
});
});
test("all environments, specific entry keys", () => {
dispatch(
{
type: Client.ActionType.RESET_ENVS,
payload: {
entryKeys: ["IMPORTED_KEY1", "KEY2"],
},
},
ownerId
);
let state = getState(ownerId);
// all environmentss should reset specified keys only
expect(
getPendingEnvWithMeta(state, {
envParentId: appId,
environmentId: development.id,
})
).toEqual({
inherits: {},
variables: {
IMPORTED_KEY2: { val: "imported-val" },
KEY1: { val: "val1" },
},
});
expect(
getPendingEnvWithMeta(state, {
envParentId: appId,
environmentId: staging.id,
})
).toEqual({
inherits: {},
variables: {
KEY1: { val: "val2" },
},
});
expect(
getPendingEnvWithMeta(state, {
envParentId: appId,
environmentId: production.id,
})
).toEqual({
inherits: {
[development.id]: ["KEY1"],
},
variables: {
KEY1: { inheritsEnvironmentId: development.id },
},
});
});
});
test("getEnvironmentPotentialConflicts", async () => {
let invitedAdminId;
// invite another user
const params = await inviteAdminUser(ownerId);
invitedAdminId = params.user.id;
await acceptInvite(params);
// make some conflicting changes
dispatch(
{
type: Client.ActionType.CREATE_ENTRY_ROW,
payload: {
envParentId: appId,
entryKey: "KEY2",
vals: {
[development.id]: { val: "conflict" },
[staging.id]: { val: "conflict" },
[production.id]: { val: "conflict" },
},
},
},
invitedAdminId
);
dispatch(
{
type: Client.ActionType.UPDATE_ENTRY_VAL,
payload: {
envParentId: appId,
environmentId: development.id,
entryKey: "IMPORTED_KEY2",
update: { val: "conflict" },
},
},
invitedAdminId
);
dispatch(
{
type: Client.ActionType.UPDATE_ENTRY_VAL,
payload: {
envParentId: appId,
environmentId: [appId, ownerId].join("|"),
entryKey: "LOCALS_KEY",
update: { val: "conflict" },
},
},
invitedAdminId
);
// and some non-conflicting changes
dispatch(
{
type: Client.ActionType.CREATE_ENTRY_ROW,
payload: {
envParentId: appId,
entryKey: "NO_CONFLICT",
vals: {
[development.id]: { val: "no-conflict" },
[staging.id]: { val: "no-conflict" },
[production.id]: { val: "no-conflict" },
},
},
},
invitedAdminId
);
dispatch(
{
type: Client.ActionType.UPDATE_ENTRY_VAL,
payload: {
envParentId: appId,
environmentId: development.id,
entryKey: "ANOTHER_NO_CONFLICT",
update: { val: "no-conflict" },
},
},
invitedAdminId
);
dispatch(
{
type: Client.ActionType.UPDATE_ENTRY_VAL,
payload: {
envParentId: appId,
environmentId: [appId, ownerId].join("|"),
entryKey: "LOCALS_NO_CONFLICT",
update: { val: "no-conflict" },
},
},
invitedAdminId
);
await dispatch(
{
type: Client.ActionType.COMMIT_ENVS,
payload: {},
},
invitedAdminId
);
await dispatch(
{
type: Client.ActionType.FETCH_ENVS,
payload: {
byEnvParentId: {
[appId]: { envs: true },
},
},
},
ownerId
);
let state = getState(ownerId);
expect(Object.keys(state.changesets).length).toBeGreaterThan(0);
expect(getEnvironmentPendingConflicts(state, development.id).length).toBe(
2
);
expect(getEnvironmentPendingConflicts(state, staging.id).length).toBe(1);
expect(getEnvironmentPendingConflicts(state, production.id).length).toBe(
1
);
expect(
getEnvironmentPendingConflicts(state, [appId, ownerId].join("|")).length
).toBe(1);
});
describe("outdated graph / outdated envs", () => {
let invitedAdminId: string;
beforeEach(async () => {
// invite another user
const params = await inviteAdminUser(ownerId);
invitedAdminId = params.user.id;
await acceptInvite(params);
});
test("with conflict", async () => {
// make some new changes
dispatch(
{
type: Client.ActionType.CREATE_ENTRY_ROW,
payload: {
envParentId: appId,
entryKey: "KEY2",
vals: {
[development.id]: { val: "conflict" },
[staging.id]: { val: "conflict" },
[production.id]: { val: "conflict" },
},
},
},
invitedAdminId
);
await dispatch(
{
type: Client.ActionType.COMMIT_ENVS,
payload: {},
},
invitedAdminId
);
const res = await dispatch(
{
type: Client.ActionType.COMMIT_ENVS,
payload: {},
},
ownerId
);
expect(res.success).toBeFalse();
});
test("without conflict", async () => {
// make some non-conflicting changes
dispatch(
{
type: Client.ActionType.CREATE_ENTRY_ROW,
payload: {
envParentId: appId,
entryKey: "NO_CONFLICT",
vals: {
[development.id]: { val: "conflict" },
[staging.id]: { val: "conflict" },
[production.id]: { val: "conflict" },
},
},
},
invitedAdminId
);
await dispatch(
{
type: Client.ActionType.COMMIT_ENVS,
payload: {},
},
invitedAdminId
);
const res = await dispatch(
{
type: Client.ActionType.COMMIT_ENVS,
payload: {},
},
ownerId
);
expect(res.success).toBeTrue();
});
});
});
}); | the_stack |
'use strict'
import { ConfigurationChangeEvent, FileSystemWatcher, StatusBarItem, WorkspaceConfiguration } from 'coc.nvim'
import { CancellationToken, Disposable, Event, Position, TextDocument, WorkspaceEdit, WorkspaceFolder } from 'vscode-languageserver-protocol'
import { Uri, Terminal, TerminalOptions } from 'coc.nvim'
// import { IAsyncDisposable } from '../types'
import { ICommandNameArgumentTypeMapping } from './commands'
// tslint:disable:no-any unified-signatures
export type Resource = Uri | undefined
export const IApplicationShell = Symbol('IApplicationShell')
export interface IApplicationShell {
/**
* Opens URL in a default browser.
*
* @param url Url to open.
*/
openUrl(url: string): void
/**
* Set a message to the status bar. This is a short hand for the more powerful
* status bar [items](#window.createStatusBarItem).
*
* @param text The message to show, supports icon substitution as in status bar [items](#StatusBarItem.text).
* @param hideAfterTimeout Timeout in milliseconds after which the message will be disposed.
* @return A disposable which hides the status bar message.
*/
setStatusBarMessage(text: string, hideAfterTimeout: number): Disposable
/**
* Set a message to the status bar. This is a short hand for the more powerful
* status bar [items](#window.createStatusBarItem).
*
* @param text The message to show, supports icon substitution as in status bar [items](#StatusBarItem.text).
* @param hideWhenDone Thenable on which completion (resolve or reject) the message will be disposed.
* @return A disposable which hides the status bar message.
*/
setStatusBarMessage(text: string, hideWhenDone: Thenable<any>): Disposable
/**
* Set a message to the status bar. This is a short hand for the more powerful
* status bar [items](#window.createStatusBarItem).
*
* *Note* that status bar messages stack and that they must be disposed when no
* longer used.
*
* @param text The message to show, supports icon substitution as in status bar [items](#StatusBarItem.text).
* @return A disposable which hides the status bar message.
*/
setStatusBarMessage(text: string): Disposable
/**
* Creates a status bar [item](#StatusBarItem).
*
* @param alignment The alignment of the item.
* @param priority The priority of the item. Higher values mean the item should be shown more to the left.
* @return A new status bar item.
*/
createStatusBarItem(priority?: number): StatusBarItem
}
export const ICommandManager = Symbol('ICommandManager')
export interface ICommandManager {
/**
* Registers a command that can be invoked via a keyboard shortcut,
* a menu item, an action, or directly.
*
* Registering a command with an existing command identifier twice
* will cause an error.
*
* @param command A unique identifier for the command.
* @param callback A command handler function.
* @param thisArg The `this` context used when invoking the handler function.
* @return Disposable which unregisters this command on disposal.
*/
registerCommand<E extends keyof ICommandNameArgumentTypeMapping, U extends ICommandNameArgumentTypeMapping[E]>(command: E, callback: (...args: U) => any, thisArg?: any): Disposable
/**
* Executes the command denoted by the given command identifier.
*
* * *Note 1:* When executing an editor command not all types are allowed to
* be passed as arguments. Allowed are the primitive types `string`, `boolean`,
* `number`, `undefined`, and `null`, as well as [`Position`](#Position), [`Range`](#Range), [`Uri`](#Uri) and [`Location`](#Location).
* * *Note 2:* There are no restrictions when executing commands that have been contributed
* by extensions.
*
* @param command Identifier of the command to execute.
* @param rest Parameters passed to the command function.
* @return A thenable that resolves to the returned value of the given command. `undefined` when
* the command handler function doesn't return anything.
*/
executeCommand<T, E extends keyof ICommandNameArgumentTypeMapping, U extends ICommandNameArgumentTypeMapping[E]>(command: E, ...rest: U): Thenable<T | undefined>
/**
* Retrieve the list of all available commands. Commands starting an underscore are
* treated as internal commands.
*
* @param filterInternal Set `true` to not see internal commands (starting with an underscore)
* @return Thenable that resolves to a list of command ids.
*/
getCommands(filterInternal?: boolean): Thenable<string[]>
}
export const IDocumentManager = Symbol('IDocumentManager')
export interface IDocumentManager {
/**
* All text documents currently known to the system.
*
* @readonly
*/
readonly textDocuments: TextDocument[]
/**
* An event that is emitted when a [text document](#TextDocument) is opened.
*/
readonly onDidOpenTextDocument: Event<TextDocument>
/**
* An event that is emitted when a [text document](#TextDocument) is disposed.
*/
readonly onDidCloseTextDocument: Event<TextDocument>
/**
* An event that is emitted when a [text document](#TextDocument) is saved to disk.
*/
readonly onDidSaveTextDocument: Event<TextDocument>
/**
* Show the given document in a text editor. A [column](#ViewColumn) can be provided
* to control where the editor is being shown. Might change the [active editor](#window.activeTextEditor).
*
* @param document A text document to be shown.
* @param column A view column in which the [editor](#TextEditor) should be shown. The default is the [one](#ViewColumn.One), other values
* are adjusted to be `Min(column, columnCount + 1)`, the [active](#ViewColumn.Active)-column is
* not adjusted.
* @param preserveFocus When `true` the editor will not take focus.
* @return A promise that resolves to an [editor](#TextEditor).
*/
showTextDocument(document: TextDocument, position?: Position, preserveFocus?: boolean): Thenable<number>
/**
* Show the given document in a text editor. [Options](#TextDocumentShowOptions) can be provided
* to control options of the editor is being shown. Might change the [active editor](#window.activeTextEditor).
*
* @param document A text document to be shown.
* @param options [Editor options](#TextDocumentShowOptions) to configure the behavior of showing the [editor](#TextEditor).
* @return A promise that resolves to an [editor](#TextEditor).
*/
showTextDocument(document: TextDocument, cmd?: string): Thenable<number>
/**
* A short-hand for `openTextDocument(uri).then(document => showTextDocument(document, options))`.
*
* @see [openTextDocument](#openTextDocument)
*
* @param uri A resource identifier.
* @param options [Editor options](#TextDocumentShowOptions) to configure the behavior of showing the [editor](#TextEditor).
* @return A promise that resolves to an [editor](#TextEditor).
*/
showTextDocument(uri: Uri): Thenable<number>
/**
* Make changes to one or many resources as defined by the given
* [workspace edit](#WorkspaceEdit).
*
* When applying a workspace edit, the editor implements an 'all-or-nothing'-strategy,
* that means failure to load one document or make changes to one document will cause
* the edit to be rejected.
*
* @param edit A workspace edit.
* @return A thenable that resolves when the edit could be applied.
*/
applyEdit(edit: WorkspaceEdit): Thenable<boolean>
/**
* Opens a document. Will return early if this document is already open. Otherwise
* the document is loaded and the [didOpen](#workspace.onDidOpenTextDocument)-event fires.
*
* The document is denoted by an [uri](#Uri). Depending on the [scheme](#Uri.scheme) the
* following rules apply:
* * `file`-scheme: Open a file on disk, will be rejected if the file does not exist or cannot be loaded.
* * `untitled`-scheme: A new file that should be saved on disk, e.g. `untitled:c:\frodo\new.js`. The language
* will be derived from the file name.
* * For all other schemes the registered text document content [providers](#TextDocumentContentProvider) are consulted.
*
* *Note* that the lifecycle of the returned document is owned by the editor and not by the extension. That means an
* [`onDidClose`](#workspace.onDidCloseTextDocument)-event can occur at any time after opening it.
*
* @param uri Identifies the resource to open.
* @return A promise that resolves to a [document](#TextDocument).
*/
openTextDocument(uri: Uri): Promise<TextDocument>
}
export const IWorkspaceService = Symbol('IWorkspaceService')
export interface IWorkspaceService {
/**
* ~~The folder that is open in the editor. `undefined` when no folder
* has been opened.~~
*
* @readonly
*/
readonly rootPath: string | undefined
/**
* List of workspace folders or `undefined` when no folder is open.
* *Note* that the first entry corresponds to the value of `rootPath`.
*
* @readonly
*/
readonly workspaceFolders: WorkspaceFolder[] | undefined
/**
* An event that is emitted when the [configuration](#WorkspaceConfiguration) changed.
*/
readonly onDidChangeConfiguration: Event<ConfigurationChangeEvent>
/**
* Creates a file system watcher.
*
* A glob pattern that filters the file events on their absolute path must be provided. Optionally,
* flags to ignore certain kinds of events can be provided. To stop listening to events the watcher must be disposed.
*
* *Note* that only files within the current [workspace folders](#workspace.workspaceFolders) can be watched.
*
* @param globPattern A [glob pattern](#GlobPattern) that is applied to the absolute paths of created, changed,
* and deleted files. Use a [relative pattern](#RelativePattern) to limit events to a certain [workspace folder](#WorkspaceFolder).
* @param ignoreCreateEvents Ignore when files have been created.
* @param ignoreChangeEvents Ignore when files have been changed.
* @param ignoreDeleteEvents Ignore when files have been deleted.
* @return A new file system watcher instance.
*/
createFileSystemWatcher(globPattern: string, ignoreCreateEvents?: boolean, ignoreChangeEvents?: boolean, ignoreDeleteEvents?: boolean): FileSystemWatcher
/**
* Find files across all [workspace folders](#workspace.workspaceFolders) in the workspace.
*
* @sample `findFiles('**∕*.js', '**∕node_modules∕**', 10)`
* @param include A [glob pattern](#GlobPattern) that defines the files to search for. The glob pattern
* will be matched against the file paths of resulting matches relative to their workspace. Use a [relative pattern](#RelativePattern)
* to restrict the search results to a [workspace folder](#WorkspaceFolder).
* @param exclude A [glob pattern](#GlobPattern) that defines files and folders to exclude. The glob pattern
* will be matched against the file paths of resulting matches relative to their workspace.
* @param maxResults An upper-bound for the result.
* @param token A token that can be used to signal cancellation to the underlying search engine.
* @return A thenable that resolves to an array of resource identifiers. Will return no results if no
* [workspace folders](#workspace.workspaceFolders) are opened.
*/
findFiles(include: string, exclude?: string, maxResults?: number, token?: CancellationToken): Thenable<Uri[]>
/**
* Get a workspace configuration object.
*
* When a section-identifier is provided only that part of the configuration
* is returned. Dots in the section-identifier are interpreted as child-access,
* like `{ myExt: { setting: { doIt: true }}}` and `getConfiguration('myExt.setting').get('doIt') === true`.
*
* When a resource is provided, configuration scoped to that resource is returned.
*
* @param section A dot-separated identifier.
* @param resource A resource for which the configuration is asked for
* @return The full configuration or a subset.
*/
getConfiguration(section?: string, resource?: Uri): WorkspaceConfiguration
/**
* Whether a workspace folder exists
* @type {boolean}
* @memberof IWorkspaceService
*/
readonly hasWorkspaceFolders: boolean
/**
* Generate a key that's unique to the workspace folder (could be fsPath).
* @param {(Uri | undefined)} resource
* @returns {string}
* @memberof IWorkspaceService
*/
getWorkspaceFolderIdentifier(resource: Uri | undefined, defaultValue?: string): string
/**
* Returns the [workspace folder](#WorkspaceFolder) that contains a given uri.
* * returns `undefined` when the given uri doesn't match any workspace folder
* * returns the *input* when the given uri is a workspace folder itself
*
* @param uri An uri.
* @return A workspace folder or `undefined`
*/
getWorkspaceFolder(uri: Resource): WorkspaceFolder | undefined
}
export const ITerminalManager = Symbol('ITerminalManager')
export interface ITerminalManager {
/**
* An [event](#Event) which fires when a terminal is disposed.
*/
readonly onDidCloseTerminal: Event<Terminal>
/**
* An [event](#Event) which fires when a terminal has been created, either through the
* [createTerminal](#window.createTerminal) API or commands.
*/
readonly onDidOpenTerminal: Event<Terminal>
/**
* Creates a [Terminal](#Terminal). The cwd of the terminal will be the workspace directory
* if it exists, regardless of whether an explicit customStartPath setting exists.
*
* @param options A TerminalOptions object describing the characteristics of the new terminal.
* @return A new Terminal.
*/
createTerminal(options: TerminalOptions): Promise<Terminal>
}
export const IApplicationEnvironment = Symbol('IApplicationEnvironment')
export interface IApplicationEnvironment {
/**
* The application name of the editor, like 'VS Code'.
*
* @readonly
*/
appName: string
/**
* The extension name.
*
* @readonly
*/
extensionName: string
/**
* The application root folder from which the editor is running.
*
* @readonly
*/
appRoot: string
/**
* Represents the preferred user-language, like `de-CH`, `fr`, or `en-US`.
*
* @readonly
*/
language: string
/**
* A unique identifier for the computer.
*
* @readonly
*/
machineId: string
/**
* A unique identifier for the current session.
* Changes each time the editor is started.
*
* @readonly
*/
sessionId: string
/**
* Contents of `package.json` as a JSON object.
*
* @type {any}
* @memberof IApplicationEnvironment
*/
packageJson: any
} | the_stack |
export declare function forEach(array: any[], fn: Function): void;
/**
* @returns array of elements matching the filter
*/
export declare function filter(array: any[], fn: Function): any;
/**
* @returns The result of processing the reduction function on all
* of the items in the array
*/
export declare function reduce(array: any[], fn: Function, initialValue?: any): any;
/**
* Concatenate two arrays into a new array
* @returns the concatenated arrays
*/
export declare function concat(array1: any[], array2: any[]): any[];
/**
* Appends one array to another
* @param array1 - the destination
* @param array2 - the source
* @returns returns <code>array1</code>
*/
export declare function append(array1: any[], array2: any[]): any[];
/**
* @returns new array of mapped values
*/
export declare function map(array: any[], fn: Function): any[];
/**
* @returns the first matching value in the array or null
*/
export declare function find(array: any[], fn: Function): any;
/**
* @returns Index of matching element or -1
*/
export declare function findIndex(array: any[], fn: Function): number;
/**
* @returns true if at least one item matched the filter
*/
export declare function some(array: any[], fn: Function): boolean;
/**
* @returns true if all of the array items matched the filter
*/
export declare function every(array: any[], fn: Function): boolean;
/**
* Asynchronously stringify data into JSON
* @param data - Object to store
* @returns a Promise for the JSON representation of <code>data</code>
*/
export declare function stringifyAsync(data: any): Promise<String>;
/**
* Asynchronously parse JSON into an object
* @param json - the JSON to be parsed
* @returns a Promise for the parsed JSON
*/
export declare function parseAsync(json: string): Promise<any>;
/**
* Sort an array (in place) by a sorting function
* @example
* async function process(data) {
* return await sortAsync(data, v=>v.someProperty)
* }
* @param array - The array to sort
* @param sort - The method to sort the array
* @returns a promise for the sorted array
*/
export declare function sortAsync(array: any[], sort: Function): Promise<any[]>;
/**
* Finds an item in an array asynchronously
* @returns promise for the item found or null if no match
*/
export declare function findAsync(array: any[], filter: Function): Promise<any | null>;
/**
* Finds an item index in an array asynchronously
* @returns promise for the index of the first item to pass the filter or -1
*/
export declare function findIndexAsync(array: any[], filter: Function): Promise<Number>;
/**
* Functions the contents of an array asynchronously
* @returns promise for the mapped array
*/
export declare function mapAsync(array: any[], mapFn: Function): Promise<any[]>;
/**
* Functions an array asynchronously
* @returns promise for the filtered array
*/
export declare function filterAsync(array: any[], filter: Function): Promise<any[]>;
/**
* Performs a reduce on an array asynchronously
* @returns a promise for the reduced value
*/
export declare function reduceAsync(array: any[], reduceFn: Function, initialValue: any): Promise<any>;
/**
* Appends one array to another asynchronously
* @returns a promise for destination after appending
*/
export declare function appendAsync(destination: any[], source: any[]): Promise<any[]>;
/**
* Concatenates 2 arrays into a new array
* @returns a promise for combined array
*/
export declare function concatAsync(array1: any[], array2: any[]): Promise<any[]>;
/**
* Asynchronously loop over the elements of an array
* @returns promise for the end of the operation
*/
export declare function forEachAsync(array: any[], fn: Function): Promise;
/**
* Asynchronously apply an array <code>some</code> operation
* returning a promise for <code>true</code> if at least
* one item matches
* @returns promise for true if at least one item matched the filter
*/
export declare function someAsync(array: any[], fn: Function): Promise<Boolean>;
/**
* Asynchronously check if every element in an array matches
* a predicate
* @returns promise for true if all items matched the filter
*/
export declare function everyAsync(array: any[], fn: Function): Promise<Boolean>;
/**
* Asynchronously compress a string to a base64 format
* @param source - the data to compress
* @returns a promise for the base64 compressed data
*/
export declare function compressToBase64Async(source: string): Promise<String>;
/**
* Asynchronously compress a string to a utf16 string
* @param source - the data to compress
* @returns a promise for the utf16 compressed data
*/
export declare function compressToUTF16Async(source: string): Promise<String>;
/**
* Asynchronously compress a string to a Uint8Array
* @param source - the data to compress
* @returns a promise for the Uint8Array of compressed data
*/
export declare function compressToUint8ArrayAsync(source: string): Promise<Uint8Array>;
/**
* Asynchronously compress a string to a URI safe version
* @param source - the data to compress
* @returns a promise for the string of compressed data
*/
export declare function compressToEncodedURIComponentAsync(source: string): Promise<String>;
/**
* Asynchronously compress a string of data with lz-string
* @param source - the data to compress
* @returns a promise for the compressed data
*/
export declare function compressAsync(source: string): Promise<String>;
/**
* Asynchronously apply lz-string base64 remapping of a string to utf16
* @param source - the data to compress
* @returns a promise for the compressed data
*/
export declare function base64CompressToUTF16Async(source: string): Promise<String>;
/**
* Asynchronously apply lz-string base64 remapping of a string
* @param source - the data to compress
* @returns a promise for the compressed data
*/
export declare function base64CompressAsync(source: string): Promise<String>;
/**
* Asynchronously compress a string to a base64 format
* @param source - the data to compress
* @returns a promise for the base64 compressed data
*/
export declare function compressToBase64Async(source: string): Promise<String>;
/**
* Asynchronously decompress a string from a utf16 source
* @param compressedData - the data to decompress
* @returns a promise for the uncompressed data
*/
export declare function decompressFromUTF16Async(compressedData: string): Promise<String>;
/**
* Asynchronously decompress a string from a utf16 source
* @param compressedData - the data to decompress
* @returns a promise for the uncompressed data
*/
export declare function decompressFromUint8ArrayAsync(compressedData: string): Promise<String>;
/**
* Asynchronously decompress a string from a URL safe URI Component encoded source
* @param compressedData - the data to decompress
* @returns a promise for the uncompressed data
*/
export declare function decompressFromEncodedURIComponentAsync(compressedData: string): Promise<String>;
/**
* Asynchronously decompress a string from a string source
* @param compressedData - the data to decompress
* @returns a promise for the uncompressed data
*/
export declare function decompressAsync(compressedData: string): Promise<String>;
/**
* Asynchronously unmap base64 encoded data to a utf16 destination
* @param base64Data - the data to decompress
* @returns a promise for the uncompressed data
*/
export declare function base64decompressFromUTF16Async(base64Data: string): Promise<String>;
/**
* Asynchronously unmap base64 encoded data
* @param base64Data - the data to decompress
* @returns a promise for the uncompressed data
*/
export declare function base64Decompress(base64Data: string): Promise<String>;
/**
* <p>
* Starts an idle time coroutine and returns a promise for its completion and
* any value it might return.
* </p>
* <p>
* You may pass a coroutine function or the result of calling such a function. The
* latter helps when you must provide parameters to the coroutine.
* </p>
* @example
* async function process() {
* let answer = await run(function * () {
* let total = 0
* for(let i=1; i < 10000000; i++) {
* total += i
* if((i % 100) === 0) yield
* }
* return total
* })
* ...
* }
*
* // Or
*
* async function process(param) {
* let answer = await run(someCoroutine(param))
* }
* @param coroutine - the routine to run or an iterator for an already started coroutine
* @param [loopWhileMsRemains = 1 (ms)] - if less than the specified number of milliseconds remain the coroutine will continue in the next idle frame
* @param [timeout = 160 (ms)] - the number of milliseconds before the coroutine will run even if the system is not idle
* @returns the result of the coroutine
*/
export declare function run(coroutine: Function, loopWhileMsRemains?: number, timeout?: number): Promise<any>;
/**
* Start an animation coroutine, the animation will continue until
* you return and will be broken up between frames by using a
* <code>yield</code>.
* @param coroutine - The animation to run
* @param [params] - Parameters to be passed to the animation function
* @returns a value that will be returned to the caller
* when the animation is complete.
*/
export declare function update(coroutine: Function, ...params?: any[]): Promise<any>;
/**
* Starts an idle time coroutine using an async generator - this is NOT normally required
* and the performance of such routines is slower than ordinary coroutines. This is included
* in case of an edge case requirement.
* @param coroutine - the routine to run
* @param [loopWhileMsRemains = 1 (ms)] - if less than the specified number of milliseconds remain the coroutine will continue in the next idle frame
* @param [timeout = 160 (ms)] - the number of milliseconds before the coroutine will run even if the system is not idle
* @returns the result of the coroutine
*/
export declare function runAsync(coroutine: Function, loopWhileMsRemains?: number, timeout?: number): Promise<any>;
/**
* Wraps a normal function into a generator function
* that <code>yield</code>s on a regular basis
* @param fn - the function to be wrapped
* @param [frequency = 8] - the number of times the function should be called
* before performing a <code>yield</code>
* @returns The wrapped yielding
* version of the function passed
*/
export declare function yielding(fn: (...params: any[]) => any, frequency?: number): Function;
/**
* Returns a function that will execute the passed
* Coroutine and return a Promise for its result. The
* returned function will take any number of parameters
* and pass them on to the coroutine.
* @param coroutine - The coroutine to run
* @returns a function that can be called to execute the coroutine
* and return its result on completion
*/
export declare function wrapAsPromise(coroutine: Function): Function; | the_stack |
import app = require("./app");
import {autoFocus} from "./utils";
let WebSocket = require('ws');
let uuid = require("uuid");
enum CardState {
NONE,
GOOD,
PENDING,
CLOSED,
ERROR,
}
enum ReplState {
CONNECTED,
DISCONNECTED,
CONNECTING,
}
export interface Query {
type: string,
query: string,
id: string,
}
interface ReplCard {
id: string,
ix: number,
state: CardState,
focused: boolean,
query: string,
result: {
fields: Array<string>,
values: Array<Array<any>>,
} | string;
}
function rerender(removeCards?: boolean) {
if (removeCards === undefined) {
removeCards = false;
}
// Batch delete closed cards on rerender
if (removeCards === true) {
let closedCards = editorCards.filter((r) => r.state === CardState.CLOSED);
if (editor.timer !== undefined) {
clearTimeout(editor.timer);
}
let focusedCard = editorCards.filter((r) => r.focused).shift();
let focusIx = 0;
if (focusedCard !== undefined) {
focusIx = focusedCard.ix;
}
focusedCard = editorCards[focusIx + 1 > editorCards.length - 1 ? editorCards.length - 1 : focusIx + 1];
focusCard(focusedCard);
editor.timer = setTimeout(() => {
for (let card of closedCards) {
deleteStoredReplCard(card);
editorCards.splice(editorCards.map((r) => r.id).indexOf(card.id),1);
}
if (closedCards !== undefined) {
editorCards.forEach((r,i) => r.ix = i);
}
rerender(false);
}, 250);
}
app.dispatch("rerender", {}).commit();
}
// ------------------
// Storage functions
// ------------------
function saveReplCard(editorCard: ReplCard) {
localStorage.setItem("eveeditor-" + editorCard.id, JSON.stringify(editorCard));
}
function loadReplCards(): Array<ReplCard> {
let storedReplCards: Array<ReplCard> = [];
for (let item in localStorage) {
if (item.substr(0,7) === "eveeditor") {
let storedReplCard = JSON.parse(localStorage[item]);
storedReplCards.push(storedReplCard);
}
}
if (storedReplCards.length > 0) {
storedReplCards.map((r) => r.focused = false);
storedReplCards = storedReplCards.sort((a,b) => a.ix - b.ix);
storedReplCards.forEach((r,i) => r.ix = i);
}
return storedReplCards;
}
function deleteStoredReplCard(editorCard: ReplCard) {
localStorage.removeItem("eveeditor-" + editorCard.id);
}
function saveCards() {
let serialized = JSON.stringify(editorCards.filter((r) => r.state !== CardState.NONE).map((r) => r.query));
let blob = new Blob([serialized], {type: "application/json"});
let url = URL.createObjectURL(blob);
editor.blob = url;
}
function saveTable() {
let editorCard = editorCards.filter((r) => r.focused).pop();
if (editorCard !== undefined) {
// If the card has results, form the csv
if (typeof editorCard.result === 'object') {
let result: any = editorCard.result;
let fields:string = result.fields.join(",");
let rows: Array<string> = result.values.map((row) => {
return row.join(",");
});
let csv: string = fields + "\r\n" + rows.join("\r\n");
let blob = new Blob([csv], {type: "text/csv"});
let url = URL.createObjectURL(blob);
editor.csv = url;
} else {
editor.csv = undefined;
}
}
}
function loadCards(event:Event, elem) {
let target = <HTMLInputElement>event.target;
if(!target.files.length) return;
if(target.files.length > 1) throw new Error("Cannot load multiple files at once");
let file = target.files[0];
let reader = new FileReader();
reader.onload = function(event:any) {
let serialized = event.target.result;
let queries = JSON.parse(serialized);
let cards = queries.map((q) => {
let card = newReplCard();
card.query = q;
return card;
});
editorCards = cards;
editorCards.forEach((r,i) => r.ix = i);
editorCards.forEach((r) => submitReplCard(r));
rerender();
};
reader.readAsText(file);
event.stopPropagation();
closeModals();
rerender();
}
// ------------------
// Repl functions
// ------------------
let editor = {
state: ReplState.CONNECTING,
blob: undefined,
csv: undefined,
load: false,
delete: false,
queue: [],
ws: null,
timer: undefined,
timeout: 0
};
app.renderRoots["eveeditor"] = root;
connectToServer();
function connectToServer() {
let wsAddress = "ws://localhost:8081";
let ws: WebSocket = new WebSocket(wsAddress, []);
editor.ws = ws;
ws.onopen = function(e: Event) {
editor.state = ReplState.CONNECTED;
editor.timeout = 0;
while(editor.queue.length > 0) {
let message = editor.queue.shift();
sendMessage(message);
}
rerender()
}
ws.onerror = function(error) {
editor.state = ReplState.DISCONNECTED;
rerender()
}
ws.onclose = function(error) {
editor.state = ReplState.DISCONNECTED;
reconnect();
rerender()
}
ws.onmessage = function(message) {
let parsed = JSON.parse(message.data);
// Update the result of the correct editor card
let targetCard = editorCards.filter((r) => r.id === parsed.id).shift();
if (targetCard !== undefined) {
if (parsed.type === "result") {
targetCard.state = CardState.GOOD;
targetCard.result = {
fields: parsed.fields,
values: parsed.values,
}
saveReplCard(targetCard);
} else if (parsed.type === "error") {
targetCard.state = CardState.ERROR;
targetCard.result = parsed.cause;
saveReplCard(targetCard);
} else if (parsed.type === "close") {
let removeIx = editorCards.map((r) => r.id).indexOf(parsed.id);
if (removeIx >= 0) {
editorCards[removeIx].state = CardState.CLOSED;
}
rerender(true);
}
}
rerender()
};
}
let checkReconnectInterval = undefined;
function reconnect() {
if(editor.state === ReplState.CONNECTED) {
clearTimeout(checkReconnectInterval);
checkReconnectInterval = undefined;
} else {
checkReconnectInterval = setTimeout(connectToServer, editor.timeout * 1000);
}
if (editor.timeout < 32) {
editor.timeout += editor.timeout > 0 ? editor.timeout : 1;
}
}
function sendMessage(message): boolean {
if (editor.ws.readyState === editor.ws.OPEN) {
editor.ws.send(JSON.stringify(message));
return true;
} else {
editor.queue.push(message);
return false;
}
}
// ------------------
// Card functions
// ------------------
function newReplCard(): ReplCard {
let editorCard: ReplCard = {
id: uuid(),
ix: editorCards.length > 0 ? editorCards.map((r) => r.ix).pop() + 1 : 0,
state: CardState.NONE,
focused: false,
query: "",
result: undefined,
}
return editorCard;
}
function deleteReplCard(editorCard: ReplCard) {
if (editorCard.state !== CardState.NONE) {
let closemessage = {
type: "close",
id: editorCard.id,
};
sendMessage(closemessage);
editorCard.state = CardState.PENDING;
editorCard.result = "Deleting card...";
}
}
function submitReplCard(editorCard: ReplCard) {
let query: Query = {
id: editorCard.id,
type: "query",
query: editorCard.query.replace(/\s+/g,' '),
}
editorCard.state = CardState.PENDING;
let sent = sendMessage(query);
if (editorCard.result === undefined) {
if (sent) {
editorCard.result = "Waiting on response from server...";
} else {
editorCard.result = "Message queued.";
}
}
// Create a new card if we submitted the last one in editorCards
if (editorCard.ix === editorCards.length - 1) {
let nReplCard = newReplCard();
editorCards.forEach((r) => r.focused = false);
nReplCard.focused = true;
editorCards.push(nReplCard);
}
}
function focusCard(editorCard: ReplCard) {
editorCards.forEach((r) => r.focused = false);
editorCard.focused = true;
}
function closeModals() {
editor.blob = undefined;
editor.delete = false;
editor.load = false;
}
// ------------------
// Event handlers
// ------------------
function queryInputKeydown(event, elem) {
let thisReplCard = editorCards[elem.ix];
// Submit the query with ctrl + enter
if ((event.keyCode === 13 || event.keyCode === 83) && event.ctrlKey === true) {
submitReplCard(thisReplCard);
// Catch tab
} else if (event.keyCode === 9) {
let range = getSelection(event.target);
//let value = event.target.innerText;
//value = value.substring(0, range[0]) + " " + value.substring(range[1]);
//event.target.innerHTML = value;
//setSelection(range[0] + 2,range[0] + 2);
// Catch ctrl + arrow up or page up
} else if (event.keyCode === 38 && event.ctrlKey === true || event.keyCode === 33) {
// Set the focus to the previous editor card
let previousIx = editorCards.filter((r) => r.ix < thisReplCard.ix && r.state !== CardState.CLOSED).map((r) => r.ix).pop();
previousIx = previousIx === undefined ? 0 : previousIx;
focusCard(editorCards[previousIx]);
// Catch ctrl + arrow down or page down
} else if (event.keyCode === 40 && event.ctrlKey === true || event.keyCode === 34) {
// Set the focus to the next editor card
let nextIx = thisReplCard.ix + 1 <= editorCards.length - 1 ? thisReplCard.ix + 1 : editorCards.length - 1;
focusCard(editorCards[nextIx]);
// Catch ctrl + delete to remove a card
} else if (event.keyCode === 46 && event.ctrlKey === true) {
deleteReplCard(thisReplCard);
// Catch ctrl + home
} else if (event.keyCode === 36 && event.ctrlKey === true) {
focusCard(editorCards[0]);
// Catch ctrl + end
} else if (event.keyCode === 35 && event.ctrlKey === true) {
focusCard(editorCards[editorCards.length - 1]);
} else {
return;
}
event.preventDefault();
rerender();
}
function getSelection(editableDiv): Array<number> {
let sel: any = window.getSelection();
let range = [sel.baseOffset, sel.extentOffset];
range = range.sort();
return range;
}
function setSelection(start: number, stop: number) {
let sel = window.getSelection();
sel.setBaseAndExtent(sel.anchorNode, start, sel.anchorNode, stop);
}
function queryInputKeyup(event, elem) {
let thisReplCard = editorCards[elem.ix];
thisReplCard.query = event.target.innerText;
}
/*function queryInputBlur(event, elem) {
let thisReplCard = editorCards[elem.ix];
thisReplCard.focused = false;
rerender();
}*/
function editorCardClick(event, elem) {
focusCard(editorCards[elem.ix]);
rerender();
}
function deleteAllCards(event, elem) {
editorCards.forEach(deleteReplCard);
closeModals();
event.stopPropagation();
rerender();
}
function focusQueryBox(node, element) {
if (element.focused) {
node.focus();
}
}
function toggleTheme(event, elem) {
var theme = localStorage["eveReplTheme"];
if (theme === "dark") {
localStorage["eveReplTheme"] = "light";
} else if(theme === "light") {
localStorage["eveReplTheme"] = "dark";
} else {
localStorage["eveReplTheme"] = "dark";
}
rerender();
}
function saveCardsClick(event, elem) {
closeModals();
saveCards();
saveTable();
event.stopPropagation();
rerender();
}
function trashCardsClick(event, elem) {
closeModals();
editor.delete = true;
event.stopPropagation();
rerender();
}
function loadCardsClick(event, elem) {
closeModals();
editor.load = true;
event.stopPropagation();
rerender();
}
function rootClick(event, elem) {
closeModals();
rerender();
}
// ------------------
// Element generation
// ------------------
function generateReplCardElement(editorCard: ReplCard) {
let queryInput = {
ix: editorCard.ix,
key: `${editorCard.id}${editorCard.focused}`,
focused: editorCard.focused,
c: "query-input",
contentEditable: true,
spellcheck: false,
text: editorCard.query,
keydown: queryInputKeydown,
//blur: queryInputBlur,
keyup: queryInputKeyup,
postRender: focusQueryBox,
};
// Set the css according to the card state
let resultcss = "query-result";
let result = undefined;
let editorClass = "repl-card";
// Format card based on state
if (editorCard.state === CardState.GOOD || (editorCard.state === CardState.PENDING && typeof editorCard.result === 'object')) {
if (editorCard.state === CardState.GOOD) {
resultcss += " good";
} else if (editorCard.state === CardState.PENDING) {
resultcss += " pending";
}
let cardresult: any = editorCard.result;
let tableHeader = {c: "header", children: cardresult.fields.map((f: string) => {
return {c: "cell", text: f};
})};
let tableBody = cardresult.values.map((r: Array<any>) => {
return {c: "row", children: r.map((c: any) => {
return {c: "cell", text: `${c}`};
})};
});
let tableRows = [tableHeader].concat(tableBody);
result = {c: "table", children: tableRows};
} else if (editorCard.state === CardState.ERROR) {
resultcss += " bad";
result = {text: editorCard.result};
} else if (editorCard.state === CardState.PENDING) {
resultcss += " pending";
result = {text: editorCard.result};
} else if (editorCard.state === CardState.CLOSED) {
resultcss += " closed";
editorClass += " no-height";
result = {text: `Query closed.`};
}
let queryResult = result === undefined ? {} : {c: resultcss, children: [result]};
editorClass += editorCard.focused ? " selected" : "";
let editorCardElement = {
id: editorCard.id,
c: editorClass,
click: editorCardClick,
children: [queryInput, queryResult],
};
return editorCardElement;
}
function generateStatusBarElement() {
let indicator = "connecting";
if (editor.state === ReplState.CONNECTED) {
indicator = "connected";
} else if (editor.state === ReplState.DISCONNECTED) {
indicator = "disconnected";
}
// Build the various callouts
let saveAllLink = {t: "a", href: editor.blob, download: "save.evedb", text: "Save Cards", click: function(event) {closeModals(); event.stopPropagation(); rerender();}};
let saveTableLink = {t: "a", href: editor.csv, download: "table.csv", text: "Export CSV", click: function(event) {closeModals(); event.stopPropagation(); rerender();}};
let downloadLink = editor.blob === undefined ? {} : {
c: "callout", children: [
{c: "button no-width", children: [saveAllLink]},
{c: `button ${editor.csv ? "" : "disabled"} no-width`, children: [saveTableLink]},
],
};
let deleteConfirm = editor.delete === false ? {} : {
c: "callout",
children: [{c: "button no-width", text: "Delete All Cards", click: deleteAllCards}],
};
let fileSelector = editor.load === false ? {} : {
c: "callout",
children: [{
c: "fileUpload",
children: [
{c: "button no-width", text: "Load Cards"},
{t: "input", type: "file", c: "upload", change: loadCards},
]
}],
};
// Build the proper elements of the status bar
let statusIndicator = {c: `indicator ${indicator} left`};
let trash = {c: "ion-trash-a button right", click: trashCardsClick, children: [deleteConfirm]};
let save = {c: "ion-ios-download-outline button right", click: saveCardsClick, children: [downloadLink]};
let load = {c: "ion-ios-upload-outline button right", click: loadCardsClick, children: [fileSelector]};
let dimmer = {c: `${localStorage["eveReplTheme"] === "light" ? "ion-ios-lightbulb" : "ion-ios-lightbulb-outline"} button right`, click: toggleTheme};
let refresh = {c: `ion-refresh button ${editor.state !== ReplState.DISCONNECTED ? "no-opacity" : ""} left no-width`, text: " Reconnect", click: function () { editor.timeout = 0; reconnect(); } };
// Build the status bar
let statusBar = {
id: "status-bar",
c: "status-bar",
children: [statusIndicator, refresh, trash, save, load, dimmer],
}
return statusBar;
}
// Create an initial editor card
let editorCards: Array<ReplCard> = loadReplCards();
editorCards.push(newReplCard());
editorCards[0].focused = true;
function root() {
let cardRoot = {
id: "card-root",
c: "card-root",
children: editorCards.map(generateReplCardElement),
}
let editorRoot = {
id: "editor_root",
c: "editor-root",
children: [generateStatusBarElement(), cardRoot],
};
let root = {
id: "root",
c: `root ${localStorage["eveReplTheme"] === undefined ? "light" : localStorage["eveReplTheme"]}`,
children: [editorRoot],
click: rootClick,
};
return root;
} | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.