text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import { html, render } from 'lit-html';
// Below path will be there when an application installs `carbon-web-components` package.
// In our dev env, we auto-generate the file and re-map below path to to point to the generated file.
// @ts-ignore
import Fade16 from 'carbon-web-components/es/icons/fade/16';
import EventManager from '../utils/event-manager';
import ifNonNull from '../../src/globals/directives/if-non-null';
/* eslint-disable import/no-duplicates */
import BXHeaderMenu from '../../src/components/ui-shell/header-menu';
// Above import does not seem to register the custom element
import '../../src/components/ui-shell/header-menu';
/* eslint-enable import/no-duplicates */
/* eslint-disable import/no-duplicates */
import BXSideNavMenuButton from '../../src/components/ui-shell/header-menu-button';
// Above import does not seem to register the custom element
import '../../src/components/ui-shell/header-menu-button';
/* eslint-enable import/no-duplicates */
import '../../src/components/ui-shell/header-name';
import '../../src/components/ui-shell/header-nav';
import '../../src/components/ui-shell/header-nav-item';
import BXSideNav, { SIDE_NAV_COLLAPSE_MODE, SIDE_NAV_USAGE_MODE } from '../../src/components/ui-shell/side-nav';
import '../../src/components/ui-shell/side-nav-link';
/* eslint-disable import/no-duplicates */
import BXSideNavMenu from '../../src/components/ui-shell/side-nav-menu';
// Above import does not seem to register the custom element
import '../../src/components/ui-shell/side-nav-menu';
/* eslint-enable import/no-duplicates */
import '../../src/components/ui-shell/side-nav-menu-item';
const headerMenuButtonTemplate = (props?) => {
const { active, buttonLabelActive, buttonLabelInactive, collapseMode, disabled, usageMode } = props ?? {};
return html`
<bx-header-menu-button
?active="${ifNonNull(active)}"
button-label-active="${ifNonNull(buttonLabelActive)}"
button-label-inactive="${ifNonNull(buttonLabelInactive)}"
collapse-mode="${ifNonNull(collapseMode)}"
?disabled="${disabled}"
usage-mode="${ifNonNull(usageMode)}">
</bx-header-menu-button>
`;
};
const headerMenuTemplate = (props?) => {
const { expanded, menuLabel, triggerContent } = props ?? {};
return html`
<bx-header-menu ?expanded="${expanded}" menu-label="${ifNonNull(menuLabel)}" trigger-content="${ifNonNull(triggerContent)}">
</bx-header-menu>
`;
};
const headerNameTemplate = (props?) => {
const { href, prefix } = props ?? {};
return html` <bx-header-name href="${ifNonNull(href)}" prefix="${ifNonNull(prefix)}"></bx-header-name> `;
};
const headerNavTemplate = (props?) => {
const { menuBarLabel } = props ?? {};
return html` <bx-header-nav menu-bar-label="${ifNonNull(menuBarLabel)}"></bx-header-nav> `;
};
const headerNavItemTemplate = (props?) => {
const { href } = props ?? {};
return html` <bx-header-nav-item href="${ifNonNull(href)}"></bx-header-nav-item> `;
};
const sideNavTemplate = (props?) => {
const { collapseMode, expanded, usageMode, children } = props ?? {};
return html`
<bx-header-menu-button></bx-header-menu-button>
<bx-side-nav collapse-mode="${ifNonNull(collapseMode)}" ?expanded="${expanded}" usage-mode="${ifNonNull(usageMode)}">
${children}
</bx-side-nav>
`;
};
const sideNavLinkTemplate = (props?) => {
const { active, href, children } = props ?? {};
return html` <bx-side-nav-link ?active="${active}" href="${ifNonNull(href)}">${children}</bx-side-nav-link> `;
};
const sideNavMenuTemplate = (props?) => {
const { active, expanded, forceCollapsed, title, children } = props ?? {};
return html`
<bx-side-nav-menu
?active="${active}"
?expanded="${expanded}"
?force-collapsed="${forceCollapsed}"
title="${ifNonNull(title)}">
${children}
</bx-side-nav-menu>
`;
};
const sideNavMenuItemTemplate = (props?) => {
const { active, href } = props ?? {};
return html`
<bx-side-nav-menu>
<bx-side-nav-menu-item ?active="${active}" href="${ifNonNull(href)}"></bx-side-nav-menu-item>
</bx-side-nav-menu>
`;
};
describe('ui-shell', function () {
const events = new EventManager();
describe('bx-header-menu-button', function () {
describe('Misc attributes', function () {
it('should render with minimum attributes', async function () {
render(headerMenuButtonTemplate(), document.body);
await Promise.resolve();
expect(document.body.querySelector('bx-header-menu-button')).toMatchSnapshot({ mode: 'shadow' });
});
it('should render with various attributes for inactive state', async function () {
render(
headerMenuButtonTemplate({
buttonLabelActive: 'button-label-active',
buttonLabelInactive: 'button-label-inactive',
collapseMode: SIDE_NAV_COLLAPSE_MODE.RESPONSIVE,
disabled: true,
usageMode: SIDE_NAV_USAGE_MODE.HEADER_NAV,
}),
document.body
);
await Promise.resolve();
expect(document.body.querySelector('bx-header-menu-button')).toMatchSnapshot({ mode: 'shadow' });
});
it('should render with various attributes for active state', async function () {
render(
headerMenuButtonTemplate({
active: true,
buttonLabelActive: 'button-label-active',
buttonLabelInactive: 'button-label-inactive',
collapseMode: SIDE_NAV_COLLAPSE_MODE.RESPONSIVE,
disabled: true,
usageMode: SIDE_NAV_USAGE_MODE.HEADER_NAV,
}),
document.body
);
await Promise.resolve();
expect(document.body.querySelector('bx-header-menu-button')).toMatchSnapshot({ mode: 'shadow' });
});
});
describe('Handling user interaction', function () {
it('should fire bx-header-menu-button-toggled event upon clicking the button', async function () {
render(headerMenuButtonTemplate(), document.body);
await Promise.resolve();
const spyAfterToggle = jasmine.createSpy('after toggle');
const button = document.body.querySelector('bx-header-menu-button');
events.on(button!, 'bx-header-menu-button-toggled', spyAfterToggle);
button!.shadowRoot!.querySelector('button')!.click();
expect(spyAfterToggle).toHaveBeenCalled();
});
});
});
describe('bx-header-menu', function () {
describe('Misc attributes', function () {
it('should render with minimum attributes', async function () {
render(headerMenuTemplate(), document.body);
await Promise.resolve();
expect(document.body.querySelector('bx-header-menu')).toMatchSnapshot({ mode: 'shadow' });
});
it('should render with various attributes', async function () {
render(
headerMenuTemplate({
expanded: true,
menuLabel: 'menu-label-foo',
triggerContent: 'trigger-content-foo',
}),
document.body
);
await Promise.resolve();
expect(document.body.querySelector('bx-header-menu')).toMatchSnapshot({ mode: 'shadow' });
});
});
describe('Handling user interaction', function () {
it('should toggle the expanded state upon clicking the button', async function () {
render(headerMenuTemplate(), document.body);
await Promise.resolve();
const menu = document.body.querySelector('bx-header-menu');
menu!.shadowRoot!.querySelector('a')!.click();
expect((menu as BXHeaderMenu).expanded).toBe(true);
menu!.shadowRoot!.querySelector('a')!.click();
expect((menu as BXHeaderMenu).expanded).toBe(false);
});
it('should collapse upon hitting ESC key', async function () {
render(headerMenuTemplate({ expanded: true }), document.body);
await Promise.resolve();
const menu = document.body.querySelector('bx-header-menu');
const trigger = menu!.shadowRoot!.querySelector('a');
spyOn(trigger!, 'focus');
trigger!.dispatchEvent(Object.assign(new CustomEvent('keydown', { bubbles: true }), { key: 'Escape' }));
expect((menu as BXHeaderMenu).expanded).toBe(false);
expect(trigger!.focus).toHaveBeenCalled();
});
it('should collapse upon losing focus', async function () {
render(headerMenuTemplate({ expanded: true }), document.body);
await Promise.resolve();
const menu = document.body.querySelector('bx-header-menu');
(menu as HTMLElement).dispatchEvent(new CustomEvent('focusout', { bubbles: true }));
expect((menu as BXHeaderMenu).expanded).toBe(false);
});
});
});
describe('bx-header-name', function () {
describe('Misc attributes', function () {
it('should render with minimum attributes', async function () {
render(headerNameTemplate(), document.body);
await Promise.resolve();
expect(document.body.querySelector('bx-header-name')).toMatchSnapshot({ mode: 'shadow' });
});
it('should render with various attributes', async function () {
render(
headerNameTemplate({
href: 'about:blank',
prefix: 'prefix-foo',
}),
document.body
);
await Promise.resolve();
expect(document.body.querySelector('bx-header-name')).toMatchSnapshot({ mode: 'shadow' });
});
});
});
describe('bx-header-nav', function () {
describe('Misc attributes', function () {
it('should render with minimum attributes', async function () {
render(headerNavTemplate(), document.body);
await Promise.resolve();
expect(document.body.querySelector('bx-header-nav')).toMatchSnapshot({ mode: 'shadow' });
});
it('should render with various attributes', async function () {
render(
headerNavTemplate({
menuBarLabel: 'menu-bar-label-foo',
}),
document.body
);
await Promise.resolve();
expect(document.body.querySelector('bx-header-nav')).toMatchSnapshot({ mode: 'shadow' });
});
});
});
describe('bx-header-nav-item', function () {
describe('Misc attributes', function () {
it('should render with minimum attributes', async function () {
render(headerNavItemTemplate(), document.body);
await Promise.resolve();
expect(document.body.querySelector('bx-header-nav-item')).toMatchSnapshot({ mode: 'shadow' });
});
it('should render with various attributes', async function () {
render(
headerNavItemTemplate({
href: 'about:blank',
}),
document.body
);
await Promise.resolve();
expect(document.body.querySelector('bx-header-nav-item')).toMatchSnapshot({ mode: 'shadow' });
});
});
});
describe('bx-side-nav-link', function () {
describe('Misc attributes', function () {
it('should render with minimum attributes', async function () {
render(sideNavLinkTemplate(), document.body);
await Promise.resolve();
expect(document.body.querySelector('bx-side-nav-link')).toMatchSnapshot({ mode: 'shadow' });
});
it('should render with various attributes', async function () {
render(
sideNavLinkTemplate({
active: true,
href: 'about:blank',
children: Fade16({ slot: 'title-icon' }),
}),
document.body
);
await Promise.resolve(); // First update cycle
await Promise.resolve(); // Update cycle upon `slotchange` event
expect(document.body.querySelector('bx-side-nav-link')).toMatchSnapshot({ mode: 'shadow' });
});
});
});
describe('bx-side-nav', function () {
describe('Handling events', function () {
it('should let child side nav menu collapse if this side nav is collapsed', async function () {
render(
sideNavTemplate({
children: html` <bx-side-nav-menu></bx-side-nav-menu> `,
}),
document.body
);
await Promise.resolve();
const nav = document.body.querySelector('bx-side-nav');
const menu = document.body.querySelector('bx-side-nav-menu');
expect((menu as BXSideNavMenu).forceCollapsed).toBe(true);
nav!.dispatchEvent(new CustomEvent('mouseover', { bubbles: true }));
await Promise.resolve();
expect((menu as BXSideNavMenu).forceCollapsed).toBe(false);
nav!.dispatchEvent(new CustomEvent('mouseout', { bubbles: true }));
await Promise.resolve();
expect((menu as BXSideNavMenu).forceCollapsed).toBe(true);
});
it('should toggle expand state upon upon clicking on header menu button', async function () {
render(sideNavTemplate(), document.body);
await Promise.resolve();
const nav = document.body.querySelector('bx-side-nav');
const menuButton = document.body.querySelector('bx-header-menu-button');
menuButton!.dispatchEvent(new CustomEvent('bx-header-menu-button-toggled', { bubbles: true, detail: { active: true } }));
expect((nav as BXSideNav).expanded).toBe(true);
menuButton!.dispatchEvent(new CustomEvent('bx-header-menu-button-toggled', { bubbles: true, detail: { active: false } }));
expect((nav as BXSideNav).expanded).toBe(false);
});
});
describe('Working with header menu button', function () {
it('should propagate mode/states to header menu button', async function () {
render(
sideNavTemplate({
collapseMode: SIDE_NAV_COLLAPSE_MODE.RAIL,
expanded: true,
}),
document.body
);
await Promise.resolve();
const menuButton = document.body.querySelector('bx-header-menu-button');
expect((menuButton as BXSideNavMenuButton).collapseMode).toBe(SIDE_NAV_COLLAPSE_MODE.RAIL);
expect((menuButton as BXSideNavMenuButton).active).toBe(true);
});
it('should propagate usage mode to header menu button', async function () {
render(
sideNavTemplate({
usageMode: SIDE_NAV_USAGE_MODE.HEADER_NAV,
}),
document.body
);
await Promise.resolve();
const menuButton = document.body.querySelector('bx-header-menu-button');
expect((menuButton as BXSideNavMenuButton).usageMode).toBe(SIDE_NAV_USAGE_MODE.HEADER_NAV);
});
});
});
describe('bx-side-nav-menu', function () {
describe('Misc attributes', function () {
it('should render with minimum attributes', async function () {
render(sideNavMenuTemplate(), document.body);
await Promise.resolve();
expect(document.body.querySelector('bx-side-nav-menu')).toMatchSnapshot({ mode: 'shadow' });
});
it('should render with various attributes', async function () {
render(
sideNavMenuTemplate({
active: true,
expanded: true,
title: 'title-foo',
}),
document.body
);
await Promise.resolve();
expect(document.body.querySelector('bx-side-nav-menu')).toMatchSnapshot({ mode: 'shadow' });
});
it('should support collapsing side nav menu upon parent side nav is collapsed as rail', async function () {
render(
sideNavMenuTemplate({
active: true,
expanded: true,
forceCollapsed: true,
}),
document.body
);
await Promise.resolve();
expect(document.body.querySelector('bx-side-nav-menu')).toMatchSnapshot({ mode: 'shadow' });
});
});
describe('Handling user interaction', function () {
it('should fire bx-side-nav-menu-beingtoggled/bx-side-nav-menu-toggled events upon toggling', async function () {
render(sideNavMenuTemplate(), document.body);
await Promise.resolve();
const spyBeforeToggle = jasmine.createSpy('before toggle');
const spyAfterToggle = jasmine.createSpy('after toggle');
const button = document.body.querySelector('bx-side-nav-menu');
events.on(button!, 'bx-side-nav-menu-beingtoggled', spyBeforeToggle);
events.on(button!, 'bx-side-nav-menu-toggled', spyAfterToggle);
button!.shadowRoot!.querySelector('button')!.click();
expect(spyBeforeToggle).toHaveBeenCalled();
expect(spyAfterToggle).toHaveBeenCalled();
});
it('should support preventing side nav menu from being toggled upon user gesture', async function () {
render(sideNavMenuTemplate(), document.body);
await Promise.resolve();
const spyAfterToggle = jasmine.createSpy('after toggle');
const button = document.body.querySelector('bx-side-nav-menu');
events.on(button!, 'bx-side-nav-menu-beingtoggled', event => {
event.preventDefault();
});
events.on(button!, 'bx-side-nav-menu-toggled', spyAfterToggle);
button!.shadowRoot!.querySelector('button')!.click();
await Promise.resolve();
expect(spyAfterToggle).not.toHaveBeenCalled();
});
});
describe('Detecting icons', function () {
it('should tell new child side nav item that the parent side nav menu has an icon', async function () {
render(
sideNavMenuTemplate({
children: Fade16({ slot: 'title-icon' }),
}),
document.body
);
await Promise.resolve();
const menu = document.body.querySelector('bx-side-nav-menu');
const menuItem = document.createElement('bx-side-nav-menu-item');
menu!.appendChild(menuItem);
await Promise.resolve(); // `slotchange` event seems to happen at EOM
expect(menuItem.hasAttribute('parent-has-icon')).toBe(true);
});
it('should tell existing child side nav item that the parent side nav menu has an icon', async function () {
render(
sideNavMenuTemplate({
children: html` <bx-side-nav-menu-item></bx-side-nav-menu-item> `,
}),
document.body
);
await Promise.resolve();
const menu = document.body.querySelector('bx-side-nav-menu');
const menuItem = menu!.querySelector('bx-side-nav-menu-item');
const svg = document.createElement('svg');
svg.setAttribute('slot', 'title-icon');
menu!.appendChild(svg);
await Promise.resolve();
expect(menuItem!.hasAttribute('parent-has-icon')).toBe(true);
});
});
});
describe('bx-side-nav-menu-item', function () {
describe('Misc attributes', function () {
it('should render with minimum attributes', async function () {
render(sideNavMenuItemTemplate(), document.body);
await Promise.resolve();
expect(document.body.querySelector('bx-side-nav-menu-item')).toMatchSnapshot({ mode: 'shadow' });
});
it('should render with various attributes', async function () {
render(
sideNavMenuItemTemplate({
active: true,
href: 'about:blank',
}),
document.body
);
await Promise.resolve();
expect(document.body.querySelector('bx-side-nav-menu-item')).toMatchSnapshot({ mode: 'shadow' });
});
});
describe('Activating', function () {
it('should mark the parent side nav menu as it has active child side nav menu item', async function () {
render(sideNavMenuItemTemplate({ active: true }), document.body);
await Promise.resolve();
expect((document.body.querySelector('bx-side-nav-menu') as BXSideNavMenu).active).toBe(true);
});
});
});
afterEach(async function () {
await render(undefined!, document.body);
events.reset();
});
}); | the_stack |
import { Injectable, Inject, Optional } from '@angular/core';
import { Http, Response } from '@angular/http';
import { SDKModels } from './SDKModels';
import { BaseLoopBackApi } from '../core/base.service';
import { LoopBackConfig } from '../../lb.config';
import { LoopBackAuth } from '../core/auth.service';
import { LoopBackFilter, } from '../../models/BaseModels';
import { JSONSearchParams } from '../core/search.params';
import { ErrorHandler } from '../core/error.service';
import { Subject } from 'rxjs/Subject';
import { Observable } from 'rxjs/Rx';
import { SystemDomain } from '../../models/SystemDomain';
import { SocketConnection } from '../../sockets/socket.connections';
import { ContentEvent } from '../../models/ContentEvent';
import { ContentPage } from '../../models/ContentPage';
import { ContentProduct } from '../../models/ContentProduct';
import { ContentPost } from '../../models/ContentPost';
import { StorageFile } from '../../models/StorageFile';
/**
* Api services for the `SystemDomain` model.
*
* **Details**
*
* System: Manage Domains and related content
*/
@Injectable()
export class SystemDomainApi extends BaseLoopBackApi {
constructor(
@Inject(Http) protected http: Http,
@Inject(SocketConnection) protected connection: SocketConnection,
@Inject(SDKModels) protected models: SDKModels,
@Inject(LoopBackAuth) protected auth: LoopBackAuth,
@Inject(JSONSearchParams) protected searchParams: JSONSearchParams,
@Optional() @Inject(ErrorHandler) protected errorHandler: ErrorHandler
) {
super(http, connection, models, auth, searchParams, errorHandler);
}
/**
* Find a related item by id for contentEvents.
*
* @param {any} id SystemDomain id
*
* @param {any} fk Foreign key for contentEvents
*
* @returns {object} An empty reference that will be
* populated with the actual data once the response is returned
* from the server.
*
* <em>
* (The remote method definition does not provide any description.
* This usually means the response is a `SystemDomain` object.)
* </em>
*/
public findByIdContentEvents(id: any, fk: any, customHeaders?: Function): Observable<any> {
let _method: string = "GET";
let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() +
"/Domains/:id/contentEvents/:fk";
let _routeParams: any = {
id: id,
fk: fk
};
let _postBody: any = {};
let _urlParams: any = {};
let result = this.request(_method, _url, _routeParams, _urlParams, _postBody, null, customHeaders);
return result;
}
/**
* Delete a related item by id for contentEvents.
*
* @param {any} id SystemDomain id
*
* @param {any} fk Foreign key for contentEvents
*
* @returns {object} An empty reference that will be
* populated with the actual data once the response is returned
* from the server.
*
* This method returns no data.
*/
public destroyByIdContentEvents(id: any, fk: any, customHeaders?: Function): Observable<any> {
let _method: string = "DELETE";
let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() +
"/Domains/:id/contentEvents/:fk";
let _routeParams: any = {
id: id,
fk: fk
};
let _postBody: any = {};
let _urlParams: any = {};
let result = this.request(_method, _url, _routeParams, _urlParams, _postBody, null, customHeaders);
return result;
}
/**
* Update a related item by id for contentEvents.
*
* @param {any} id SystemDomain id
*
* @param {any} fk Foreign key for contentEvents
*
* @param {object} data Request data.
*
* This method expects a subset of model properties as request parameters.
*
* @returns {object} An empty reference that will be
* populated with the actual data once the response is returned
* from the server.
*
* <em>
* (The remote method definition does not provide any description.
* This usually means the response is a `SystemDomain` object.)
* </em>
*/
public updateByIdContentEvents(id: any, fk: any, data: any = {}, customHeaders?: Function): Observable<any> {
let _method: string = "PUT";
let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() +
"/Domains/:id/contentEvents/:fk";
let _routeParams: any = {
id: id,
fk: fk
};
let _postBody: any = {
data: data
};
let _urlParams: any = {};
let result = this.request(_method, _url, _routeParams, _urlParams, _postBody, null, customHeaders);
return result;
}
/**
* Find a related item by id for contentPages.
*
* @param {any} id SystemDomain id
*
* @param {any} fk Foreign key for contentPages
*
* @returns {object} An empty reference that will be
* populated with the actual data once the response is returned
* from the server.
*
* <em>
* (The remote method definition does not provide any description.
* This usually means the response is a `SystemDomain` object.)
* </em>
*/
public findByIdContentPages(id: any, fk: any, customHeaders?: Function): Observable<any> {
let _method: string = "GET";
let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() +
"/Domains/:id/contentPages/:fk";
let _routeParams: any = {
id: id,
fk: fk
};
let _postBody: any = {};
let _urlParams: any = {};
let result = this.request(_method, _url, _routeParams, _urlParams, _postBody, null, customHeaders);
return result;
}
/**
* Delete a related item by id for contentPages.
*
* @param {any} id SystemDomain id
*
* @param {any} fk Foreign key for contentPages
*
* @returns {object} An empty reference that will be
* populated with the actual data once the response is returned
* from the server.
*
* This method returns no data.
*/
public destroyByIdContentPages(id: any, fk: any, customHeaders?: Function): Observable<any> {
let _method: string = "DELETE";
let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() +
"/Domains/:id/contentPages/:fk";
let _routeParams: any = {
id: id,
fk: fk
};
let _postBody: any = {};
let _urlParams: any = {};
let result = this.request(_method, _url, _routeParams, _urlParams, _postBody, null, customHeaders);
return result;
}
/**
* Update a related item by id for contentPages.
*
* @param {any} id SystemDomain id
*
* @param {any} fk Foreign key for contentPages
*
* @param {object} data Request data.
*
* This method expects a subset of model properties as request parameters.
*
* @returns {object} An empty reference that will be
* populated with the actual data once the response is returned
* from the server.
*
* <em>
* (The remote method definition does not provide any description.
* This usually means the response is a `SystemDomain` object.)
* </em>
*/
public updateByIdContentPages(id: any, fk: any, data: any = {}, customHeaders?: Function): Observable<any> {
let _method: string = "PUT";
let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() +
"/Domains/:id/contentPages/:fk";
let _routeParams: any = {
id: id,
fk: fk
};
let _postBody: any = {
data: data
};
let _urlParams: any = {};
let result = this.request(_method, _url, _routeParams, _urlParams, _postBody, null, customHeaders);
return result;
}
/**
* Find a related item by id for contentProducts.
*
* @param {any} id SystemDomain id
*
* @param {any} fk Foreign key for contentProducts
*
* @returns {object} An empty reference that will be
* populated with the actual data once the response is returned
* from the server.
*
* <em>
* (The remote method definition does not provide any description.
* This usually means the response is a `SystemDomain` object.)
* </em>
*/
public findByIdContentProducts(id: any, fk: any, customHeaders?: Function): Observable<any> {
let _method: string = "GET";
let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() +
"/Domains/:id/contentProducts/:fk";
let _routeParams: any = {
id: id,
fk: fk
};
let _postBody: any = {};
let _urlParams: any = {};
let result = this.request(_method, _url, _routeParams, _urlParams, _postBody, null, customHeaders);
return result;
}
/**
* Delete a related item by id for contentProducts.
*
* @param {any} id SystemDomain id
*
* @param {any} fk Foreign key for contentProducts
*
* @returns {object} An empty reference that will be
* populated with the actual data once the response is returned
* from the server.
*
* This method returns no data.
*/
public destroyByIdContentProducts(id: any, fk: any, customHeaders?: Function): Observable<any> {
let _method: string = "DELETE";
let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() +
"/Domains/:id/contentProducts/:fk";
let _routeParams: any = {
id: id,
fk: fk
};
let _postBody: any = {};
let _urlParams: any = {};
let result = this.request(_method, _url, _routeParams, _urlParams, _postBody, null, customHeaders);
return result;
}
/**
* Update a related item by id for contentProducts.
*
* @param {any} id SystemDomain id
*
* @param {any} fk Foreign key for contentProducts
*
* @param {object} data Request data.
*
* This method expects a subset of model properties as request parameters.
*
* @returns {object} An empty reference that will be
* populated with the actual data once the response is returned
* from the server.
*
* <em>
* (The remote method definition does not provide any description.
* This usually means the response is a `SystemDomain` object.)
* </em>
*/
public updateByIdContentProducts(id: any, fk: any, data: any = {}, customHeaders?: Function): Observable<any> {
let _method: string = "PUT";
let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() +
"/Domains/:id/contentProducts/:fk";
let _routeParams: any = {
id: id,
fk: fk
};
let _postBody: any = {
data: data
};
let _urlParams: any = {};
let result = this.request(_method, _url, _routeParams, _urlParams, _postBody, null, customHeaders);
return result;
}
/**
* Find a related item by id for contentPosts.
*
* @param {any} id SystemDomain id
*
* @param {any} fk Foreign key for contentPosts
*
* @returns {object} An empty reference that will be
* populated with the actual data once the response is returned
* from the server.
*
* <em>
* (The remote method definition does not provide any description.
* This usually means the response is a `SystemDomain` object.)
* </em>
*/
public findByIdContentPosts(id: any, fk: any, customHeaders?: Function): Observable<any> {
let _method: string = "GET";
let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() +
"/Domains/:id/contentPosts/:fk";
let _routeParams: any = {
id: id,
fk: fk
};
let _postBody: any = {};
let _urlParams: any = {};
let result = this.request(_method, _url, _routeParams, _urlParams, _postBody, null, customHeaders);
return result;
}
/**
* Delete a related item by id for contentPosts.
*
* @param {any} id SystemDomain id
*
* @param {any} fk Foreign key for contentPosts
*
* @returns {object} An empty reference that will be
* populated with the actual data once the response is returned
* from the server.
*
* This method returns no data.
*/
public destroyByIdContentPosts(id: any, fk: any, customHeaders?: Function): Observable<any> {
let _method: string = "DELETE";
let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() +
"/Domains/:id/contentPosts/:fk";
let _routeParams: any = {
id: id,
fk: fk
};
let _postBody: any = {};
let _urlParams: any = {};
let result = this.request(_method, _url, _routeParams, _urlParams, _postBody, null, customHeaders);
return result;
}
/**
* Update a related item by id for contentPosts.
*
* @param {any} id SystemDomain id
*
* @param {any} fk Foreign key for contentPosts
*
* @param {object} data Request data.
*
* This method expects a subset of model properties as request parameters.
*
* @returns {object} An empty reference that will be
* populated with the actual data once the response is returned
* from the server.
*
* <em>
* (The remote method definition does not provide any description.
* This usually means the response is a `SystemDomain` object.)
* </em>
*/
public updateByIdContentPosts(id: any, fk: any, data: any = {}, customHeaders?: Function): Observable<any> {
let _method: string = "PUT";
let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() +
"/Domains/:id/contentPosts/:fk";
let _routeParams: any = {
id: id,
fk: fk
};
let _postBody: any = {
data: data
};
let _urlParams: any = {};
let result = this.request(_method, _url, _routeParams, _urlParams, _postBody, null, customHeaders);
return result;
}
/**
* Find a related item by id for storageFiles.
*
* @param {any} id SystemDomain id
*
* @param {any} fk Foreign key for storageFiles
*
* @returns {object} An empty reference that will be
* populated with the actual data once the response is returned
* from the server.
*
* <em>
* (The remote method definition does not provide any description.
* This usually means the response is a `SystemDomain` object.)
* </em>
*/
public findByIdStorageFiles(id: any, fk: any, customHeaders?: Function): Observable<any> {
let _method: string = "GET";
let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() +
"/Domains/:id/storageFiles/:fk";
let _routeParams: any = {
id: id,
fk: fk
};
let _postBody: any = {};
let _urlParams: any = {};
let result = this.request(_method, _url, _routeParams, _urlParams, _postBody, null, customHeaders);
return result;
}
/**
* Delete a related item by id for storageFiles.
*
* @param {any} id SystemDomain id
*
* @param {any} fk Foreign key for storageFiles
*
* @returns {object} An empty reference that will be
* populated with the actual data once the response is returned
* from the server.
*
* This method returns no data.
*/
public destroyByIdStorageFiles(id: any, fk: any, customHeaders?: Function): Observable<any> {
let _method: string = "DELETE";
let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() +
"/Domains/:id/storageFiles/:fk";
let _routeParams: any = {
id: id,
fk: fk
};
let _postBody: any = {};
let _urlParams: any = {};
let result = this.request(_method, _url, _routeParams, _urlParams, _postBody, null, customHeaders);
return result;
}
/**
* Update a related item by id for storageFiles.
*
* @param {any} id SystemDomain id
*
* @param {any} fk Foreign key for storageFiles
*
* @param {object} data Request data.
*
* This method expects a subset of model properties as request parameters.
*
* @returns {object} An empty reference that will be
* populated with the actual data once the response is returned
* from the server.
*
* <em>
* (The remote method definition does not provide any description.
* This usually means the response is a `SystemDomain` object.)
* </em>
*/
public updateByIdStorageFiles(id: any, fk: any, data: any = {}, customHeaders?: Function): Observable<any> {
let _method: string = "PUT";
let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() +
"/Domains/:id/storageFiles/:fk";
let _routeParams: any = {
id: id,
fk: fk
};
let _postBody: any = {
data: data
};
let _urlParams: any = {};
let result = this.request(_method, _url, _routeParams, _urlParams, _postBody, null, customHeaders);
return result;
}
/**
* Queries contentEvents of SystemDomain.
*
* @param {any} id SystemDomain id
*
* @param {object} filter
*
* @returns {object[]} An empty reference that will be
* populated with the actual data once the response is returned
* from the server.
*
* <em>
* (The remote method definition does not provide any description.
* This usually means the response is a `SystemDomain` object.)
* </em>
*/
public getContentEvents(id: any, filter: LoopBackFilter = {}, customHeaders?: Function): Observable<any> {
let _method: string = "GET";
let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() +
"/Domains/:id/contentEvents";
let _routeParams: any = {
id: id
};
let _postBody: any = {};
let _urlParams: any = {};
if (typeof filter !== 'undefined' && filter !== null) _urlParams.filter = filter;
let result = this.request(_method, _url, _routeParams, _urlParams, _postBody, null, customHeaders);
return result;
}
/**
* Creates a new instance in contentEvents of this model.
*
* @param {any} id SystemDomain id
*
* @param {object} data Request data.
*
* This method expects a subset of model properties as request parameters.
*
* @returns {object} An empty reference that will be
* populated with the actual data once the response is returned
* from the server.
*
* <em>
* (The remote method definition does not provide any description.
* This usually means the response is a `SystemDomain` object.)
* </em>
*/
public createContentEvents(id: any, data: any = {}, customHeaders?: Function): Observable<any> {
let _method: string = "POST";
let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() +
"/Domains/:id/contentEvents";
let _routeParams: any = {
id: id
};
let _postBody: any = {
data: data
};
let _urlParams: any = {};
let result = this.request(_method, _url, _routeParams, _urlParams, _postBody, null, customHeaders);
return result;
}
/**
* Deletes all contentEvents of this model.
*
* @param {any} id SystemDomain id
*
* @returns {object} An empty reference that will be
* populated with the actual data once the response is returned
* from the server.
*
* This method returns no data.
*/
public deleteContentEvents(id: any, customHeaders?: Function): Observable<any> {
let _method: string = "DELETE";
let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() +
"/Domains/:id/contentEvents";
let _routeParams: any = {
id: id
};
let _postBody: any = {};
let _urlParams: any = {};
let result = this.request(_method, _url, _routeParams, _urlParams, _postBody, null, customHeaders);
return result;
}
/**
* Counts contentEvents of SystemDomain.
*
* @param {any} id SystemDomain id
*
* @param {object} where Criteria to match model instances
*
* @returns {object} An empty reference that will be
* populated with the actual data once the response is returned
* from the server.
*
* Data properties:
*
* - `count` – `{number}` -
*/
public countContentEvents(id: any, where: any = {}, customHeaders?: Function): Observable<any> {
let _method: string = "GET";
let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() +
"/Domains/:id/contentEvents/count";
let _routeParams: any = {
id: id
};
let _postBody: any = {};
let _urlParams: any = {};
if (typeof where !== 'undefined' && where !== null) _urlParams.where = where;
let result = this.request(_method, _url, _routeParams, _urlParams, _postBody, null, customHeaders);
return result;
}
/**
* Queries contentPages of SystemDomain.
*
* @param {any} id SystemDomain id
*
* @param {object} filter
*
* @returns {object[]} An empty reference that will be
* populated with the actual data once the response is returned
* from the server.
*
* <em>
* (The remote method definition does not provide any description.
* This usually means the response is a `SystemDomain` object.)
* </em>
*/
public getContentPages(id: any, filter: LoopBackFilter = {}, customHeaders?: Function): Observable<any> {
let _method: string = "GET";
let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() +
"/Domains/:id/contentPages";
let _routeParams: any = {
id: id
};
let _postBody: any = {};
let _urlParams: any = {};
if (typeof filter !== 'undefined' && filter !== null) _urlParams.filter = filter;
let result = this.request(_method, _url, _routeParams, _urlParams, _postBody, null, customHeaders);
return result;
}
/**
* Creates a new instance in contentPages of this model.
*
* @param {any} id SystemDomain id
*
* @param {object} data Request data.
*
* This method expects a subset of model properties as request parameters.
*
* @returns {object} An empty reference that will be
* populated with the actual data once the response is returned
* from the server.
*
* <em>
* (The remote method definition does not provide any description.
* This usually means the response is a `SystemDomain` object.)
* </em>
*/
public createContentPages(id: any, data: any = {}, customHeaders?: Function): Observable<any> {
let _method: string = "POST";
let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() +
"/Domains/:id/contentPages";
let _routeParams: any = {
id: id
};
let _postBody: any = {
data: data
};
let _urlParams: any = {};
let result = this.request(_method, _url, _routeParams, _urlParams, _postBody, null, customHeaders);
return result;
}
/**
* Deletes all contentPages of this model.
*
* @param {any} id SystemDomain id
*
* @returns {object} An empty reference that will be
* populated with the actual data once the response is returned
* from the server.
*
* This method returns no data.
*/
public deleteContentPages(id: any, customHeaders?: Function): Observable<any> {
let _method: string = "DELETE";
let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() +
"/Domains/:id/contentPages";
let _routeParams: any = {
id: id
};
let _postBody: any = {};
let _urlParams: any = {};
let result = this.request(_method, _url, _routeParams, _urlParams, _postBody, null, customHeaders);
return result;
}
/**
* Counts contentPages of SystemDomain.
*
* @param {any} id SystemDomain id
*
* @param {object} where Criteria to match model instances
*
* @returns {object} An empty reference that will be
* populated with the actual data once the response is returned
* from the server.
*
* Data properties:
*
* - `count` – `{number}` -
*/
public countContentPages(id: any, where: any = {}, customHeaders?: Function): Observable<any> {
let _method: string = "GET";
let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() +
"/Domains/:id/contentPages/count";
let _routeParams: any = {
id: id
};
let _postBody: any = {};
let _urlParams: any = {};
if (typeof where !== 'undefined' && where !== null) _urlParams.where = where;
let result = this.request(_method, _url, _routeParams, _urlParams, _postBody, null, customHeaders);
return result;
}
/**
* Queries contentProducts of SystemDomain.
*
* @param {any} id SystemDomain id
*
* @param {object} filter
*
* @returns {object[]} An empty reference that will be
* populated with the actual data once the response is returned
* from the server.
*
* <em>
* (The remote method definition does not provide any description.
* This usually means the response is a `SystemDomain` object.)
* </em>
*/
public getContentProducts(id: any, filter: LoopBackFilter = {}, customHeaders?: Function): Observable<any> {
let _method: string = "GET";
let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() +
"/Domains/:id/contentProducts";
let _routeParams: any = {
id: id
};
let _postBody: any = {};
let _urlParams: any = {};
if (typeof filter !== 'undefined' && filter !== null) _urlParams.filter = filter;
let result = this.request(_method, _url, _routeParams, _urlParams, _postBody, null, customHeaders);
return result;
}
/**
* Creates a new instance in contentProducts of this model.
*
* @param {any} id SystemDomain id
*
* @param {object} data Request data.
*
* This method expects a subset of model properties as request parameters.
*
* @returns {object} An empty reference that will be
* populated with the actual data once the response is returned
* from the server.
*
* <em>
* (The remote method definition does not provide any description.
* This usually means the response is a `SystemDomain` object.)
* </em>
*/
public createContentProducts(id: any, data: any = {}, customHeaders?: Function): Observable<any> {
let _method: string = "POST";
let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() +
"/Domains/:id/contentProducts";
let _routeParams: any = {
id: id
};
let _postBody: any = {
data: data
};
let _urlParams: any = {};
let result = this.request(_method, _url, _routeParams, _urlParams, _postBody, null, customHeaders);
return result;
}
/**
* Deletes all contentProducts of this model.
*
* @param {any} id SystemDomain id
*
* @returns {object} An empty reference that will be
* populated with the actual data once the response is returned
* from the server.
*
* This method returns no data.
*/
public deleteContentProducts(id: any, customHeaders?: Function): Observable<any> {
let _method: string = "DELETE";
let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() +
"/Domains/:id/contentProducts";
let _routeParams: any = {
id: id
};
let _postBody: any = {};
let _urlParams: any = {};
let result = this.request(_method, _url, _routeParams, _urlParams, _postBody, null, customHeaders);
return result;
}
/**
* Counts contentProducts of SystemDomain.
*
* @param {any} id SystemDomain id
*
* @param {object} where Criteria to match model instances
*
* @returns {object} An empty reference that will be
* populated with the actual data once the response is returned
* from the server.
*
* Data properties:
*
* - `count` – `{number}` -
*/
public countContentProducts(id: any, where: any = {}, customHeaders?: Function): Observable<any> {
let _method: string = "GET";
let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() +
"/Domains/:id/contentProducts/count";
let _routeParams: any = {
id: id
};
let _postBody: any = {};
let _urlParams: any = {};
if (typeof where !== 'undefined' && where !== null) _urlParams.where = where;
let result = this.request(_method, _url, _routeParams, _urlParams, _postBody, null, customHeaders);
return result;
}
/**
* Queries contentPosts of SystemDomain.
*
* @param {any} id SystemDomain id
*
* @param {object} filter
*
* @returns {object[]} An empty reference that will be
* populated with the actual data once the response is returned
* from the server.
*
* <em>
* (The remote method definition does not provide any description.
* This usually means the response is a `SystemDomain` object.)
* </em>
*/
public getContentPosts(id: any, filter: LoopBackFilter = {}, customHeaders?: Function): Observable<any> {
let _method: string = "GET";
let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() +
"/Domains/:id/contentPosts";
let _routeParams: any = {
id: id
};
let _postBody: any = {};
let _urlParams: any = {};
if (typeof filter !== 'undefined' && filter !== null) _urlParams.filter = filter;
let result = this.request(_method, _url, _routeParams, _urlParams, _postBody, null, customHeaders);
return result;
}
/**
* Creates a new instance in contentPosts of this model.
*
* @param {any} id SystemDomain id
*
* @param {object} data Request data.
*
* This method expects a subset of model properties as request parameters.
*
* @returns {object} An empty reference that will be
* populated with the actual data once the response is returned
* from the server.
*
* <em>
* (The remote method definition does not provide any description.
* This usually means the response is a `SystemDomain` object.)
* </em>
*/
public createContentPosts(id: any, data: any = {}, customHeaders?: Function): Observable<any> {
let _method: string = "POST";
let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() +
"/Domains/:id/contentPosts";
let _routeParams: any = {
id: id
};
let _postBody: any = {
data: data
};
let _urlParams: any = {};
let result = this.request(_method, _url, _routeParams, _urlParams, _postBody, null, customHeaders);
return result;
}
/**
* Deletes all contentPosts of this model.
*
* @param {any} id SystemDomain id
*
* @returns {object} An empty reference that will be
* populated with the actual data once the response is returned
* from the server.
*
* This method returns no data.
*/
public deleteContentPosts(id: any, customHeaders?: Function): Observable<any> {
let _method: string = "DELETE";
let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() +
"/Domains/:id/contentPosts";
let _routeParams: any = {
id: id
};
let _postBody: any = {};
let _urlParams: any = {};
let result = this.request(_method, _url, _routeParams, _urlParams, _postBody, null, customHeaders);
return result;
}
/**
* Counts contentPosts of SystemDomain.
*
* @param {any} id SystemDomain id
*
* @param {object} where Criteria to match model instances
*
* @returns {object} An empty reference that will be
* populated with the actual data once the response is returned
* from the server.
*
* Data properties:
*
* - `count` – `{number}` -
*/
public countContentPosts(id: any, where: any = {}, customHeaders?: Function): Observable<any> {
let _method: string = "GET";
let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() +
"/Domains/:id/contentPosts/count";
let _routeParams: any = {
id: id
};
let _postBody: any = {};
let _urlParams: any = {};
if (typeof where !== 'undefined' && where !== null) _urlParams.where = where;
let result = this.request(_method, _url, _routeParams, _urlParams, _postBody, null, customHeaders);
return result;
}
/**
* Queries storageFiles of SystemDomain.
*
* @param {any} id SystemDomain id
*
* @param {object} filter
*
* @returns {object[]} An empty reference that will be
* populated with the actual data once the response is returned
* from the server.
*
* <em>
* (The remote method definition does not provide any description.
* This usually means the response is a `SystemDomain` object.)
* </em>
*/
public getStorageFiles(id: any, filter: LoopBackFilter = {}, customHeaders?: Function): Observable<any> {
let _method: string = "GET";
let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() +
"/Domains/:id/storageFiles";
let _routeParams: any = {
id: id
};
let _postBody: any = {};
let _urlParams: any = {};
if (typeof filter !== 'undefined' && filter !== null) _urlParams.filter = filter;
let result = this.request(_method, _url, _routeParams, _urlParams, _postBody, null, customHeaders);
return result;
}
/**
* Creates a new instance in storageFiles of this model.
*
* @param {any} id SystemDomain id
*
* @param {object} data Request data.
*
* This method expects a subset of model properties as request parameters.
*
* @returns {object} An empty reference that will be
* populated with the actual data once the response is returned
* from the server.
*
* <em>
* (The remote method definition does not provide any description.
* This usually means the response is a `SystemDomain` object.)
* </em>
*/
public createStorageFiles(id: any, data: any = {}, customHeaders?: Function): Observable<any> {
let _method: string = "POST";
let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() +
"/Domains/:id/storageFiles";
let _routeParams: any = {
id: id
};
let _postBody: any = {
data: data
};
let _urlParams: any = {};
let result = this.request(_method, _url, _routeParams, _urlParams, _postBody, null, customHeaders);
return result;
}
/**
* Deletes all storageFiles of this model.
*
* @param {any} id SystemDomain id
*
* @returns {object} An empty reference that will be
* populated with the actual data once the response is returned
* from the server.
*
* This method returns no data.
*/
public deleteStorageFiles(id: any, customHeaders?: Function): Observable<any> {
let _method: string = "DELETE";
let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() +
"/Domains/:id/storageFiles";
let _routeParams: any = {
id: id
};
let _postBody: any = {};
let _urlParams: any = {};
let result = this.request(_method, _url, _routeParams, _urlParams, _postBody, null, customHeaders);
return result;
}
/**
* Counts storageFiles of SystemDomain.
*
* @param {any} id SystemDomain id
*
* @param {object} where Criteria to match model instances
*
* @returns {object} An empty reference that will be
* populated with the actual data once the response is returned
* from the server.
*
* Data properties:
*
* - `count` – `{number}` -
*/
public countStorageFiles(id: any, where: any = {}, customHeaders?: Function): Observable<any> {
let _method: string = "GET";
let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() +
"/Domains/:id/storageFiles/count";
let _routeParams: any = {
id: id
};
let _postBody: any = {};
let _urlParams: any = {};
if (typeof where !== 'undefined' && where !== null) _urlParams.where = where;
let result = this.request(_method, _url, _routeParams, _urlParams, _postBody, null, customHeaders);
return result;
}
/**
* Patch an existing model instance or insert a new one into the data source.
*
* @param {object} data Request data.
*
* - `data` – `{object}` - Model instance data
*
* @returns {object} An empty reference that will be
* populated with the actual data once the response is returned
* from the server.
*
* <em>
* (The remote method definition does not provide any description.
* This usually means the response is a `SystemDomain` object.)
* </em>
*/
public patchOrCreate(data: any = {}, customHeaders?: Function): Observable<any> {
let _method: string = "PATCH";
let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() +
"/Domains";
let _routeParams: any = {};
let _postBody: any = {
data: data
};
let _urlParams: any = {};
let result = this.request(_method, _url, _routeParams, _urlParams, _postBody, null, customHeaders);
return result;
}
/**
* Patch attributes for a model instance and persist it into the data source.
*
* @param {any} id SystemDomain id
*
* @param {object} data Request data.
*
* - `data` – `{object}` - An object of model property name/value pairs
*
* @returns {object} An empty reference that will be
* populated with the actual data once the response is returned
* from the server.
*
* <em>
* (The remote method definition does not provide any description.
* This usually means the response is a `SystemDomain` object.)
* </em>
*/
public patchAttributes(id: any, data: any = {}, customHeaders?: Function): Observable<any> {
let _method: string = "PATCH";
let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() +
"/Domains/:id";
let _routeParams: any = {
id: id
};
let _postBody: any = {
data: data
};
let _urlParams: any = {};
let result = this.request(_method, _url, _routeParams, _urlParams, _postBody, null, customHeaders);
return result;
}
/**
* Import a file by URL
*
* @param {any} id SystemDomain id
*
* @param {object} data Request data.
*
* - `url` – `{String}` -
*
* - `fileName` – `{String}` -
*
* @returns {object} An empty reference that will be
* populated with the actual data once the response is returned
* from the server.
*
* <em>
* (The remote method definition does not provide any description.
* This usually means the response is a `SystemDomain` object.)
* </em>
*/
public importFileByUrl(id: any, url: any, fileName: any = {}, customHeaders?: Function): Observable<any> {
let _method: string = "POST";
let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() +
"/Domains/:id/importFileByUrl";
let _routeParams: any = {
id: id
};
let _postBody: any = {};
let _urlParams: any = {};
if (typeof url !== 'undefined' && url !== null) _urlParams.url = url;
if (typeof fileName !== 'undefined' && fileName !== null) _urlParams.fileName = fileName;
let result = this.request(_method, _url, _routeParams, _urlParams, _postBody, null, customHeaders);
return result;
}
/**
* Creates a new instance in contentEvents of this model.
*
* @param {any} id SystemDomain id
*
* @param {object} data Request data.
*
* This method expects a subset of model properties as request parameters.
*
* @returns {object[]} An empty reference that will be
* populated with the actual data once the response is returned
* from the server.
*
* <em>
* (The remote method definition does not provide any description.
* This usually means the response is a `SystemDomain` object.)
* </em>
*/
public createManyContentEvents(id: any, data: any[] = [], customHeaders?: Function): Observable<any> {
let _method: string = "POST";
let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() +
"/Domains/:id/contentEvents";
let _routeParams: any = {
id: id
};
let _postBody: any = {
data: data
};
let _urlParams: any = {};
let result = this.request(_method, _url, _routeParams, _urlParams, _postBody, null, customHeaders);
return result;
}
/**
* Creates a new instance in contentPages of this model.
*
* @param {any} id SystemDomain id
*
* @param {object} data Request data.
*
* This method expects a subset of model properties as request parameters.
*
* @returns {object[]} An empty reference that will be
* populated with the actual data once the response is returned
* from the server.
*
* <em>
* (The remote method definition does not provide any description.
* This usually means the response is a `SystemDomain` object.)
* </em>
*/
public createManyContentPages(id: any, data: any[] = [], customHeaders?: Function): Observable<any> {
let _method: string = "POST";
let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() +
"/Domains/:id/contentPages";
let _routeParams: any = {
id: id
};
let _postBody: any = {
data: data
};
let _urlParams: any = {};
let result = this.request(_method, _url, _routeParams, _urlParams, _postBody, null, customHeaders);
return result;
}
/**
* Creates a new instance in contentProducts of this model.
*
* @param {any} id SystemDomain id
*
* @param {object} data Request data.
*
* This method expects a subset of model properties as request parameters.
*
* @returns {object[]} An empty reference that will be
* populated with the actual data once the response is returned
* from the server.
*
* <em>
* (The remote method definition does not provide any description.
* This usually means the response is a `SystemDomain` object.)
* </em>
*/
public createManyContentProducts(id: any, data: any[] = [], customHeaders?: Function): Observable<any> {
let _method: string = "POST";
let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() +
"/Domains/:id/contentProducts";
let _routeParams: any = {
id: id
};
let _postBody: any = {
data: data
};
let _urlParams: any = {};
let result = this.request(_method, _url, _routeParams, _urlParams, _postBody, null, customHeaders);
return result;
}
/**
* Creates a new instance in contentPosts of this model.
*
* @param {any} id SystemDomain id
*
* @param {object} data Request data.
*
* This method expects a subset of model properties as request parameters.
*
* @returns {object[]} An empty reference that will be
* populated with the actual data once the response is returned
* from the server.
*
* <em>
* (The remote method definition does not provide any description.
* This usually means the response is a `SystemDomain` object.)
* </em>
*/
public createManyContentPosts(id: any, data: any[] = [], customHeaders?: Function): Observable<any> {
let _method: string = "POST";
let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() +
"/Domains/:id/contentPosts";
let _routeParams: any = {
id: id
};
let _postBody: any = {
data: data
};
let _urlParams: any = {};
let result = this.request(_method, _url, _routeParams, _urlParams, _postBody, null, customHeaders);
return result;
}
/**
* Creates a new instance in storageFiles of this model.
*
* @param {any} id SystemDomain id
*
* @param {object} data Request data.
*
* This method expects a subset of model properties as request parameters.
*
* @returns {object[]} An empty reference that will be
* populated with the actual data once the response is returned
* from the server.
*
* <em>
* (The remote method definition does not provide any description.
* This usually means the response is a `SystemDomain` object.)
* </em>
*/
public createManyStorageFiles(id: any, data: any[] = [], customHeaders?: Function): Observable<any> {
let _method: string = "POST";
let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() +
"/Domains/:id/storageFiles";
let _routeParams: any = {
id: id
};
let _postBody: any = {
data: data
};
let _urlParams: any = {};
let result = this.request(_method, _url, _routeParams, _urlParams, _postBody, null, customHeaders);
return result;
}
/**
* The name of the model represented by this $resource,
* i.e. `SystemDomain`.
*/
public getModelName() {
return "SystemDomain";
}
} | the_stack |
import * as Code from '../code';
import * as Error from '../error';
import * as FileWriter from '../file-writer';
import * as ImmutableImportUtils from '../immutable-import-utils';
import * as Maybe from '../maybe';
import * as ObjC from '../objc';
import * as ObjCImportUtils from '../objc-import-utils';
import * as ObjCNullabilityUtils from '../objc-nullability-utils';
import * as ObjectGeneration from '../object-generation';
import * as StringUtils from '../string-utils';
import * as ObjectSpec from '../object-spec';
import * as ObjectSpecUtils from '../object-spec-utils';
import * as ObjectSpecCodeUtils from '../object-spec-code-utils';
function nameOfBuilderForValueTypeWithName(valueTypeName: string): string {
return valueTypeName + 'Builder';
}
function shortNameOfObjectToBuildForValueTypeWithName(
valueTypeName: string,
): string {
return StringUtils.lowercased(
StringUtils.stringRemovingCapitalizedPrefix(valueTypeName),
);
}
function builderClassMethodForValueType(
objectType: ObjectSpec.Type,
): ObjC.Method {
return {
preprocessors: [],
belongsToProtocol: null,
code: [
'return [' +
nameOfBuilderForValueTypeWithName(objectType.typeName) +
' new];',
],
comments: [],
compilerAttributes: [],
keywords: [
{
name: shortNameOfObjectToBuildForValueTypeWithName(objectType.typeName),
argument: null,
},
],
returnType: {
type: {
name: 'instancetype',
reference: 'instancetype',
},
modifiers: [],
},
};
}
function keywordArgumentNameForBuilderFromExistingObjectClassMethodForValueType(
objectType: ObjectSpec.Type,
): string {
return (
'existing' +
StringUtils.capitalize(
shortNameOfObjectToBuildForValueTypeWithName(objectType.typeName),
)
);
}
function openingBrace(): string {
return '[';
}
function indentationForItemAtIndexWithOffset(
offset: number,
): (index: number) => string {
return function (index: number): string {
const indentation = offset - index;
return StringUtils.stringContainingSpaces(
indentation > 0 ? indentation : 0,
);
};
}
function toWithInvocationCallForBuilderFromExistingObjectClassMethodForAttribute(
indentationProvider: (index: number) => string,
existingObjectName: string,
soFar: string[],
attribute: ObjectSpec.Attribute,
index: number,
array: ObjectSpec.Attribute[],
): string[] {
return soFar.concat(
indentationProvider(index) +
keywordNameForAttribute(attribute) +
':' +
existingObjectName +
'.' +
attribute.name +
']',
);
}
function stringsWithLastItemContainingStringAtEnd(
strings: string[],
stringToIncludeAtEndOfLastString: string,
): string[] {
const updatedStrings: string[] = strings.concat();
updatedStrings[updatedStrings.length - 1] =
updatedStrings[updatedStrings.length - 1] +
stringToIncludeAtEndOfLastString;
return updatedStrings;
}
function codeForBuilderFromExistingObjectClassMethodForValueType(
objectType: ObjectSpec.Type,
): string[] {
const returnOpening: string = 'return ';
const openingBracesForWithMethodInvocations: string[] =
objectType.attributes.map(openingBrace);
const builderCreationCall: string =
'[' +
nameOfBuilderForValueTypeWithName(objectType.typeName) +
' ' +
shortNameOfObjectToBuildForValueTypeWithName(objectType.typeName) +
']';
const openingLine: string =
returnOpening +
openingBracesForWithMethodInvocations.join('') +
builderCreationCall;
const indentationProvider: (index: number) => string =
indentationForItemAtIndexWithOffset(
returnOpening.length + openingBracesForWithMethodInvocations.length,
);
const existingObjectName: string =
keywordArgumentNameForBuilderFromExistingObjectClassMethodForValueType(
objectType,
);
const linesForBuildingValuesIntoBuilder: string[] =
objectType.attributes.reduce(
toWithInvocationCallForBuilderFromExistingObjectClassMethodForAttribute.bind(
null,
indentationProvider,
existingObjectName,
),
[],
);
const code: string[] = [openingLine].concat(
linesForBuildingValuesIntoBuilder,
);
return stringsWithLastItemContainingStringAtEnd(code, ';');
}
function builderFromExistingObjectClassMethodForValueType(
objectType: ObjectSpec.Type,
): ObjC.Method {
return {
preprocessors: [],
belongsToProtocol: null,
code: codeForBuilderFromExistingObjectClassMethodForValueType(objectType),
comments: [],
compilerAttributes: [],
keywords: [
{
name:
shortNameOfObjectToBuildForValueTypeWithName(objectType.typeName) +
'FromExisting' +
StringUtils.capitalize(
shortNameOfObjectToBuildForValueTypeWithName(objectType.typeName),
),
argument: {
name: keywordArgumentNameForBuilderFromExistingObjectClassMethodForValueType(
objectType,
),
modifiers: [],
type: {
name: objectType.typeName,
reference: ObjectSpecUtils.typeReferenceForValueTypeWithName(
objectType.typeName,
),
},
},
},
],
returnType: {
type: {
name: 'instancetype',
reference: 'instancetype',
},
modifiers: [],
},
};
}
function valueGeneratorForInvokingInitializerWithAttribute(
attribute: ObjectSpec.Attribute,
): string {
return ObjectSpecCodeUtils.ivarForAttribute(attribute);
}
function buildObjectInstanceMethodForValueType(
objectType: ObjectSpec.Type,
): ObjC.Method {
return {
preprocessors: [],
belongsToProtocol: null,
code: [
'return ' +
ObjectSpecCodeUtils.methodInvocationForConstructor(
objectType,
valueGeneratorForInvokingInitializerWithAttribute,
) +
';',
],
comments: [],
compilerAttributes: [],
keywords: [
{
name: 'build',
argument: null,
},
],
returnType: {
type: {
name: objectType.typeName,
reference: ObjectSpecUtils.typeReferenceForValueTypeWithName(
objectType.typeName,
),
},
modifiers: [],
},
};
}
function keywordArgumentNameForAttribute(
attribute: ObjectSpec.Attribute,
): string {
return attribute.name;
}
function keywordNameForAttribute(attribute: ObjectSpec.Attribute): string {
return (
'with' + StringUtils.capitalize(keywordArgumentNameForAttribute(attribute))
);
}
function valueToAssignIntoInternalStateForAttribute(
supportsValueSemantics: boolean,
attribute: ObjectSpec.Attribute,
): string {
const keywordArgumentName: string =
keywordArgumentNameForAttribute(attribute);
if (
ObjectSpecCodeUtils.shouldCopyIncomingValueForAttribute(
supportsValueSemantics,
attribute,
)
) {
return '[' + keywordArgumentName + ' copy]';
} else {
return keywordArgumentName;
}
}
function withInstanceMethodForAttribute(
supportsValueSemantics: boolean,
attribute: ObjectSpec.Attribute,
): ObjC.Method {
return {
preprocessors: [],
belongsToProtocol: null,
code: [
ObjectSpecCodeUtils.ivarForAttribute(attribute) +
' = ' +
valueToAssignIntoInternalStateForAttribute(
supportsValueSemantics,
attribute,
) +
';',
'return self;',
],
comments: [],
compilerAttributes: [],
keywords: [
{
name: keywordNameForAttribute(attribute),
argument: {
name: keywordArgumentNameForAttribute(attribute),
modifiers:
ObjCNullabilityUtils.keywordArgumentModifiersForNullability(
attribute.nullability,
),
type: {
name: attribute.type.name,
reference: attribute.type.reference,
},
},
},
],
returnType: {
type: {
name: 'instancetype',
reference: 'instancetype',
},
modifiers: [],
},
};
}
function instanceVariableForAttribute(
attribute: ObjectSpec.Attribute,
): ObjC.InstanceVariable {
return {
name: attribute.name,
comments: [],
returnType: {
name: attribute.type.name,
reference: attribute.type.reference,
},
modifiers: [],
access: ObjC.InstanceVariableAccess.Private(),
};
}
export function importsForTypeLookupsOfObjectType(
objectType: ObjectSpec.Type,
): ObjC.Import[] {
const needsImportsForAllTypeLookups =
objectType.includes.indexOf('UseForwardDeclarations') !== -1;
return objectType.typeLookups
.map(function (typeLookup: ObjectGeneration.TypeLookup): ObjC.Import {
if (!typeLookup.canForwardDeclare) {
return ObjCImportUtils.importForTypeLookup(
objectType.libraryName,
true,
typeLookup,
);
} else if (needsImportsForAllTypeLookups) {
return ObjCImportUtils.importForTypeLookup(
objectType.libraryName,
false,
typeLookup,
);
} else {
return null!;
}
})
.filter(function (maybeImport: ObjC.Import): boolean {
return maybeImport != null;
});
}
function makePublicImportsForValueType(objectType: ObjectSpec.Type): boolean {
return objectType.includes.indexOf('UseForwardDeclarations') === -1;
}
function importsForBuilder(
objectType: ObjectSpec.Type,
forBaseFile: boolean,
): ObjC.Import[] {
const typeLookupImports: ObjC.Import[] =
importsForTypeLookupsOfObjectType(objectType);
const makePublicImports = makePublicImportsForValueType(objectType);
const skipAttributeImports =
!makePublicImports &&
objectType.includes.indexOf('SkipImportsInImplementation') !== -1;
const attributeImports: ObjC.Import[] = skipAttributeImports
? []
: objectType.attributes
.filter((attribute) =>
ObjCImportUtils.shouldIncludeImportForType(
objectType.typeLookups,
attribute.type.name,
),
)
.map(function (attribute: ObjectSpec.Attribute): ObjC.Import {
return ObjCImportUtils.importForAttribute(
attribute.type.name,
attribute.type.underlyingType,
attribute.type.libraryTypeIsDefinedIn,
attribute.type.fileTypeIsDefinedIn,
objectType.libraryName,
false,
);
});
return [
{
file: 'Foundation.h',
isPublic: true,
requiresCPlusPlus: false,
library: 'Foundation',
},
{
file: objectType.typeName + '.h',
isPublic: false,
requiresCPlusPlus: false,
library: objectType.libraryName,
},
...conditionallyAddToSpread(!forBaseFile, {
file: nameOfBuilderForValueTypeWithName(objectType.typeName) + '.h',
isPublic: false,
requiresCPlusPlus: false,
library: null,
}),
]
.concat(typeLookupImports)
.concat(attributeImports);
}
function forwardDeclarationsForBuilder(
objectType: ObjectSpec.Type,
): ObjC.ForwardDeclaration[] {
return [
ObjC.ForwardDeclaration.ForwardClassDeclaration(objectType.typeName),
...ImmutableImportUtils.forwardClassDeclarationsForObjectType(objectType),
];
}
function classesForBuilder(objectType: ObjectSpec.Type): ObjC.Class[] {
return [
{
baseClassName: 'NSObject',
covariantTypes: [],
classMethods: [
builderClassMethodForValueType(objectType),
builderFromExistingObjectClassMethodForValueType(objectType),
],
comments: [],
inlineBlockTypedefs: [],
instanceMethods: [
buildObjectInstanceMethodForValueType(objectType),
].concat(
objectType.attributes.map((attribute) =>
withInstanceMethodForAttribute(
ObjectSpecUtils.typeSupportsValueObjectSemantics(objectType),
attribute,
),
),
),
name: nameOfBuilderForValueTypeWithName(objectType.typeName),
properties: [],
instanceVariables: objectType.attributes.map(
instanceVariableForAttribute,
),
implementedProtocols: [],
nullability:
objectType.includes.indexOf('RMAssumeNonnull') >= 0
? ObjC.ClassNullability.assumeNonnull
: ObjC.ClassNullability.default,
subclassingRestricted: false,
},
];
}
function conditionallyAddToSpread<T>(addIt: boolean, value: T): T[] {
return addIt ? [value] : [];
}
function builderFileForValueType(
objectType: ObjectSpec.Type,
forBaseFile: boolean,
): Code.File {
return {
name: nameOfBuilderForValueTypeWithName(objectType.typeName),
type: Code.FileType.ObjectiveC,
imports: importsForBuilder(objectType, forBaseFile),
forwardDeclarations: forwardDeclarationsForBuilder(objectType),
comments: [],
enumerations: [],
blockTypes: [],
staticConstants: [],
globalVariables: [],
functions: [],
classes: classesForBuilder(objectType),
diagnosticIgnores: [],
structs: [],
cppClasses: [],
namespaces: [],
macros: [],
};
}
export function createPlugin(): ObjectSpec.Plugin {
return {
additionalFiles: function (objectType: ObjectSpec.Type): Code.File[] {
return [builderFileForValueType(objectType, false)];
},
transformBaseFile: function (
objectType: ObjectSpec.Type,
baseFile: Code.File,
): Code.File {
baseFile.imports = baseFile.imports.concat(
importsForBuilder(objectType, true),
);
baseFile.forwardDeclarations = baseFile.forwardDeclarations.concat(
forwardDeclarationsForBuilder(objectType),
);
baseFile.classes = baseFile.classes.concat(classesForBuilder(objectType));
return baseFile;
},
additionalTypes: function (objectType: ObjectSpec.Type): ObjectSpec.Type[] {
return [];
},
attributes: function (objectType: ObjectSpec.Type): ObjectSpec.Attribute[] {
return [];
},
classMethods: function (objectType: ObjectSpec.Type): ObjC.Method[] {
return [];
},
transformFileRequest: function (
request: FileWriter.Request,
): FileWriter.Request {
return request;
},
fileType: function (objectType: ObjectSpec.Type): Code.FileType | null {
return null;
},
forwardDeclarations: function (
objectType: ObjectSpec.Type,
): ObjC.ForwardDeclaration[] {
return [];
},
functions: function (objectType: ObjectSpec.Type): ObjC.Function[] {
return [];
},
headerComments: function (objectType: ObjectSpec.Type): ObjC.Comment[] {
return [];
},
implementedProtocols: function (
objectType: ObjectSpec.Type,
): ObjC.ImplementedProtocol[] {
return [];
},
imports: function (objectType: ObjectSpec.Type): ObjC.Import[] {
return [];
},
instanceMethods: function (objectType: ObjectSpec.Type): ObjC.Method[] {
return [];
},
macros: function (valueType: ObjectSpec.Type): ObjC.Macro[] {
return [];
},
properties: function (objectType: ObjectSpec.Type): ObjC.Property[] {
return [];
},
requiredIncludesToRun: ['RMBuilder'],
staticConstants: function (objectType: ObjectSpec.Type): ObjC.Constant[] {
return [];
},
validationErrors: function (objectType: ObjectSpec.Type): Error.Error[] {
return [];
},
nullability: function (
objectType: ObjectSpec.Type,
): ObjC.ClassNullability | null {
return null;
},
subclassingRestricted: function (objectType: ObjectSpec.Type): boolean {
return false;
},
};
} | the_stack |
import * as React from 'react';
import {
Animated,
Easing,
findNodeHandle,
Platform,
ScrollView,
StyleSheet,
Text,
TextStyle,
TouchableHighlight,
UIManager,
View,
ViewStyle,
} from 'react-native';
import { dropMenu } from '../../_styles/themes/default.components';
import { screenH, screenW } from '../../_styles/themes/device';
import { innerScaleSize } from '../../_styles/themes/responsive';
import guid from '../../_utils/guid';
import MDIcon from '../icon/index';
import MDRadioList from '../radio-list/index';
import RootView from '../root-view';
import { IMDOptionSet } from '../types';
export interface IMDDropMenuProps {
isShow?: boolean;
style?: ViewStyle;
data?: DropMenuData[];
alignCenter?: boolean; // item内容是否居中 todo 默认为true
defaultValue?: boolean[] | number[] | string[]; // 默认值,如[1],[1,2]
optionRender?: (listItem: IMDOptionSet) => React.ReactNode; // 自定义item项
/**
* 数据变化时通知用户
* @param dropMenuData 菜单项的所有数据
* @param selectOption 选中项的数据
*/
onChange?: (dropMenuData: DropMenuData, selectOption: IMDOptionSet) => void;
onShow?: () => void; // 展开时通知用户
onHide?: () => void; // 收起时通知用户
}
// 单个DropMenu对象
export interface DropMenuData {
text: string; // 下拉列表Menu的文案
options: IMDOptionSet[]; // 下拉列表数据
disabled?: boolean; // 下拉列表Menu是否可用
selectedOption?: IMDOptionSet;
}
// 状态
interface IMDDropMenuState {
isShow: boolean; // true表示展示 false表示隐藏
dropMenuIndex: number; // 最近展示/使用的dropMenu的索引
values?: boolean[] | number[] | string[];
contentTop: number; // 内容区的Top坐标
}
// 样式
interface IMDDropMenuStyle {
// style?: StyleProp<ViewStyle>|undefined;
// dropMenu文案和图片的组合样式
dropMenuStyle: ViewStyle;
dropMenuTextStyle: ViewStyle | TextStyle;
radioListContentShowStyle: ViewStyle;
radioListContentHideStyle: ViewStyle;
radioListShowStyle: ViewStyle;
radioListHideStyle: ViewStyle;
disableStyle: ViewStyle;
checkedOrSelectedStyle: TextStyle;
}
// 样式实现
export const MDDropMenuStyles: IMDDropMenuStyle = {
// scrollView内容样式
radioListContentShowStyle: {
flexDirection: 'column',
justifyContent: 'flex-start',
backgroundColor: 'rgba(0,0,0,0)',
borderWidth: 0,
},
radioListContentHideStyle: {
display: 'none',
},
// 列表显示
radioListShowStyle: {
flex: 1,
width: '100%',
flexDirection: 'column',
zIndex: 99,
borderWidth: 0,
position: 'absolute',
},
// 列表隐藏
radioListHideStyle: {
display: 'none',
},
dropMenuStyle: {
justifyContent: 'center',
alignItems: 'center',
padding: innerScaleSize(20),
flexDirection: 'row',
zIndex: 99,
},
dropMenuTextStyle: {
fontSize: dropMenu.fontSize,
fontWeight: dropMenu.fontWeight,
color: dropMenu.normalColor,
textAlign: 'center',
padding: innerScaleSize(10),
},
// disable时的样式
disableStyle: {
opacity: 0.3,
},
// 选中或checked时的样式
checkedOrSelectedStyle: {
// todo 改名 highLightColor
color: dropMenu.highLightColor,
},
};
const styles = StyleSheet.create<IMDDropMenuStyle>(MDDropMenuStyles);
export default class MDDropMenu extends React.Component<
IMDDropMenuProps,
IMDDropMenuState
> {
constructor (props: IMDDropMenuProps) {
super(props);
if (!props.data) {
// todo throw err
throw new Error('data not empty!');
}
// styles.style = props.style;
// 默认的dropMenu的索引
const dropMenuIndex = 0;
this.animValues = props.data!.map((index) => {
const value = new Animated.Value(0);
// todo 需要移除Listener
value.addListener((state) => {
if (state.value === 0) {
if (this.state.isShow) {
this.setState({
isShow: false,
});
}
if (this.isApp()) {
this.removeContentLayout();
}
}
});
return value;
});
this.state = {
isShow: props.isShow ? props.isShow : false,
dropMenuIndex,
values: props.defaultValue ? props.defaultValue : [],
contentTop: 0,
};
// 展开动画
this.expandAnim = this.animValues.map((animValue) => {
return Animated.timing(animValue, {
toValue: 1,
duration: 200,
easing: Easing.ease,
});
});
this.unExpandAnim = this.animValues.map((animValue) => {
return Animated.timing(animValue, {
toValue: 0,
duration: 200,
easing: Easing.ease,
});
});
if (props.defaultValue) {
for (let i = 0; i < props.defaultValue.length; i++) {
this.changeValue(props.defaultValue[i], i);
}
}
}
// 动画值
private animValues: Animated.Value[];
// 展开动画
private expandAnim: Animated.CompositeAnimation[];
// 收起动画
private unExpandAnim: Animated.CompositeAnimation[];
// dropMenu引用
private dropMenuLayoutRef: any = null;
// 菜单的总宽度
private dropMenusLayoutWidth: number = 0;
// 菜单距离左边的距离
private dropMenusLayoutLeft: number = 0;
public render () {
// todo
if (!this.props.data) {
return null;
}
// data是DropMenusData
const { data, style } = this.props;
// menu数据集合数组
const dropMenuDataArray = data!;
// dropMenu集合
const dropMenus = this.dropMenus(dropMenuDataArray);
if (this.isApp()) {
return (
/*
*****重要!重要!重要!
onLayout={this.onLayoutDropMenuLayout.bind(this)}
这里的this.onLayoutDropMenuLayout 虽然是空实现,但是如果去掉的话,
在toggle时调用UIManange.measure测量不出来这个View的尺寸,返回值会成为undefined
*/
<View
ref={(e) => (this.dropMenuLayoutRef = e)}
style={[{ flexDirection: 'row' }, style]}
onLayout={this.onLayoutDropMenuLayout.bind(this)}
>
{dropMenus}
</View>
);
} else {
// 定义DropMenuView
return (
/*
*****重要!重要!重要!
onLayout={this.onLayoutDropMenuLayout.bind(this)}
这里的this.onLayoutDropMenuLayout 虽然是空实现,但是如果去掉的话,
在toggle时调用UIManange.measure测量不出来这个View的尺寸,返回值会成为undefined
*/
<View style={[{ flexDirection: 'column', zIndex: 99 }, style]}>
<View
ref={(e) => (this.dropMenuLayoutRef = e)}
style={{ flexDirection: 'row' }}
onLayout={this.onLayoutDropMenuLayout.bind(this)}
>
{dropMenus}
</View>
{this.webExpandContentLayout(
dropMenuDataArray[this.state.dropMenuIndex!],
this.state.isShow,
this.state.contentTop,
this.state.dropMenuIndex!
)}
</View>
);
}
}
public componentWillUnmount () {
this.hide(this.state.dropMenuIndex!);
this.animValues.forEach((value) => {
value.removeAllListeners();
});
if (this.isApp()) {
this.removeContentLayout();
}
}
/**
* 获取某菜单项选中值
* @param index 要获取的菜单索;引,返回的内容:
* @returns @see IMDOptionSet
*/
public getSelectedValue (index: number) {
if (!this.props.data) {
return undefined;
}
if (index >= 0 && index < this.props.data!.length) {
return this.props.data![index].selectedOption;
} else {
return undefined;
}
}
/**
* 获值
* @return IMDOptionSet[]
*/
public getSelectedValues () {
const selecteValues = new Array();
if (this.props.data) {
const dropMenuDataArr = this.props.data;
dropMenuDataArr.forEach((dropMenuData) => {
if (dropMenuData.selectedOption) {
selecteValues.push(dropMenuData.selectedOption);
}
});
return selecteValues.length === 0 ? undefined : selecteValues;
} else {
return undefined;
}
}
/**
* 当某个DropMenu点击时,触发
* @param clicked;Index 点击的dropMenu的索引
*/
private onAppToggle (clickedIndex: number) {
if (!this.props.data) {
return;
}
const curIndex = this.state.isShow ? this.state.dropMenuIndex : clickedIndex;
const isShow = !this.state.isShow;
const handle = findNodeHandle(this.dropMenuLayoutRef);
UIManager.measureInWindow(handle!, (x, y, width, height) => {
this.onMeasuredInApp(x, y, width, height, curIndex, isShow);
});
}
private onMeasuredInApp (
x: number,
y: number,
width: number,
height: number,
curIndex: number,
isShow: boolean
) {
const contentLayout = this.appExpandContentLayout(
this.props.data![curIndex!],
isShow,
y + height,
curIndex!
);
this.setState({
dropMenuIndex: curIndex ? curIndex : 0,
contentTop: y + height,
isShow,
});
this.addContentLayout(contentLayout);
if (isShow) {
this.show(curIndex!);
} else {
this.hide(curIndex!);
}
}
/**
* 当某个DropMenu点击时,触发
* @param clickedIndex 点击的dropMenu的索引
*/
private onWebToggle (clickedIndex: number) {
const curIndex = this.state.isShow ? this.state.dropMenuIndex : clickedIndex;
const isShow = !this.state.isShow;
const handle = findNodeHandle(this.dropMenuLayoutRef);
UIManager.measureInWindow(handle!, (x, y, width, height) => {
this.onMeasuredInWeb(x, y, width, height, curIndex, isShow);
});
}
private onMeasuredInWeb (
x: number,
y: number,
width: number,
height: number,
curIndex: number,
isShow: boolean
) {
this.setState({
dropMenuIndex: curIndex ? curIndex : 0,
contentTop: height,
isShow,
});
if (isShow) {
this.show(curIndex!);
} else {
this.hide(curIndex!);
}
}
private addContentLayout (contentLayout: any) {
RootView.add(contentLayout);
}
private removeContentLayout () {
// todo 只remove自己
RootView.removeAll();
}
// 定义DropMenu集合
private dropMenus (dropMenuDataArray: DropMenuData[]) {
return dropMenuDataArray!.map(
(dropMenuData: DropMenuData, index: number) => {
return (
<TouchableHighlight
key={index}
style={[
{ borderWidth: 0, flexGrow: 1 },
dropMenuData.disabled ? styles.disableStyle : {},
]}
activeOpacity={1}
underlayColor='#FFF'
onPress={() => {
if (!dropMenuData.disabled) {
if (this.isApp()) {
this.onAppToggle(index);
} else {
this.onWebToggle(index);
}
}
}}
>
<View style={styles.dropMenuStyle}>
<Text
style={[
styles.dropMenuTextStyle,
dropMenuData.selectedOption ||
(this.state.isShow && index === this.state.dropMenuIndex)
? styles.checkedOrSelectedStyle
: {},
]}
>
{dropMenuData.selectedOption
? dropMenuData.selectedOption.label
: dropMenuData.text}
</Text>
<Animated.View
key={index}
style={{
transform: [
{
rotateZ: this.animValues[index].interpolate({
inputRange: [0, 1],
outputRange: ['0deg', '180deg'],
}),
},
],
}}
>
<MDIcon name='arrow-down' color='black' />
</Animated.View>
</View>
</TouchableHighlight>
);
}
);
}
/**
* 重要!重要!重要!不可删除
* onLayout={this.onLayoutDropMenuLayout.bind(this)}
* 这里的this.onLayoutDropMenuLayout 虽然是空实现,但是如果去掉的话,
* 在toggle时调用UIManange.measure测量不出来相关View的尺寸,返回值会成为undefined
* @param event
*/
private onLayoutDropMenuLayout (event: any) {
setTimeout(() => {
this.measureWidthAndLeft();
}, 1000);
}
/**
* 测量下拉列表的左侧和宽度
*/
private measureWidthAndLeft () {
this.dropMenuLayoutRef.measure(
(
x: number,
y: number,
width: number,
height: number,
pageX: number,
pageY: number
) => {
console.log('pageX=', pageX);
this.dropMenusLayoutWidth = width;
this.dropMenusLayoutLeft = pageX;
}
);
}
/**
* 点击DropMenu时,展开的View
* @param currentDropMenuData zh
* @param styles
* @param isShow true展开 false收起
* @param contentTop top所处于屏幕的y坐标
* @param dropMenuIndex 点击的是哪个DropMenu,索引从0开始
*/
private appExpandContentLayout (
currentDropMenuData: DropMenuData,
isShow: boolean,
contentTop: number,
dropMenuIndex: number
) {
return (
<ScrollView
onTouchEnd={() => {
if (this.state.isShow) {
this.hide(this.state.dropMenuIndex!);
}
}}
key={'content_layout_key' + guid()}
style={[
isShow ? styles.radioListShowStyle : styles.radioListHideStyle,
{
top: contentTop,
backgroundColor: 'rgba(0,0,0,0.2)',
flexDirection: 'column',
},
{
height: screenH - contentTop,
width: this.dropMenusLayoutWidth,
left: this.dropMenusLayoutLeft,
},
]}
contentContainerStyle={
isShow
? styles.radioListContentShowStyle
: styles.radioListContentHideStyle
}
>
<Animated.View
style={[
{
transform: [
{
translateY: this.animValues[dropMenuIndex].interpolate({
inputRange: [0, 1],
outputRange: [-screenH + contentTop, 0], // 0 : 150, 0.5 : 75, 1 : 0
}),
},
],
},
{ backgroundColor: '#FFF' },
]}
>
<MDRadioList
options={currentDropMenuData.options}
defaultValue={this.state.values![dropMenuIndex]}
onChange={(value, index) => {
this.onChange(value, index);
}}
alignCenter={this.props.alignCenter}
optionRender={this.props.optionRender}
/>
</Animated.View>
</ScrollView>
);
}
/**
* 点击DropMenu时,展开的View
* @param currentDropMenuData zh
* @param styles
* @param isShow true展开 false收起
* @param contentTop top所处于屏幕的y坐标
* @param dropMenuIndex 点击的是哪个DropMenu,索引从0开始
*/
private webExpandContentLayout (
currentDropMenuData: DropMenuData,
isShow: boolean,
contentTop: number,
dropMenuIndex: number
) {
return (
<TouchableHighlight
activeOpacity={1}
underlayColor={'rgba(0,0,0,0.2)'}
onPress={() => {
if (this.state.isShow) {
this.hide(this.state.dropMenuIndex!);
}
}}
key={'content_layout_key' + guid()}
style={[
isShow ? styles.radioListShowStyle : styles.radioListHideStyle,
{
top: contentTop,
backgroundColor: 'rgba(0,0,0,0.2)',
flexDirection: 'column',
},
{ height: screenH - contentTop },
]}
>
<ScrollView
contentContainerStyle={
isShow
? styles.radioListContentShowStyle
: styles.radioListContentHideStyle
}
>
<Animated.View
style={[
{
transform: [
{
translateY: this.animValues[dropMenuIndex].interpolate({
inputRange: [0, 1],
outputRange: [-screenH + contentTop, 0], // 0 : 150, 0.5 ;: 75, 1 : 0
}),
},
],
},
{ backgroundColor: '#FFF' },
]}
>
<MDRadioList
options={currentDropMenuData.options}
onChange={(value, index) => {
this.onChange(value, index);
}}
alignCenter={this.props.alignCenter}
defaultValue={this.state.values![dropMenuIndex]}
optionRender={this.props.optionRender}
/>
</Animated.View>
</ScrollView>
</TouchableHighlight>
);
}
/**
* 展开内容区
* @param index dropMenu 的索引,以0开始
*/
private show (index: number) {
if (!index) {
index = this.state.dropMenuIndex!;
}
this.startExpandAnim(index);
if (this.props.onShow) {
this.props.onShow();
}
}
/**
* 收起内容区
* @param index dropMenu 的索引,以0开始
*/
private hide (index: number) {
if (!index) {
index = this.state.dropMenuIndex!;
}
this.startUnexpandAnim(index);
if (this.props.onHide) {
this.props.onHide();
}
}
/**
* @@param value 选中项的值
* @param optionIndex 选中项的index
*/
private onChange (
value: boolean | string | number,
optionIndex: number
): void {
const mergeResult = this.mergeValueToState(
value,
this.props.data![this.state.dropMenuIndex!].options
);
if (mergeResult != null && mergeResult.selectedOption != null) {
this.props.data![this.state.dropMenuIndex!] = Object.assign(
{},
{ ...this.props.data![this.state.dropMenuIndex!] },
{ selectedOption: mergeResult.selectedOption }
);
}
// const mergeResult = this.changeValue(value, index);
if (this.state.isShow && !this.isApp()) {
this.hide(this.state.dropMenuIndex!);
}
// 通知用户
if (
this.props.onChange &&
mergeResult != null &&
mergeResult.selectedOption != null
) {
this.props.onChange(
this.props.data![this.state.dropMenuIndex!],
mergeResult.selectedOption
);
}
this.setState((preState) => {
const { values } = preState;
// defaultValue![this.state.index!] = vallet
values![this.state.dropMenuIndex!] = value;
return {
values,
};
});
}
/**
*
* @param value 选中项的值
* @param menuIndex 菜单的序号
*/
private changeValue (value: boolean | string | number, menuIndex: number) {
const mergeResult = this.mergeValueToState(
value,
this.props.data![menuIndex].options
);
if (mergeResult != null && mergeResult.selectedOption != null) {
this.props.data![menuIndex] = Object.assign(
{},
{ ...this.props.data![menuIndex] },
{ selectedOption: mergeResult.selectedOption }
);
} else {
this.props.data![menuIndex] = Object.assign(
{},
{ ...this.props.data![menuIndex] },
{ selectedOption: null }
);
}
if (this.state.isShow && !this.isApp()) {
this.hide(menuIndex);
}
// 通知用户
if (
this.props.onChange &&
mergeResult != null &&
mergeResult.selectedOption != null
) {
this.props.onChange(
this.props.data![menuIndex],
mergeResult.selectedOption
);
}
return mergeResult;
}
/**
* 开始展开动画
*/
private startExpandAnim (index: number) {
this.expandAnim[index].start();
}
/**;
* 开始收起动画
*/
private startUnexpandAnim (index: number) {
this.unExpandAnim[index].start();
}
/**
* 设置选择项的check 状态
* @param value 选中项的值
* @param optionIndex 选中项的索引
* @param options 选择数据的集合
*/
private mergeValueToState (
value: boolean | number | string,
options: IMDOptionSet[]
): { options: IMDOptionSet[]; selectedOption?: IMDOptionSet } {
let matchOption: IMDOptionSet | undefined;
const items = options.map((option, iteratorIndex) => {
if (value === option.value) {
matchOption = Object.assign({}, { ...option }, { checked: true });
return matchOption;
}
return Object.assign({}, { ...option }, { checked: false });
});
return {
options: items,
selectedOption: matchOption,
};
}
/**
* return true表示在app中,否则在web中
*/
private isApp () {
return Platform.OS === 'ios' || Platform.OS === 'android';
}
} | the_stack |
const __static: string
interface ShareVars extends AppConfig {
isPinPanel: boolean
selectedText: string
mainWindowId?: number
openSaladict: string
[key: string]: any
}
declare namespace NodeJS {
interface Global {
__static: string
shareVars: ShareVars
}
interface ProcessEnv {
readonly NODE_ENV: 'development' | 'production' | 'test'
}
}
declare module '*.bmp' {
const src: string
export default src
}
declare module '*.gif' {
const src: string
export default src
}
declare module '*.jpg' {
const src: string
export default src
}
declare module '*.jpeg' {
const src: string
export default src
}
declare module '*.png' {
const src: string
export default src
}
declare module '*.webp' {
const src: string
export default src
}
declare module '*.svg' {
import * as React from 'react'
export const ReactComponent: React.FunctionComponent<React.SVGProps<
SVGSVGElement
>>
const src: string
export default src
}
declare module '*.module.css' {
const classes: { readonly [key: string]: string }
export default classes
}
declare module '*.module.scss' {
const classes: { readonly [key: string]: string }
export default classes
}
declare module '*.module.sass' {
const classes: { readonly [key: string]: string }
export default classes
}
declare type LangCode = 'zh-CN' | 'zh-TW' | 'en'
declare type TCDirection =
| 'CENTER'
| 'TOP'
| 'RIGHT'
| 'BOTTOM'
| 'LEFT'
| 'TOP_LEFT'
| 'TOP_RIGHT'
| 'BOTTOM_LEFT'
| 'BOTTOM_RIGHT'
declare type InstantSearchKey = 'direct' | 'ctrl' | 'alt' | 'shift'
declare type PreloadSource = '' | 'clipboard' | 'selection'
interface AppConfig {
version: number
/** activate app, won't affect triple-ctrl setting */
active: boolean
/** enable Google analytics */
analytics: boolean
/** enable update check */
updateCheck: boolean
/** disable selection on type fields, like input and textarea */
noTypeField: boolean
/** use animation for transition */
animation: boolean
/** language code for locales */
langCode: LangCode
/** panel width */
panelWidth: number
/** panel max height in percentage, 0 < n < 100 */
panelMaxHeightRatio: number
bowlOffsetX: number
bowlOffsetY: number
darkMode: boolean
/** custom panel css */
panelCSS: string
/** panel font-size */
fontSize: number
/** sniff pdf request */
pdfSniff: boolean
/** URLs, [regexp.source, match_pattern] */
pdfWhitelist: [string, string][]
/** URLs, [regexp.source, match_pattern] */
pdfBlacklist: [string, string][]
/** track search history */
searhHistory: boolean
/** incognito mode */
searhHistoryInco: boolean
/** open word editor when adding a word to notebook */
editOnFav: boolean
/** Show suggestions when typing on search box */
searchSuggests: boolean
/** Enable touch related support */
touchMode: boolean
/** when and how to search text */
mode: {
/** show pop icon first */
icon: boolean
/** how panel directly */
direct: boolean
/** double click */
double: boolean
/** holding a key */
holding: {
shift: boolean
ctrl: boolean
meta: boolean
}
/** cursor instant capture */
instant: {
enable: boolean
key: InstantSearchKey
delay: number
}
}
/** when and how to search text if the panel is pinned */
pinMode: {
/** direct: on mouseup */
direct: boolean
/** double: double click */
double: boolean
/** holding a key */
holding: {
shift: boolean
ctrl: boolean
meta: boolean
}
/** cursor instant capture */
instant: {
enable: boolean
key: InstantSearchKey
delay: number
}
}
/** when and how to search text inside dict panel */
panelMode: {
/** direct: on mouseup */
direct: boolean
/** double: double click */
double: boolean
/** holding a key */
holding: {
shift: boolean
ctrl: boolean
meta: boolean
}
/** cursor instant capture */
instant: {
enable: boolean
key: InstantSearchKey
delay: number
}
}
/** when this is a quick search standalone panel running */
qsPanelMode: {
/** direct: on mouseup */
direct: boolean
/** double: double click */
double: boolean
/** holding a key */
holding: {
shift: boolean
ctrl: boolean
meta: boolean
}
/** cursor instant capture */
instant: {
enable: boolean
key: InstantSearchKey
delay: number
}
}
/** hover instead of click */
bowlHover: boolean
/** double click delay, in ms */
doubleClickDelay: number
/** show panel when triple press ctrl */
tripleCtrl: boolean
/** preload source */
tripleCtrlPreload: PreloadSource
/** auto search when triple hit ctrl */
tripleCtrlAuto: boolean
/** where should the dict appears */
tripleCtrlLocation: TCDirection
/** should panel be in a standalone window */
tripleCtrlStandalone: boolean
/** standalone panel height */
tripleCtrlHeight: number
/** resize main widnow to leave space to standalone window */
tripleCtrlSidebar: GamepadHand
/** should standalone panel response to page selection */
tripleCtrlPageSel: boolean
/** browser action panel preload source */
baPreload: PreloadSource
/** auto search when browser action panel shows */
baAuto: boolean
/**
* browser action behavior
* 'popup_panel' - show dict panel
* 'popup_fav' - add selection to notebook
* 'popup_options' - opten options
* 'popup_standalone' - open standalone panel
* others are same as context menus
*/
baOpen: string
/** context tranlate engines */
ctxTrans: {
google: boolean
sogou: boolean
youdaotrans: boolean
baidu: boolean
tencent: boolean
caiyun: boolean
}
/** start searching when source containing the languages */
language: any
/** auto pronunciation */
autopron: {
cn: {
dict:
| ''
| 'baidu'
| 'bing'
| 'caiyun'
| 'cambridge'
| 'cnki'
| 'cobuild'
| 'etymonline'
| 'eudic'
| 'google'
| 'googledict'
| 'guoyu'
| 'hjdict'
| 'jukuu'
| 'lexico'
| 'liangan'
| 'longman'
| 'macmillan'
| 'mojidict'
| 'naver'
| 'renren'
| 'shanbay'
| 'sogou'
| 'tencent'
| 'urban'
| 'vocabulary'
| 'weblio'
| 'weblioejje'
| 'websterlearner'
| 'wikipedia'
| 'youdao'
| 'youdaotrans'
| 'zdic'
list: (
| 'baidu'
| 'bing'
| 'caiyun'
| 'cambridge'
| 'cnki'
| 'cobuild'
| 'etymonline'
| 'eudic'
| 'google'
| 'googledict'
| 'guoyu'
| 'hjdict'
| 'jukuu'
| 'lexico'
| 'liangan'
| 'longman'
| 'macmillan'
| 'mojidict'
| 'naver'
| 'renren'
| 'shanbay'
| 'sogou'
| 'tencent'
| 'urban'
| 'vocabulary'
| 'weblio'
| 'weblioejje'
| 'websterlearner'
| 'wikipedia'
| 'youdao'
| 'youdaotrans'
| 'zdic'
)[]
}
en: {
dict:
| ''
| 'baidu'
| 'bing'
| 'caiyun'
| 'cambridge'
| 'cnki'
| 'cobuild'
| 'etymonline'
| 'eudic'
| 'google'
| 'googledict'
| 'guoyu'
| 'hjdict'
| 'jukuu'
| 'lexico'
| 'liangan'
| 'longman'
| 'macmillan'
| 'mojidict'
| 'naver'
| 'renren'
| 'shanbay'
| 'sogou'
| 'tencent'
| 'urban'
| 'vocabulary'
| 'weblio'
| 'weblioejje'
| 'websterlearner'
| 'wikipedia'
| 'youdao'
| 'youdaotrans'
| 'zdic'
list: (
| 'baidu'
| 'bing'
| 'caiyun'
| 'cambridge'
| 'cnki'
| 'cobuild'
| 'etymonline'
| 'eudic'
| 'google'
| 'googledict'
| 'guoyu'
| 'hjdict'
| 'jukuu'
| 'lexico'
| 'liangan'
| 'longman'
| 'macmillan'
| 'mojidict'
| 'naver'
| 'renren'
| 'shanbay'
| 'sogou'
| 'tencent'
| 'urban'
| 'vocabulary'
| 'weblio'
| 'weblioejje'
| 'websterlearner'
| 'wikipedia'
| 'youdao'
| 'youdaotrans'
| 'zdic'
)[]
accent: 'uk' | 'us'
}
machine: {
dict:
| ''
| 'baidu'
| 'bing'
| 'caiyun'
| 'cambridge'
| 'cnki'
| 'cobuild'
| 'etymonline'
| 'eudic'
| 'google'
| 'googledict'
| 'guoyu'
| 'hjdict'
| 'jukuu'
| 'lexico'
| 'liangan'
| 'longman'
| 'macmillan'
| 'mojidict'
| 'naver'
| 'renren'
| 'shanbay'
| 'sogou'
| 'tencent'
| 'urban'
| 'vocabulary'
| 'weblio'
| 'weblioejje'
| 'websterlearner'
| 'wikipedia'
| 'youdao'
| 'youdaotrans'
| 'zdic'
list: string[]
src: 'trans' | 'searchText'
}
}
/** URLs, [regexp.source, match_pattern] */
whitelist: [string, string][]
/** URLs, [regexp.source, match_pattern] */
blacklist: [string, string][]
contextMenus: {
selected: string[]
all: {
baidu_page_translate: string
baidu_search: string
bing_dict: string
bing_search: string
cambridge: string
copy_pdf_url: string
dictcn: string
etymonline: string
google_cn_page_translate: string
google_page_translate: string
google_search: string
google_translate: string
guoyu: string
iciba: string
liangan: string
longman_business: string
merriam_webster: string
microsoft_page_translate: string
oxford: string
saladict: string
sogou_page_translate: string
sogou: string
view_as_pdf: string
youdao_page_translate: string
youdao: string
youglish: string
} & {
[index: string]: any
}
}
}
declare namespace mitt {
type Handler = (event?: any) => void
type WildcardHandler = (type?: string, event?: any) => void
interface MittStatic {
(all?: { [key: string]: Array<Handler> }): Emitter
}
interface Emitter {
/**
* Register an event handler for the given type.
*
* @param {string} type Type of event to listen for, or `"*"` for all events.
* @param {Handler} handler Function to call in response to the given event.
*
* @memberOf Mitt
*/
on(type: keyof ShareVars, handler: Handler): void
on(type: '*', handler: WildcardHandler): void
/**
* Function to call in response to the given event
*
* @param {string} type Type of event to unregister `handler` from, or `"*"`
* @param {Handler} handler Handler function to remove.
*
* @memberOf Mitt
*/
off(type: keyof ShareVars, handler: Handler): void
off(type: '*', handler: WildcardHandler): void
/**
* Invoke all handlers for the given type.
* If present, `"*"` handlers are invoked prior to type-matched handlers.
*
* @param {string} type The event type to invoke
* @param {any} [event] An event object, passed to each handler
*
* @memberOf Mitt
*/
emit(type: keyof ShareVars, event?: any): void
}
} | the_stack |
import { JsonUtils, Logger, LoggingMetaData, RealityDataStatus } from "@itwin/core-bentley";
import { Cartographic, EcefLocation } from "@itwin/core-common";
import { Matrix3d, Point3d, Range3d, Transform, Vector3d, YawPitchRollAngles } from "@itwin/core-geometry";
import { FrontendLoggerCategory } from "../FrontendLoggerCategory";
import { PublisherProductInfo, RealityDataError, SpatialLocationAndExtents } from "../RealityDataSource";
const loggerCategory: string = FrontendLoggerCategory.RealityData;
/** This interface provides information about 3dTile files for this reality data
* Currently only used for debbugging
* @internal
*/
export interface ThreeDTileFileInfo {
/** the number of children at the root of this reality data */
rootChildren?: number;
}
/**
* This class provide methods used to interpret Cesium 3dTile format
* @internal
*/
export class ThreeDTileFormatInterpreter {
/** Gets reality data spatial location and extents
* @param json root document file in json format
* @returns spatial location and volume of interest, in meters, centered around `spatial location`
* @throws [[RealityDataError]] if source is invalid or cannot be read
* @internal
*/
public static getSpatialLocationAndExtents(json: any): SpatialLocationAndExtents {
const worldRange = new Range3d();
let isGeolocated = true;
let location: Cartographic | EcefLocation;
Logger.logTrace(loggerCategory, "RealityData getSpatialLocationAndExtents");
if (undefined === json?.root) {
Logger.logWarning(loggerCategory, `Error getSpatialLocationAndExtents - no root in json`);
// return first 1024 char from the json
const getMetaData: LoggingMetaData = () => {return {json: JSON.stringify(json).substring(0,1024)};};
const error = new RealityDataError(RealityDataStatus.InvalidData, "Invalid or unknown data - no root in json", getMetaData);
throw error;
}
try {
if (undefined !== json?.root?.boundingVolume?.region) {
const region = JsonUtils.asArray(json.root.boundingVolume.region);
Logger.logTrace(loggerCategory, "RealityData json.root.boundingVolume.region", () => ({ ...region }));
if (undefined === region) {
Logger.logError(loggerCategory, `Error getSpatialLocationAndExtents - region undefined`);
throw new TypeError("Unable to determine GeoLocation - no root Transform or Region on root.");
}
const ecefLow = (Cartographic.fromRadians({ longitude: region[0], latitude: region[1], height: region[4] })).toEcef();
const ecefHigh = (Cartographic.fromRadians({ longitude: region[2], latitude: region[3], height: region[5] })).toEcef();
const ecefRange = Range3d.create(ecefLow, ecefHigh);
const cartoCenter = Cartographic.fromRadians({ longitude: (region[0] + region[2]) / 2.0, latitude: (region[1] + region[3]) / 2.0, height: (region[4] + region[5]) / 2.0 });
location = cartoCenter;
const ecefLocation = EcefLocation.createFromCartographicOrigin(cartoCenter);
// iModelDb.setEcefLocation(ecefLocation);
const ecefToWorld = ecefLocation.getTransform().inverse()!;
worldRange.extendRange(Range3d.fromJSON(ecefToWorld.multiplyRange(ecefRange)));
} else {
let worldToEcefTransform = ThreeDTileFormatInterpreter.transformFromJson(json.root.transform);
Logger.logTrace(loggerCategory, "RealityData json.root.transform", () => ({ ...worldToEcefTransform }));
const range = ThreeDTileFormatInterpreter.rangeFromBoundingVolume(json.root.boundingVolume)!;
if (undefined === worldToEcefTransform)
worldToEcefTransform = Transform.createIdentity();
const ecefRange = worldToEcefTransform.multiplyRange(range); // range in model -> range in ecef
const ecefCenter = worldToEcefTransform.multiplyPoint3d(range.center); // range center in model -> range center in ecef
const cartoCenter = Cartographic.fromEcef(ecefCenter); // ecef center to cartographic center
const isNotNearEarthSurface = cartoCenter && (cartoCenter.height < -5000); // 5 km under ground!
const earthCenterToRangeCenterRayLenght = range.center.magnitude();
if (worldToEcefTransform.matrix.isIdentity && (earthCenterToRangeCenterRayLenght < 1.0E5 || isNotNearEarthSurface)) {
isGeolocated = false;
worldRange.extendRange(Range3d.fromJSON(ecefRange));
const centerOfEarth = new EcefLocation({ origin: { x: 0.0, y: 0.0, z: 0.0 }, orientation: { yaw: 0.0, pitch: 0.0, roll: 0.0 } });
location = centerOfEarth;
Logger.logTrace(loggerCategory, "RealityData NOT Geolocated", () => ({ ...location }));
} else {
let ecefLocation: EcefLocation;
const locationOrientation = YawPitchRollAngles.tryFromTransform(worldToEcefTransform);
// Fix Bug 445630: [RDV][Regression] Orientation of georeferenced Reality Mesh is wrong.
// Use json.root.transform only if defined and not identity -> otherwise will use a transform computed from cartographic center.
if (!worldToEcefTransform.matrix.isIdentity && locationOrientation !== undefined && locationOrientation.angles !== undefined)
ecefLocation = new EcefLocation({ origin: locationOrientation.origin, orientation: locationOrientation.angles.toJSON() });
else
ecefLocation = EcefLocation.createFromCartographicOrigin(cartoCenter!);
location = ecefLocation;
Logger.logTrace(loggerCategory, "RealityData is worldToEcefTransform.matrix.isIdentity", () => ({ isIdentity: worldToEcefTransform!.matrix.isIdentity }));
// iModelDb.setEcefLocation(ecefLocation);
const ecefToWorld = ecefLocation.getTransform().inverse()!;
worldRange.extendRange(Range3d.fromJSON(ecefToWorld.multiplyRange(ecefRange)));
Logger.logTrace(loggerCategory, "RealityData ecefToWorld", () => ({ ...ecefToWorld }));
}
}
} catch (e) {
Logger.logWarning(loggerCategory, `Error getSpatialLocationAndExtents - cannot interpret json`);
// return first 1024 char from the json
const getMetaData: LoggingMetaData = () => {return {json: JSON.stringify(json).substring(0,1024)};};
const error = new RealityDataError(RealityDataStatus.InvalidData, "Invalid or unknown data", getMetaData);
throw error;
}
const spatialLocation: SpatialLocationAndExtents = { location, worldRange, isGeolocated };
return spatialLocation;
}
/** Gets information to identify the product and engine that create this reality data
* Will return undefined if cannot be resolved
* @param rootDocjson root document file in json format
* @returns information to identify the product and engine that create this reality data
* @alpha
*/
public static getPublisherProductInfo(rootDocjson: any): PublisherProductInfo {
const info: PublisherProductInfo = {product: "", engine: "", version: ""};
if (rootDocjson && rootDocjson.root) {
if (rootDocjson.root.SMPublisherInfo) {
info.product = rootDocjson.root.SMPublisherInfo.Product ? rootDocjson.root.SMPublisherInfo.Product : "";
info.engine = rootDocjson.root.SMPublisherInfo.Publisher ? rootDocjson.root.SMPublisherInfo.Publisher : "";
info.version = rootDocjson.root.SMPublisherInfo["Publisher Version"] ? rootDocjson.root.SMPublisherInfo["Publisher Version"] : "" ;
}
}
return info;
}
/** Gets information about 3dTile file for this reality data
* Will return undefined if cannot be resolved
* @param rootDocjson root document file in json format
* @returns information about 3dTile file for this reality data
* @internal
*/
public static getFileInfo(rootDocjson: any): ThreeDTileFileInfo {
const info: ThreeDTileFileInfo = {
rootChildren: rootDocjson?.root?.children?.length ?? 0,
};
return info;
}
/** Convert a boundingVolume into a range
* @param boundingVolume the bounding volume to convert
* @returns the range or undefined if cannot convert
* @internal
*/
public static rangeFromBoundingVolume(boundingVolume: any): Range3d | undefined {
if (undefined === boundingVolume)
return undefined;
if (Array.isArray(boundingVolume.box)) {
const box: number[] = boundingVolume.box;
const center = Point3d.create(box[0], box[1], box[2]);
const ux = Vector3d.create(box[3], box[4], box[5]);
const uy = Vector3d.create(box[6], box[7], box[8]);
const uz = Vector3d.create(box[9], box[10], box[11]);
const corners: Point3d[] = [];
for (let j = 0; j < 2; j++) {
for (let k = 0; k < 2; k++) {
for (let l = 0; l < 2; l++) {
corners.push(center.plus3Scaled(ux, (j ? -1.0 : 1.0), uy, (k ? -1.0 : 1.0), uz, (l ? -1.0 : 1.0)));
}
}
}
return Range3d.createArray(corners);
} else if (Array.isArray(boundingVolume.sphere)) {
const sphere: number[] = boundingVolume.sphere;
const center = Point3d.create(sphere[0], sphere[1], sphere[2]);
const radius = sphere[3];
return Range3d.createXYZXYZ(center.x - radius, center.y - radius, center.z - radius, center.x + radius, center.y + radius, center.z + radius);
}
return undefined;
}
/** Convert a boundingVolume into a range
* @internal
*/
public static maximumSizeFromGeometricTolerance(range: Range3d, geometricError: number): number {
const minToleranceRatio = .5; // Nominally the error on screen size of a tile. Increasing generally increases performance (fewer draw calls) at expense of higher load times.
return minToleranceRatio * range.diagonal().magnitude() / geometricError;
}
/** Convert a boundingVolume into a range
* @internal
*/
public static transformFromJson(jTrans: number[] | undefined): Transform | undefined {
return (jTrans === undefined) ? undefined : Transform.createOriginAndMatrix(Point3d.create(jTrans[12], jTrans[13], jTrans[14]), Matrix3d.createRowValues(jTrans[0], jTrans[4], jTrans[8], jTrans[1], jTrans[5], jTrans[9], jTrans[2], jTrans[6], jTrans[10]));
}
} | the_stack |
import { CumulativePriceLevel,
Level3Order,
Orderbook,
OrderbookState,
PriceComparable,
PriceLevel,
PriceLevelWithOrders,
PriceTreeFactory } from './Orderbook';
import { Big, BigJS, Biglike, ZERO } from './types';
import { Side } from './sides';
import { RBTree } from 'bintrees';
import { EventEmitter } from 'events';
import { ConsoleLoggerFactory, Logger } from '../utils/Logger';
import assert = require('assert');
export function AggregatedLevelFactory(totalSize: Biglike, price: Biglike, side: Side): AggregatedLevelWithOrders {
const level = new AggregatedLevelWithOrders(Big(price));
const size = Big(totalSize);
if (!size.eq(ZERO)) {
const order: Level3Order = {
id: price.toString(),
price: Big(price),
size: Big(totalSize),
side: side
};
level.addOrder(order);
}
return level;
}
export function AggregatedLevelFromPriceLevel(priceLevel: PriceLevelWithOrders): AggregatedLevelWithOrders {
const level = new AggregatedLevelWithOrders(priceLevel.price);
level.totalSize = priceLevel.totalSize;
level.totalValue = priceLevel.price.times(priceLevel.totalSize);
(level as any)._orders = priceLevel.orders;
return level;
}
/**
* For cumulative order calculations, indicates at which price to start counting at and from which order size to start
* within that level
*/
export interface StartPoint {
price: BigJS;
size: BigJS;
}
export interface OrderPool { [id: string]: Level3Order; }
export class AggregatedLevel implements PriceLevel {
totalSize: BigJS;
totalValue: BigJS;
readonly price: BigJS;
private _numOrders: number;
constructor(price: BigJS) {
this._numOrders = 0;
this.totalSize = ZERO;
this.totalValue = ZERO;
this.price = price;
}
get numOrders(): number {
return this._numOrders;
}
isEmpty(): boolean {
return this._numOrders === 0;
}
equivalent(level: AggregatedLevel) {
return this.price.eq(level.price) && this.totalSize.eq(level.totalSize);
}
protected add(amount: BigJS) {
this.totalSize = this.totalSize.plus(amount);
this.totalValue = this.totalValue.plus(amount.times(this.price));
}
protected subtract(amount: BigJS) {
this.totalSize = this.totalSize.minus(amount);
this.totalValue = this.totalValue.minus(amount.times(this.price));
}
}
export class AggregatedLevelWithOrders extends AggregatedLevel implements PriceLevelWithOrders {
private readonly _orders: Level3Order[];
constructor(price: BigJS) {
super(price);
this._orders = [];
}
get orders(): Level3Order[] {
return this._orders;
}
get numOrders(): number {
return this._orders.length;
}
findOrder(id: string): Level3Order {
return this._orders.find((order: Level3Order) => order.id === id);
}
addOrder(order: Level3Order): boolean {
if (!this.price.eq(order.price)) {
throw new Error(`Tried to add order with price ${order.price.toString()} to level with price ${this.price.toString()}`);
}
if (this.findOrder(order.id)) {
return false;
}
this.add(order.size);
this._orders.push(order);
return true;
}
removeOrder(id: string): boolean {
const order: Level3Order = this.findOrder(id);
if (!order) {
return false;
}
this.subtract(order.size);
const i = this._orders.indexOf(order);
this._orders.splice(i, 1);
return true;
}
}
/**
* BookBuilder is a convenience class for maintaining an in-memory Level 3 order book. Each
* side of the book is represented internally by a binary tree and a global order hash map
*
* The individual orders can be tracked globally via the orderPool set, or per level. The orderpool and the aggregated
* levels point to the same order objects, and not copies.
*
* Call #state to get a hierarchical object representation of the orderbook
*/
export class BookBuilder extends EventEmitter implements Orderbook {
public sequence: number;
protected readonly bids: RBTree<AggregatedLevelWithOrders> = PriceTreeFactory<AggregatedLevelWithOrders>();
protected readonly asks: RBTree<AggregatedLevelWithOrders> = PriceTreeFactory<AggregatedLevelWithOrders>();
protected _bidsTotal: BigJS;
protected _bidsValueTotal: BigJS;
protected _asksTotal: BigJS;
protected _asksValueTotal: BigJS;
private _orderPool: OrderPool;
private readonly logger: Logger;
constructor(logger: Logger) {
super();
this.logger = logger || ConsoleLoggerFactory();
this.clear();
}
clear() {
this.bids.clear();
this.asks.clear();
this._bidsTotal = ZERO;
this._asksTotal = ZERO;
this._bidsValueTotal = ZERO;
this._asksValueTotal = ZERO;
this._orderPool = {};
this.sequence = -1;
}
get bidsTotal(): BigJS {
return this._bidsTotal;
}
get bidsValueTotal(): BigJS {
return this._bidsValueTotal;
}
get asksTotal(): BigJS {
return this._asksTotal;
}
get asksValueTotal(): BigJS {
return this._asksValueTotal;
}
get numAsks(): number {
return this.asks.size;
}
get numBids(): number {
return this.bids.size;
}
get orderPool(): OrderPool {
return this._orderPool;
}
set orderPool(value: OrderPool) {
this._orderPool = value;
}
get highestBid(): AggregatedLevelWithOrders {
return this.bids.max();
}
get lowestAsk(): AggregatedLevelWithOrders {
return this.asks.min();
}
getOrder(id: string): Level3Order {
return this._orderPool[id];
}
hasOrder(orderId: string): boolean {
return this._orderPool.hasOwnProperty(orderId);
}
getLevel(side: Side, price: BigJS): AggregatedLevelWithOrders {
const tree = this.getTree(side);
return tree.find({ price: price } as any);
}
/**
* Add an order's information to the book
* @param order
*/
add(order: Level3Order): boolean {
const side = order.side;
const tree = this.getTree(side);
let level = new AggregatedLevelWithOrders(order.price);
const existing: AggregatedLevelWithOrders = tree.find(level);
if (existing) {
level = existing;
} else {
if (!tree.insert(level)) {
return false;
}
}
// Add order to the aggregated level
if (!level.addOrder(order)) {
return false;
}
// Update global order pool stats
this._orderPool[order.id] = order;
this.addToTotal(order.size, order.side, order.price);
return true;
}
/**
* Changes the size of an existing order to newSize. If the order doesn't exist, returns false.
* If newSize is negative, an error is thrown.
* Even if newSize is zero, the order is kept.
* It is possible for an order to switch sides, in which case the newSide parameter determines the new side.
*/
modify(id: string, newSize: BigJS, newSide?: Side): boolean {
if (newSize.lt(ZERO)) {
throw new Error('Cannot set an order size to a negative number');
}
const order = this.remove(id);
if (!order) {
return false;
}
order.size = newSize;
order.side = newSide || order.side;
this.add(order);
return true;
}
// Add a complete price level with orders to the order book. If the price level already exists, throw an exception
addLevel(side: Side, level: AggregatedLevelWithOrders) {
const tree = this.getTree(side);
if (tree.find(level)) {
throw new Error(`cannot add a new level to orderbook since the level already exists at price ${level.price.toString()}`);
}
tree.insert(level);
this.addToTotal(level.totalSize, side, level.price);
// Add links to orders
level.orders.forEach((order: Level3Order) => {
this._orderPool[order.id] = order;
});
}
/**
* Remove a complete level and links to orders in the order pool. If the price level doesn't exist, it returns
* false
*/
removeLevel(side: Side, priceLevel: PriceComparable): boolean {
const tree = this.getTree(side);
const level: AggregatedLevelWithOrders = tree.find(priceLevel as any);
if (!level) {
return false;
}
assert(tree.remove(level));
level.orders.forEach((order: Level3Order) => {
delete this.orderPool[order.id];
});
this.subtractFromTotal(level.totalSize, side, level.price);
return true;
}
/**
* Shortcut method for replacing a level. First removeLevel is called, and then addLevel
*/
setLevel(side: Side, level: AggregatedLevelWithOrders): boolean {
this.removeLevel(side, level);
if (level.numOrders > 0) {
this.addLevel(side, level);
}
return true;
}
/**
* Remove the order from the orderbook If numOrders drops to zero, remove the level
*/
remove(orderId: string): Level3Order {
const order: Level3Order = this.getOrder(orderId);
if (!order) {
return null;
}
const side = order.side;
const tree = this.getTree(side);
let level = new AggregatedLevelWithOrders(order.price);
level = tree.find(level);
if (!level) {
// If a market order has filled, we can carry on
if (order.size.eq(ZERO)) {
return order;
}
this.logger.log('error', `There should have been orders at price level ${order.price} for at least ${order.size}, but there were none`);
return null;
}
if (this.removeFromPool(order.id)) {
this.subtractFromTotal(order.size, order.side, order.price);
}
level.removeOrder(order.id);
if (level.numOrders === 0) {
if (!(level.totalSize.eq(ZERO))) {
this.logger.log('error', `Total size should be zero at level $${level.price} but was ${level.totalSize}.`);
return null;
}
tree.remove(level);
}
return order;
}
getTree(side: Side): RBTree<AggregatedLevelWithOrders> {
return side === 'buy' ? this.bids : this.asks;
}
/**
* Returns a book object that has all the bids and asks at this current moment. For performance reasons, this method
* returns a shallow copy of the underlying orders, so modifying the state object may break the orderbook generally.
* For deep copies, call #stateCopy instead
*/
state(): OrderbookState {
const book: OrderbookState = {
sequence: this.sequence,
asks: [],
bids: [],
orderPool: this.orderPool
};
this.bids.reach((bid: AggregatedLevelWithOrders) => {
book.bids.push(bid);
});
this.asks.each((ask: AggregatedLevelWithOrders) => {
book.asks.push(ask);
});
return book;
}
/**
* Returns a deep copy of the orderbook state.
*/
stateCopy(): OrderbookState {
const shallowBook: OrderbookState = this.state();
return Object.assign({}, shallowBook);
}
fromState(state: OrderbookState) {
this.clear();
this.sequence = state.sequence;
// The order pool gets set up in setLevel
state.asks.forEach((priceLevel: PriceLevelWithOrders) => {
const level: AggregatedLevelWithOrders = AggregatedLevelFromPriceLevel(priceLevel);
this.setLevel('sell', level);
});
state.bids.forEach((priceLevel: PriceLevelWithOrders) => {
const level: AggregatedLevelWithOrders = AggregatedLevelFromPriceLevel(priceLevel);
this.setLevel('buy', level);
});
}
/**
* Return an array of (aggregated) orders whose sum is equal to or greater than `value`.
* The side parameter is from the perspective of the purchaser, so 'buy' returns asks and 'sell' bids.
* If useQuote is true, value is assumed to represent price * size, otherwise just size is used
* startPrice sets the first price to start counting from (inclusive). The default is undefined, which starts at the best bid/by
*/
ordersForValue(side: Side, value: BigJS, useQuote: boolean, start?: StartPoint): CumulativePriceLevel[] {
const source = side === 'buy' ? this.asks : this.bids;
const iter = source.iterator();
let totalSize = ZERO;
let totalValue = ZERO;
const orders: CumulativePriceLevel[] = [];
let level: AggregatedLevelWithOrders;
// Find start order with price >= startPrice (for buys)
if (start) {
if (side === 'buy') {
do {
level = iter.next();
} while (level && level.price.lt(start.price));
} else {
do {
level = iter.prev();
} while (level && level.price.gt(start.price));
}
level = Object.assign({}, level);
level.totalSize = level.totalSize.minus(start.size);
} else {
level = side === 'buy' ? iter.next() : iter.prev();
}
while (level !== null && (
(useQuote && totalValue.lt(value)) || (!useQuote && totalSize.lt(value))
)) {
let levelValue = level.price.times(level.totalSize);
let levelSize = level.totalSize;
if (useQuote && levelValue.plus(totalValue).gte(value)) {
levelValue = value.minus(totalValue);
levelSize = levelValue.div(level.price);
} else if (!useQuote && levelSize.plus(totalSize).gte(value)) {
levelSize = value.minus(totalSize);
levelValue = levelSize.times(level.price);
} else {
levelSize = level.totalSize;
levelValue = levelSize.times(level.price);
}
totalSize = totalSize.plus(levelSize);
totalValue = totalValue.plus(levelValue);
orders.push({
totalSize: levelSize,
value: levelValue,
price: level.price,
cumSize: totalSize,
cumValue: totalValue,
orders: level.orders
});
level = side === 'buy' ? iter.next() : iter.prev();
}
return orders;
}
protected removeFromPool(orderId: string): boolean {
const exists = this.hasOrder(orderId);
if (exists) { delete this._orderPool[orderId]; }
return exists;
}
private subtractFromTotal(amount: BigJS, side: Side, price: BigJS) {
if (side === 'buy') {
this._bidsTotal = this._bidsTotal.minus(amount);
this._bidsValueTotal = this._bidsValueTotal.minus(amount.times(price));
} else {
this._asksTotal = this._asksTotal.minus(amount);
this._asksValueTotal = this._asksValueTotal.minus(amount.times(price));
}
}
private addToTotal(amount: BigJS, side: Side, price: BigJS) {
if (side === 'buy') {
this._bidsTotal = this._bidsTotal.plus(amount);
this._bidsValueTotal = this._bidsValueTotal.plus(amount.times(price));
} else {
this._asksTotal = this._asksTotal.plus(amount);
this._asksValueTotal = this._asksValueTotal.plus(amount.times(price));
}
}
} | the_stack |
import { EventEmitter } from 'events';
import * as os from 'os';
import * as path from 'path';
import { Writable } from 'stream';
// @ts-ignore
import * as Bunyan from '@salesforce/bunyan';
import { parseJson, parseJsonMap } from '@salesforce/kit';
import {
Dictionary,
ensure,
ensureNumber,
isArray,
isFunction,
isKeyOf,
isObject,
isPlainObject,
isString,
Many,
Optional,
} from '@salesforce/ts-types';
import * as Debug from 'debug';
import { Global, Mode } from './global';
import { SfdxError } from './sfdxError';
import { fs } from './util/fs';
/**
* A Bunyan `Serializer` function.
*
* @param input The input to be serialized.
* **See** {@link https://github.com/forcedotcom/node-bunyan#serializers|Bunyan Serializers API}
*/
export type Serializer = (input: unknown) => unknown;
/**
* A collection of named `Serializer`s.
*
* **See** {@link https://github.com/forcedotcom/node-bunyan#serializers|Bunyan Serializers API}
*/
export interface Serializers {
[key: string]: Serializer;
}
/**
* The common set of `Logger` options.
*/
export interface LoggerOptions {
/**
* The logger name.
*/
name: string;
/**
* The logger format type. Current options include LogFmt or JSON (default).
*/
format?: LoggerFormat;
/**
* The logger's serializers.
*/
serializers?: Serializers;
/**
* Whether or not to log source file, line, and function information.
*/
src?: boolean;
/**
* The desired log level.
*/
level?: LoggerLevelValue;
/**
* A stream to write to.
*/
stream?: Writable;
/**
* An array of streams to write to.
*/
streams?: LoggerStream[];
}
/**
* Standard `Logger` levels.
*
* **See** {@link https://github.com/forcedotcom/node-bunyan#levels|Bunyan Levels}
*/
export enum LoggerLevel {
TRACE = 10,
DEBUG = 20,
INFO = 30,
WARN = 40,
ERROR = 50,
FATAL = 60,
}
/**
* `Logger` format types.
*/
export enum LoggerFormat {
JSON,
LOGFMT,
}
/**
* A Bunyan stream configuration.
*
* @see {@link https://github.com/forcedotcom/node-bunyan#streams|Bunyan Streams}
*/
export interface LoggerStream {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
[key: string]: any;
/**
* The type of stream -- may be inferred from other properties.
*/
type?: string;
/**
* The desired log level for the stream.
*/
level?: LoggerLevelValue;
/**
* The stream to write to. Mutually exclusive with `path`.
*/
stream?: Writable;
/**
* The name of the stream.
*/
name?: string;
/**
* A log file path to write to. Mutually exclusive with `stream`.
*/
path?: string;
}
/**
* Any numeric `Logger` level.
*/
export type LoggerLevelValue = LoggerLevel | number;
/**
* A collection of named `FieldValue`s.
*
* **See** {@link https://github.com/forcedotcom/node-bunyan#log-record-fields|Bunyan Log Record Fields}
*/
export interface Fields {
[key: string]: FieldValue;
}
/**
* All possible field value types.
*/
export type FieldValue = string | number | boolean;
/**
* Log line interface
*/
export interface LogLine {
name: string;
hostname: string;
pid: string;
log: string;
level: number;
msg: string;
time: string;
v: number;
}
/**
* A logging abstraction powered by {@link https://github.com/forcedotcom/node-bunyan|Bunyan} that provides both a default
* logger configuration that will log to `sfdx.log`, and a way to create custom loggers based on the same foundation.
*
* ```
* // Gets the root sfdx logger
* const logger = await Logger.root();
*
* // Creates a child logger of the root sfdx logger with custom fields applied
* const childLogger = await Logger.child('myRootChild', {tag: 'value'});
*
* // Creates a custom logger unaffiliated with the root logger
* const myCustomLogger = new Logger('myCustomLogger');
*
* // Creates a child of a custom logger unaffiliated with the root logger with custom fields applied
* const myCustomChildLogger = myCustomLogger.child('myCustomChild', {tag: 'value'});
* ```
* **See** https://github.com/forcedotcom/node-bunyan
*
* **See** https://developer.salesforce.com/docs/atlas.en-us.sfdx_setup.meta/sfdx_setup/sfdx_dev_cli_log_messages.htm
*/
export class Logger {
/**
* The name of the root sfdx `Logger`.
*/
public static readonly ROOT_NAME = 'sfdx';
/**
* The default `LoggerLevel` when constructing new `Logger` instances.
*/
public static readonly DEFAULT_LEVEL = LoggerLevel.WARN;
/**
* A list of all lower case `LoggerLevel` names.
*
* **See** {@link LoggerLevel}
*/
public static readonly LEVEL_NAMES = Object.values(LoggerLevel)
.filter(isString)
.map((v: string) => v.toLowerCase());
// Rollup all instance-specific process event listeners together to prevent global `MaxListenersExceededWarning`s.
private static readonly lifecycle = (() => {
const events = new EventEmitter();
events.setMaxListeners(0); // never warn on listener counts
process.on('uncaughtException', (err) => events.emit('uncaughtException', err));
process.on('exit', () => events.emit('exit'));
return events;
})();
// The sfdx root logger singleton
private static rootLogger?: Logger;
/**
* Whether debug is enabled for this Logger.
*/
public debugEnabled = false;
// The actual Bunyan logger
private bunyan: Bunyan;
private readonly format: LoggerFormat;
/**
* Constructs a new `Logger`.
*
* @param optionsOrName A set of `LoggerOptions` or name to use with the default options.
*
* **Throws** *{@link SfdxError}{ name: 'RedundantRootLogger' }* More than one attempt is made to construct the root
* `Logger`.
*/
public constructor(optionsOrName: LoggerOptions | string) {
let options: LoggerOptions;
if (typeof optionsOrName === 'string') {
options = {
name: optionsOrName,
level: Logger.DEFAULT_LEVEL,
serializers: Bunyan.stdSerializers,
};
} else {
options = optionsOrName;
}
if (Logger.rootLogger && options.name === Logger.ROOT_NAME) {
throw new SfdxError('RedundantRootLogger');
}
// Inspect format to know what logging format to use then delete from options to
// ensure it doesn't conflict with Bunyan.
this.format = options.format || LoggerFormat.JSON;
delete options.format;
// If the log format is LOGFMT, we need to convert any stream(s) into a LOGFMT type stream.
if (this.format === LoggerFormat.LOGFMT && options.stream) {
const ls: LoggerStream = this.createLogFmtFormatterStream({ stream: options.stream });
options.stream = ls.stream;
}
if (this.format === LoggerFormat.LOGFMT && options.streams) {
const logFmtConvertedStreams: LoggerStream[] = [];
options.streams.forEach((ls: LoggerStream) => {
logFmtConvertedStreams.push(this.createLogFmtFormatterStream(ls));
});
options.streams = logFmtConvertedStreams;
}
this.bunyan = new Bunyan(options);
this.bunyan.name = options.name;
this.bunyan.filters = [];
if (!options.streams && !options.stream) {
this.bunyan.streams = [];
}
// all SFDX loggers must filter sensitive data
this.addFilter((...args) => _filter(...args));
if (Global.getEnvironmentMode() !== Mode.TEST) {
Logger.lifecycle.on('uncaughtException', this.uncaughtExceptionHandler);
Logger.lifecycle.on('exit', this.exitHandler);
}
this.trace(`Created '${this.getName()}' logger instance`);
}
/**
* Gets the root logger with the default level, file stream, and DEBUG enabled.
*/
public static async root(): Promise<Logger> {
if (this.rootLogger) {
return this.rootLogger;
}
const rootLogger = (this.rootLogger = new Logger(Logger.ROOT_NAME).setLevel());
// disable log file writing, if applicable
if (process.env.SFDX_DISABLE_LOG_FILE !== 'true' && Global.getEnvironmentMode() !== Mode.TEST) {
await rootLogger.addLogFileStream(Global.LOG_FILE_PATH);
}
rootLogger.enableDEBUG();
return rootLogger;
}
/**
* Gets the root logger with the default level, file stream, and DEBUG enabled.
*/
public static getRoot(): Logger {
if (this.rootLogger) {
return this.rootLogger;
}
const rootLogger = (this.rootLogger = new Logger(Logger.ROOT_NAME).setLevel());
// disable log file writing, if applicable
if (process.env.SFDX_DISABLE_LOG_FILE !== 'true' && Global.getEnvironmentMode() !== Mode.TEST) {
rootLogger.addLogFileStreamSync(Global.LOG_FILE_PATH);
}
rootLogger.enableDEBUG();
return rootLogger;
}
/**
* Destroys the root `Logger`.
*
* @ignore
*/
public static destroyRoot(): void {
if (this.rootLogger) {
this.rootLogger.close();
this.rootLogger = undefined;
}
}
/**
* Create a child of the root logger, inheriting this instance's configuration such as `level`, `streams`, etc.
*
* @param name The name of the child logger.
* @param fields Additional fields included in all log lines.
*/
public static async child(name: string, fields?: Fields): Promise<Logger> {
return (await Logger.root()).child(name, fields);
}
/**
* Create a child of the root logger, inheriting this instance's configuration such as `level`, `streams`, etc.
*
* @param name The name of the child logger.
* @param fields Additional fields included in all log lines.
*/
public static childFromRoot(name: string, fields?: Fields): Logger {
return Logger.getRoot().child(name, fields);
}
/**
* Gets a numeric `LoggerLevel` value by string name.
*
* @param {string} levelName The level name to convert to a `LoggerLevel` enum value.
*
* **Throws** *{@link SfdxError}{ name: 'UnrecognizedLoggerLevelName' }* The level name was not case-insensitively recognized as a valid `LoggerLevel` value.
* @see {@Link LoggerLevel}
*/
public static getLevelByName(levelName: string): LoggerLevelValue {
levelName = levelName.toUpperCase();
if (!isKeyOf(LoggerLevel, levelName)) {
throw new SfdxError('UnrecognizedLoggerLevelName');
}
return LoggerLevel[levelName];
}
/**
* Adds a stream.
*
* @param stream The stream configuration to add.
* @param defaultLevel The default level of the stream.
*/
public addStream(stream: LoggerStream, defaultLevel?: LoggerLevelValue): void {
if (this.format === LoggerFormat.LOGFMT) {
stream = this.createLogFmtFormatterStream(stream);
}
this.bunyan.addStream(stream, defaultLevel);
}
/**
* Adds a file stream to this logger. Resolved or rejected upon completion of the addition.
*
* @param logFile The path to the log file. If it doesn't exist it will be created.
*/
public async addLogFileStream(logFile: string): Promise<void> {
try {
// Check if we have write access to the log file (i.e., we created it already)
await fs.access(logFile, fs.constants.W_OK);
} catch (err1) {
try {
await fs.mkdirp(path.dirname(logFile), {
mode: fs.DEFAULT_USER_DIR_MODE,
});
} catch (err2) {
// noop; directory exists already
}
try {
await fs.writeFile(logFile, '', { mode: fs.DEFAULT_USER_FILE_MODE });
} catch (err3) {
throw SfdxError.wrap(err3);
}
}
// avoid multiple streams to same log file
if (
!this.bunyan.streams.find(
// No bunyan typings
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(stream: any) => stream.type === 'file' && stream.path === logFile
)
) {
// TODO: rotating-file
// https://github.com/trentm/node-bunyan#stream-type-rotating-file
this.addStream({
type: 'file',
path: logFile,
level: this.bunyan.level() as number,
});
}
}
/**
* Adds a file stream to this logger. Resolved or rejected upon completion of the addition.
*
* @param logFile The path to the log file. If it doesn't exist it will be created.
*/
public addLogFileStreamSync(logFile: string): void {
try {
// Check if we have write access to the log file (i.e., we created it already)
fs.accessSync(logFile, fs.constants.W_OK);
} catch (err1) {
try {
fs.mkdirpSync(path.dirname(logFile), {
mode: fs.DEFAULT_USER_DIR_MODE,
});
} catch (err2) {
// noop; directory exists already
}
try {
fs.writeFileSync(logFile, '', { mode: fs.DEFAULT_USER_FILE_MODE });
} catch (err3) {
throw SfdxError.wrap(err3);
}
}
// avoid multiple streams to same log file
if (
!this.bunyan.streams.find(
// No bunyan typings
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(stream: any) => stream.type === 'file' && stream.path === logFile
)
) {
// TODO: rotating-file
// https://github.com/trentm/node-bunyan#stream-type-rotating-file
this.addStream({
type: 'file',
path: logFile,
level: this.bunyan.level() as number,
});
}
}
/**
* Gets the name of this logger.
*/
public getName(): string {
return this.bunyan.name;
}
/**
* Gets the current level of this logger.
*/
public getLevel(): LoggerLevelValue {
return this.bunyan.level();
}
/**
* Set the logging level of all streams for this logger. If a specific `level` is not provided, this method will
* attempt to read it from the environment variable `SFDX_LOG_LEVEL`, and if not found,
* {@link Logger.DEFAULT_LOG_LEVEL} will be used instead. For convenience `this` object is returned.
*
* @param {LoggerLevelValue} [level] The logger level.
*
* **Throws** *{@link SfdxError}{ name: 'UnrecognizedLoggerLevelName' }* A value of `level` read from `SFDX_LOG_LEVEL`
* was invalid.
*
* ```
* // Sets the level from the environment or default value
* logger.setLevel()
*
* // Set the level from the INFO enum
* logger.setLevel(LoggerLevel.INFO)
*
* // Sets the level case-insensitively from a string value
* logger.setLevel(Logger.getLevelByName('info'))
* ```
*/
public setLevel(level?: LoggerLevelValue): Logger {
if (level == null) {
level = process.env.SFDX_LOG_LEVEL ? Logger.getLevelByName(process.env.SFDX_LOG_LEVEL) : Logger.DEFAULT_LEVEL;
}
this.bunyan.level(level);
return this;
}
/**
* Gets the underlying Bunyan logger.
*/
public getBunyanLogger() {
return this.bunyan;
}
/**
* Compares the requested log level with the current log level. Returns true if
* the requested log level is greater than or equal to the current log level.
*
* @param level The requested log level to compare against the currently set log level.
*/
public shouldLog(level: LoggerLevelValue): boolean {
if (typeof level === 'string') {
level = Bunyan.levelFromName(level) as number;
}
return level >= this.getLevel();
}
/**
* Use in-memory logging for this logger instance instead of any parent streams. Useful for testing.
* For convenience this object is returned.
*
* **WARNING: This cannot be undone for this logger instance.**
*/
public useMemoryLogging(): Logger {
this.bunyan.streams = [];
this.bunyan.ringBuffer = new Bunyan.RingBuffer({ limit: 5000 });
this.addStream({
type: 'raw',
stream: this.bunyan.ringBuffer,
level: this.bunyan.level(),
});
return this;
}
/**
* Gets an array of log line objects. Each element is an object that corresponds to a log line.
*/
public getBufferedRecords(): LogLine[] {
if (this.bunyan.ringBuffer) {
return this.bunyan.ringBuffer.records;
}
return [];
}
/**
* Reads a text blob of all the log lines contained in memory or the log file.
*/
public readLogContentsAsText(): string {
if (this.bunyan.ringBuffer) {
return this.getBufferedRecords().reduce((accum, line) => {
accum += JSON.stringify(line) + os.EOL;
return accum;
}, '');
} else {
let content = '';
// No bunyan typings
// eslint-disable-next-line @typescript-eslint/no-explicit-any
this.bunyan.streams.forEach(async (stream: any) => {
if (stream.type === 'file') {
content += await fs.readFile(stream.path, 'utf8');
}
});
return content;
}
}
/**
* Adds a filter to be applied to all logged messages.
*
* @param filter A function with signature `(...args: any[]) => any[]` that transforms log message arguments.
*/
public addFilter(filter: (...args: unknown[]) => unknown): void {
// eslint disable-line @typescript-eslint/no-explicit-any
if (!this.bunyan.filters) {
this.bunyan.filters = [];
}
this.bunyan.filters.push(filter);
}
/**
* Close the logger, including any streams, and remove all listeners.
*
* @param fn A function with signature `(stream: LoggerStream) => void` to call for each stream with
* the stream as an arg.
*/
public close(fn?: (stream: LoggerStream) => void): void {
if (this.bunyan.streams) {
try {
this.bunyan.streams.forEach((entry: LoggerStream) => {
if (fn) {
fn(entry);
}
// close file streams, flush buffer to disk
// eslint-disable-next-line @typescript-eslint/unbound-method
if (entry.type === 'file' && entry.stream && isFunction(entry.stream.end)) {
entry.stream.end();
}
});
} finally {
Logger.lifecycle.removeListener('uncaughtException', this.uncaughtExceptionHandler);
Logger.lifecycle.removeListener('exit', this.exitHandler);
}
}
}
/**
* Create a child logger, typically to add a few log record fields. For convenience this object is returned.
*
* @param name The name of the child logger that is emitted w/ log line as `log:<name>`.
* @param fields Additional fields included in all log lines for the child logger.
*/
public child(name: string, fields: Fields = {}): Logger {
if (!name) {
throw new SfdxError('LoggerNameRequired');
}
fields.log = name;
const child = new Logger(name);
// only support including additional fields on log line (no config)
child.bunyan = this.bunyan.child(fields, true);
child.bunyan.name = name;
child.bunyan.filters = this.bunyan.filters;
this.trace(`Setup child '${name}' logger instance`);
return child;
}
/**
* Add a field to all log lines for this logger. For convenience `this` object is returned.
*
* @param name The name of the field to add.
* @param value The value of the field to be logged.
*/
public addField(name: string, value: FieldValue): Logger {
this.bunyan.fields[name] = value;
return this;
}
/**
* Logs at `trace` level with filtering applied. For convenience `this` object is returned.
*
* @param args Any number of arguments to be logged.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
public trace(...args: any[]): Logger {
this.bunyan.trace(this.applyFilters(LoggerLevel.TRACE, ...args));
return this;
}
/**
* Logs at `debug` level with filtering applied. For convenience `this` object is returned.
*
* @param args Any number of arguments to be logged.
*/
public debug(...args: unknown[]): Logger {
this.bunyan.debug(this.applyFilters(LoggerLevel.DEBUG, ...args));
return this;
}
/**
* Logs at `debug` level with filtering applied.
*
* @param cb A callback that returns on array objects to be logged.
*/
public debugCallback(cb: () => unknown[] | string) {
if (this.getLevel() === LoggerLevel.DEBUG || process.env.DEBUG) {
const result = cb();
if (isArray(result)) {
this.bunyan.debug(this.applyFilters(LoggerLevel.DEBUG, ...result));
} else {
this.bunyan.debug(this.applyFilters(LoggerLevel.DEBUG, ...[result]));
}
}
}
/**
* Logs at `info` level with filtering applied. For convenience `this` object is returned.
*
* @param args Any number of arguments to be logged.
*/
public info(...args: unknown[]): Logger {
this.bunyan.info(this.applyFilters(LoggerLevel.INFO, ...args));
return this;
}
/**
* Logs at `warn` level with filtering applied. For convenience `this` object is returned.
*
* @param args Any number of arguments to be logged.
*/
public warn(...args: unknown[]): Logger {
this.bunyan.warn(this.applyFilters(LoggerLevel.WARN, ...args));
return this;
}
/**
* Logs at `error` level with filtering applied. For convenience `this` object is returned.
*
* @param args Any number of arguments to be logged.
*/
public error(...args: unknown[]): Logger {
this.bunyan.error(this.applyFilters(LoggerLevel.ERROR, ...args));
return this;
}
/**
* Logs at `fatal` level with filtering applied. For convenience `this` object is returned.
*
* @param args Any number of arguments to be logged.
*/
public fatal(...args: unknown[]): Logger {
// always show fatal to stderr
// eslint-disable-next-line no-console
console.error(...args);
this.bunyan.fatal(this.applyFilters(LoggerLevel.FATAL, ...args));
return this;
}
/**
* Enables logging to stdout when the DEBUG environment variable is used. It uses the logger
* name as the debug name, so you can do DEBUG=<logger-name> to filter the results to your logger.
*/
public enableDEBUG() {
// The debug library does this for you, but no point setting up the stream if it isn't there
if (process.env.DEBUG && !this.debugEnabled) {
const debuggers: Dictionary<Debug.IDebugger> = {};
debuggers.core = Debug(`${this.getName()}:core`);
this.addStream({
name: 'debug',
stream: new Writable({
write: (chunk, encoding, next) => {
try {
const json = parseJsonMap(chunk.toString());
const logLevel = ensureNumber(json.level);
if (this.getLevel() <= logLevel) {
let debuggerName = 'core';
if (isString(json.log)) {
debuggerName = json.log;
if (!debuggers[debuggerName]) {
debuggers[debuggerName] = Debug(`${this.getName()}:${debuggerName}`);
}
}
const level = LoggerLevel[logLevel];
ensure(debuggers[debuggerName])(`${level} ${json.msg}`);
}
} catch (err) {
// do nothing
}
next();
},
}),
// Consume all levels
level: 0,
});
this.debugEnabled = true;
}
}
private applyFilters(logLevel: LoggerLevel, ...args: unknown[]): Optional<Many<unknown>> {
if (this.shouldLog(logLevel)) {
// No bunyan typings
// eslint-disable-next-line @typescript-eslint/no-explicit-any
this.bunyan.filters.forEach((filter: any) => (args = filter(...args)));
}
return args && args.length === 1 ? args[0] : args;
}
private uncaughtExceptionHandler = (err: Error) => {
// W-7558552
// Only log uncaught exceptions in root logger
if (this === Logger.rootLogger) {
// log the exception
// FIXME: good chance this won't be logged because
// process.exit was called before this is logged
// https://github.com/trentm/node-bunyan/issues/95
this.fatal(err);
}
};
private exitHandler = () => {
this.close();
};
private createLogFmtFormatterStream(loggerStream: LoggerStream): LoggerStream {
const logFmtWriteableStream = new Writable({
write: (chunk, enc, cb) => {
try {
const parsedJSON = JSON.parse(chunk.toString());
const keys = Object.keys(parsedJSON);
let logEntry = '';
keys.forEach((key) => {
let logMsg = `${parsedJSON[key]}`;
if (logMsg.trim().includes(' ')) {
logMsg = `"${logMsg}"`;
}
logEntry += `${key}=${logMsg} `;
});
if (loggerStream.stream) {
loggerStream.stream.write(logEntry.trimRight() + '\n');
}
} catch (error) {
if (loggerStream.stream) {
loggerStream.stream.write(chunk.toString());
}
}
cb(null);
},
});
return Object.assign({}, loggerStream, { stream: logFmtWriteableStream });
}
}
type FilteredKey = string | { name: string; regex: string };
// Ok to log clientid
const FILTERED_KEYS: FilteredKey[] = [
'sid',
'Authorization',
// Any json attribute that contains the words "access" and "token" will have the attribute/value hidden
{ name: 'access_token', regex: 'access[^\'"]*token' },
// Any json attribute that contains the words "refresh" and "token" will have the attribute/value hidden
{ name: 'refresh_token', regex: 'refresh[^\'"]*token' },
'clientsecret',
// Any json attribute that contains the words "sfdx", "auth", and "url" will have the attribute/value hidden
{ name: 'sfdxauthurl', regex: 'sfdx[^\'"]*auth[^\'"]*url' },
];
// SFDX code and plugins should never show tokens or connect app information in the logs
const _filter = (...args: unknown[]): unknown => {
return args.map((arg) => {
if (isArray(arg)) {
return _filter(...arg);
}
if (arg) {
let _arg: string;
// Normalize all objects into a string. This include errors.
if (arg instanceof Buffer) {
_arg = '<Buffer>';
} else if (isObject(arg)) {
_arg = JSON.stringify(arg);
} else if (isString(arg)) {
_arg = arg;
} else {
_arg = '';
}
const HIDDEN = 'HIDDEN';
FILTERED_KEYS.forEach((key: FilteredKey) => {
let expElement = key;
let expName = key;
// Filtered keys can be strings or objects containing regular expression components.
if (isPlainObject(key)) {
expElement = key.regex;
expName = key.name;
}
const hiddenAttrMessage = `"<${expName} - ${HIDDEN}>"`;
// Match all json attribute values case insensitive: ex. {" Access*^&(*()^* Token " : " 45143075913458901348905 \n\t" ...}
const regexTokens = new RegExp(`(['"][^'"]*${expElement}[^'"]*['"]\\s*:\\s*)['"][^'"]*['"]`, 'gi');
_arg = _arg.replace(regexTokens, `$1${hiddenAttrMessage}`);
// Match all key value attribute case insensitive: ex. {" key\t" : ' access_token ' , " value " : " dsafgasr431 " ....}
const keyRegex = new RegExp(
`(['"]\\s*key\\s*['"]\\s*:)\\s*['"]\\s*${expElement}\\s*['"]\\s*.\\s*['"]\\s*value\\s*['"]\\s*:\\s*['"]\\s*[^'"]*['"]`,
'gi'
);
_arg = _arg.replace(keyRegex, `$1${hiddenAttrMessage}`);
});
_arg = _arg.replace(/(00D\w{12,15})![.\w]*/, `<${HIDDEN}>`);
// return an object if an object was logged; otherwise return the filtered string.
return isObject(arg) ? parseJson(_arg) : _arg;
} else {
return arg;
}
});
}; | the_stack |
import React, {
useEffect,
useImperativeHandle,
useRef,
useMemo,
useState,
ReactNode,
CSSProperties,
} from 'react';
import {
Key,
getValidScrollTop,
getCompareItemRelativeTop,
getItemAbsoluteTop,
getItemRelativeTop,
getNodeHeight,
getRangeIndex,
getScrollPercentage,
GHOST_ITEM_KEY,
getLongestItemIndex,
getLocationItem,
} from './utils/itemUtil';
import { raf, caf } from '../../_util/raf';
import { isNumber } from '../../_util/is';
import usePrevious from '../../_util/hooks/usePrevious';
import { findListDiffIndex, getIndexByStartLoc } from './utils/algorithmUtil';
import Filler from './Filler';
import useStateWithPromise from '../../_util/hooks/useStateWithPromise';
import useIsFirstRender from '../../_util/hooks/useIsFirstRender';
import useForceUpdate from '../../_util/hooks/useForceUpdate';
import ResizeObserver from '../../_util/resizeObserver';
import useIsomorphicLayoutEffect from '../../_util/hooks/useIsomorphicLayoutEffect';
export type RenderFunc<T> = (
item: T,
index: number,
props: { style: React.CSSProperties }
) => ReactNode;
type Status = 'NONE' | 'MEASURE_START' | 'MEASURE_DONE';
export interface VirtualListProps<T> extends React.HTMLAttributes<any> {
children: RenderFunc<T>;
data: T[];
/* Viewable area height (`2.11.0` starts support `string` type such as `80%`) */
height?: number | string;
/* The element height used to calculate how many elements are actually rendered */
itemHeight?: number;
/* HTML tags for wrapping */
wrapper?: string | React.FC<any> | React.ComponentClass<any>;
/* Threshold of the number of elements that auto enable virtual scrolling, use `null` to disable virtual scrolling */
threshold?: number | null;
/* Whether it's static elements of the same height */
isStaticItemHeight?: boolean;
/* Key of the specified element, or function to get the key */
itemKey?: Key | ((item: T, index: number) => Key);
/* Whether need to measure longest child element */
measureLongestItem?: boolean;
/* Configure the default behavior related to scrolling */
scrollOptions?: ScrollIntoViewOptions;
needFiller?: boolean;
/** Custom filler outer style */
outerStyle?: CSSProperties;
onScroll?: React.UIEventHandler<HTMLElement>;
}
export type AvailableVirtualListProps = Pick<
VirtualListProps<any>,
'height' | 'itemHeight' | 'threshold' | 'isStaticItemHeight' | 'scrollOptions'
>;
interface RelativeScroll {
itemIndex: number;
relativeTop: number;
}
interface VirtualListState {
status: Status;
startIndex: number;
endIndex: number;
itemIndex: number;
itemOffsetPtg: number;
startItemTop: number;
scrollTop: number;
}
export type VirtualListHandle = {
dom: HTMLElement;
scrollTo: (
arg:
| number
| {
index: number;
options?: ScrollIntoViewOptions;
}
| {
key: Key;
options?: ScrollIntoViewOptions;
}
) => void;
};
// map for height of each element
type ItemHeightMap = { [p: string]: number };
// height of the virtual element, used to calculate total height of the virtual list
const DEFAULT_VIRTUAL_ITEM_HEIGHT = 32;
const KEY_VIRTUAL_ITEM_HEIGHT = `__virtual_item_height_${Math.random().toFixed(5).slice(2)}`;
// after collecting the real height of the first screen element, calculate the virtual ItemHeight to trigger list re-rendering
const useComputeVirtualItemHeight = (refItemHeightMap: React.MutableRefObject<ItemHeightMap>) => {
const forceUpdate = useForceUpdate();
const { current: heightMap } = refItemHeightMap;
useEffect(() => {
// virtual item height should be static as possible, otherwise it is easy to cause jitter
if (Object.keys(heightMap).length && !heightMap[KEY_VIRTUAL_ITEM_HEIGHT]) {
heightMap[KEY_VIRTUAL_ITEM_HEIGHT] = Object.entries(heightMap).reduce(
(sum, [, currentHeight], currentIndex, array) => {
const nextSum = sum + currentHeight;
return currentIndex === array.length - 1 ? Math.round(nextSum / array.length) : nextSum;
},
0
);
forceUpdate();
}
}, [Object.keys(heightMap).length]);
};
// cache the constructed results of child nodes to avoid redrawing of child nodes caused by re-construction during drawing
const useCacheChildrenNodes = (children: VirtualListProps<any>['children']) => {
const refCacheMap = useRef<{ [key: number]: ReactNode }>({});
const refPrevChildren = useRef(children);
useEffect(() => {
refPrevChildren.current = children;
}, [children]);
// children change means state of parent component is updated, so clear cache
if (children !== refPrevChildren.current) {
refCacheMap.current = {};
}
return (item, index, props) => {
if (!refCacheMap.current.hasOwnProperty(index)) {
refCacheMap.current[index] = children(item, index, props);
}
return refCacheMap.current[index];
};
};
const VirtualList: React.ForwardRefExoticComponent<
VirtualListProps<any> & React.RefAttributes<VirtualListHandle>
> = React.forwardRef((props: VirtualListProps<any>, ref) => {
const {
style,
className,
children,
data = [],
itemKey,
threshold = 100,
wrapper: WrapperTagName = 'div',
height: propHeight = '100%',
isStaticItemHeight = true,
itemHeight: propItemHeight,
measureLongestItem,
scrollOptions,
onScroll,
needFiller = true,
outerStyle,
...restProps
} = props;
// Compatible with setting the height of the list through style.maxHeight
const styleListMaxHeight = (style && style.maxHeight) || propHeight;
const refItemHeightMap = useRef<ItemHeightMap>({});
const [stateHeight, setStateHeight] = useState(200);
const renderChild = useCacheChildrenNodes(children);
useComputeVirtualItemHeight(refItemHeightMap);
// Elements with the same height, the height of the item is based on the first rendering
const itemCount = data.length;
const itemHeight =
propItemHeight ||
refItemHeightMap.current[KEY_VIRTUAL_ITEM_HEIGHT] ||
DEFAULT_VIRTUAL_ITEM_HEIGHT;
const viewportHeight = isNumber(styleListMaxHeight) ? styleListMaxHeight : stateHeight;
const itemCountVisible = Math.ceil(viewportHeight / itemHeight);
const itemTotalHeight = itemHeight * itemCount;
const isVirtual =
threshold !== null && itemCount >= threshold && itemTotalHeight > viewportHeight;
const refList = useRef(null);
const refRafId = useRef(null);
const refLockScroll = useRef(false);
const refIsVirtual = useRef(isVirtual);
// The paddingTop of the record scrolling list is used to correct the scrolling distance
const scrollListPadding = useMemo<{ top: number; bottom: number }>(() => {
if (refList.current) {
const getPadding = (property) =>
+window.getComputedStyle(refList.current)[property].replace(/\D/g, '');
return {
top: getPadding('paddingTop'),
bottom: getPadding('paddingBottom'),
};
}
return { top: 0, bottom: 0 };
}, [refList.current]);
const [state, setState] = useStateWithPromise<VirtualListState>({
// measure status
status: 'NONE',
// render range info
startIndex: 0,
endIndex: 0,
itemIndex: 0,
itemOffsetPtg: 0,
// scroll info
startItemTop: 0,
scrollTop: 0,
});
const prevData = usePrevious(data) || [];
const isFirstRender = useIsFirstRender();
const getItemKey = (item, index) => {
return typeof itemKey === 'function'
? itemKey(item, index)
: typeof itemKey === 'string'
? item[itemKey]
: item.key || index;
};
const getItemKeyByIndex = (index, items = data) => {
if (index === items.length) {
return GHOST_ITEM_KEY;
}
const item = items[index];
return item !== undefined ? getItemKey(item, index) : null;
};
const getCachedItemHeight = (key: Key): number => {
return refItemHeightMap.current[key] || itemHeight;
};
const internalScrollTo = (relativeScroll: RelativeScroll): void => {
const { itemIndex: compareItemIndex, relativeTop: compareItemRelativeTop } = relativeScroll;
const { scrollHeight, clientHeight } = refList.current;
const originScrollTop = state.scrollTop;
const maxScrollTop = scrollHeight - clientHeight;
let bestSimilarity = Number.MAX_VALUE;
let bestScrollTop: number = null;
let bestItemIndex: number = null;
let bestItemOffsetPtg: number = null;
let bestStartIndex: number = null;
let bestEndIndex: number = null;
let missSimilarity = 0;
for (let i = 0; i < maxScrollTop; i++) {
const scrollTop = getIndexByStartLoc(0, maxScrollTop, originScrollTop, i);
const scrollPtg = getScrollPercentage({ scrollTop, scrollHeight, clientHeight });
const { itemIndex, itemOffsetPtg, startIndex, endIndex } = getRangeIndex(
scrollPtg,
itemCount,
itemCountVisible
);
if (startIndex <= compareItemIndex && compareItemIndex <= endIndex) {
const locatedItemRelativeTop = getItemRelativeTop({
itemHeight: getCachedItemHeight(getItemKeyByIndex(itemIndex)),
itemOffsetPtg,
clientHeight,
scrollPtg,
});
const compareItemTop = getCompareItemRelativeTop({
locatedItemRelativeTop,
locatedItemIndex: itemIndex,
compareItemIndex,
startIndex,
endIndex,
itemHeight,
getItemKey: getItemKeyByIndex,
itemElementHeights: refItemHeightMap.current,
});
const similarity = Math.abs(compareItemTop - compareItemRelativeTop);
if (similarity < bestSimilarity) {
bestSimilarity = similarity;
bestScrollTop = scrollTop;
bestItemIndex = itemIndex;
bestItemOffsetPtg = itemOffsetPtg;
bestStartIndex = startIndex;
bestEndIndex = endIndex;
missSimilarity = 0;
} else {
missSimilarity += 1;
}
}
if (missSimilarity > 10) {
break;
}
}
if (bestScrollTop !== null) {
refLockScroll.current = true;
refList.current.scrollTop = bestScrollTop;
setState({
...state,
status: 'MEASURE_START',
scrollTop: bestScrollTop,
itemIndex: bestItemIndex,
itemOffsetPtg: bestItemOffsetPtg,
startIndex: bestStartIndex,
endIndex: bestEndIndex,
});
}
refRafId.current = raf(() => {
refLockScroll.current = false;
});
};
// Record the current element position when the real list is scrolled, and ensure that the position is correct after switching to the virtual list
const rawListScrollHandler = (event) => {
const { scrollTop: rawScrollTop, clientHeight, scrollHeight } = refList.current;
const scrollTop = getValidScrollTop(rawScrollTop, scrollHeight - clientHeight);
const scrollPtg = getScrollPercentage({
scrollTop,
clientHeight,
scrollHeight,
});
const { index, offsetPtg } = getLocationItem(scrollPtg, itemCount);
setState({
...state,
scrollTop,
itemIndex: index,
itemOffsetPtg: offsetPtg,
});
event && onScroll && onScroll(event);
};
// Modify the state and recalculate the position in the next render
const virtualListScrollHandler = (event, isInit = false) => {
const { scrollTop: rawScrollTop, clientHeight, scrollHeight } = refList.current;
const scrollTop = getValidScrollTop(rawScrollTop, scrollHeight - clientHeight);
// Prevent jitter
if (!isInit && (scrollTop === state.scrollTop || refLockScroll.current)) {
return;
}
const scrollPtg = getScrollPercentage({
scrollTop,
clientHeight,
scrollHeight,
});
const { itemIndex, itemOffsetPtg, startIndex, endIndex } = getRangeIndex(
scrollPtg,
itemCount,
itemCountVisible
);
setState({
...state,
scrollTop,
itemIndex,
itemOffsetPtg,
startIndex,
endIndex,
status: 'MEASURE_START',
});
event && onScroll && onScroll(event);
};
useEffect(() => {
return () => {
refRafId.current && caf(refRafId.current);
};
}, []);
// rerender when the number of visible elements changes
useEffect(() => {
if (refList.current) {
if (isFirstRender) {
refList.current.scrollTop = 0;
}
virtualListScrollHandler(null, true);
}
}, [itemCountVisible]);
// Handle additions and deletions of list items or switching the virtual state
useEffect(() => {
let changedItemIndex: number = null;
const switchTo = refIsVirtual.current !== isVirtual ? (isVirtual ? 'virtual' : 'raw') : '';
refIsVirtual.current = isVirtual;
if (viewportHeight && prevData.length !== data.length) {
const diff = findListDiffIndex(prevData, data, getItemKey);
changedItemIndex = diff ? diff.index : null;
}
// No need to correct the position when the number of elements in the real list changes
if (switchTo || (isVirtual && changedItemIndex)) {
const { clientHeight } = refList.current;
const locatedItemRelativeTop = getItemRelativeTop({
itemHeight: getCachedItemHeight(getItemKeyByIndex(state.itemIndex, prevData)),
itemOffsetPtg: state.itemOffsetPtg,
scrollPtg: getScrollPercentage({
scrollTop: state.scrollTop,
scrollHeight: prevData.length * itemHeight,
clientHeight,
}),
clientHeight,
});
if (switchTo === 'raw') {
let rawTop = locatedItemRelativeTop;
for (let index = 0; index < state.itemIndex; index++) {
rawTop -= getCachedItemHeight(getItemKeyByIndex(index));
}
refList.current.scrollTop = -rawTop;
refLockScroll.current = true;
refRafId.current = raf(() => {
refLockScroll.current = false;
});
} else {
internalScrollTo({
itemIndex: state.itemIndex,
relativeTop: locatedItemRelativeTop,
});
}
}
}, [data, isVirtual]);
useIsomorphicLayoutEffect(() => {
if (state.status === 'MEASURE_START') {
const { scrollTop, scrollHeight, clientHeight } = refList.current;
const scrollPtg = getScrollPercentage({
scrollTop,
scrollHeight,
clientHeight,
});
// Calculate the top value of the first rendering element
let startItemTop = getItemAbsoluteTop({
scrollPtg,
clientHeight,
scrollTop: scrollTop - (scrollListPadding.top + scrollListPadding.bottom) * scrollPtg,
itemHeight: getCachedItemHeight(getItemKeyByIndex(state.itemIndex)),
itemOffsetPtg: state.itemOffsetPtg,
});
for (let index = state.itemIndex - 1; index >= state.startIndex; index--) {
startItemTop -= getCachedItemHeight(getItemKeyByIndex(index));
}
setState({
...state,
startItemTop,
status: 'MEASURE_DONE',
});
}
}, [state]);
useImperativeHandle<any, VirtualListHandle>(
ref,
() => ({
dom: refList.current,
// Scroll to a certain height or an element
scrollTo: (arg) => {
refRafId.current && caf(refRafId.current);
refRafId.current = raf(() => {
if (typeof arg === 'number') {
refList.current.scrollTop = arg;
return;
}
const index =
'index' in arg
? arg.index
: 'key' in arg
? data.findIndex((item, index) => getItemKey(item, index) === arg.key)
: 0;
const item = data[index];
if (!item) {
return;
}
let align: ScrollIntoViewOptions['block'] =
typeof arg === 'object' && arg.options?.block
? arg.options.block
: scrollOptions?.block || 'nearest';
const { clientHeight, scrollTop } = refList.current;
if (isVirtual && !isStaticItemHeight) {
if (align === 'nearest') {
const { itemIndex, itemOffsetPtg } = state;
if (Math.abs(itemIndex - index) < itemCountVisible) {
let itemTop = getItemRelativeTop({
itemHeight: getCachedItemHeight(getItemKeyByIndex(itemIndex)),
itemOffsetPtg,
clientHeight,
scrollPtg: getScrollPercentage(refList.current),
});
if (index < itemIndex) {
for (let i = index; i < itemIndex; i++) {
itemTop -= getCachedItemHeight(getItemKeyByIndex(i));
}
} else {
for (let i = itemIndex; i < index; i++) {
itemTop += getCachedItemHeight(getItemKeyByIndex(i));
}
}
// When the target element is within the field of view, exit directly
if (itemTop < 0 || itemTop > clientHeight) {
align = itemTop < 0 ? 'start' : 'end';
} else {
return;
}
} else {
align = index < itemIndex ? 'start' : 'end';
}
}
setState({
...state,
startIndex: Math.max(0, index - itemCountVisible),
endIndex: Math.min(itemCount - 1, index + itemCountVisible),
}).then(() => {
const itemHeight = getCachedItemHeight(getItemKey(item, index));
internalScrollTo({
itemIndex: index,
relativeTop:
align === 'start'
? 0
: (clientHeight - itemHeight) / (align === 'center' ? 2 : 1),
});
});
} else {
const indexItemHeight = getCachedItemHeight(getItemKeyByIndex(index));
let itemTop = 0;
for (let i = 0; i < index; i++) {
itemTop += getCachedItemHeight(getItemKeyByIndex(i));
}
const itemBottom = itemTop + indexItemHeight;
if (align === 'nearest') {
if (itemTop < scrollTop) {
align = 'start';
} else if (itemBottom > scrollTop + clientHeight) {
align = 'end';
}
}
const viewportHeight = clientHeight - indexItemHeight;
refList.current.scrollTop =
itemTop - (align === 'start' ? 0 : viewportHeight / (align === 'center' ? 2 : 1));
}
});
},
}),
[data, itemHeight, state]
);
const renderChildren = (list, startIndex: number) => {
return list.map((item, index) => {
const originIndex = startIndex + index;
const node = renderChild(item, originIndex, {
style: {},
}) as React.ReactElement;
const key = getItemKey(item, originIndex);
return React.cloneElement(node, {
key,
ref: (ele: HTMLElement) => {
const { current: heightMap } = refItemHeightMap;
// Minimize the measurement of element height as much as possible to avoid frequent triggering of browser reflow
// Method getNodeHeight get the clientHeight from the DOM referred by React ref. If result is wrong, check the ref of this element
if (
ele &&
state.status === 'MEASURE_START' &&
(!isStaticItemHeight || heightMap[key] === undefined)
) {
if (isStaticItemHeight) {
if (!heightMap[KEY_VIRTUAL_ITEM_HEIGHT]) {
heightMap[KEY_VIRTUAL_ITEM_HEIGHT] = getNodeHeight(ele);
}
heightMap[key] = heightMap[KEY_VIRTUAL_ITEM_HEIGHT];
} else {
heightMap[key] = getNodeHeight(ele);
}
}
},
});
});
};
// Render the widest element to provide the maximum width of the container initially
const refLongestItemIndex = useRef<number>(null);
// Don't add `renderChild` to the array dependency, it will change every time when rerender
useEffect(() => {
refLongestItemIndex.current = null;
}, [data]);
const renderLongestItem = () => {
if (measureLongestItem) {
const index =
refLongestItemIndex.current === null
? getLongestItemIndex(data)
: refLongestItemIndex.current;
const item = data[index];
refLongestItemIndex.current = index;
return item ? (
<div style={{ height: 1, overflow: 'hidden', opacity: 0 }}>
{renderChild(item, index, { style: {} })}
</div>
) : null;
}
return null;
};
return (
<ResizeObserver
onResize={() => {
if (refList.current && !isNumber(styleListMaxHeight)) {
const { clientHeight } = refList.current;
setStateHeight(clientHeight);
}
}}
>
<WrapperTagName
ref={refList}
style={{
overflowY: 'auto',
overflowAnchor: 'none',
...style,
maxHeight: styleListMaxHeight,
}}
className={className}
onScroll={isVirtual ? virtualListScrollHandler : rawListScrollHandler}
{...restProps}
>
{isVirtual ? (
<>
<Filler
height={itemTotalHeight}
offset={state.status === 'MEASURE_DONE' ? state.startItemTop : 0}
outerStyle={outerStyle}
>
{renderChildren(data.slice(state.startIndex, state.endIndex + 1), state.startIndex)}
</Filler>
{renderLongestItem()}
</>
) : needFiller ? (
<Filler height={viewportHeight}>{renderChildren(data, 0)}</Filler>
) : (
renderChildren(data, 0)
)}
</WrapperTagName>
</ResizeObserver>
);
});
VirtualList.displayName = 'VirtualList';
export default VirtualList; | the_stack |
export interface Value {
value: any;
type: string;
namespace: string;
range: [number, number];
ownerRange: [number, number];
parent: Tag;
}
export interface TagParseError {
range: [number, number];
message: string;
type: "error" | "warning";
}
export interface Tag {
tags: { [index: string]: Tag[]; };
namespaces: { [index: string]: Tag; };
values: Value[];
attributes: { [index: string]: Value[]; };
parent: Tag | null;
isNamespace?: boolean;
range?: [number, number];
attributesRange?: [number, number];
errors?: TagParseError[];
}
var unicodeChar = /^'(.*?)'/;
var dateTime = /^(\d{4})\/(\d{2})\/(\d{2})\s(\d{2}):(\d{2})(?::(\d{2}))?(?:\.(\d+))?(?:-([a-zA-Z0-9_]\/[a-zA-Z0-9_]|[A-Z]{3}|GMT[+-]\d{2}(?::\d{2})?))?/;
var timespan = /^([+-])?(?:(\d+)d)?(\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?/;
var date = /^(\d{4})\/(\d{2})\/(\d{2})/;
var longInteger = /^([+-]?\d+)[Ll]/;
var double = /^([+-]?\d+\.\d+)[Dd]?/;
var float = /^([+-]?\d+\.\d+)[Ff]/;
var decimal = /^([+-]?\d+\.\d+)(?:BD|bd)/;
var integer = /^([+-]?\d+)/;
var boolean = /^(true|false|on|off)/;
var binaryValue = /^\[([a-zA-Z0-9\+\/=\s]+)\]/;
var nullValue = /^(null)/;
var identifier = /^([A-Za-z_\.\$][A-Za-z0-9_\-\.\$]*)/;
var wysiwygString = /^`([\S\s]*?)`/;
var stringWhitespaceChar = /[^\S\n]/;
function parseStringLiteral(sdl: string) {
if (sdl.length < 2)
return null;
if (sdl[0] == '`') {
var match = wysiwygString.exec(sdl);
if (match) {
return { string: match[1], length: match[0].length }
}
else {
return { string: sdl.substr(1), length: sdl.length };
}
}
else if (sdl[0] == '"') {
var str = "";
var skipWhitespace = false;
var escape = false;
for (var i = 1; i < sdl.length; i++) {
if (escape) {
skipWhitespace = false;
if (sdl[i] == '"')
str += '"';
else if (sdl[i] == '\\')
str += '\\';
else if (sdl[i] == 'n')
str += '\n';
else if (sdl[i] == 'r')
str += '\r';
else if (sdl[i] == 't')
str += '\t';
else if (sdl[i] == ' ')
str += ' ';
else if (sdl[i] == '\n') {
skipWhitespace = true;
}
escape = false;
}
else {
if (sdl[i] == '\\')
escape = true;
else if (sdl[i] == '"')
return { string: str, length: i + 1 };
else {
if (skipWhitespace && stringWhitespaceChar.exec(sdl[i]))
continue;
else {
skipWhitespace = false;
str += sdl[i];
}
}
}
}
return { string: str, length: sdl.length };
}
else return null;
}
var lineComment = /^(?:#|\/\/|--).*?(?=\n|$)/;
var blockComment = /^\/\*[\s\S]*?\*\//;
var whitespace = /^[^\S\n]+/;
var escapedNewline = /^\\\n/;
var endtoken = /^(\n+|;)/;
var blockStart = /^{/;
var blockEnd = /^}/;
export function tokenizeSDL(sdl: string) {
sdl += "\n";
var original = sdl;
var tokens = [];
var isAttribute = false;
var attributeName;
var attributeRange;
var index = 0;
while (sdl.length) {
var startLen = sdl.length;
index = original.length - sdl.length;
if (sdl.substr(0, 64) != original.substr(index, 64))
throw "Faulty index.\nRemaining: '" + sdl.substr(0, 64) + "'\nAccording to index: '" + original.substr(index, 64) + "'";
var match;
if (match = unicodeChar.exec(sdl)) {
tokens.push({ type: "value", range: [index, index + match[0].length], valuetype: "char", value: match[1] });
sdl = sdl.substr(match[0].length);
} else if (match = dateTime.exec(sdl)) {
tokens.push({ type: "value", range: [index, index + match[0].length], valuetype: "datetime", value: { year: parseInt(match[1]), month: parseInt(match[2]), day: parseInt(match[3]), hours: parseInt(match[4]), minutes: parseInt(match[5]), seconds: match[6] ? parseInt(match[6]) : undefined, milliseconds: match[7] ? parseInt(match[7]) : undefined, timezone: match[8] } });
sdl = sdl.substr(match[0].length);
} else if (match = timespan.exec(sdl)) {
tokens.push({ type: "value", range: [index, index + match[0].length], valuetype: "timespan", value: { sign: match[1] || "+", days: match[2] ? parseInt(match[2]) : undefined, hours: parseInt(match[3]), minutes: parseInt(match[4]), seconds: parseInt(match[5]), milliseconds: match[6] ? parseInt(match[6]) : undefined } });
sdl = sdl.substr(match[0].length);
} else if (match = date.exec(sdl)) {
tokens.push({ type: "value", range: [index, index + match[0].length], valuetype: "date", value: { year: parseInt(match[1]), month: parseInt(match[2]), day: parseInt(match[3]) } });
sdl = sdl.substr(match[0].length);
} else if (match = longInteger.exec(sdl)) {
tokens.push({ type: "value", range: [index, index + match[0].length], valuetype: "long", value: parseInt(match[1]) });
sdl = sdl.substr(match[0].length);
} else if (match = double.exec(sdl)) {
tokens.push({ type: "value", range: [index, index + match[0].length], valuetype: "double", value: parseFloat(match[1]) });
sdl = sdl.substr(match[0].length);
} else if (match = float.exec(sdl)) {
tokens.push({ type: "value", range: [index, index + match[0].length], valuetype: "float", value: parseFloat(match[1]) });
sdl = sdl.substr(match[0].length);
} else if (match = decimal.exec(sdl)) {
tokens.push({ type: "value", range: [index, index + match[0].length], valuetype: "decimal", value: parseFloat(match[1]) });
sdl = sdl.substr(match[0].length);
} else if (match = integer.exec(sdl)) {
tokens.push({ type: "value", range: [index, index + match[0].length], valuetype: "int", value: parseInt(match[1]) });
sdl = sdl.substr(match[0].length);
} else if (match = boolean.exec(sdl)) {
tokens.push({ type: "value", range: [index, index + match[0].length], valuetype: "boolean", value: match[1] == "true" || match[1] == "on" });
sdl = sdl.substr(match[0].length);
} else if (match = binaryValue.exec(sdl)) {
tokens.push({ type: "value", range: [index, index + match[0].length], valuetype: "binary", value: Buffer.from(match[1].replace(/\s/g, ""), "base64") });
sdl = sdl.substr(match[0].length);
} else if (match = nullValue.exec(sdl)) {
tokens.push({ type: "value", range: [index, index + match[0].length], valuetype: "null", value: null });
sdl = sdl.substr(match[0].length);
} else if (match = identifier.exec(sdl)) {
if (sdl.length > 0) {
if (sdl[match[0].length] == ':') {
tokens.push({ type: "namespace", range: [index, index + match[0].length + 1], namespace: match[1] });
sdl = sdl.substr(match[0].length + 1);
continue;
}
else if (sdl[match[0].length] == '=') {
attributeName = match[1];
attributeRange = [index, index + match[0].length + 1];
isAttribute = true;
sdl = sdl.substr(match[0].length + 1);
continue;
}
tokens.push({ type: "identifier", range: [index, index + match[0].length], name: match[1] });
sdl = sdl.substr(match[0].length);
} else {
tokens.push({ type: "unknown-identifier", range: [index, index + match[0].length], name: match[1] });
sdl = sdl.substr(match[0].length);
}
} else if (match = parseStringLiteral(sdl)) {
tokens.push({ type: "value", range: [index, index + match.length], valuetype: "string", value: match.string });
sdl = sdl.substr(match.length);
} else if (match = whitespace.exec(sdl)) {
sdl = sdl.substr(match[0].length);
} else if (match = escapedNewline.exec(sdl)) {
sdl = sdl.substr(match[0].length);
} else if (match = endtoken.exec(sdl)) {
tokens.push({ type: "end", marker: index + 1 });
sdl = sdl.substr(match[0].length);
} else if (match = blockComment.exec(sdl)) {
sdl = sdl.substr(match[0].length);
} else if (match = lineComment.exec(sdl)) {
sdl = sdl.substr(match[0].length);
} else if (match = blockStart.exec(sdl)) {
tokens.push({ type: "block-start", marker: index });
sdl = sdl.substr(match[0].length);
} else if (match = blockEnd.exec(sdl)) {
tokens.push({ type: "block-end", marker: index + 1 });
sdl = sdl.substr(match[0].length);
}
/*if (tokens.length >= 2 && tokens[tokens.length - 1].type == "end" && tokens[tokens.length - 2].type == "end") {
if (tokens[tokens.length - 2].marker < tokens[tokens.length - 1].marker)
tokens[tokens.length - 2].marker = tokens[tokens.length - 1].marker;
tokens.pop();
}*/
if (startLen == sdl.length)
break;
if (isAttribute && attributeRange) {
if (tokens[tokens.length - 1].type == "value")
tokens[tokens.length - 1] = { type: "attribute", range: attributeRange, name: attributeName, value: tokens[tokens.length - 1] }
else {
var lastTok: any = tokens[tokens.length - 1];
tokens.pop();
tokens.push({ type: "attribute", range: [attributeRange[0], attributeRange[1] + 1], name: attributeName, value: undefined });
tokens.push(lastTok);
}
isAttribute = false;
}
}
tokens.push({ type: "end", marker: original.length });
/*if (tokens.length >= 2 && tokens[tokens.length - 1].type == "end" && tokens[tokens.length - 2].type == "end") {
if (tokens[tokens.length - 2].marker < tokens[tokens.length - 1].marker)
tokens[tokens.length - 2].marker = tokens[tokens.length - 1].marker;
tokens.pop();
}*/
return tokens;
}
export function parseSDL(sdl: string): Tag {
var tokens = tokenizeSDL(sdl);
var root: Tag = {
attributes: {},
namespaces: {},
tags: {},
values: [],
parent: null,
errors: [],
range: undefined
}
var currTag: Tag | null = root;
var currNamespace = "";
var anon = true;
var lastWasEnd = true;
var inIdentifier = false;
for (var i = 0; i < tokens.length; i++) {
var token = tokens[i];
if (token.type != "end")
lastWasEnd = false;
if (!currTag)
break;
if (token.type == "value") {
if (anon) {
if (!currTag.tags[""])
currTag.tags[""] = [{
attributes: {},
namespaces: {},
tags: {},
values: [],
parent: currTag.parent || currTag
}];
currTag.tags[""][0].values.push({ namespace: "", ownerRange: [0, 0], parent: currTag, range: token.range, type: token.valuetype, value: token.value });
}
else {
currTag.values.push({ namespace: "", ownerRange: [0, 0], parent: currTag, range: token.range, type: token.valuetype, value: token.value });
}
} else if (token.type == "attribute") {
if (!currTag.attributes[token.name])
currTag.attributes[token.name] = [];
if (token.value)
currTag.attributes[token.name].push({ namespace: currNamespace, ownerRange: token.range, parent: currTag, range: token.value.range, type: token.value.valuetype, value: token.value.value });
else
currTag.attributes[token.name].push({ namespace: currNamespace, ownerRange: token.range, parent: currTag, range: [token.range[1], token.range[1] + 1], type: "none", value: null });
currNamespace = "";
} else if (token.type == "unknown-identifier") {
if (!currTag.attributes[token.name])
currTag.attributes[token.name] = [];
currTag.attributes[token.name].push({ namespace: currNamespace, ownerRange: token.range, parent: currTag, range: [sdl.length, sdl.length], type: "none", value: null });
currNamespace = "";
} else if (token.type == "namespace") {
if (currNamespace != "")
root.errors!.push({ range: token.range, message: "Can't stack namespaces", type: "error" });
currNamespace = token.namespace;
} else if (token.type == "identifier") {
if (inIdentifier) {
if (!currTag.attributes[token.name])
currTag.attributes[token.name] = [];
currTag.attributes[token.name].push({ namespace: currNamespace, ownerRange: token.range, parent: currTag, range: [token.range[1], token.range[1]], type: "none", value: null });
currNamespace = "";
root.errors!.push({ range: token.range, message: "An identifier doesn't belong here", type: "error" });
}
else {
if (currNamespace) {
if (!currTag.namespaces[currNamespace])
currTag.namespaces[currNamespace] = {
attributes: {},
namespaces: {},
tags: {},
values: [],
parent: currTag,
isNamespace: true,
};
currTag = currTag.namespaces[currNamespace];
}
if (!currTag.tags[token.name])
currTag.tags[token.name] = [];
var tag: Tag = {
attributes: {},
namespaces: {},
tags: {},
values: [],
parent: currTag,
range: token.range,
attributesRange: [token.range[1] + 1, token.range[1]]
};
currTag.tags[token.name].push(tag);
currTag = tag;
anon = false;
currNamespace = "";
inIdentifier = true;
}
} else if (token.type == "end") {
if (!anon && !lastWasEnd) {
inIdentifier = false;
if (currTag.range)
currTag.range[1] = token.marker;
if (currTag.attributesRange)
currTag.attributesRange[1] = token.marker;
if (currTag.parent)
currTag = currTag.parent;
if (currTag.isNamespace)
currTag = currTag.parent;
anon = true;
}
lastWasEnd = true;
} else if (token.type == "block-start") {
inIdentifier = false;
if (anon) {
if (!currTag.tags[""])
currTag.tags[""] = [{
attributes: {},
namespaces: {},
tags: {},
values: [],
parent: currTag.parent || currTag,
range: [token.marker, sdl.length]
}];
currTag = currTag.tags[""][0];
}
else {
if (currTag.range)
currTag.range[1] = token.marker;
if (currTag.attributesRange)
currTag.attributesRange[1] = token.marker;
anon = true;
}
} else if (token.type == "block-end") {
inIdentifier = false;
if (currTag.range)
currTag.range[1] = token.marker;
if (anon && currTag.parent && currTag.parent.range)
currTag.parent.range[1] = token.marker;
if (currTag.parent)
currTag = currTag.parent;
else
root.errors!.push({ range: [token.marker - 1, token.marker], message: "Invalid block end", type: "error" });
if (currTag.isNamespace)
currTag = currTag.parent;
} else throw "Unknown token type '" + token.type + "'";
}
return root;
} | the_stack |
import { strict as assert } from "assert";
import config from "../../src/config";
import { matrixClient, mjolnir } from "./mjolnirSetupUtils";
import { newTestUser } from "./clientHelper";
import { ReportManager, ABUSE_ACTION_CONFIRMATION_KEY, ABUSE_REPORT_KEY } from "../../src/report/ReportManager";
/**
* Test the ability to turn abuse reports into room messages.
*/
const REPORT_NOTICE_REGEXPS = {
reporter: /Filed by (?<reporterDisplay>[^ ]*) \((?<reporterId>[^ ]*)\)/,
accused: /Against (?<accusedDisplay>[^ ]*) \((?<accusedId>[^ ]*)\)/,
room: /Room (?<roomAliasOrId>[^ ]*)/,
event: /Event (?<eventId>[^ ]*) Go to event/,
content: /Content (?<eventContent>.*)/,
comments: /Comments Comments (?<comments>.*)/
};
describe("Test: Reporting abuse", async () => {
it('Mjölnir intercepts abuse reports', async function() {
this.timeout(10000);
// Listen for any notices that show up.
let notices = [];
matrixClient().on("room.event", (roomId, event) => {
if (roomId = config.managementRoom) {
notices.push(event);
}
});
// Create a few users and a room.
let goodUser = await newTestUser(false, "reporting-abuse-good-user");
let badUser = await newTestUser(false, "reporting-abuse-bad-user");
let goodUserId = await goodUser.getUserId();
let badUserId = await badUser.getUserId();
let roomId = await goodUser.createRoom({ invite: [await badUser.getUserId()] });
await goodUser.inviteUser(await badUser.getUserId(), roomId);
await badUser.joinRoom(roomId);
console.log("Test: Reporting abuse - send messages");
// Exchange a few messages.
let goodText = `GOOD: ${Math.random()}`; // Will NOT be reported.
let badText = `BAD: ${Math.random()}`; // Will be reported as abuse.
let badText2 = `BAD: ${Math.random()}`; // Will be reported as abuse.
let badText3 = `<b>BAD</b>: ${Math.random()}`; // Will be reported as abuse.
let badText4 = [...Array(1024)].map(_ => `${Math.random()}`).join(""); // Text is too long.
let badText5 = [...Array(1024)].map(_ => "ABC").join("\n"); // Text has too many lines.
let goodEventId = await goodUser.sendText(roomId, goodText);
let badEventId = await badUser.sendText(roomId, badText);
let badEventId2 = await badUser.sendText(roomId, badText2);
let badEventId3 = await badUser.sendText(roomId, badText3);
let badEventId4 = await badUser.sendText(roomId, badText4);
let badEventId5 = await badUser.sendText(roomId, badText5);
let badEvent2Comment = `COMMENT: ${Math.random()}`;
console.log("Test: Reporting abuse - send reports");
let reportsToFind = []
// Time to report, first without a comment, then with one.
try {
await goodUser.doRequest("POST", `/_matrix/client/r0/rooms/${encodeURIComponent(roomId)}/report/${encodeURIComponent(badEventId)}`);
reportsToFind.push({
reporterId: goodUserId,
accusedId: badUserId,
eventId: badEventId,
text: badText,
comment: null,
});
} catch (e) {
console.error("Could not send first report", e.body || e);
throw e;
}
try {
await goodUser.doRequest("POST", `/_matrix/client/r0/rooms/${encodeURIComponent(roomId)}/report/${encodeURIComponent(badEventId2)}`, "", {
reason: badEvent2Comment
});
reportsToFind.push({
reporterId: goodUserId,
accusedId: badUserId,
eventId: badEventId2,
text: badText2,
comment: badEvent2Comment,
});
} catch (e) {
console.error("Could not send second report", e.body || e);
throw e;
}
try {
await goodUser.doRequest("POST", `/_matrix/client/r0/rooms/${encodeURIComponent(roomId)}/report/${encodeURIComponent(badEventId3)}`, "");
reportsToFind.push({
reporterId: goodUserId,
accusedId: badUserId,
eventId: badEventId3,
text: badText3,
comment: null,
});
} catch (e) {
console.error("Could not send third report", e.body || e);
throw e;
}
try {
await goodUser.doRequest("POST", `/_matrix/client/r0/rooms/${encodeURIComponent(roomId)}/report/${encodeURIComponent(badEventId4)}`, "");
reportsToFind.push({
reporterId: goodUserId,
accusedId: badUserId,
eventId: badEventId4,
text: null,
textPrefix: badText4.substring(0, 256),
comment: null,
});
} catch (e) {
console.error("Could not send fourth report", e.body || e);
throw e;
}
try {
await goodUser.doRequest("POST", `/_matrix/client/r0/rooms/${encodeURIComponent(roomId)}/report/${encodeURIComponent(badEventId5)}`, "");
reportsToFind.push({
reporterId: goodUserId,
accusedId: badUserId,
eventId: badEventId5,
text: null,
textPrefix: badText5.substring(0, 256).split("\n").join(" "),
comment: null,
});
} catch (e) {
console.error("Could not send fifth report", e.body || e);
throw e;
}
console.log("Test: Reporting abuse - wait");
await new Promise(resolve => setTimeout(resolve, 1000));
let found = [];
for (let toFind of reportsToFind) {
for (let event of notices) {
if ("content" in event && "body" in event.content) {
if (!(ABUSE_REPORT_KEY in event.content) || event.content[ABUSE_REPORT_KEY].event_id != toFind.eventId) {
// Not a report or not our report.
continue;
}
let report = event.content[ABUSE_REPORT_KEY];
let body = event.content.body as string;
let matches = new Map();
for (let key of Object.keys(REPORT_NOTICE_REGEXPS)) {
let match = body.match(REPORT_NOTICE_REGEXPS[key]);
if (match) {
console.debug("We have a match", key, REPORT_NOTICE_REGEXPS[key], match.groups);
} else {
console.debug("Not a match", key, REPORT_NOTICE_REGEXPS[key]);
// Not a report, skipping.
matches = null;
break;
}
matches.set(key, match);
}
if (!matches) {
// Not a report, skipping.
continue;
}
assert(body.length < 3000, `The report shouldn't be too long ${body.length}`);
assert(body.split("\n").length < 200, "The report shouldn't have too many newlines.");
assert.equal(matches.get("event")!.groups.eventId, toFind.eventId, "The report should specify the correct event id");;
assert.equal(matches.get("reporter")!.groups.reporterId, toFind.reporterId, "The report should specify the correct reporter");
assert.equal(report.reporter_id, toFind.reporterId, "The embedded report should specify the correct reporter");
assert.ok(toFind.reporterId.includes(matches.get("reporter")!.groups.reporterDisplay), "The report should display the correct reporter");
assert.equal(matches.get("accused")!.groups.accusedId, toFind.accusedId, "The report should specify the correct accused");
assert.equal(report.accused_id, toFind.accusedId, "The embedded report should specify the correct accused");
assert.ok(toFind.accusedId.includes(matches.get("accused")!.groups.accusedDisplay), "The report should display the correct reporter");
if (toFind.text) {
assert.equal(matches.get("content")!.groups.eventContent, toFind.text, "The report should contain the text we inserted in the event");
}
if (toFind.textPrefix) {
assert.ok(matches.get("content")!.groups.eventContent.startsWith(toFind.textPrefix), `The report should contain a prefix of the long text we inserted in the event: ${toFind.textPrefix} in? ${matches.get("content")!.groups.eventContent}`);
}
if (toFind.comment) {
assert.equal(matches.get("comments")!.groups.comments, toFind.comment, "The report should contain the comment we added");
}
assert.equal(matches.get("room")!.groups.roomAliasOrId, roomId, "The report should specify the correct room");
assert.equal(report.room_id, roomId, "The embedded report should specify the correct room");
found.push(toFind);
break;
}
}
}
assert.deepEqual(found, reportsToFind);
// Since Mjölnir is not a member of the room, the only buttons we should find
// are `help` and `ignore`.
for (let event of notices) {
if (event.content && event.content["m.relates_to"] && event.content["m.relates_to"]["key"]) {
let regexp = /\/([[^]]*)\]/;
let matches = event.content["m.relates_to"]["key"].match(regexp);
if (!matches) {
continue;
}
switch (matches[1]) {
case "bad-report":
case "help":
continue;
default:
throw new Error(`Didn't expect label ${matches[1]}`);
}
}
}
});
it('The redact action works', async function() {
this.timeout(10000);
// Listen for any notices that show up.
let notices = [];
matrixClient().on("room.event", (roomId, event) => {
if (roomId = config.managementRoom) {
notices.push(event);
}
});
// Create a moderator.
let moderatorUser = await newTestUser(false, "reacting-abuse-moderator-user");
matrixClient().inviteUser(await moderatorUser.getUserId(), config.managementRoom);
await moderatorUser.joinRoom(config.managementRoom);
// Create a few users and a room.
let goodUser = await newTestUser(false, "reacting-abuse-good-user");
let badUser = await newTestUser(false, "reacting-abuse-bad-user");
let goodUserId = await goodUser.getUserId();
let badUserId = await badUser.getUserId();
let roomId = await moderatorUser.createRoom({ invite: [await badUser.getUserId()] });
await moderatorUser.inviteUser(await goodUser.getUserId(), roomId);
await moderatorUser.inviteUser(await badUser.getUserId(), roomId);
await badUser.joinRoom(roomId);
await goodUser.joinRoom(roomId);
// Setup Mjölnir as moderator for our room.
await moderatorUser.inviteUser(await matrixClient().getUserId(), roomId);
await moderatorUser.setUserPowerLevel(await matrixClient().getUserId(), roomId, 100);
console.log("Test: Reporting abuse - send messages");
// Exchange a few messages.
let goodText = `GOOD: ${Math.random()}`; // Will NOT be reported.
let badText = `BAD: ${Math.random()}`; // Will be reported as abuse.
let goodEventId = await goodUser.sendText(roomId, goodText);
let badEventId = await badUser.sendText(roomId, badText);
let goodEventId2 = await goodUser.sendText(roomId, goodText);
console.log("Test: Reporting abuse - send reports");
// Time to report.
let reportToFind = {
reporterId: goodUserId,
accusedId: badUserId,
eventId: badEventId,
text: badText,
comment: null,
};
try {
await goodUser.doRequest("POST", `/_matrix/client/r0/rooms/${encodeURIComponent(roomId)}/report/${encodeURIComponent(badEventId)}`);
} catch (e) {
console.error("Could not send first report", e.body || e);
throw e;
}
console.log("Test: Reporting abuse - wait");
await new Promise(resolve => setTimeout(resolve, 1000));
let mjolnirRooms = new Set(await matrixClient().getJoinedRooms());
assert.ok(mjolnirRooms.has(roomId), "Mjölnir should be a member of the room");
// Find the notice
let noticeId;
for (let event of notices) {
if ("content" in event && ABUSE_REPORT_KEY in event.content) {
if (!(ABUSE_REPORT_KEY in event.content) || event.content[ABUSE_REPORT_KEY].event_id != badEventId) {
// Not a report or not our report.
continue;
}
noticeId = event.event_id;
break;
}
}
assert.ok(noticeId, "We should have found our notice");
// Find the buttons.
let buttons = [];
for (let event of notices) {
if (event["type"] != "m.reaction") {
continue;
}
if (event["content"]["m.relates_to"]["rel_type"] != "m.annotation") {
continue;
}
if (event["content"]["m.relates_to"]["event_id"] != noticeId) {
continue;
}
buttons.push(event);
}
// Find the redact button... and click it.
let redactButtonId = null;
for (let button of buttons) {
if (button["content"]["m.relates_to"]["key"].includes("[redact-message]")) {
redactButtonId = button["event_id"];
await moderatorUser.sendEvent(config.managementRoom, "m.reaction", button["content"]);
break;
}
}
assert.ok(redactButtonId, "We should have found the redact button");
await new Promise(resolve => setTimeout(resolve, 1000));
// This should have triggered a confirmation request, with more buttons!
let confirmEventId = null;
for (let event of notices) {
console.debug("Is this the confirm button?", event);
if (!event["content"]["m.relates_to"]) {
console.debug("Not a reaction");
continue;
}
if (!event["content"]["m.relates_to"]["key"].includes("[confirm]")) {
console.debug("Not confirm");
continue;
}
if (!event["content"]["m.relates_to"]["event_id"] == redactButtonId) {
console.debug("Not reaction to redact button");
continue;
}
// It's the confirm button, click it!
confirmEventId = event["event_id"];
await moderatorUser.sendEvent(config.managementRoom, "m.reaction", event["content"]);
break;
}
assert.ok(confirmEventId, "We should have found the confirm button");
await new Promise(resolve => setTimeout(resolve, 1000));
// This should have redacted the message.
let newBadEvent = await matrixClient().getEvent(roomId, badEventId);
assert.deepEqual(Object.keys(newBadEvent.content), [], "Redaction should have removed the content of the offending event");
});
}); | the_stack |
import { ViewPortInstruction, RouteConfig, ViewPort, LifecycleArguments, ViewPortComponent } from './interfaces';
import { Router } from './router';
import { ActivationStrategyType, InternalActivationStrategy } from './activation-strategy';
/**
* Initialization options for a navigation instruction
*/
export interface NavigationInstructionInit {
fragment: string;
queryString?: string;
params?: Record<string, any>;
queryParams?: Record<string, any>;
config: RouteConfig;
parentInstruction?: NavigationInstruction;
previousInstruction?: NavigationInstruction;
router: Router;
options?: Object;
plan?: Record<string, /*ViewPortInstruction*/any>;
}
export interface ViewPortInstructionInit {
name: string;
strategy: ActivationStrategyType;
moduleId: string;
component: ViewPortComponent;
}
/**
* Class used to represent an instruction during a navigation.
*/
export class NavigationInstruction {
/**
* The URL fragment.
*/
fragment: string;
/**
* The query string.
*/
queryString: string;
/**
* Parameters extracted from the route pattern.
*/
params: any;
/**
* Parameters extracted from the query string.
*/
queryParams: any;
/**
* The route config for the route matching this instruction.
*/
config: RouteConfig;
/**
* The parent instruction, if this instruction was created by a child router.
*/
parentInstruction: NavigationInstruction;
parentCatchHandler: any;
/**
* The instruction being replaced by this instruction in the current router.
*/
previousInstruction: NavigationInstruction;
/**
* viewPort instructions to used activation.
*/
viewPortInstructions: Record<string, /*ViewPortInstruction*/any>;
/**
* The router instance.
*/
router: Router;
/**
* Current built viewport plan of this nav instruction
*/
plan: Record<string, /*ViewPortPlan*/any> = null;
options: Record<string, any> = {};
/**@internal */
lifecycleArgs: LifecycleArguments;
/**@internal */
resolve?: (val?: any) => void;
constructor(init: NavigationInstructionInit) {
Object.assign(this, init);
this.params = this.params || {};
this.viewPortInstructions = {};
let ancestorParams = [];
let current: NavigationInstruction = this;
do {
let currentParams = Object.assign({}, current.params);
if (current.config && current.config.hasChildRouter) {
// remove the param for the injected child route segment
delete currentParams[current.getWildCardName()];
}
ancestorParams.unshift(currentParams);
current = current.parentInstruction;
} while (current);
let allParams = Object.assign({}, this.queryParams, ...ancestorParams);
this.lifecycleArgs = [allParams, this.config, this];
}
/**
* Gets an array containing this instruction and all child instructions for the current navigation.
*/
getAllInstructions(): Array<NavigationInstruction> {
let instructions: NavigationInstruction[] = [this];
let viewPortInstructions: Record<string, ViewPortInstruction> = this.viewPortInstructions;
for (let key in viewPortInstructions) {
let childInstruction = viewPortInstructions[key].childNavigationInstruction;
if (childInstruction) {
instructions.push(...childInstruction.getAllInstructions());
}
}
return instructions;
}
/**
* Gets an array containing the instruction and all child instructions for the previous navigation.
* Previous instructions are no longer available after navigation completes.
*/
getAllPreviousInstructions(): Array<NavigationInstruction> {
return this.getAllInstructions().map(c => c.previousInstruction).filter(c => c);
}
/**
* Adds a viewPort instruction. Returns the newly created instruction based on parameters
*/
addViewPortInstruction(initOptions: ViewPortInstructionInit): /*ViewPortInstruction*/ any;
addViewPortInstruction(viewPortName: string, strategy: ActivationStrategyType, moduleId: string, component: any): /*ViewPortInstruction*/ any;
addViewPortInstruction(
nameOrInitOptions: string | ViewPortInstructionInit,
strategy?: ActivationStrategyType,
moduleId?: string,
component?: any
): /*ViewPortInstruction*/ any {
let viewPortInstruction: ViewPortInstruction;
let viewPortName = typeof nameOrInitOptions === 'string' ? nameOrInitOptions : nameOrInitOptions.name;
const lifecycleArgs = this.lifecycleArgs;
const config: RouteConfig = Object.assign({}, lifecycleArgs[1], { currentViewPort: viewPortName });
if (typeof nameOrInitOptions === 'string') {
viewPortInstruction = {
name: nameOrInitOptions,
strategy: strategy,
moduleId: moduleId,
component: component,
childRouter: component.childRouter,
lifecycleArgs: [lifecycleArgs[0], config, lifecycleArgs[2]] as LifecycleArguments
};
} else {
viewPortInstruction = {
name: viewPortName,
strategy: nameOrInitOptions.strategy,
component: nameOrInitOptions.component,
moduleId: nameOrInitOptions.moduleId,
childRouter: nameOrInitOptions.component.childRouter,
lifecycleArgs: [lifecycleArgs[0], config, lifecycleArgs[2]] as LifecycleArguments
};
}
return this.viewPortInstructions[viewPortName] = viewPortInstruction;
}
/**
* Gets the name of the route pattern's wildcard parameter, if applicable.
*/
getWildCardName(): string {
// todo: potential issue, or at least unsafe typings
let configRoute = this.config.route as string;
let wildcardIndex = configRoute.lastIndexOf('*');
return configRoute.substr(wildcardIndex + 1);
}
/**
* Gets the path and query string created by filling the route
* pattern's wildcard parameter with the matching param.
*/
getWildcardPath(): string {
let wildcardName = this.getWildCardName();
let path = this.params[wildcardName] || '';
let queryString = this.queryString;
if (queryString) {
path += '?' + queryString;
}
return path;
}
/**
* Gets the instruction's base URL, accounting for wildcard route parameters.
*/
getBaseUrl(): string {
let $encodeURI = encodeURI;
let fragment = decodeURI(this.fragment);
if (fragment === '') {
let nonEmptyRoute = this.router.routes.find(route => {
return route.name === this.config.name &&
route.route !== '';
});
if (nonEmptyRoute) {
fragment = nonEmptyRoute.route as any;
}
}
if (!this.params) {
return $encodeURI(fragment);
}
let wildcardName = this.getWildCardName();
let path = this.params[wildcardName] || '';
if (!path) {
return $encodeURI(fragment);
}
return $encodeURI(fragment.substr(0, fragment.lastIndexOf(path)));
}
/**
* Finalize a viewport instruction
* @internal
*/
_commitChanges(waitToSwap: boolean): Promise<void> {
let router = this.router;
router.currentInstruction = this;
const previousInstruction = this.previousInstruction;
if (previousInstruction) {
previousInstruction.config.navModel.isActive = false;
}
this.config.navModel.isActive = true;
router.refreshNavigation();
let loads: Promise<void>[] = [];
let delaySwaps: ISwapPlan[] = [];
let viewPortInstructions: Record<string, ViewPortInstruction> = this.viewPortInstructions;
for (let viewPortName in viewPortInstructions) {
let viewPortInstruction = viewPortInstructions[viewPortName];
let viewPort = router.viewPorts[viewPortName];
if (!viewPort) {
throw new Error(`There was no router-view found in the view for ${viewPortInstruction.moduleId}.`);
}
let childNavInstruction = viewPortInstruction.childNavigationInstruction;
if (viewPortInstruction.strategy === InternalActivationStrategy.Replace) {
if (childNavInstruction && childNavInstruction.parentCatchHandler) {
loads.push(childNavInstruction._commitChanges(waitToSwap));
} else {
if (waitToSwap) {
delaySwaps.push({ viewPort, viewPortInstruction });
}
loads.push(
viewPort
.process(viewPortInstruction, waitToSwap)
.then(() => childNavInstruction
? childNavInstruction._commitChanges(waitToSwap)
: Promise.resolve()
)
);
}
} else {
if (childNavInstruction) {
loads.push(childNavInstruction._commitChanges(waitToSwap));
}
}
}
return Promise
.all(loads)
.then(() => {
delaySwaps.forEach(x => x.viewPort.swap(x.viewPortInstruction));
return null;
})
.then(() => prune(this));
}
/**@internal */
_updateTitle(): void {
let router = this.router;
let title = this._buildTitle(router.titleSeparator);
if (title) {
router.history.setTitle(title);
}
}
/**@internal */
_buildTitle(separator: string = ' | '): string {
let title = '';
let childTitles = [];
let navModelTitle = this.config.navModel.title;
let instructionRouter = this.router;
let viewPortInstructions: Record<string, ViewPortInstruction> = this.viewPortInstructions;
if (navModelTitle) {
title = instructionRouter.transformTitle(navModelTitle);
}
for (let viewPortName in viewPortInstructions) {
let viewPortInstruction = viewPortInstructions[viewPortName];
let child_nav_instruction = viewPortInstruction.childNavigationInstruction;
if (child_nav_instruction) {
let childTitle = child_nav_instruction._buildTitle(separator);
if (childTitle) {
childTitles.push(childTitle);
}
}
}
if (childTitles.length) {
title = childTitles.join(separator) + (title ? separator : '') + title;
}
if (instructionRouter.title) {
title += (title ? separator : '') + instructionRouter.transformTitle(instructionRouter.title);
}
return title;
}
}
const prune = (instruction: NavigationInstruction): void => {
instruction.previousInstruction = null;
instruction.plan = null;
};
interface ISwapPlan {
viewPort: ViewPort;
viewPortInstruction: ViewPortInstruction;
} | the_stack |
import { AuthenticationVirtualMachine } from '../../vm/virtual-machine';
import {
AuthenticationProgramStateExecutionStack,
AuthenticationProgramStateMinimum,
AuthenticationProgramStateStack,
} from '../../vm/vm-types';
import { createCompilerCommonSynchronous } from '../compiler';
import { CompilationData, CompilationEnvironment } from '../compiler-types';
import { CompilationResult, CompilationResultSuccess } from './language-types';
import { getResolutionErrors } from './language-utils';
import { parseScript } from './parse';
import { reduceScript } from './reduce';
import { createIdentifierResolver, resolveScriptSegment } from './resolve';
/**
* A text-formatting method to pretty-print the list of expected inputs
* (`Encountered unexpected input while parsing script. Expected ...`). If
* present, the `EOF` expectation is always moved to the end of the list.
* @param expectedArray - the alphabetized list of expected inputs produced by
* `parseScript`
*/
export const describeExpectedInput = (expectedArray: string[]) => {
/**
* The constant used by the parser to denote the end of the input
*/
const EOF = 'EOF';
const newArray = expectedArray.filter((value) => value !== EOF);
// eslint-disable-next-line functional/no-conditional-statement
if (newArray.length !== expectedArray.length) {
// eslint-disable-next-line functional/no-expression-statement, functional/immutable-data
newArray.push('the end of the script');
}
const withoutLastElement = newArray.slice(0, newArray.length - 1);
const lastElement = newArray[newArray.length - 1];
const arrayRequiresCommas = 3;
const arrayRequiresOr = 2;
return `Encountered unexpected input while parsing script. Expected ${
newArray.length >= arrayRequiresCommas
? withoutLastElement.join(', ').concat(`, or ${lastElement}`)
: newArray.length === arrayRequiresOr
? newArray.join(' or ')
: lastElement
}.`;
};
/**
* This method is generally for internal use. The `compileScript` method is the
* recommended API for direct compilation.
*/
export const compileScriptContents = <
ProgramState extends AuthenticationProgramStateStack &
AuthenticationProgramStateExecutionStack = AuthenticationProgramStateStack &
AuthenticationProgramStateExecutionStack,
TransactionContext = unknown
>({
data,
environment,
script,
}: {
script: string;
data: CompilationData<TransactionContext>;
environment: CompilationEnvironment<TransactionContext>;
}): CompilationResult<ProgramState> => {
const parseResult = parseScript(script);
if (!parseResult.status) {
return {
errorType: 'parse',
errors: [
{
error: describeExpectedInput(parseResult.expected),
range: {
endColumn: parseResult.index.column,
endLineNumber: parseResult.index.line,
startColumn: parseResult.index.column,
startLineNumber: parseResult.index.line,
},
},
],
success: false,
};
}
const resolver = createIdentifierResolver({ data, environment });
const resolvedScript = resolveScriptSegment(parseResult.value, resolver);
const resolutionErrors = getResolutionErrors(resolvedScript);
if (resolutionErrors.length !== 0) {
return {
errorType: 'resolve',
errors: resolutionErrors,
parse: parseResult.value,
resolve: resolvedScript,
success: false,
};
}
const reduction = reduceScript<ProgramState, unknown>(
resolvedScript,
environment.vm,
environment.createAuthenticationProgram
);
return {
...(reduction.errors === undefined
? { bytecode: reduction.bytecode, success: true }
: { errorType: 'reduce', errors: reduction.errors, success: false }),
parse: parseResult.value,
reduce: reduction,
resolve: resolvedScript,
};
};
const emptyRange = () => ({
endColumn: 0,
endLineNumber: 0,
startColumn: 0,
startLineNumber: 0,
});
/**
* This method is generally for internal use. The `compileScript` method is the
* recommended API for direct compilation.
*/
export const compileScriptRaw = <
ProgramState extends AuthenticationProgramStateStack &
AuthenticationProgramStateExecutionStack &
AuthenticationProgramStateMinimum = AuthenticationProgramStateStack &
AuthenticationProgramStateExecutionStack &
AuthenticationProgramStateMinimum,
TransactionContext = unknown
>({
data,
environment,
scriptId,
}: {
data: CompilationData<TransactionContext>;
environment: CompilationEnvironment<TransactionContext>;
scriptId: string;
}): CompilationResult<ProgramState> => {
const script = environment.scripts[scriptId] as string | undefined;
if (script === undefined) {
return {
errorType: 'parse',
errors: [
{
error: `No script with an ID of "${scriptId}" was provided in the compilation environment.`,
range: emptyRange(),
},
],
success: false,
};
}
if (environment.sourceScriptIds?.includes(scriptId) === true) {
return {
errorType: 'parse',
errors: [
{
error: `A circular dependency was encountered: script "${scriptId}" relies on itself to be generated. (Source scripts: ${environment.sourceScriptIds.join(
' → '
)})`,
range: emptyRange(),
},
],
success: false,
};
}
const sourceScriptIds =
environment.sourceScriptIds === undefined
? [scriptId]
: [...environment.sourceScriptIds, scriptId];
return compileScriptContents<ProgramState, TransactionContext>({
data,
environment: { ...environment, sourceScriptIds },
script,
});
};
export const compileScriptP2shLocking = <AuthenticationProgram, ProgramState>({
lockingBytecode,
vm,
}: {
lockingBytecode: Uint8Array;
vm:
| AuthenticationVirtualMachine<AuthenticationProgram, ProgramState>
| undefined;
}) => {
const compiler = createCompilerCommonSynchronous({
scripts: {
p2shLocking: 'OP_HASH160 <$(<lockingBytecode> OP_HASH160)> OP_EQUAL',
},
variables: { lockingBytecode: { type: 'AddressData' } },
vm,
});
return compiler.generateBytecode('p2shLocking', {
bytecode: { lockingBytecode },
});
};
export const compileScriptP2shUnlocking = <ProgramState>({
lockingBytecode,
unlockingBytecode,
}: {
lockingBytecode: Uint8Array;
unlockingBytecode: Uint8Array;
}) => {
const compiler = createCompilerCommonSynchronous({
scripts: {
p2shUnlocking: 'unlockingBytecode <lockingBytecode>',
},
variables: {
lockingBytecode: { type: 'AddressData' },
unlockingBytecode: { type: 'AddressData' },
},
});
return compiler.generateBytecode('p2shUnlocking', {
bytecode: { lockingBytecode, unlockingBytecode },
}) as CompilationResultSuccess<ProgramState>;
};
/**
* Parse, resolve, and reduce the selected script using the provided `data` and
* `environment`.
*
* Note, locktime validation only occurs if `transactionContext` is provided in
* the environment.
*/
// eslint-disable-next-line complexity
export const compileScript = <
ProgramState extends AuthenticationProgramStateStack &
AuthenticationProgramStateExecutionStack &
AuthenticationProgramStateMinimum = AuthenticationProgramStateStack &
AuthenticationProgramStateExecutionStack &
AuthenticationProgramStateMinimum,
TransactionContext extends { locktime: number; sequenceNumber: number } = {
locktime: number;
sequenceNumber: number;
}
>(
scriptId: string,
data: CompilationData<TransactionContext>,
environment: CompilationEnvironment<TransactionContext>
): CompilationResult<ProgramState> => {
const locktimeDisablingSequenceNumber = 0xffffffff;
const lockTimeTypeBecomesTimestamp = 500000000;
if (data.transactionContext?.locktime !== undefined) {
if (
environment.unlockingScriptTimeLockTypes?.[scriptId] === 'height' &&
data.transactionContext.locktime >= lockTimeTypeBecomesTimestamp
) {
return {
errorType: 'parse',
errors: [
{
error: `The script "${scriptId}" requires a height-based locktime (less than 500,000,000), but this transaction uses a timestamp-based locktime ("${data.transactionContext.locktime}").`,
range: emptyRange(),
},
],
success: false,
};
}
if (
environment.unlockingScriptTimeLockTypes?.[scriptId] === 'timestamp' &&
data.transactionContext.locktime < lockTimeTypeBecomesTimestamp
) {
return {
errorType: 'parse',
errors: [
{
error: `The script "${scriptId}" requires a timestamp-based locktime (greater than or equal to 500,000,000), but this transaction uses a height-based locktime ("${data.transactionContext.locktime}").`,
range: emptyRange(),
},
],
success: false,
};
}
}
if (
data.transactionContext?.sequenceNumber !== undefined &&
environment.unlockingScriptTimeLockTypes?.[scriptId] !== undefined &&
data.transactionContext.sequenceNumber === locktimeDisablingSequenceNumber
) {
return {
errorType: 'parse',
errors: [
{
error: `The script "${scriptId}" requires a locktime, but this input's sequence number is set to disable transaction locktime (0xffffffff). This will cause the OP_CHECKLOCKTIMEVERIFY operation to error when the transaction is verified. To be valid, this input must use a sequence number which does not disable locktime.`,
range: emptyRange(),
},
],
success: false,
};
}
const rawResult = compileScriptRaw<ProgramState, TransactionContext>({
data,
environment,
scriptId,
});
if (!rawResult.success) {
return rawResult;
}
const unlocks = environment.unlockingScripts?.[scriptId];
const unlockingScriptType =
unlocks === undefined
? undefined
: environment.lockingScriptTypes?.[unlocks];
const isP2shUnlockingScript = unlockingScriptType === 'p2sh';
const lockingScriptType = environment.lockingScriptTypes?.[scriptId];
const isP2shLockingScript = lockingScriptType === 'p2sh';
if (isP2shLockingScript) {
const transformedResult = compileScriptP2shLocking<unknown, ProgramState>({
lockingBytecode: rawResult.bytecode,
vm: environment.vm,
});
if (!transformedResult.success) {
return transformedResult;
}
return {
...rawResult,
bytecode: transformedResult.bytecode,
transformed: 'p2sh-locking',
};
}
if (isP2shUnlockingScript) {
const lockingBytecodeResult = compileScriptRaw<
ProgramState,
TransactionContext
>({
data,
environment,
scriptId: unlocks as string,
});
if (!lockingBytecodeResult.success) {
return lockingBytecodeResult;
}
const transformedResult = compileScriptP2shUnlocking<ProgramState>({
lockingBytecode: lockingBytecodeResult.bytecode,
unlockingBytecode: rawResult.bytecode,
});
return {
...rawResult,
bytecode: transformedResult.bytecode,
transformed: 'p2sh-unlocking',
};
}
return rawResult;
}; | the_stack |
import isObj from "lodash.isplainobject";
import trim from "lodash.trim";
import without from "lodash.without";
import { decode } from "html-entities";
import { rApply } from "ranges-apply";
import { Ranges } from "ranges-push";
import { right } from "string-left-right";
import {
characterSuitableForNames,
prepHopefullyAnArray,
notWithinAttrQuotes,
Obj,
} from "./util";
import { version as v } from "../package.json";
const version: string = v;
import { Range, Ranges as RangesType } from "../../../scripts/common";
interface Tag {
attributes: string[];
lastClosingBracketAt: number;
lastOpeningBracketAt: number;
slashPresent: number;
leftOuterWhitespace: number;
onlyPlausible: boolean;
nameStarts: number;
nameContainsLetters: boolean;
nameEnds: number;
name: string;
}
interface CbObj {
tag: Tag;
deleteFrom: null | number;
deleteTo: null | number;
insert: null | string;
rangesArr: Ranges;
proposedReturn: Range | null;
}
interface Opts {
ignoreTags: string[];
onlyStripTags: string[];
stripTogetherWithTheirContents: string[];
skipHtmlDecoding: boolean;
trimOnlySpaces: boolean;
dumpLinkHrefsNearby: {
enabled: boolean;
putOnNewLine: boolean;
wrapHeads: string;
wrapTails: string;
};
cb: null | ((cbObj: CbObj) => void);
}
const defaults = {
ignoreTags: [],
onlyStripTags: [],
stripTogetherWithTheirContents: ["script", "style", "xml"],
skipHtmlDecoding: false,
trimOnlySpaces: false,
dumpLinkHrefsNearby: {
enabled: false,
putOnNewLine: false,
wrapHeads: "",
wrapTails: "",
},
cb: null,
};
interface Res {
log: {
timeTakenInMilliseconds: number;
};
result: string;
ranges: RangesType;
allTagLocations: [number, number][];
filteredTagLocations: [number, number][];
}
/**
* Strips HTML tags from strings. No parser, accepts mixed sources.
*/
function stripHtml(str: string, originalOpts?: Partial<Opts>): Res {
// const
// ===========================================================================
const start = Date.now();
const definitelyTagNames = new Set([
"!doctype",
"abbr",
"address",
"area",
"article",
"aside",
"audio",
"base",
"bdi",
"bdo",
"blockquote",
"body",
"br",
"button",
"canvas",
"caption",
"cite",
"code",
"col",
"colgroup",
"data",
"datalist",
"dd",
"del",
"details",
"dfn",
"dialog",
"div",
"dl",
"doctype",
"dt",
"em",
"embed",
"fieldset",
"figcaption",
"figure",
"footer",
"form",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"head",
"header",
"hgroup",
"hr",
"html",
"iframe",
"img",
"input",
"ins",
"kbd",
"keygen",
"label",
"legend",
"li",
"link",
"main",
"map",
"mark",
"math",
"menu",
"menuitem",
"meta",
"meter",
"nav",
"noscript",
"object",
"ol",
"optgroup",
"option",
"output",
"param",
"picture",
"pre",
"progress",
"rb",
"rp",
"rt",
"rtc",
"ruby",
"samp",
"script",
"section",
"select",
"slot",
"small",
"source",
"span",
"strong",
"style",
"sub",
"summary",
"sup",
"svg",
"table",
"tbody",
"td",
"template",
"textarea",
"tfoot",
"th",
"thead",
"time",
"title",
"tr",
"track",
"ul",
"var",
"video",
"wbr",
"xml",
]);
const singleLetterTags = new Set(["a", "b", "i", "p", "q", "s", "u"]);
const punctuation = new Set([
".",
",",
"?",
";",
")",
"\u2026",
'"',
"\u00BB",
]);
// \u00BB is » - guillemet - right angled quote
// \u2026 is … - ellipsis
// we'll gather opening tags from ranged-pairs here:
const rangedOpeningTags: Obj[] = [];
// we'll put tag locations here
const allTagLocations: [number, number][] = [];
let filteredTagLocations: [number, number][] = [];
// variables
// ===========================================================================
// records the info about the suspected tag:
let tag: Obj = {};
function resetTag() {
tag = { attributes: [] };
}
resetTag();
// records the beginning of the current whitespace chunk:
let chunkOfWhitespaceStartsAt = null;
// records the beginning of the current chunk of spaces (strictly spaces-only):
let chunkOfSpacesStartsAt = null;
// temporary variable to assemble the attribute pieces:
let attrObj: Obj = {};
// marker to store captured href, used in opts.dumpLinkHrefsNearby.enabled
let hrefDump: {
tagName: string;
hrefValue: string;
openingTagEnds: number | undefined;
} = {
tagName: "",
hrefValue: "",
openingTagEnds: undefined,
};
// used to insert extra things when pushing into ranges array
let stringToInsertAfter = "";
// state flag
let hrefInsertionActive = false;
// marker to keep a note where does the whitespace chunk that follows closing bracket end.
// It's necessary for opts.trimOnlySpaces when there's closing bracket, whitespace, non-space
// whitespace character ("\n", "\t" etc), whitspace, end-of-file. Trim will kick in and will
// try to trim up until the EOF, be we'll have to pull the end of trim back, back to the first
// character of aforementioned non-space whitespace character sequence.
// This variable will tell exactly where it is located.
let spacesChunkWhichFollowsTheClosingBracketEndsAt = null;
// functions
// ===========================================================================
function existy(x: any): boolean {
return x != null;
}
function isStr(something: any): boolean {
return typeof something === "string";
}
function treatRangedTags(i: number, opts: Opts, rangesToDelete: Ranges) {
console.log(`281 treatRangedTags(${i}) called`);
console.log(
`283 opts.stripTogetherWithTheirContents = ${JSON.stringify(
opts.stripTogetherWithTheirContents,
null,
0
)}; tag.name = ${tag.name}`
);
if (
Array.isArray(opts.stripTogetherWithTheirContents) &&
(opts.stripTogetherWithTheirContents.includes(tag.name) ||
opts.stripTogetherWithTheirContents.includes("*"))
) {
// it depends, is it opening or closing range tag:
// We could try to distinguish opening from closing tags by presence of
// slash, but that would be a liability for dirty code cases where clash
// is missing. Better, instead, just see if an entry for that tag name
// already exists in the rangesToDelete[].
console.log(
`302 FIY, ${`\u001b[${33}m${`rangedOpeningTags`}\u001b[${39}m`} = ${JSON.stringify(
rangedOpeningTags,
null,
4
)}`
);
if (
Array.isArray(rangedOpeningTags) &&
rangedOpeningTags.some(
(obj) => obj.name === tag.name && obj.lastClosingBracketAt < i
)
) {
// if (tag.slashPresent) {
console.log(
`316 \u001b[${31}m${`treatRangedTags():`}\u001b[${39}m closing ranged tag`
);
// closing tag.
// filter and remove the found tag
for (let y = rangedOpeningTags.length; y--; ) {
if (rangedOpeningTags[y].name === tag.name) {
// we'll remove from opening tag's opening bracket to closing tag's
// closing bracket because whitespace will be taken care of separately,
// when tags themselves will be removed.
// Basically, for each range tag there will be 3 removals:
// opening tag, closing tag and all from opening to closing tag.
// We keep removing opening and closing tags along whole range
// because of few reasons: 1. cases of broken/dirty code, 2. keeping
// the algorithm simpler, 3. opts that control whitespace removal
// around tags.
// 1. add range without caring about surrounding whitespace around
// the range
console.log(
`rangesToDelete.current(): ${JSON.stringify(
rangesToDelete.current(),
null,
0
)}`
);
console.log(
`343 ABOUT TO cb()-PUSH RANGE: [${rangedOpeningTags[y].lastOpeningBracketAt}, ${i}]`
);
// also, tend filteredTagLocations in the output - tags which are to be
// deleted with contents should be reported as one large range in
// filteredTagLocations - from opening to closing - not two ranges
console.log(
`351 FIY, ${`\u001b[${33}m${`rangedOpeningTags`}\u001b[${39}m`} = ${JSON.stringify(
rangedOpeningTags,
null,
4
)}`
);
/* istanbul ignore else */
if (
opts.stripTogetherWithTheirContents.includes(tag.name) ||
opts.stripTogetherWithTheirContents.includes("*")
) {
console.log(
`364 ${`\u001b[${33}m${`filteredTagLocations`}\u001b[${39}m`} BEFORE: ${JSON.stringify(
filteredTagLocations,
null,
4
)}`
);
filteredTagLocations = filteredTagLocations.filter(
([from, upto]) =>
(from < rangedOpeningTags[y].lastOpeningBracketAt ||
from >= i + 1) &&
(upto <= rangedOpeningTags[y].lastOpeningBracketAt ||
upto > i + 1)
);
console.log(
`378 ${`\u001b[${33}m${`filteredTagLocations`}\u001b[${39}m`} AFTER: ${JSON.stringify(
filteredTagLocations,
null,
4
)}`
);
}
let endingIdx = i + 1;
if (tag.lastClosingBracketAt) {
endingIdx = tag.lastClosingBracketAt + 1;
}
console.log(
`392 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${
rangedOpeningTags[y].lastOpeningBracketAt
}, ${endingIdx}] to filteredTagLocations`
);
filteredTagLocations.push([
rangedOpeningTags[y].lastOpeningBracketAt,
endingIdx,
]);
/* istanbul ignore else */
if (punctuation.has(str[i]) && opts.cb) {
opts.cb({
tag: tag as Tag,
deleteFrom: rangedOpeningTags[y].lastOpeningBracketAt,
deleteTo: i + 1,
insert: null,
rangesArr: rangesToDelete as any,
proposedReturn: [
rangedOpeningTags[y].lastOpeningBracketAt,
i,
null,
],
});
// null will remove any spaces added so far. Opening and closing range tags might
// have received spaces as separate entities, but those might not be necessary for range:
// "text <script>deleteme</script>."
} else if (opts.cb) {
opts.cb({
tag: tag as any,
deleteFrom: rangedOpeningTags[y].lastOpeningBracketAt,
deleteTo: i,
insert: "",
rangesArr: rangesToDelete as any,
proposedReturn: [
rangedOpeningTags[y].lastOpeningBracketAt,
i,
"",
],
});
}
// 2. delete the reference to this range from rangedOpeningTags[]
// because there might be more ranged tags of the same name or
// different, overlapping or encompassing ranged tags with same
// or different name.
rangedOpeningTags.splice(y, 1);
console.log(
`438 new \u001b[${33}m${`rangedOpeningTags`}\u001b[${39}m = ${JSON.stringify(
rangedOpeningTags,
null,
4
)}`
);
// 3. stop the loop
break;
}
}
} else {
// opening tag.
console.log(
`451 \u001b[${31}m${`treatRangedTags():`}\u001b[${39}m opening ranged tag`
);
rangedOpeningTags.push(tag);
console.log(
`455 pushed tag{} to \u001b[${33}m${`rangedOpeningTags`}\u001b[${39}m\nwhich is now equal to:\n${JSON.stringify(
rangedOpeningTags,
null,
4
)}`
);
}
}
}
function calculateWhitespaceToInsert(
str2: string, // whole string
currCharIdx: number, // current index
fromIdx: null | number, // leftmost whitespace edge around tag
toIdx: null | number, // rightmost whitespace edge around tag
lastOpeningBracketAt: number, // tag actually starts here (<)
lastClosingBracketAt: number // tag actually ends here (>)
) {
console.log(
`474 \u001b[${35}m${`calculateWhitespaceToInsert() called`}\u001b[${39}m`
);
console.log(
`477 calculateWhitespaceToInsert(): ${`\u001b[${33}m${`currCharIdx`}\u001b[${39}m`} = ${JSON.stringify(
currCharIdx,
null,
0
)}; ${`\u001b[${33}m${`str2[currCharIdx]`}\u001b[${39}m`} = ${JSON.stringify(
str2[currCharIdx],
null,
0
)}; ${`\u001b[${33}m${`str2[tag.leftOuterWhitespace]`}\u001b[${39}m`} = ${JSON.stringify(
str2[tag.leftOuterWhitespace],
null,
0
)}; ${`\u001b[${33}m${`str2[tag.leftOuterWhitespace - 1]`}\u001b[${39}m`} = ${JSON.stringify(
str2[tag.leftOuterWhitespace - 1],
null,
0
)}; ${`\u001b[${33}m${`fromIdx`}\u001b[${39}m`} = ${JSON.stringify(
fromIdx,
null,
0
)}; ${`\u001b[${33}m${`toIdx`}\u001b[${39}m`} = ${JSON.stringify(
toIdx,
null,
0
)}`
);
let strToEvaluateForLineBreaks = "";
if (
Number.isInteger(fromIdx) &&
(fromIdx as number) < lastOpeningBracketAt
) {
strToEvaluateForLineBreaks += str2.slice(
fromIdx as number,
lastOpeningBracketAt
);
console.log(
`513 strToEvaluateForLineBreaks = ${JSON.stringify(
strToEvaluateForLineBreaks,
null,
0
)} (length ${
strToEvaluateForLineBreaks.length
}; sliced [${fromIdx}, ${lastOpeningBracketAt}])`
);
}
if (
Number.isInteger(toIdx) &&
(toIdx as number) > lastClosingBracketAt + 1
) {
// limit whitespace that follows the tag, stop at linebreak. That's to make
// the algorithm composable - we include linebreaks in front but not after.
const temp = str2.slice(lastClosingBracketAt + 1, toIdx as number);
if (temp.includes("\n") && isOpeningAt(toIdx as number, str2)) {
strToEvaluateForLineBreaks += " ";
} else {
strToEvaluateForLineBreaks += temp;
}
console.log(
`535 strToEvaluateForLineBreaks = ${JSON.stringify(
strToEvaluateForLineBreaks,
null,
0
)} (length ${strToEvaluateForLineBreaks.length}; sliced [${
lastClosingBracketAt + 1
}, ${toIdx}])`
);
}
console.log(
`545 strToEvaluateForLineBreaks = ${JSON.stringify(
strToEvaluateForLineBreaks,
null,
0
)} (length ${strToEvaluateForLineBreaks.length})`
);
if (!punctuation.has(str2[currCharIdx]) && str2[currCharIdx] !== "!") {
const foundLineBreaks = strToEvaluateForLineBreaks.match(/\n/g);
if (Array.isArray(foundLineBreaks) && foundLineBreaks.length) {
if (foundLineBreaks.length === 1) {
return "\n";
}
if (foundLineBreaks.length === 2) {
return "\n\n";
}
// return three line breaks maximum
return "\n\n\n";
}
// default spacer - a single space
return " ";
}
// default case: space
return "";
}
function calculateHrefToBeInserted(opts: Opts) {
if (
opts.dumpLinkHrefsNearby.enabled &&
hrefDump.tagName &&
hrefDump.tagName === tag.name &&
tag.lastOpeningBracketAt &&
((hrefDump.openingTagEnds &&
tag.lastOpeningBracketAt > hrefDump.openingTagEnds) ||
!hrefDump.openingTagEnds)
) {
hrefInsertionActive = true;
console.log(
`582 calculateHrefToBeInserted(): hrefInsertionActive = "${hrefInsertionActive}"`
);
}
if (hrefInsertionActive) {
const lineBreaks = opts.dumpLinkHrefsNearby.putOnNewLine ? "\n\n" : "";
stringToInsertAfter = `${lineBreaks}${hrefDump.hrefValue}${lineBreaks}`;
console.log(
`590 calculateHrefToBeInserted(): stringToInsertAfter = ${stringToInsertAfter}`
);
}
}
function isOpeningAt(i: number, customStr?: string): boolean {
if (customStr) {
return customStr[i] === "<" && customStr[i + 1] !== "%";
}
return str[i] === "<" && str[i + 1] !== "%";
}
function isClosingAt(i: number): boolean {
return str[i] === ">" && str[i - 1] !== "%";
}
// validation
// ===========================================================================
if (typeof str !== "string") {
throw new TypeError(
`string-strip-html/stripHtml(): [THROW_ID_01] Input must be string! Currently it's: ${(typeof str).toLowerCase()}, equal to:\n${JSON.stringify(
str,
null,
4
)}`
);
}
if (originalOpts && !isObj(originalOpts)) {
throw new TypeError(
`string-strip-html/stripHtml(): [THROW_ID_02] Optional Options Object must be a plain object! Currently it's: ${(typeof originalOpts).toLowerCase()}, equal to:\n${JSON.stringify(
originalOpts,
null,
4
)}`
);
}
// eslint-disable-next-line consistent-return
function resetHrefMarkers() {
// reset the hrefDump
if (hrefInsertionActive) {
hrefDump = {
tagName: "",
hrefValue: "",
openingTagEnds: undefined,
};
hrefInsertionActive = false;
}
}
// prep opts
// ===========================================================================
const opts: Opts = { ...defaults, ...originalOpts };
if (Object.prototype.hasOwnProperty.call(opts, "returnRangesOnly")) {
throw new TypeError(
`string-strip-html/stripHtml(): [THROW_ID_03] opts.returnRangesOnly has been removed from the API since v.5 release.`
);
}
// filter non-string or whitespace entries from the following arrays or turn
// them into arrays:
opts.ignoreTags = prepHopefullyAnArray(opts.ignoreTags, "opts.ignoreTags");
opts.onlyStripTags = prepHopefullyAnArray(
opts.onlyStripTags,
"opts.onlyStripTags"
);
// let's define the onlyStripTagsMode. Since opts.onlyStripTags can cancel
// out the entries in opts.onlyStripTags, it can be empty but this mode has
// to be switched on:
const onlyStripTagsMode = !!opts.onlyStripTags.length;
// if both opts.onlyStripTags and opts.ignoreTags are set, latter is respected,
// we simply exclude ignored tags from the opts.onlyStripTags.
if (opts.onlyStripTags.length && opts.ignoreTags.length) {
opts.onlyStripTags = without(opts.onlyStripTags, ...opts.ignoreTags);
}
if (!isObj(opts.dumpLinkHrefsNearby)) {
opts.dumpLinkHrefsNearby = { ...defaults.dumpLinkHrefsNearby };
}
// Object.assign doesn't deep merge, so we take care of opts.dumpLinkHrefsNearby:
opts.dumpLinkHrefsNearby = defaults.dumpLinkHrefsNearby;
if (
originalOpts &&
Object.prototype.hasOwnProperty.call(originalOpts, "dumpLinkHrefsNearby") &&
existy(originalOpts.dumpLinkHrefsNearby)
) {
/* istanbul ignore else */
if (isObj(originalOpts.dumpLinkHrefsNearby)) {
opts.dumpLinkHrefsNearby = {
...defaults.dumpLinkHrefsNearby,
...originalOpts.dumpLinkHrefsNearby,
};
} else if (originalOpts.dumpLinkHrefsNearby) {
// checking to omit value as number zero
throw new TypeError(
`string-strip-html/stripHtml(): [THROW_ID_04] Optional Options Object's key dumpLinkHrefsNearby was set to ${typeof originalOpts.dumpLinkHrefsNearby}, equal to ${JSON.stringify(
originalOpts.dumpLinkHrefsNearby,
null,
4
)}. The only allowed value is a plain object. See the API reference.`
);
}
}
if (!opts.stripTogetherWithTheirContents) {
opts.stripTogetherWithTheirContents = [];
} else if (
typeof opts.stripTogetherWithTheirContents === "string" &&
(opts.stripTogetherWithTheirContents as string).length
) {
opts.stripTogetherWithTheirContents = [opts.stripTogetherWithTheirContents];
}
const somethingCaught: Obj = {};
if (
opts.stripTogetherWithTheirContents &&
Array.isArray(opts.stripTogetherWithTheirContents) &&
opts.stripTogetherWithTheirContents.length &&
!opts.stripTogetherWithTheirContents.every((el, i) => {
if (!(typeof el === "string")) {
somethingCaught.el = el;
somethingCaught.i = i;
return false;
}
return true;
})
) {
throw new TypeError(
`string-strip-html/stripHtml(): [THROW_ID_05] Optional Options Object's key stripTogetherWithTheirContents was set to contain not just string elements! For example, element at index ${
somethingCaught.i
} has a value ${
somethingCaught.el
} which is not string but ${(typeof somethingCaught.el).toLowerCase()}.`
);
}
// prep the opts.cb
console.log(`730 opts.cb type = ${typeof opts.cb}`);
if (!opts.cb) {
opts.cb = ({ rangesArr, proposedReturn }) => {
if (proposedReturn) {
(rangesArr as any).push(...proposedReturn);
}
};
}
console.log(
`740 string-strip-html: final ${`\u001b[${33}m${`opts`}\u001b[${39}m`} = ${JSON.stringify(
opts,
null,
4
)}; ${`\u001b[${33}m${`input`}\u001b[${39}m`} = "${str}"`
);
// if the links have to be on a new line, we need to increase the allowance for line breaks
// in Ranges class, it's the ranges-push API setting opts.limitLinebreaksCount
// see https://www.npmjs.com/package/ranges-push#optional-options-object
const rangesToDelete = new Ranges({
limitToBeAddedWhitespace: true,
limitLinebreaksCount: 2,
});
// TODO: it's chummy - ranges will be unreliable if initial str has changed
// use ranges-ent-decode
if (!opts.skipHtmlDecoding) {
while (str !== decode(str, { scope: "strict" })) {
// eslint-disable-next-line no-param-reassign
str = decode(str, { scope: "strict" });
}
}
// step 1.
// ===========================================================================
for (let i = 0, len = str.length; i < len; i++) {
console.log(
`\u001b[${36}m${`===============================`}\u001b[${39}m \u001b[${35}m${`str[ ${i} ] = ${`\u001b[${31}m${
str[i] && str[i].trim() === ""
? str[i] === null
? "null"
: str[i] === "\n"
? "line break"
: str[i] === "\t"
? "tab"
: "space"
: str[i]
}\u001b[${39}m`}`}\u001b[${39}m \u001b[${36}m${`===============================`}\u001b[${39}m`
);
// catch the first ending of the spaces chunk that follows the closing bracket.
// -------------------------------------------------------------------------
// There can be no space after bracket, in that case, the result will be that character that
// follows the closing bracket.
// There can be bunch of spaces that end with EOF. In that case it's fine, this variable will
// be null.
if (
Object.keys(tag).length > 1 &&
tag.lastClosingBracketAt &&
tag.lastClosingBracketAt < i &&
str[i] !== " " &&
spacesChunkWhichFollowsTheClosingBracketEndsAt === null
) {
spacesChunkWhichFollowsTheClosingBracketEndsAt = i;
}
// skip known ESP token pairs
// -------------------------------------------------------------------------
if (str[i] === "%" && str[i - 1] === "{" && str.includes("%}", i + 1)) {
i = str.indexOf("%}", i) - 1;
console.log(
`803 offset i = ${i}; then ${`\u001b[${32}m${`CONTINUE`}\u001b[${39}m`}`
);
continue;
}
// catch the closing bracket of dirty tags with missing opening brackets
// -------------------------------------------------------------------------
if (isClosingAt(i)) {
console.log(`811 closing bracket caught`);
// tend cases where opening bracket of a tag is missing:
if ((!tag || Object.keys(tag).length < 2) && i > 1) {
console.log("814 TRAVERSE BACKWARDS");
// traverse backwards either until start of string or ">" is found
for (let y = i; y--; ) {
console.log(`\u001b[${35}m${`str[${y}] = ${str[y]}`}\u001b[${39}m`);
if (str[y - 1] === undefined || isClosingAt(y)) {
console.log("820 BREAK");
const startingPoint = str[y - 1] === undefined ? y : y + 1;
const culprit = str.slice(startingPoint, i + 1);
console.log(
`825 CULPRIT: "${`\u001b[${31}m${culprit}\u001b[${39}m`}"`
);
// Check if the culprit starts with a tag that's more likely a tag
// name (like "body" or "article"). Single-letter tag names are excluded
// because they can be plausible, ie. in math texts and so on.
// Nobody uses puts comparison signs between words like: "article > ",
// but single letter names can be plausible: "a > b" in math.
console.log(
`835 "${trim(
(culprit as any)
.trim()
.split(/\s+/)
.filter((val2: string) => val2.trim())
.filter((_val3: string, i3: number) => i3 === 0),
"/>"
)}"`
);
if (
str !== `<${trim(culprit.trim(), "/>")}>` && // recursion prevention
[...definitelyTagNames].some(
(val) =>
trim(
(culprit as any)
.trim()
.split(/\s+/)
.filter((val2: string) => val2.trim())
.filter((_val3: string, i3: number) => i3 === 0),
"/>"
).toLowerCase() === val
) &&
stripHtml(`<${culprit.trim()}>`, opts).result === ""
) {
/* istanbul ignore else */
if (
!allTagLocations.length ||
allTagLocations[allTagLocations.length - 1][0] !==
tag.lastOpeningBracketAt
) {
allTagLocations.push([startingPoint, i + 1]);
console.log(
`868 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${
tag.lastOpeningBracketAt
}, ${tag.lastClosingBracketAt + 1}] to allTagLocations`
);
}
/* istanbul ignore else */
if (
!filteredTagLocations.length ||
filteredTagLocations[filteredTagLocations.length - 1][0] !==
tag.lastOpeningBracketAt
) {
filteredTagLocations.push([startingPoint, i + 1]);
console.log(
`882 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${
tag.lastOpeningBracketAt
}, ${tag.lastClosingBracketAt + 1}] to filteredTagLocations`
);
}
const whiteSpaceCompensation = calculateWhitespaceToInsert(
str,
i,
startingPoint,
i + 1,
startingPoint,
i + 1
);
console.log(
`897 \u001b[${33}m${`SUBMIT RANGE #3: [${startingPoint}, ${
i + 1
}, "${whiteSpaceCompensation}"]`}\u001b[${39}m`
);
let deleteUpTo = i + 1;
if (str[deleteUpTo] && !str[deleteUpTo].trim()) {
for (let z = deleteUpTo; z < len; z++) {
if (str[z].trim()) {
deleteUpTo = z;
break;
}
}
}
console.log(
`911 cb()-PUSHING [${startingPoint}, ${deleteUpTo}, "${whiteSpaceCompensation}"]`
);
opts.cb({
tag: tag as any,
deleteFrom: startingPoint,
deleteTo: deleteUpTo,
insert: whiteSpaceCompensation,
rangesArr: rangesToDelete as any,
proposedReturn: [
startingPoint,
deleteUpTo,
whiteSpaceCompensation,
],
});
}
break;
}
}
}
}
// catch slash
// -------------------------------------------------------------------------
if (
str[i] === "/" &&
!(tag.quotes && tag.quotes.value) &&
Number.isInteger(tag.lastOpeningBracketAt) &&
!Number.isInteger(tag.lastClosingBracketAt)
) {
console.log(`940 \u001b[${33}m${`tag.slashPresent`}\u001b[${39}m = true`);
tag.slashPresent = i;
}
// catch double or single quotes
// -------------------------------------------------------------------------
if (str[i] === '"' || str[i] === "'") {
if (
tag.nameStarts &&
tag.quotes &&
tag.quotes.value &&
tag.quotes.value === str[i]
) {
// 1. finish assembling the "attrObj{}"
attrObj.valueEnds = i;
attrObj.value = str.slice(attrObj.valueStarts, i);
console.log(
`957 PUSHING ${`\u001b[${33}m${`attrObj`}\u001b[${39}m`} = ${JSON.stringify(
attrObj,
null,
4
)}`
);
tag.attributes.push(attrObj);
// reset:
attrObj = {};
// 2. finally, delete the quotes marker, we don't need it any more
tag.quotes = undefined;
// 3. if opts.dumpLinkHrefsNearby.enabled is on, catch href
let hrefVal;
if (
opts.dumpLinkHrefsNearby.enabled &&
// eslint-disable-next-line
tag.attributes.some((obj: Obj) => {
if (obj.name && obj.name.toLowerCase() === "href") {
hrefVal = `${opts.dumpLinkHrefsNearby.wrapHeads || ""}${
obj.value
}${opts.dumpLinkHrefsNearby.wrapTails || ""}`;
return true;
}
})
) {
hrefDump = {
tagName: tag.name,
hrefValue: hrefVal as any,
openingTagEnds: undefined,
};
console.log(
`988 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`hrefDump`}\u001b[${39}m`} = ${JSON.stringify(
hrefDump,
null,
4
)}`
);
}
} else if (!tag.quotes && tag.nameStarts) {
// 1. if it's opening marker, record the type and location of quotes
console.log(
`998 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} tag.quotes = {}, tag.quotes.value = ${
str[i]
}, tag.quotes.start = ${i}`
);
tag.quotes = {};
tag.quotes.value = str[i];
tag.quotes.start = i;
// 2. start assembling the attribute object which we'll dump into tag.attributes[] array:
if (
attrObj.nameStarts &&
attrObj.nameEnds &&
attrObj.nameEnds < i &&
attrObj.nameStarts < i &&
!attrObj.valueStarts
) {
attrObj.name = str.slice(attrObj.nameStarts, attrObj.nameEnds);
console.log(
`1015 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`attrObj`}\u001b[${39}m`} = ${JSON.stringify(
attrObj,
null,
4
)}`
);
}
}
}
// catch the ending of the tag name:
// -------------------------------------------------------------------------
if (
tag.nameStarts !== undefined &&
tag.nameEnds === undefined &&
(!str[i].trim() || !characterSuitableForNames(str[i]))
) {
// 1. mark the name ending
tag.nameEnds = i;
console.log(
`1035 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} \u001b[${33}m${`tag.nameEnds`}\u001b[${39}m = ${
tag.nameEnds
}`
);
// 2. extract the full name string
/* istanbul ignore next */
tag.name = str.slice(
tag.nameStarts,
tag.nameEnds +
/* istanbul ignore next */
(!isClosingAt(i) && str[i] !== "/" && str[i + 1] === undefined
? 1
: 0)
);
console.log(
`1050 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} \u001b[${33}m${`tag.name`}\u001b[${39}m = ${
tag.name
}`
);
console.log(
`1056 ${`\u001b[${33}m${`tag`}\u001b[${39}m`} is currently = ${JSON.stringify(
tag,
null,
4
)}`
);
if (
// if we caught "----" from "<----" or "---->", bail:
(str[tag.nameStarts - 1] !== "!" && // protection against <!--
!tag.name.replace(/-/g, "").length) ||
// if tag name starts with a number character
/^\d+$/.test(tag.name[0])
) {
tag = {};
continue;
}
if (isOpeningAt(i)) {
// process it because we need to tackle this new tag
console.log(`1076 opening bracket caught`);
calculateHrefToBeInserted(opts);
console.log(
`1080 ${`\u001b[${33}m${`stringToInsertAfter`}\u001b[${39}m`} = ${JSON.stringify(
stringToInsertAfter,
null,
4
)}`
);
// calculateWhitespaceToInsert() API:
// str, // whole string
// currCharIdx, // current index
// fromIdx, // leftmost whitespace edge around tag
// toIdx, // rightmost whitespace edge around tag
// lastOpeningBracketAt, // tag actually starts here (<)
// lastClosingBracketAt // tag actually ends here (>)
const whiteSpaceCompensation = calculateWhitespaceToInsert(
str,
i,
tag.leftOuterWhitespace,
i,
tag.lastOpeningBracketAt,
i
);
console.log(
`1104 \u001b[${33}m${`cb()-PUSH: [${tag.leftOuterWhitespace}, ${i}, "${whiteSpaceCompensation}${stringToInsertAfter}${whiteSpaceCompensation}"]`}\u001b[${39}m`
);
console.log(
`1107 ${`\u001b[${33}m${`tag`}\u001b[${39}m`} = ${JSON.stringify(
tag,
null,
4
)}`
);
// only on pair tags, exclude the opening counterpart and closing
// counterpart if whole pair is to be deleted
if (
opts.stripTogetherWithTheirContents.includes(tag.name) ||
opts.stripTogetherWithTheirContents.includes("*")
) {
console.log(
`1121 ${`\u001b[${33}m${`filteredTagLocations`}\u001b[${39}m`} BEFORE: ${JSON.stringify(
filteredTagLocations,
null,
4
)}`
);
/* istanbul ignore next */
filteredTagLocations = filteredTagLocations.filter(
([from, upto]) => !(from === tag.leftOuterWhitespace && upto === i)
);
console.log(
`1132 ${`\u001b[${33}m${`filteredTagLocations`}\u001b[${39}m`} AFTER: ${JSON.stringify(
filteredTagLocations,
null,
4
)}`
);
}
// console.log(
// `1011 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${
// tag.leftOuterWhitespace
// }, ${i}] to filteredTagLocations`
// );
// filteredTagLocations.push([tag.leftOuterWhitespace, i]);
opts.cb({
tag: tag as Tag,
deleteFrom: tag.leftOuterWhitespace,
deleteTo: i,
insert: `${whiteSpaceCompensation}${stringToInsertAfter}${whiteSpaceCompensation}`,
rangesArr: rangesToDelete as any,
proposedReturn: [
tag.leftOuterWhitespace,
i,
`${whiteSpaceCompensation}${stringToInsertAfter}${whiteSpaceCompensation}`,
],
});
resetHrefMarkers();
// also,
treatRangedTags(i, opts, rangesToDelete);
}
}
// catch beginning of an attribute value
// -------------------------------------------------------------------------
if (
tag.quotes &&
tag.quotes.start &&
tag.quotes.start < i &&
!tag.quotes.end &&
attrObj.nameEnds &&
attrObj.equalsAt &&
!attrObj.valueStarts
) {
console.log(
`1178 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} \u001b[${33}m${`attrObj.valueStarts`}\u001b[${39}m = ${
attrObj.valueStarts
}`
);
attrObj.valueStarts = i;
}
// catch rare cases when attributes name has some space after it, before equals
// -------------------------------------------------------------------------
if (
!tag.quotes &&
attrObj.nameEnds &&
str[i] === "=" &&
!attrObj.valueStarts &&
!attrObj.equalsAt
) {
attrObj.equalsAt = i;
console.log(
`1196 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} \u001b[${33}m${`attrObj.equalsAt`}\u001b[${39}m = ${
attrObj.equalsAt
}`
);
}
// catch the ending of the whole attribute
// -------------------------------------------------------------------------
// for example, <a b c> this "c" ends "b" because it's not "equals" sign.
// We even anticipate for cases where whitespace anywhere between attribute parts:
// < article class = " something " / >
if (
!tag.quotes &&
attrObj.nameStarts &&
attrObj.nameEnds &&
!attrObj.valueStarts &&
str[i].trim() &&
str[i] !== "="
) {
// if (!tag.attributes) {
// tag.attributes = [];
// }
tag.attributes.push(attrObj);
console.log("1219 PUSHED attrObj into tag.attributes, reset attrObj");
attrObj = {};
}
// catch the ending of an attribute's name
// -------------------------------------------------------------------------
if (!tag.quotes && attrObj.nameStarts && !attrObj.nameEnds) {
console.log("1226");
if (!str[i].trim()) {
attrObj.nameEnds = i;
console.log(
`1230 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`attrObj.nameEnds`}\u001b[${39}m`} = ${JSON.stringify(
attrObj.nameEnds,
null,
4
)}`
);
attrObj.name = str.slice(attrObj.nameStarts, attrObj.nameEnds);
} else if (str[i] === "=") {
console.log(`1238 equal char clauses`);
/* istanbul ignore else */
if (!attrObj.equalsAt) {
console.log(`1241 equal hasn't been met`);
attrObj.nameEnds = i;
console.log(
`1244 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`attrObj.nameEnds`}\u001b[${39}m`} = ${JSON.stringify(
attrObj.nameEnds,
null,
4
)}`
);
attrObj.equalsAt = i;
console.log(
`1252 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`attrObj.equalsAt`}\u001b[${39}m`} = ${JSON.stringify(
attrObj.equalsAt,
null,
4
)}`
);
attrObj.name = str.slice(attrObj.nameStarts, attrObj.nameEnds);
}
} else if (str[i] === "/" || isClosingAt(i)) {
console.log(
`1262 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`attrObj.nameEnds`}\u001b[${39}m`} = ${JSON.stringify(
attrObj.nameEnds,
null,
4
)}`
);
attrObj.nameEnds = i;
attrObj.name = str.slice(attrObj.nameStarts, attrObj.nameEnds);
console.log(
`1271 \u001b[${33}m${`PUSH attrObj and wipe`}\u001b[${39}m`
);
// if (!tag.attributes) {
// tag.attributes = [];
// }
tag.attributes.push(attrObj);
attrObj = {};
} else if (isOpeningAt(i)) {
console.log(
`1280 \u001b[${33}m${`ATTR NAME ENDS WITH NEW TAG`}\u001b[${39}m - ${`\u001b[${31}m${`TODO`}\u001b[${39}m`}`
);
// TODO - address both cases of onlyPlausible
attrObj.nameEnds = i;
attrObj.name = str.slice(attrObj.nameStarts, attrObj.nameEnds);
// if (!tag.attributes) {
// tag.attributes = [];
// }
tag.attributes.push(attrObj);
attrObj = {};
}
}
// catch the beginning of an attribute's name
// -------------------------------------------------------------------------
if (
!tag.quotes &&
tag.nameEnds < i &&
!str[i - 1].trim() &&
str[i].trim() &&
!`<>/!`.includes(str[i]) &&
!attrObj.nameStarts &&
!tag.lastClosingBracketAt
) {
attrObj.nameStarts = i;
console.log(
`1306 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} \u001b[${33}m${`attrObj.nameStarts`}\u001b[${39}m = ${
attrObj.nameStarts
}`
);
}
// catch "< /" - turn off "onlyPlausible"
// -------------------------------------------------------------------------
if (
tag.lastOpeningBracketAt !== null &&
tag.lastOpeningBracketAt < i &&
str[i] === "/" &&
tag.onlyPlausible
) {
tag.onlyPlausible = false;
}
// catch character that follows an opening bracket:
// -------------------------------------------------------------------------
if (
tag.lastOpeningBracketAt !== null &&
tag.lastOpeningBracketAt < i &&
str[i] !== "/" // there can be closing slashes in various places, legit and not
) {
// 1. identify, is it definite or just plausible tag
if (tag.onlyPlausible === undefined) {
if ((!str[i].trim() || isOpeningAt(i)) && !tag.slashPresent) {
tag.onlyPlausible = true;
} else {
tag.onlyPlausible = false;
}
console.log(
`1338 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} \u001b[${33}m${`tag.onlyPlausible`}\u001b[${39}m = ${
tag.onlyPlausible
}`
);
}
// 2. catch the beginning of the tag name. Consider custom HTML tag names
// and also known (X)HTML tags:
if (
str[i].trim() &&
tag.nameStarts === undefined &&
!isOpeningAt(i) &&
str[i] !== "/" &&
!isClosingAt(i) &&
str[i] !== "!"
) {
tag.nameStarts = i;
tag.nameContainsLetters = false;
console.log(
`1356 \u001b[${33}m${`tag.nameStarts`}\u001b[${39}m = ${
tag.nameStarts
}`
);
}
}
// Catch letters in the tag name. Necessary to filter out false positives like "<------"
if (
tag.nameStarts &&
!tag.quotes &&
str[i].toLowerCase() !== str[i].toUpperCase()
) {
tag.nameContainsLetters = true;
}
// catch closing bracket
// -------------------------------------------------------------------------
if (
// it's closing bracket
isClosingAt(i) &&
//
// precaution against JSP comparison
// kl <c:when test="${!empty ab.cd && ab.cd > 0.00}"> mn
// ^
// we're here, it's false ending
//
notWithinAttrQuotes(tag, str, i)
) {
const itIsClosing = true;
if (itIsClosing && tag.lastOpeningBracketAt !== undefined) {
// 1. mark the index
tag.lastClosingBracketAt = i;
console.log(
`1392 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} tag.lastClosingBracketAt = ${
tag.lastClosingBracketAt
}`
);
// 2. reset the spacesChunkWhichFollowsTheClosingBracketEndsAt
spacesChunkWhichFollowsTheClosingBracketEndsAt = null;
// 3. push attrObj into tag.attributes[]
if (Object.keys(attrObj).length) {
console.log(
`1401 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} \u001b[${33}m${`attrObj`}\u001b[${39}m & reset`
);
// if (!tag.attributes) {
// tag.attributes = [];
// }
tag.attributes.push(attrObj);
attrObj = {};
}
// 4. if opts.dumpLinkHrefsNearby.enabled is on and we just recorded an href,
if (
opts.dumpLinkHrefsNearby.enabled &&
hrefDump.tagName &&
!hrefDump.openingTagEnds
) {
// finish assembling the hrefDump{}
hrefDump.openingTagEnds = i; // or tag.lastClosingBracketAt, same
console.log(
`1418 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`hrefDump`}\u001b[${39}m`} = ${JSON.stringify(
hrefDump,
null,
4
)}`
);
}
}
}
// catch the ending of the tag
// -------------------------------------------------------------------------
// the tag is "released" into "rApply":
if (tag.lastOpeningBracketAt !== undefined) {
console.log(`1433 opening bracket has been met`);
console.log(
`1435 FIY, ${`\u001b[${33}m${`tag.lastClosingBracketAt`}\u001b[${39}m`} = ${JSON.stringify(
tag.lastClosingBracketAt,
null,
4
)}`
);
if (tag.lastClosingBracketAt === undefined) {
console.log(`1442 closing bracket hasn't been met`);
if (
tag.lastOpeningBracketAt < i &&
!isOpeningAt(i) && // to prevent cases like "text <<<<<< text"
(str[i + 1] === undefined || isOpeningAt(i + 1)) &&
tag.nameContainsLetters
) {
console.log(`1449 str[i + 1] = ${str[i + 1]}`);
// find out the tag name earlier than dedicated tag name ending catching section:
// if (str[i + 1] === undefined) {
tag.name = str
.slice(tag.nameStarts, tag.nameEnds ? tag.nameEnds : i + 1)
.toLowerCase();
console.log(
`1456 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`tag.name`}\u001b[${39}m`} = ${JSON.stringify(
tag.name,
null,
4
)}`
);
// submit tag to allTagLocations
/* istanbul ignore else */
if (
!allTagLocations.length ||
allTagLocations[allTagLocations.length - 1][0] !==
tag.lastOpeningBracketAt
) {
allTagLocations.push([tag.lastOpeningBracketAt, i + 1]);
console.log(
`1472 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${
tag.lastOpeningBracketAt
}, ${i + 1}] to allTagLocations`
);
}
if (
// if it's an ignored tag
opts.ignoreTags.includes(tag.name) ||
// or just plausible and unrecognised
(tag.onlyPlausible && !definitelyTagNames.has(tag.name))
) {
console.log(
`1485 Ignored tag - \u001b[${31}m${`WIPE AND RESET`}\u001b[${39}m`
);
tag = {};
attrObj = {};
continue;
}
// if the tag is only plausible (there's space after opening bracket) and it's not among
// recognised tags, leave it as it is:
console.log(`1495`);
if (
((definitelyTagNames.has(tag.name) ||
singleLetterTags.has(tag.name)) &&
(tag.onlyPlausible === false ||
(tag.onlyPlausible === true && tag.attributes.length))) ||
str[i + 1] === undefined
) {
calculateHrefToBeInserted(opts);
console.log(
`1505 ${`\u001b[${33}m${`stringToInsertAfter`}\u001b[${39}m`} = ${JSON.stringify(
stringToInsertAfter,
null,
4
)}`
);
const whiteSpaceCompensation = calculateWhitespaceToInsert(
str,
i,
tag.leftOuterWhitespace,
i + 1,
tag.lastOpeningBracketAt,
tag.lastClosingBracketAt
);
console.log(
`1522 \u001b[${33}m${`cb()-PUSH: [${tag.leftOuterWhitespace}, ${
i + 1
}, "${whiteSpaceCompensation}${stringToInsertAfter}${whiteSpaceCompensation}"]`}\u001b[${39}m`
);
console.log(
`1527 ${`\u001b[${33}m${`tag`}\u001b[${39}m`} = ${JSON.stringify(
tag,
null,
4
)}`
);
opts.cb({
tag: tag as Tag,
deleteFrom: tag.leftOuterWhitespace,
deleteTo: i + 1,
insert: `${whiteSpaceCompensation}${stringToInsertAfter}${whiteSpaceCompensation}`,
rangesArr: rangesToDelete as any,
proposedReturn: [
tag.leftOuterWhitespace,
i + 1,
`${whiteSpaceCompensation}${stringToInsertAfter}${whiteSpaceCompensation}`,
],
});
resetHrefMarkers();
// also,
treatRangedTags(i, opts, rangesToDelete);
}
console.log(`1551`);
/* istanbul ignore else */
if (
!filteredTagLocations.length ||
(filteredTagLocations[filteredTagLocations.length - 1][0] !==
tag.lastOpeningBracketAt &&
filteredTagLocations[filteredTagLocations.length - 1][1] !==
i + 1)
) {
console.log(`1561`);
// filter out opening/closing tag pair because whole chunk
// from opening's opening to closing's closing will be pushed
if (
opts.stripTogetherWithTheirContents.includes(tag.name) ||
opts.stripTogetherWithTheirContents.includes("*")
) {
console.log(
`1570 FIY, ${`\u001b[${33}m${`rangedOpeningTags`}\u001b[${39}m`} = ${JSON.stringify(
rangedOpeningTags,
null,
4
)}`
);
// get the last opening counterpart of the pair
// iterate rangedOpeningTags from the, pick the first
// ranged opening tag whose name is same like current, closing's
let lastRangedOpeningTag: any;
for (let z = rangedOpeningTags.length; z--; ) {
/* istanbul ignore else */
if (rangedOpeningTags[z].name === tag.name) {
lastRangedOpeningTag = rangedOpeningTags[z];
console.log(
`1586 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`lastRangedOpeningTag`}\u001b[${39}m`} = ${JSON.stringify(
lastRangedOpeningTag,
null,
4
)}`
);
console.log(`1592 BREAK`);
}
}
/* istanbul ignore else */
if (lastRangedOpeningTag) {
console.log(
`1599 ${`\u001b[${33}m${`filteredTagLocations`}\u001b[${39}m`} BEFORE: ${JSON.stringify(
filteredTagLocations,
null,
4
)}`
);
filteredTagLocations = filteredTagLocations.filter(
([from]) => from !== lastRangedOpeningTag.lastOpeningBracketAt
);
console.log(
`1609 ${`\u001b[${33}m${`filteredTagLocations`}\u001b[${39}m`} AFTER: ${JSON.stringify(
filteredTagLocations,
null,
4
)}`
);
filteredTagLocations.push([
lastRangedOpeningTag.lastOpeningBracketAt,
i + 1,
]);
console.log(
`1621 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${
lastRangedOpeningTag.lastOpeningBracketAt
}, ${i + 1}] to filteredTagLocations`
);
} else {
/* istanbul ignore next */
filteredTagLocations.push([tag.lastOpeningBracketAt, i + 1]);
console.log(
`1629 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${
tag.lastOpeningBracketAt
}, ${i + 1}] to filteredTagLocations`
);
}
} else {
// if it's not ranged tag, just push it as it is to filteredTagLocations
filteredTagLocations.push([tag.lastOpeningBracketAt, i + 1]);
console.log(
`1638 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${
tag.lastOpeningBracketAt
}, ${i + 1}] to filteredTagLocations`
);
}
}
}
console.log(`1645 end`);
} else if (
(i > tag.lastClosingBracketAt && str[i].trim()) ||
str[i + 1] === undefined
) {
console.log(`1650 closing bracket has been met`);
// case 2. closing bracket HAS BEEN met
// we'll look for a non-whitespace character and delete up to it
// BUT, we'll wipe the tag object only if that non-whitespace character
// is not a ">". This way we'll catch and delete sequences of closing brackets.
// part 1.
let endingRangeIndex = tag.lastClosingBracketAt === i ? i + 1 : i;
console.log(
`1660 ${`\u001b[${33}m${`endingRangeIndex`}\u001b[${39}m`} = ${JSON.stringify(
endingRangeIndex,
null,
4
)}`
);
if (
opts.trimOnlySpaces &&
endingRangeIndex === len - 1 &&
spacesChunkWhichFollowsTheClosingBracketEndsAt !== null &&
spacesChunkWhichFollowsTheClosingBracketEndsAt < i
) {
endingRangeIndex = spacesChunkWhichFollowsTheClosingBracketEndsAt;
}
// if it's a dodgy suspicious tag where space follows opening bracket, there's an extra requirement
// for this tag to be considered a tag - there has to be at least one attribute with equals if
// the tag name is not recognised.
console.log(
`1681 ${`\u001b[${33}m${`tag.name`}\u001b[${39}m`} = ${JSON.stringify(
tag.name,
null,
4
)}`
);
// submit tag to allTagLocations
/* istanbul ignore else */
if (
!allTagLocations.length ||
allTagLocations[allTagLocations.length - 1][0] !==
tag.lastOpeningBracketAt
) {
allTagLocations.push([
tag.lastOpeningBracketAt,
tag.lastClosingBracketAt + 1,
]);
console.log(
`1700 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${
tag.lastOpeningBracketAt
}, ${tag.lastClosingBracketAt + 1}] to allTagLocations`
);
}
if (
(!onlyStripTagsMode && opts.ignoreTags.includes(tag.name)) ||
(onlyStripTagsMode && !opts.onlyStripTags.includes(tag.name))
) {
// ping the callback with nulls:
opts.cb({
tag: tag as Tag,
deleteFrom: null,
deleteTo: null,
insert: null,
rangesArr: rangesToDelete as any,
proposedReturn: null,
});
// don't submit the tag onto "filteredTagLocations"
// then reset:
console.log(
`1724 Ignored tag - \u001b[${31}m${`WIPE AND RESET`}\u001b[${39}m`
);
tag = {};
attrObj = {};
// continue;
} else if (
!tag.onlyPlausible ||
// tag name is recognised and there are no attributes:
(tag.attributes.length === 0 &&
tag.name &&
(definitelyTagNames.has(tag.name.toLowerCase()) ||
singleLetterTags.has(tag.name.toLowerCase()))) ||
// OR there is at least one equals that follow the attribute's name:
(tag.attributes &&
tag.attributes.some((attrObj2: any) => attrObj2.equalsAt))
) {
// submit tag to filteredTagLocations
/* istanbul ignore else */
if (
!filteredTagLocations.length ||
filteredTagLocations[filteredTagLocations.length - 1][0] !==
tag.lastOpeningBracketAt
) {
filteredTagLocations.push([
tag.lastOpeningBracketAt,
tag.lastClosingBracketAt + 1,
]);
console.log(
`1752 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${
tag.lastOpeningBracketAt
}, ${tag.lastClosingBracketAt + 1}] to filteredTagLocations`
);
}
// if this was an ignored tag name, algorithm would have bailed earlier,
// in stage "catch the ending of the tag name".
const whiteSpaceCompensation = calculateWhitespaceToInsert(
str,
i,
tag.leftOuterWhitespace,
endingRangeIndex,
tag.lastOpeningBracketAt,
tag.lastClosingBracketAt
);
console.log(
`1770 ${`\u001b[${33}m${`whiteSpaceCompensation`}\u001b[${39}m`} = ${JSON.stringify(
whiteSpaceCompensation,
null,
4
)} (length: ${whiteSpaceCompensation.length})`
);
// calculate optional opts.dumpLinkHrefsNearby.enabled HREF to insert
stringToInsertAfter = "";
hrefInsertionActive = false;
calculateHrefToBeInserted(opts);
console.log(
`1784 ${`\u001b[${33}m${`stringToInsertAfter`}\u001b[${39}m`} = ${JSON.stringify(
stringToInsertAfter,
null,
4
)}`
);
let insert;
if (isStr(stringToInsertAfter) && stringToInsertAfter.length) {
insert = `${whiteSpaceCompensation}${stringToInsertAfter}${
/* istanbul ignore next */
whiteSpaceCompensation === "\n\n" ? "\n" : whiteSpaceCompensation
}`;
console.log(
`1797 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`insert`}\u001b[${39}m`} = ${JSON.stringify(
insert,
null,
4
)}`
);
} else {
insert = whiteSpaceCompensation;
console.log(
`1806 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`insert`}\u001b[${39}m`} = ${JSON.stringify(
insert,
null,
4
)}`
);
}
if (
tag.leftOuterWhitespace === 0 ||
!right(str, endingRangeIndex - 1)
) {
insert = "";
console.log(
`1820 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`insert`}\u001b[${39}m`} = ${JSON.stringify(
insert,
null,
4
)}`
);
}
// pass the range onto the callback function, be it default or user's
console.log(
`1830 \u001b[${33}m${`cb()-SUBMIT RANGE #2: [${
tag.leftOuterWhitespace
}, ${endingRangeIndex}, ${JSON.stringify(
insert,
null,
0
)}]`}\u001b[${39}m`
);
opts.cb({
tag: tag as Tag,
deleteFrom: tag.leftOuterWhitespace,
deleteTo: endingRangeIndex,
insert,
rangesArr: rangesToDelete as any,
proposedReturn: [tag.leftOuterWhitespace, endingRangeIndex, insert],
});
resetHrefMarkers();
// also,
treatRangedTags(i, opts, rangesToDelete);
} else {
console.log(`1851 \u001b[${33}m${`RESET tag{}`}\u001b[${39}m`);
tag = {};
}
// part 2.
if (!isClosingAt(i)) {
console.log(`1857 \u001b[${33}m${`RESET tag{}`}\u001b[${39}m`);
tag = {};
}
}
}
// catch an opening bracket
// -------------------------------------------------------------------------
if (
isOpeningAt(i) &&
!isOpeningAt(i - 1) &&
!`'"`.includes(str[i + 1]) &&
(!`'"`.includes(str[i + 2]) || /\w/.test(str[i + 1])) &&
//
// precaution JSP,
// against <c:
!(str[i + 1] === "c" && str[i + 2] === ":") &&
// against <fmt:
!(
str[i + 1] === "f" &&
str[i + 2] === "m" &&
str[i + 3] === "t" &&
str[i + 4] === ":"
) &&
// against <sql:
!(
str[i + 1] === "s" &&
str[i + 2] === "q" &&
str[i + 3] === "l" &&
str[i + 4] === ":"
) &&
// against <x:
!(str[i + 1] === "x" && str[i + 2] === ":") &&
// against <fn:
!(str[i + 1] === "f" && str[i + 2] === "n" && str[i + 3] === ":") &&
//
// kl <c:when test="${!empty ab.cd && ab.cd < 0.00}"> mn
// ^
// we're here, it's false alarm
notWithinAttrQuotes(tag, str, i)
) {
console.log(`1898 caught opening bracket`);
// cater sequences of opening brackets "<<<<div>>>"
if (isClosingAt(right(str, i) as number)) {
// cater cases like: "<><><>"
console.log(`1902 cases like <><><>`);
continue;
} else {
console.log(`1905 opening brackets else clauses`);
// 1. Before (re)setting flags, check, do we have a case of a tag with a
// missing closing bracket, and this is a new tag following it.
console.log(
`1910 R1: ${!!tag.nameEnds}; R2: ${
tag.nameEnds < i
}; R3: ${!tag.lastClosingBracketAt}`
);
if (tag.nameEnds && tag.nameEnds < i && !tag.lastClosingBracketAt) {
console.log(`1915`);
console.log(
`1917 R1: ${!!tag.onlyPlausible}; R2: ${!definitelyTagNames.has(
tag.name
)}; R3: ${!singleLetterTags.has(tag.name)}; R4: ${!(
tag.attributes && tag.attributes.length
)}`
);
if (
(tag.onlyPlausible === true &&
tag.attributes &&
tag.attributes.length) ||
tag.onlyPlausible === false
) {
console.log(`1929`);
// tag.onlyPlausible can be undefined too
const whiteSpaceCompensation = calculateWhitespaceToInsert(
str,
i,
tag.leftOuterWhitespace,
i,
tag.lastOpeningBracketAt,
i
);
console.log(
`1941 cb()-PUSH range [${tag.leftOuterWhitespace}, ${i}, "${whiteSpaceCompensation}"]`
);
opts.cb({
tag: tag as Tag,
deleteFrom: tag.leftOuterWhitespace,
deleteTo: i,
insert: whiteSpaceCompensation,
rangesArr: rangesToDelete as any,
proposedReturn: [
tag.leftOuterWhitespace,
i,
whiteSpaceCompensation,
],
});
// also,
treatRangedTags(i, opts, rangesToDelete);
// then, for continuity, mark everything up accordingly if it's a new bracket:
tag = {};
attrObj = {};
}
}
// 2. if new tag starts, reset:
if (
tag.lastOpeningBracketAt !== undefined &&
tag.onlyPlausible &&
tag.name &&
!tag.quotes
) {
// reset:
console.log(`1973 ${`\u001b[${31}m${`RESET`}\u001b[${39}m`} tag`);
tag.lastOpeningBracketAt = undefined;
tag.name = undefined;
tag.onlyPlausible = false;
console.log(
`1978 NOW ${`\u001b[${33}m${`tag`}\u001b[${39}m`} = ${JSON.stringify(
tag,
null,
4
)}`
);
}
if (
(tag.lastOpeningBracketAt === undefined || !tag.onlyPlausible) &&
!tag.quotes
) {
tag.lastOpeningBracketAt = i;
tag.slashPresent = false;
tag.attributes = [];
// since 2.1.0 we started to care about not trimming outer whitespace which is not spaces.
// For example, " \t <a> \n ". Tag's whitespace boundaries should not extend to string
// edges but until "\t" on the left and "\n" on the right IF opts.trimOnlySpaces is on.
if (chunkOfWhitespaceStartsAt === null) {
tag.leftOuterWhitespace = i;
} else if (opts.trimOnlySpaces && chunkOfWhitespaceStartsAt === 0) {
// if whitespace extends to the beginning of a string, there's a risk it might include
// not only spaces. To fix that, switch to space-only range marker:
/* istanbul ignore next */
tag.leftOuterWhitespace = chunkOfSpacesStartsAt || i;
} else {
tag.leftOuterWhitespace = chunkOfWhitespaceStartsAt;
}
// tag.leftOuterWhitespace =
// chunkOfWhitespaceStartsAt === null ? i : chunkOfWhitespaceStartsAt;
console.log(
`2014 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} \u001b[${33}m${`tag.leftOuterWhitespace`}\u001b[${39}m = ${
tag.leftOuterWhitespace
}; \u001b[${33}m${`tag.lastOpeningBracketAt`}\u001b[${39}m = ${
tag.lastOpeningBracketAt
}; \u001b[${33}m${`tag.slashPresent`}\u001b[${39}m = false`
);
// tend the HTML comments: <!-- --> or CDATA: <![CDATA[ ... ]]>
// if opening comment tag is detected, traverse forward aggressively
// until EOL or "-->" is reached and offset outer index "i".
if (
`${str[i + 1]}${str[i + 2]}${str[i + 3]}` === "!--" ||
`${str[i + 1]}${str[i + 2]}${str[i + 3]}${str[i + 4]}${str[i + 5]}${
str[i + 6]
}${str[i + 7]}${str[i + 8]}` === "![CDATA["
) {
console.log(
`2031 \u001b[${31}m${`███████████████████████████████████████`}\u001b[${39}m`
);
// make a note which one it is:
let cdata = true;
if (str[i + 2] === "-") {
cdata = false;
}
console.log("2038 traversing forward");
let closingFoundAt;
for (let y = i; y < len; y++) {
console.log(
`${`\u001b[${33}m${`str[${y}]`}\u001b[${39}m`} = ${str[y]}`
);
if (
(!closingFoundAt &&
cdata &&
`${str[y - 2]}${str[y - 1]}${str[y]}` === "]]>") ||
(!cdata && `${str[y - 2]}${str[y - 1]}${str[y]}` === "-->")
) {
closingFoundAt = y;
console.log(`2051 closingFoundAt = ${closingFoundAt}`);
}
if (
closingFoundAt &&
((closingFoundAt < y && str[y].trim()) ||
str[y + 1] === undefined)
) {
console.log("2059 END detected");
let rangeEnd = y;
if (
(str[y + 1] === undefined && !str[y].trim()) ||
str[y] === ">"
) {
rangeEnd += 1;
}
// submit the tag
/* istanbul ignore else */
if (
!allTagLocations.length ||
allTagLocations[allTagLocations.length - 1][0] !==
tag.lastOpeningBracketAt
) {
allTagLocations.push([
tag.lastOpeningBracketAt,
closingFoundAt + 1,
]);
console.log(
`2080 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${
tag.lastOpeningBracketAt
}, ${closingFoundAt + 1}] to allTagLocations`
);
}
/* istanbul ignore else */
if (
!filteredTagLocations.length ||
filteredTagLocations[filteredTagLocations.length - 1][0] !==
tag.lastOpeningBracketAt
) {
filteredTagLocations.push([
tag.lastOpeningBracketAt,
closingFoundAt + 1,
]);
console.log(
`2097 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${
tag.lastOpeningBracketAt
}, ${closingFoundAt + 1}] to filteredTagLocations`
);
}
const whiteSpaceCompensation = calculateWhitespaceToInsert(
str,
y,
tag.leftOuterWhitespace,
rangeEnd,
tag.lastOpeningBracketAt,
closingFoundAt
);
console.log(
`2112 cb()-PUSH range [${tag.leftOuterWhitespace}, ${rangeEnd}, "${whiteSpaceCompensation}"]`
);
opts.cb({
tag: tag as Tag,
deleteFrom: tag.leftOuterWhitespace,
deleteTo: rangeEnd,
insert: whiteSpaceCompensation,
rangesArr: rangesToDelete as any,
proposedReturn: [
tag.leftOuterWhitespace,
rangeEnd,
whiteSpaceCompensation,
],
});
// offset:
i = y - 1;
if (str[y] === ">") {
i = y;
}
// resets:
tag = {};
attrObj = {};
// finally,
break;
}
}
}
}
}
}
// catch whitespace
// -------------------------------------------------------------------------
if (!str[i].trim()) {
// 1. catch chunk boundaries:
if (chunkOfWhitespaceStartsAt === null) {
chunkOfWhitespaceStartsAt = i;
console.log(
`2151 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} \u001b[${33}m${`chunkOfWhitespaceStartsAt`}\u001b[${39}m = ${chunkOfWhitespaceStartsAt}`
);
if (
tag.lastOpeningBracketAt !== undefined &&
tag.lastOpeningBracketAt < i &&
tag.nameStarts &&
tag.nameStarts < tag.lastOpeningBracketAt &&
i === tag.lastOpeningBracketAt + 1 &&
// insurance against tail part of ranged tag being deleted:
!rangedOpeningTags.some(
// eslint-disable-next-line no-loop-func
(rangedTagObj) => rangedTagObj.name === tag.name
)
) {
console.log(
`2166 RESET ALL \u001b[${31}m${`███████████████████████████████████████`}\u001b[${39}m`
);
tag.onlyPlausible = true;
tag.name = undefined;
tag.nameStarts = undefined;
}
}
} else if (chunkOfWhitespaceStartsAt !== null) {
console.log("2174");
// 1. piggyback the catching of the attributes with equal and no value
if (
!tag.quotes &&
attrObj.equalsAt > chunkOfWhitespaceStartsAt - 1 &&
attrObj.nameEnds &&
attrObj.equalsAt > attrObj.nameEnds &&
str[i] !== '"' &&
str[i] !== "'"
) {
/* istanbul ignore else */
if (isObj(attrObj)) {
console.log(
`2187 PUSHING ${`\u001b[${33}m${`attrObj`}\u001b[${39}m`} = ${JSON.stringify(
attrObj,
null,
4
)}`
);
tag.attributes.push(attrObj);
}
// reset:
attrObj = {};
tag.equalsSpottedAt = undefined;
}
// 2. reset whitespace marker
chunkOfWhitespaceStartsAt = null;
console.log(
`2203 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} \u001b[${33}m${`chunkOfWhitespaceStartsAt`}\u001b[${39}m = ${chunkOfWhitespaceStartsAt}`
);
}
// catch spaces-only chunks (needed for outer trim option opts.trimOnlySpaces)
// -------------------------------------------------------------------------
if (str[i] === " ") {
// 1. catch spaces boundaries:
if (chunkOfSpacesStartsAt === null) {
chunkOfSpacesStartsAt = i;
console.log(
`2215 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} \u001b[${33}m${`chunkOfSpacesStartsAt`}\u001b[${39}m = ${chunkOfSpacesStartsAt}`
);
}
} else if (chunkOfSpacesStartsAt !== null) {
// 2. reset the marker
chunkOfSpacesStartsAt = null;
console.log(
`2222 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} \u001b[${33}m${`chunkOfSpacesStartsAt`}\u001b[${39}m = ${chunkOfSpacesStartsAt}`
);
}
// log all
// -------------------------------------------------------------------------
console.log(`\u001b[${32}m${`===============`}\u001b[${39}m`);
// console.log(
// `${`\u001b[${33}m${`chunkOfSpacesStartsAt`}\u001b[${39}m`} = ${JSON.stringify(
// chunkOfSpacesStartsAt,
// null,
// 4
// )}`
// );
console.log(
`2237 ${`\u001b[${33}m${`rangedOpeningTags`}\u001b[${39}m`} = ${JSON.stringify(
rangedOpeningTags,
null,
4
)}`
);
console.log(
`2244 ${`\u001b[${33}m${`filteredTagLocations`}\u001b[${39}m`} = ${JSON.stringify(
filteredTagLocations,
null,
4
)}`
);
console.log(
`2251 ${`\u001b[${33}m${`spacesChunkWhichFollowsTheClosingBracketEndsAt`}\u001b[${39}m`} = ${JSON.stringify(
spacesChunkWhichFollowsTheClosingBracketEndsAt,
null,
4
)}`
);
// console.log(
// `${`\u001b[${33}m${`chunkOfWhitespaceStartsAt`}\u001b[${39}m`} = ${JSON.stringify(
// chunkOfWhitespaceStartsAt,
// null,
// 4
// )}`
// );
console.log(
`2265 ${`\u001b[${33}m${`hrefDump`}\u001b[${39}m`} = ${JSON.stringify(
hrefDump,
null,
4
)}`
);
console.log(
`2272 ${`\u001b[${33}m${`attrObj`}\u001b[${39}m`} = ${JSON.stringify(
attrObj,
null,
4
)}`
);
console.log(
`2279 ${
Object.keys(tag).length
? `${`\u001b[${35}m${`tag`}\u001b[${39}m`} = ${Object.keys(tag)
// eslint-disable-next-line no-loop-func
.map((key) => {
return `${`\u001b[${90}m${`\u001b[${7}m${key}\u001b[${27}m`}\u001b[${39}m`} ${`\u001b[${90}m: ${
isObj(tag[key]) || Array.isArray(tag[key])
? JSON.stringify(tag[key], null, 4)
: tag[key]
}\u001b[${39}m`}`;
})
.join(",\n")}\n`
: ""
}${
rangesToDelete.current()
? `RANGES: ${JSON.stringify(rangesToDelete.current(), null, 0)}`
: ""
}`
);
}
console.log("\n\n\n\n\n\n END \n\n\n\n\n\n");
// trim but in ranges
// first tackle the beginning on the string
if (
str &&
// if only spaces were meant to be trimmed,
((opts.trimOnlySpaces &&
// and first character is a space
str[0] === " ") ||
// if normal trim is requested
(!opts.trimOnlySpaces &&
// and the first character is whitespace character
!str[0].trim()))
) {
console.log(`2315 trim frontal part`);
for (let i = 0, len = str.length; i < len; i++) {
if (
(opts.trimOnlySpaces && str[i] !== " ") ||
(!opts.trimOnlySpaces && str[i].trim())
) {
console.log(`2321 PUSH [0, ${i}]`);
rangesToDelete.push([0, i]);
break;
} else if (!str[i + 1]) {
// if end has been reached and whole string has been trimmable
console.log(`2326 PUSH [0, ${i + 1}]`);
rangesToDelete.push([0, i + 1]);
}
}
}
if (
str &&
// if only spaces were meant to be trimmed,
((opts.trimOnlySpaces &&
// and last character is a space
str[str.length - 1] === " ") ||
// if normal trim is requested
(!opts.trimOnlySpaces &&
// and the last character is whitespace character
!str[str.length - 1].trim()))
) {
for (let i = str.length; i--; ) {
if (
(opts.trimOnlySpaces && str[i] !== " ") ||
(!opts.trimOnlySpaces && str[i].trim())
) {
console.log(`2348 PUSH [i + 1, ${str.length}]`);
rangesToDelete.push([i + 1, str.length]);
break;
}
// don't tackle end-to-end because it would have been already caught on the
// start-to-end direction loop above.
}
}
// last correction, imagine we've got text-whitespace-tag.
// That last part "tag" was removed but "whitespace" in between is on the left.
// We need to trim() that too if applicable.
// By now we'll be able to tell, is starting/ending range array touching
// the start (index 0) or end (str.length - 1) character indexes, and if so,
// their inner sides will need to be trimmed accordingly, considering the
// "opts.trimOnlySpaces" of course.
const curr = rangesToDelete.current();
if ((!originalOpts || !originalOpts.cb) && curr) {
// check front - the first range of gathered ranges, does it touch start (0)
if (curr[0] && !curr[0][0]) {
console.log(
`2369 ${`\u001b[${33}m${`the first range`}\u001b[${39}m`} = ${JSON.stringify(
curr[0],
null,
4
)}`
);
const startingIdx = curr[0][1];
// check the character at str[startingIdx]
console.log(
`2378 ${`\u001b[${33}m${`startingIdx`}\u001b[${39}m`} = ${JSON.stringify(
startingIdx,
null,
4
)}`
);
// manually edit Ranges class:
(rangesToDelete.ranges as any)[0] = [
(rangesToDelete.ranges as any)[0][0],
(rangesToDelete.ranges as any)[0][1],
];
}
// check end - the last range of gathered ranges, does it touch the end (str.length)
// PS. remember ending is not inclusive, so ranges covering the whole ending
// would go up to str.length, not up to str.length - 1!
if (curr[curr.length - 1] && curr[curr.length - 1][1] === str.length) {
console.log(
`2397 ${`\u001b[${33}m${`the last range`}\u001b[${39}m`} = ${JSON.stringify(
curr[curr.length - 1],
null,
4
)}; str.length = ${str.length}`
);
const startingIdx = curr[curr.length - 1][0];
// check character at str[startingIdx - 1]
console.log(
`2406 ${`\u001b[${33}m${`startingIdx`}\u001b[${39}m`} = ${JSON.stringify(
startingIdx,
null,
4
)}`
);
// remove third element from the last range "what to add" - because
// ranges will crop aggressively, covering all whitespace, but they
// then restore missing spaces (in which case it's not missing).
// We already have tight crop, we just need to remove that "what to add"
// third element.
// hard edit:
/* istanbul ignore else */
if (rangesToDelete.ranges) {
let startingIdx2 =
rangesToDelete.ranges[rangesToDelete.ranges.length - 1][0];
if (
str[startingIdx2 - 1] &&
((opts.trimOnlySpaces && str[startingIdx2 - 1] === " ") ||
(!opts.trimOnlySpaces && !str[startingIdx2 - 1].trim()))
) {
startingIdx2 -= 1;
}
const backupWhatToAdd =
rangesToDelete.ranges[rangesToDelete.ranges.length - 1][2];
rangesToDelete.ranges[rangesToDelete.ranges.length - 1] = [
startingIdx2,
rangesToDelete.ranges[rangesToDelete.ranges.length - 1][1],
];
// for cases of opts.dumpLinkHrefsNearby
if (backupWhatToAdd && backupWhatToAdd.trim()) {
rangesToDelete.ranges[rangesToDelete.ranges.length - 1].push(
backupWhatToAdd.trimEnd() as any
);
}
}
}
}
const res: Res = {
log: {
timeTakenInMilliseconds: Date.now() - start,
},
result: rApply(str, rangesToDelete.current()),
ranges: rangesToDelete.current(),
allTagLocations,
filteredTagLocations,
};
console.log(
`2461 ${`\u001b[${32}m${`FINAL RESULT`}\u001b[${39}m`} = ${JSON.stringify(
res,
null,
4
)}`
);
return res;
}
export { stripHtml, defaults, version, CbObj }; | the_stack |
import { expect } from 'chai'
import { format, FormatOptions } from '../../src/format'
import { AMatcher, AnythingMatcher } from '../../src/matchers'
describe('format', () => {
const DEFAULTS: FormatOptions = {
minusZero: false,
uniqueNaNs: false,
ignorePrototypes: false,
compareErrorStack: false,
indentSize: 2,
inline: false,
maxLineLength: Infinity,
skipMatcherReplacement: false,
requireStrictEquality: false,
}
interface TestCaseGroup {
name: string
testCases: TestCase[]
}
type TestCase = [unknown, unknown, string, Partial<FormatOptions>?]
const groups: TestCaseGroup[] = [
{
name: 'numbers',
testCases: [
[1, null, '1'],
[0.2, null, '0.2'],
[-3, null, '-3'],
[1e50, null, '1e+50'],
[NaN, null, 'NaN'],
[NaN, NaN, 'NaN'],
[NaN, NaN, 'NaN (different)', { uniqueNaNs: true }],
[Infinity, null, 'Infinity'],
[-Infinity, null, '-Infinity'],
[0, null, '0'],
[-0, null, '0'],
[-0, null, '-0', { minusZero: true }],
],
},
{
name: 'symbols',
testCases: [
[Symbol(), null, 'Symbol()'],
[Symbol('foo'), null, 'Symbol(foo)'],
[Symbol('foo'), Symbol('foo'), 'Symbol(foo) (different)'],
[Symbol('foo'), Symbol('bar'), 'Symbol(foo)'],
[Symbol.for('foo'), null, 'Symbol.for("foo")'],
[Symbol.for('foo'), Symbol.for('foo'), 'Symbol.for("foo")'],
[Symbol.iterator, null, 'Symbol.iterator'],
],
},
{
name: 'strings',
testCases: [
['foo', null, '"foo"'],
['', null, '""'],
['a\nb', null, '"a\\nb"'],
],
},
{
name: 'bigints',
testCases: [
[BigInt(1), null, '1n'],
[BigInt(0), null, '0n'],
[BigInt(-1234), null, '-1234n'],
],
},
{
name: 'other primitives',
testCases: [
[true, null, 'true'],
[false, null, 'false'],
[null, null, 'null'],
[undefined, null, 'undefined'],
],
},
{
name: 'functions',
testCases: [
[function a() {}, null, 'function a()'],
[function a() {}, function a() {}, 'function a() (different)'],
[function () {}, null, 'function [anonymous]()'],
[function () {}, function () {}, 'function [anonymous]() (different)'],
[function* foo() {}, null, 'function* foo()'],
[function* foo() {}, function* foo() {}, 'function* foo() (different)'],
[function* () {}, null, 'function* [anonymous]()'],
[function* () {}, function* () {}, 'function* [anonymous]() (different)'],
// This is eval-ed to avoid typescript transpiling it
// With a higher target this wouldn't be necessary
// eslint-disable-next-line no-eval
...eval(`[
[async function foo() {}, null, 'async function foo()'],
[async function foo() {}, async function foo() {}, 'async function foo() (different)'],
[async function () {}, null, 'async function [anonymous]()'],
[async function () {}, async function () {}, 'async function [anonymous]() (different)'],
[async function* foo() {}, null, 'async function* foo()'],
[async function* foo() {}, async function* foo() {}, 'async function* foo() (different)'],
[async function* () {}, null, 'async function* [anonymous]()'],
[async function* () {}, async function* () {}, 'async function* [anonymous]() (different)'],
]`),
[Set.prototype.has, null, 'function has()'],
[Set.prototype.has, Map.prototype.has, 'function has() (different)'],
[class A {}, null, 'class A'],
[class A {}, class A {}, 'class A (different)'],
[class {}, null, 'class [anonymous]'],
[class {}, class {}, 'class [anonymous] (different)'],
[Array, null, 'function Array()'],
[Object.assign(function x() {}, { a: 1 }), null, 'function x() & {\n a: 1\n}'],
[Object.assign(function x() {}, { a: 1 }), function x() {}, 'function x() (different) & {\n a: 1\n}'],
[Object.assign(function () {}, { a: 1 }), null, 'function [anonymous]() & {\n a: 1\n}'],
[
class X {
static x = 2
},
null,
'class X & {\n x: 2\n}',
],
[Object.assign(class {}, { a: 1 }), null, 'class [anonymous] & {\n a: 1\n}'],
],
},
{
name: 'objects',
testCases: [
[{}, null, '{}'],
[{ x: 1, y: 2 }, null, '{\n x: 1\n y: 2\n}'],
[{ x: 1, y: 2 }, null, '{\n x: 1\n y: 2\n}', { indentSize: 4 }],
[{ x: 1, y: 2 }, null, '{ x: 1, y: 2 }', { inline: true }],
[{ y: 2, x: 1 }, null, '{\n x: 1\n y: 2\n}'],
[{ '': 1, y: 2 }, null, '{\n "": 1\n y: 2\n}'],
[{ 'foo\nbar': 1 }, null, '{\n "foo\\nbar": 1\n}'],
[{ x: 1, y: { a: 'x', b: 'y' } }, null, '{\n x: 1\n y: {\n a: "x"\n b: "y"\n }\n}'],
[{ x: 1, y: { a: 'x', b: 'y' } }, null, '{\n x: 1\n y: {\n a: "x"\n b: "y"\n }\n}', { indentSize: 1 }],
[{ x: 1, y: { a: 'x', b: 'y' } }, null, '{ x: 1, y: { a: "x", b: "y" } }', { inline: true }],
[new (class Foo {})(), null, 'Foo {}'],
[new (class Foo {})(), null, 'Foo {}', { inline: true }],
[
new (class Vector2 {
constructor(public x: number, public y: number) {}
})(1, 2),
null,
'Vector2 {\n x: 1\n y: 2\n}',
],
[
new (class Vector2 {
constructor(public x: number, public y: number) {}
})(1, 2),
new (class Vector2 {
constructor(public x: number, public y: number) {}
})(1, 2),
'Vector2 (different prototype) {\n x: 1\n y: 2\n}',
],
[
new (class Vector2 {
constructor(public x: number, public y: number) {}
})(1, 2),
null,
'{\n x: 1\n y: 2\n}',
{ ignorePrototypes: true },
],
[{ x: 1 }, {}, `(different) {\n x: 1\n}`, { requireStrictEquality: true }],
[
Object.assign(Object.create({}), { constructor: undefined }),
null,
'[custom prototype] {\n constructor: undefined\n}',
],
],
},
{
name: 'self-referencing objects',
testCases: [
[
(() => {
const x = { y: 2 }
;(x as any).x = x
return x
})(),
null,
'{ x: <Circular .>, y: 2 }',
{ inline: true },
],
[
(() => {
const a = { x: 1, y: 1 }
const x = { a, b: a }
return x
})(),
null,
'{ a: { x: 1, y: 1 }, b: { x: 1, y: 1 } }',
{ inline: true },
],
[
(() => {
const x = { x: { y: { z: {} } } }
x.x.y.z = x.x
return x
})(),
null,
'{ x: { y: { z: <Circular ..> } } }',
{ inline: true },
],
[
(() => {
const x = { x: { y: { z: {} } } }
x.x.y.z = x
return x
})(),
null,
'{ x: { y: { z: <Circular ...> } } }',
{ inline: true },
],
[
(() => {
const a = { ax: {}, ay: 1 }
const b = { bx: {}, by: 1 }
a.ax = b
b.bx = a
return a
})(),
null,
'{ ax: { bx: <Circular ..>, by: 1 }, ay: 1 }',
{ inline: true },
],
[
(() => {
function foo() {}
foo.x = foo
return foo
})(),
null,
'function foo() & { x: <Circular .> }',
{ inline: true },
],
],
},
{
name: 'arrays',
testCases: [
[[], null, '[]'],
[[1, 2, 'asd', { x: 1, y: 2 }], null, '[\n 1\n 2\n "asd"\n {\n x: 1\n y: 2\n }\n]'],
[[1, 2, 'asd', { x: 1, y: 2 }], null, '[1, 2, "asd", { x: 1, y: 2 }]', { inline: true }],
[[1, 2, 'asd', { x: 1, y: 2 }], null, '[\n 1\n 2\n "asd"\n {\n x: 1\n y: 2\n }\n]'],
[Object.assign([1, 2, 3], { y: 'foo', x: 'bar' }), null, '[\n 1\n 2\n 3\n x: "bar"\n y: "foo"\n]'],
[Object.assign([1, 2], { 3: 4 }), null, '[\n 1\n 2\n <empty>\n 4\n]'],
[
Object.assign([1, 2], { 4: 5 }, { length: 8 }),
null,
'[\n 1\n 2\n <2 empty items>\n 5\n <3 empty items>\n]',
],
[new Array(5), null, '[\n <5 empty items>\n]'],
[
Object.assign([1, 2], { 4: 5 }, { y: 'foo', x: 'bar' }),
null,
'[\n 1\n 2\n <2 empty items>\n 5\n x: "bar"\n y: "foo"\n]',
],
[class MyArray extends Array {}.from([1, 2]), null, 'MyArray [\n 1\n 2\n]'],
[class MyArray extends Array {}.from([]), null, 'MyArray []'],
[
class MyArray extends Array {}.from([1, 2]),
class MyArray extends Array {}.from([1, 2]),
'MyArray (different prototype) [\n 1\n 2\n]',
],
[class MyArray extends Array {}.from([1, 2]), null, '[\n 1\n 2\n]', { ignorePrototypes: true }],
],
},
{
name: 'date',
testCases: [
[new Date('2005-04-02T21:37:00.000+02:00'), null, 'Date 2005-04-02T19:37:00.000Z'],
[
Object.assign(new Date('2005-04-02T21:37:00.000+02:00'), { foo: 'bar' }),
null,
'Date 2005-04-02T19:37:00.000Z & {\n foo: "bar"\n}',
],
[new (class MyDate extends Date {})(0), null, 'MyDate 1970-01-01T00:00:00.000Z'],
[
new (class MyDate extends Date {})(0),
new (class MyDate extends Date {})(0),
'MyDate (different prototype) 1970-01-01T00:00:00.000Z',
],
[new (class MyDate extends Date {})(0), null, 'Date 1970-01-01T00:00:00.000Z', { ignorePrototypes: true }],
],
},
{
name: 'regexps',
testCases: [
[/asd/, null, '/asd/'],
[/asd/i, null, '/asd/i'],
[Object.assign(/asd/, { foo: 'bar' }), null, '/asd/ & {\n foo: "bar"\n}'],
[new (class MyRegExp extends RegExp {})('foo', 'gi'), null, 'MyRegExp /foo/gi'],
[
new (class MyRegExp extends RegExp {})('foo', 'gi'),
new (class MyRegExp extends RegExp {})('foo', 'gi'),
'MyRegExp (different prototype) /foo/gi',
],
[new (class MyRegExp extends RegExp {})('foo', 'gi'), null, '/foo/gi', { ignorePrototypes: true }],
],
},
{
name: 'primitive classes',
testCases: [
[new String('foo'), null, 'String "foo"'],
[new Number(123), null, 'Number 123'],
[new Boolean(false), null, 'Boolean false'],
[Object.assign(new String('foo'), { foo: 'bar' }), null, 'String "foo" & {\n foo: "bar"\n}'],
[new (class MyString extends String {})('foo'), null, 'MyString "foo"'],
[
new (class MyString extends String {})('foo'),
new (class MyString extends String {})('foo'),
'MyString (different prototype) "foo"',
],
[
new (class MyString extends String {})('foo'),
new (class MyString extends String {})('foo'),
'String "foo"',
{ ignorePrototypes: true },
],
[new (class MyNumber extends Number {})(123), null, 'MyNumber 123'],
[new (class MyBoolean extends Boolean {})(true), null, 'MyBoolean true'],
],
},
{
name: 'unique instances',
testCases: [
[Promise.resolve('foo'), null, 'Promise'],
[Promise.resolve('foo'), Promise.resolve('foo'), 'Promise (different)'],
[new WeakMap(), null, 'WeakMap'],
[new WeakMap(), new WeakMap(), 'WeakMap (different)'],
[new WeakSet(), null, 'WeakSet'],
[new WeakSet(), new WeakSet(), 'WeakSet (different)'],
[class MyPromise extends Promise<number> {}.resolve(1), null, 'MyPromise'],
[
class MyPromise extends Promise<number> {}.resolve(1),
class MyPromise extends Promise<number> {}.resolve(1),
'MyPromise (different prototype)',
],
[
class MyPromise extends Promise<number> {}.resolve(1),
class MyPromise extends Promise<number> {}.resolve(1),
'Promise (different)',
{ ignorePrototypes: true },
],
[
...(() => {
class MyPromise extends Promise<number> {}
return [MyPromise.resolve(1), MyPromise.resolve(1)]
})(),
'MyPromise (different)',
],
[class MyPromise extends Promise<number> {}.resolve(1), null, 'Promise', { ignorePrototypes: true }],
[new (class MyWeakMap extends WeakMap {})(), null, 'MyWeakMap'],
[
new (class MyWeakMap extends WeakMap {})(),
new (class MyWeakMap extends WeakMap {})(),
'MyWeakMap (different prototype)',
],
[
new (class MyWeakMap extends WeakMap {})(),
new (class MyWeakMap extends WeakMap {})(),
'WeakMap (different)',
{ ignorePrototypes: true },
],
[
...(() => {
class MyWeakMap extends WeakMap {}
return [new MyWeakMap(), new MyWeakMap()]
})(),
'MyWeakMap (different)',
],
[new (class MyWeakMap extends WeakMap {})(), null, 'WeakMap', { ignorePrototypes: true }],
[new (class MyWeakSet extends WeakSet {})(), null, 'MyWeakSet'],
[
new (class MyWeakSet extends WeakSet {})(),
new (class MyWeakSet extends WeakSet {})(),
'MyWeakSet (different prototype)',
],
[
new (class MyWeakSet extends WeakSet {})(),
new (class MyWeakSet extends WeakSet {})(),
'WeakSet (different)',
{ ignorePrototypes: true },
],
[
...(() => {
class MyWeakSet extends WeakSet {}
return [new MyWeakSet(), new MyWeakSet()]
})(),
'MyWeakSet (different)',
],
[new (class MyWeakSet extends WeakSet {})(), null, 'WeakSet', { ignorePrototypes: true }],
],
},
{
name: 'errors',
testCases: [
[new Error('foo'), null, 'Error {\n message: "foo"\n name: "Error"\n}'],
[new TypeError('foo'), null, 'TypeError {\n message: "foo"\n name: "TypeError"\n}'],
[new TypeError('foo'), null, 'Error {\n message: "foo"\n name: "TypeError"\n}', { ignorePrototypes: true }],
[new (class MyError extends Error {})('foo'), null, 'MyError {\n message: "foo"\n name: "Error"\n}'],
[
new (class MyError extends Error {})('foo'),
new (class MyError extends Error {})('foo'),
'MyError (different prototype) {\n message: "foo"\n name: "Error"\n}',
],
[
new (class MyError extends Error {})('foo'),
new (class MyError extends Error {})('foo'),
'Error {\n message: "foo"\n name: "Error"\n}',
{ ignorePrototypes: true },
],
[
new (class MyError extends Error {
asd = 3
})('foo'),
null,
'MyError {\n asd: 3\n message: "foo"\n name: "Error"\n}',
],
[Object.assign(new Error('foo'), { stack: 'foobar' }), null, 'Error {\n message: "foo"\n name: "Error"\n}'],
[
Object.assign(new Error('foo'), { stack: 'foobar' }),
null,
'Error {\n message: "foo"\n name: "Error"\n stack: "foobar"\n}',
{ compareErrorStack: true },
],
],
},
{
name: 'matchers',
testCases: [
[new AMatcher(String), 'foo', '"foo"'],
[new AMatcher(String), 'foo', 'Matcher [A: String]', { skipMatcherReplacement: true }],
[new AMatcher(String), 123, 'Matcher [A: String]'],
[new AnythingMatcher(), null, 'null'],
[new AnythingMatcher(), null, 'Matcher [Anything]', { skipMatcherReplacement: true }],
[{ foo: new AnythingMatcher() }, {}, '{\n foo: Matcher [Anything]\n}'],
[[new AnythingMatcher()], [], '[\n Matcher [Anything]\n]'],
[
{ x: new AnythingMatcher() },
(() => {
const x = { x: { y: { z: {} } } }
x.x.y.z = x
return x
})(),
'{ x: { y: { z: <Circular ...> } } }',
{ inline: true },
],
[
[new AnythingMatcher()],
(() => {
const x = [[[]]]
;(x as any)[0][0][0] = x
return x
})(),
'[[[<Circular ...>]]]',
{ inline: true },
],
],
},
{
name: 'sets',
testCases: [
[new Set(), null, 'Set {}'],
[new Set([1, 2, 3]), null, 'Set {\n 1\n 2\n 3\n}'],
[new Set([1, 2, 3, 4]), new Set([3, 2, 5]), 'Set {\n 3\n 2\n 1\n 4\n}'],
[new Set([{ x: 1 }]), new Set([{ x: 1 }]), 'Set {\n (different) {\n x: 1\n }\n}'],
[
new Set([{ x: { y: 1 } }]),
new Set([{ x: { y: 1 } }]),
'Set {\n (different) {\n x: {\n y: 1\n }\n }\n}',
],
[new Set([[[]]]), new Set([[[]]]), 'Set {\n (different) [\n []\n ]\n}'],
[Object.assign(new Set([1, 2]), { foo: 'bar' }), null, 'Set {\n 1\n 2\n foo: "bar"\n}'],
],
},
{
name: 'maps',
testCases: [
[new Map(), null, 'Map {}'],
[new Map([[1, 'a']]), null, 'Map {\n 1 => "a"\n}'],
[Object.assign(new Map([[1, 'a']]), { foo: 'bar' }), null, 'Map {\n 1 => "a"\n foo: "bar"\n}'],
[
new Map([
[1, 'a'],
[2, 'b'],
]),
null,
'Map {\n 1 => "a"\n 2 => "b"\n}',
],
[
new Map([
[1, 'a'],
[2, 'b'],
[3, 'c'],
[4, 'd'],
]),
new Map([
[3, 'x'],
[2, 'y'],
[5, 'z'],
]),
'Map {\n 3 => "c"\n 2 => "b"\n 1 => "a"\n 4 => "d"\n}',
],
[new Map([['a', true]]), null, 'Map {\n "a" => true\n}'],
[new Map([[{}, true]]), null, 'Map {\n {} => true\n}'],
[new Map([[{}, true]]), new Map([[{}, true]]), 'Map {\n (different) {} => true\n}'],
[new Map([[{}, {}]]), new Map([[{}, {}]]), 'Map {\n (different) {} => {}\n}'],
[new Map([[1, new AnythingMatcher()]]), new Map([[1, {}]]), 'Map {\n 1 => {}\n}'],
[new Map([[1, new AnythingMatcher()]]), new Map([[2, {}]]), 'Map {\n 1 => Matcher [Anything]\n}'],
[new Map([[{ x: 1 }, [2]]]), null, 'Map {\n {\n x: 1\n } => [\n 2\n ]\n}'],
[new Map([[{ x: 1 }, [2]]]), null, 'Map { { x: 1 } => [2] }', { inline: true }],
],
},
]
for (const { name, testCases } of groups) {
describe(name, () => {
for (const [a, b, expected, options] of testCases) {
const flags = options ? ` [${Object.keys(options).join(' ')}]` : ''
it(`${expected.replace(/\n/g, '\\n')}${flags}`, () => {
const result = format(a, b, { ...DEFAULTS, ...options })
expect(result).to.equal(expected)
})
}
})
}
}) | the_stack |
import fetchMock, { MockMatcherFunction } from "fetch-mock";
import { request } from "@octokit/request";
import { Octokit } from "@octokit/core";
import { createOAuthAppAuth, createOAuthUserAuth } from "../src/index";
test("README example with {type: 'oauth-app'}", async () => {
const auth = createOAuthAppAuth({
clientId: "123",
clientSecret: "secret",
});
const authentication = await auth({
type: "oauth-app",
});
expect(authentication).toEqual({
type: "oauth-app",
clientId: "123",
clientSecret: "secret",
clientType: "oauth-app",
headers: {
authorization: "basic MTIzOnNlY3JldA==", // btoa('123:secret')
},
});
});
test("README web flow example", async () => {
const mock = fetchMock.sandbox().postOnce(
"https://github.com/login/oauth/access_token",
{
access_token: "secret123",
scope: "",
token_type: "bearer",
},
{
headers: {
accept: "application/json",
"user-agent": "test",
"content-type": "application/json; charset=utf-8",
},
body: {
client_id: "123",
client_secret: "secret",
code: "random123",
state: "mystate123",
},
}
);
const auth = createOAuthAppAuth({
clientId: "123",
clientSecret: "secret",
request: request.defaults({
headers: {
"user-agent": "test",
},
request: {
fetch: mock,
},
}),
});
const authentication = await auth({
type: "oauth-user",
code: "random123",
state: "mystate123",
});
expect(authentication).toEqual({
clientId: "123",
clientSecret: "secret",
clientType: "oauth-app",
type: "token",
tokenType: "oauth",
token: "secret123",
scopes: [],
});
});
test("README device flow example", async () => {
const mock = fetchMock
.sandbox()
.postOnce(
"https://github.com/login/device/code",
{
device_code: "devicecode123",
user_code: "usercode123",
verification_uri: "https://github.com/login/device",
expires_in: 900,
// use low number because jest.useFakeTimers() & jest.runAllTimers() didn't work for me
interval: 0.005,
},
{
headers: {
accept: "application/json",
"user-agent": "test",
"content-type": "application/json; charset=utf-8",
},
body: {
client_id: "1234567890abcdef1234",
scope: "",
},
}
)
.postOnce(
"https://github.com/login/oauth/access_token",
{
access_token: "token123",
scope: "",
},
{
headers: {
accept: "application/json",
"user-agent": "test",
"content-type": "application/json; charset=utf-8",
},
body: {
client_id: "1234567890abcdef1234",
device_code: "devicecode123",
grant_type: "urn:ietf:params:oauth:grant-type:device_code",
},
overwriteRoutes: false,
}
);
const auth = createOAuthAppAuth({
clientId: "1234567890abcdef1234",
clientSecret: "secret",
// pass request mock for testing
request: request.defaults({
headers: {
"user-agent": "test",
},
request: {
fetch: mock,
},
}),
});
const onVerification = jest.fn();
const authentication = await auth({
type: "oauth-user",
onVerification,
});
expect(authentication).toEqual({
type: "token",
tokenType: "oauth",
clientType: "oauth-app",
clientId: "1234567890abcdef1234",
clientSecret: "secret",
token: "token123",
scopes: [],
});
expect(onVerification).toHaveBeenCalledWith({
device_code: "devicecode123",
expires_in: 900,
interval: 0.005,
user_code: "usercode123",
verification_uri: "https://github.com/login/device",
});
});
test("device flow with scopes", async () => {
const mock = fetchMock
.sandbox()
.postOnce(
"https://github.com/login/device/code",
{
device_code: "devicecode123",
user_code: "usercode123",
verification_uri: "https://github.com/login/device",
expires_in: 900,
// use low number because jest.useFakeTimers() & jest.runAllTimers() didn't work for me
interval: 0.005,
},
{
headers: {
accept: "application/json",
"user-agent": "test",
"content-type": "application/json; charset=utf-8",
},
body: {
client_id: "1234567890abcdef1234",
scope: "repo gist",
},
}
)
.postOnce(
"https://github.com/login/oauth/access_token",
{
access_token: "token123",
scope: "repo gist",
},
{
headers: {
accept: "application/json",
"user-agent": "test",
"content-type": "application/json; charset=utf-8",
},
body: {
client_id: "1234567890abcdef1234",
device_code: "devicecode123",
grant_type: "urn:ietf:params:oauth:grant-type:device_code",
},
overwriteRoutes: false,
}
);
const auth = createOAuthAppAuth({
clientId: "1234567890abcdef1234",
clientSecret: "secret",
// pass request mock for testing
request: request.defaults({
headers: {
"user-agent": "test",
},
request: {
fetch: mock,
},
}),
});
const onVerification = jest.fn();
const authentication = await auth({
type: "oauth-user",
scopes: ["repo", "gist"],
onVerification,
});
expect(authentication).toEqual({
type: "token",
tokenType: "oauth",
clientType: "oauth-app",
clientId: "1234567890abcdef1234",
clientSecret: "secret",
token: "token123",
scopes: ["repo", "gist"],
});
expect(onVerification).toHaveBeenCalledWith({
device_code: "devicecode123",
expires_in: 900,
interval: 0.005,
user_code: "usercode123",
verification_uri: "https://github.com/login/device",
});
});
test("README Octokit usage example", async () => {
const matchGetUserRequest: MockMatcherFunction = (url, options) => {
expect(url).toEqual("https://api.github.com/user");
expect(options.headers).toEqual(
expect.objectContaining({
accept: "application/vnd.github.v3+json",
authorization: "token token123",
})
);
return true;
};
const mock = fetchMock
.sandbox()
.postOnce(
"https://api.github.com/applications/1234567890abcdef1234/token",
{ ok: true },
{
body: {
access_token: "existingtoken123",
},
}
)
.postOnce(
"https://github.com/login/oauth/access_token",
{
access_token: "token123",
scope: "",
},
{
body: {
client_id: "1234567890abcdef1234",
client_secret: "1234567890abcdef1234567890abcdef12345678",
code: "code123",
},
}
)
.getOnce(matchGetUserRequest, {
login: "octocat",
});
const appOctokit = new Octokit({
authStrategy: createOAuthAppAuth,
auth: {
clientId: "1234567890abcdef1234",
clientSecret: "1234567890abcdef1234567890abcdef12345678",
},
userAgent: "test",
request: {
fetch: mock,
},
});
// Send requests as app
const { data } = await appOctokit.request(
"POST /applications/{client_id}/token",
{
client_id: "1234567890abcdef1234",
access_token: "existingtoken123",
}
);
expect(data).toEqual({ ok: true });
// create a new octokit instance that is authenticated as the user
const userOctokit = (await appOctokit.auth({
type: "oauth-user",
code: "code123",
factory: (options: any) => {
return new Octokit({
authStrategy: createOAuthUserAuth,
auth: options,
userAgent: "test",
request: {
fetch: mock,
},
});
},
})) as Octokit;
// Exchanges the code for the user access token authentication on first request
// and caches the authentication for successive requests
const {
data: { login },
} = await userOctokit.request("GET /user");
expect(login).toEqual("octocat");
});
test("GitHub App", async () => {
const mock = fetchMock.sandbox().postOnce(
"https://github.com/login/oauth/access_token",
{
access_token: "secret123",
scope: "",
token_type: "bearer",
},
{
headers: {
accept: "application/json",
"user-agent": "test",
"content-type": "application/json; charset=utf-8",
},
body: {
client_id: "lv1.1234567890abcdef",
client_secret: "1234567890abcdef1234567890abcdef12345678",
code: "random123",
state: "mystate123",
},
}
);
const auth = createOAuthAppAuth({
clientId: "lv1.1234567890abcdef",
clientSecret: "1234567890abcdef1234567890abcdef12345678",
clientType: "github-app",
request: request.defaults({
headers: {
"user-agent": "test",
},
request: {
fetch: mock,
},
}),
});
const authentication = await auth({
type: "oauth-user",
code: "random123",
state: "mystate123",
});
expect(authentication).toEqual({
clientId: "lv1.1234567890abcdef",
clientSecret: "1234567890abcdef1234567890abcdef12345678",
clientType: "github-app",
type: "token",
tokenType: "oauth",
token: "secret123",
});
});
test("`factory` auth option", async () => {
const mock = fetchMock.sandbox().postOnce(
"https://github.com/login/oauth/access_token",
{
access_token: "secret123",
scope: "",
token_type: "bearer",
},
{
headers: {
accept: "application/json",
"user-agent": "test",
"content-type": "application/json; charset=utf-8",
},
body: {
client_id: "1234567890abcdef1234",
client_secret: "1234567890abcdef1234567890abcdef12345678",
code: "random123",
},
}
);
const appAuth = createOAuthAppAuth({
clientType: "oauth-app",
clientId: "1234567890abcdef1234",
clientSecret: "1234567890abcdef1234567890abcdef12345678",
request: request.defaults({
headers: {
"user-agent": "test",
},
request: {
fetch: mock,
},
}),
});
const userAuth = await appAuth({
type: "oauth-user",
code: "random123",
factory: (options) => createOAuthUserAuth(options),
});
const authentication = await userAuth();
expect(authentication).toEqual({
clientId: "1234567890abcdef1234",
clientSecret: "1234567890abcdef1234567890abcdef12345678",
clientType: "oauth-app",
type: "token",
tokenType: "oauth",
token: "secret123",
scopes: [],
});
});
test("request with custom baseUrl (GHE)", async () => {
const mock = fetchMock.sandbox().postOnce(
"https://github.acme-inc.com/login/oauth/access_token",
{
access_token: "secret123",
scope: "",
token_type: "bearer",
},
{
headers: {
accept: "application/json",
"user-agent": "test",
"content-type": "application/json; charset=utf-8",
},
body: {
client_id: "123",
client_secret: "secret",
code: "random123",
},
}
);
const auth = createOAuthAppAuth({
clientId: "123",
clientSecret: "secret",
request: request.defaults({
baseUrl: "https://github.acme-inc.com/api/v3",
headers: {
"user-agent": "test",
},
request: {
fetch: mock,
},
}),
});
const authentication = await auth({
type: "oauth-user",
code: "random123",
});
expect(authentication).toMatchInlineSnapshot(`
Object {
"clientId": "123",
"clientSecret": "secret",
"clientType": "oauth-app",
"scopes": Array [],
"token": "secret123",
"tokenType": "oauth",
"type": "token",
}
`);
});
test("auth.hook with custom baseUrl (GHE)", async () => {
const mock = fetchMock.sandbox().postOnce(
"https://github.acme-inc.com/api/v3/applications/123/token",
{ ok: true },
{
body: {
access_token: "secret123",
},
}
);
const auth = createOAuthAppAuth({
clientId: "123",
clientSecret: "secret",
});
const requestWithMock = request.defaults({
baseUrl: "https://github.acme-inc.com/api/v3",
request: {
fetch: mock,
hook: auth.hook,
},
});
const { data } = await auth.hook(
requestWithMock,
"POST /applications/{client_id}/token",
{
client_id: "123",
access_token: "secret123",
}
);
expect(data).toEqual({
ok: true,
});
});
test("auth.hook(request, 'POST https://github.com/login/oauth/access_token') does not send request twice (#35)", async () => {
const mock = fetchMock
.sandbox()
.postOnce("https://github.com/login/oauth/access_token", {
access_token: "secret123",
scope: "",
});
const auth = createOAuthAppAuth({
clientId: "123",
clientSecret: "secret",
});
const requestWithAuth = request.defaults({
request: {
fetch: mock,
hook: auth.hook,
},
});
await requestWithAuth("POST https://github.com/login/oauth/access_token", {
headers: {
accept: "application/json",
},
type: "token",
code: "random123",
state: "mystate123",
});
});
test("auth.hook(request, 'POST /applications/{client_id}/token') checks token", async () => {
const mock = fetchMock
.sandbox()
.postOnce("https://github.com/login/oauth/access_token", {
access_token: "secret123",
scope: "",
})
.postOnce(
"https://api.github.com/applications/123/token",
{
token: "secret123",
},
{
body: {
access_token: "secret123",
},
}
);
const auth = createOAuthAppAuth({
clientId: "123",
clientSecret: "secret",
});
const requestWithAuth = request.defaults({
request: {
fetch: mock,
hook: auth.hook,
},
});
const response = await requestWithAuth(
"POST /applications/{client_id}/token",
{
client_id: "123",
access_token: "secret123",
}
);
expect(response.data.token).toEqual("secret123");
});
test("auth.hook(request, 'GET /user)", async () => {
const mock = fetchMock.sandbox().getOnce("https://api.github.com/user", {
status: 401,
});
const auth = createOAuthAppAuth({
clientId: "12345678901234567890",
clientSecret: "1234567890123456789012345678901234567890",
});
const requestWithAuth = request.defaults({
request: {
fetch: mock,
hook: auth.hook,
},
});
await expect(async () => requestWithAuth("GET /user")).rejects.toThrow(
'[@octokit/auth-oauth-app] "GET /user" does not support clientId/clientSecret basic authentication'
);
});
test("auth.hook(request, 'GET /repos/{owner}/{repo})", async () => {
const mock = fetchMock
.sandbox()
.getOnce("https://api.github.com/repos/octokit/octokit.js", {
ok: true,
});
const auth = createOAuthAppAuth({
clientId: "12345678901234567890",
clientSecret: "1234567890123456789012345678901234567890",
});
const requestWithAuth = request.defaults({
request: {
fetch: mock,
hook: auth.hook,
},
});
const { data } = await requestWithAuth("GET /repos/{owner}/{repo}", {
owner: "octokit",
repo: "octokit.js",
});
expect(data).toStrictEqual({ ok: true });
});
test("auth.hook(request, 'GET /repos/{owner}/{repo}) as GitHub App", async () => {
const mock = fetchMock
.sandbox()
.getOnce("https://api.github.com/repos/octokit/octokit.js", {
ok: true,
});
const auth = createOAuthAppAuth({
clientType: "github-app",
clientId: "lv1.1234567890abcdef",
clientSecret: "1234567890abcdef1234567890abcdef12345678",
});
const requestWithAuth = request.defaults({
request: {
fetch: mock,
hook: auth.hook,
},
});
await expect(async () =>
requestWithAuth("GET /repos/{owner}/{repo}")
).rejects.toThrow(
'[@octokit/auth-oauth-app] GitHub Apps cannot use their client ID/secret for basic authentication for endpoints other than "/applications/{client_id}/**". "GET /repos/{owner}/{repo}" is not supported.'
);
}); | the_stack |
import { ServiceClientOptions, RequestOptions, ServiceCallback, HttpOperationResponse } from 'ms-rest';
import * as models from '../models';
/**
* @class
* Operations
* __NOTE__: An instance of this class is automatically created for an
* instance of the HanaManagementClient.
*/
export interface Operations {
/**
* Gets a list of SAP HANA management operations.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<OperationList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.OperationList>>;
/**
* Gets a list of SAP HANA management operations.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {OperationList} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {OperationList} [result] - The deserialized result object if an error did not occur.
* See {@link OperationList} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.OperationList>;
list(callback: ServiceCallback<models.OperationList>): void;
list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.OperationList>): void;
}
/**
* @class
* HanaInstances
* __NOTE__: An instance of this class is automatically created for an
* instance of the HanaManagementClient.
*/
export interface HanaInstances {
/**
* @summary Gets a list of SAP HANA instances in the specified subscription.
*
* Gets a list of SAP HANA instances in the specified subscription. The
* operations returns various properties of each SAP HANA on Azure instance.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<HanaInstancesListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.HanaInstancesListResult>>;
/**
* @summary Gets a list of SAP HANA instances in the specified subscription.
*
* Gets a list of SAP HANA instances in the specified subscription. The
* operations returns various properties of each SAP HANA on Azure instance.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {HanaInstancesListResult} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {HanaInstancesListResult} [result] - The deserialized result object if an error did not occur.
* See {@link HanaInstancesListResult} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.HanaInstancesListResult>;
list(callback: ServiceCallback<models.HanaInstancesListResult>): void;
list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.HanaInstancesListResult>): void;
/**
* @summary Gets a list of SAP HANA instances in the specified subscription and
* the resource group.
*
* Gets a list of SAP HANA instances in the specified subscription and the
* resource group. The operations returns various properties of each SAP HANA
* on Azure instance.
*
* @param {string} resourceGroupName Name of the resource group.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<HanaInstancesListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listByResourceGroupWithHttpOperationResponse(resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.HanaInstancesListResult>>;
/**
* @summary Gets a list of SAP HANA instances in the specified subscription and
* the resource group.
*
* Gets a list of SAP HANA instances in the specified subscription and the
* resource group. The operations returns various properties of each SAP HANA
* on Azure instance.
*
* @param {string} resourceGroupName Name of the resource group.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {HanaInstancesListResult} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {HanaInstancesListResult} [result] - The deserialized result object if an error did not occur.
* See {@link HanaInstancesListResult} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listByResourceGroup(resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.HanaInstancesListResult>;
listByResourceGroup(resourceGroupName: string, callback: ServiceCallback<models.HanaInstancesListResult>): void;
listByResourceGroup(resourceGroupName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.HanaInstancesListResult>): void;
/**
* @summary Gets properties of a SAP HANA instance.
*
* Gets properties of a SAP HANA instance for the specified subscription,
* resource group, and instance name.
*
* @param {string} resourceGroupName Name of the resource group.
*
* @param {string} hanaInstanceName Name of the SAP HANA on Azure instance.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<HanaInstance>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getWithHttpOperationResponse(resourceGroupName: string, hanaInstanceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.HanaInstance>>;
/**
* @summary Gets properties of a SAP HANA instance.
*
* Gets properties of a SAP HANA instance for the specified subscription,
* resource group, and instance name.
*
* @param {string} resourceGroupName Name of the resource group.
*
* @param {string} hanaInstanceName Name of the SAP HANA on Azure instance.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {HanaInstance} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {HanaInstance} [result] - The deserialized result object if an error did not occur.
* See {@link HanaInstance} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
get(resourceGroupName: string, hanaInstanceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.HanaInstance>;
get(resourceGroupName: string, hanaInstanceName: string, callback: ServiceCallback<models.HanaInstance>): void;
get(resourceGroupName: string, hanaInstanceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.HanaInstance>): void;
/**
* @summary Patches the Tags field of a SAP HANA instance.
*
* Patches the Tags field of a SAP HANA instance for the specified
* subscription, resource group, and instance name.
*
* @param {string} resourceGroupName Name of the resource group.
*
* @param {string} hanaInstanceName Name of the SAP HANA on Azure instance.
*
* @param {object} tagsParameter Request body that only contains the new Tags
* field
*
* @param {object} [tagsParameter.tags] Tags field of the HANA instance.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<HanaInstance>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
updateWithHttpOperationResponse(resourceGroupName: string, hanaInstanceName: string, tagsParameter: models.Tags, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.HanaInstance>>;
/**
* @summary Patches the Tags field of a SAP HANA instance.
*
* Patches the Tags field of a SAP HANA instance for the specified
* subscription, resource group, and instance name.
*
* @param {string} resourceGroupName Name of the resource group.
*
* @param {string} hanaInstanceName Name of the SAP HANA on Azure instance.
*
* @param {object} tagsParameter Request body that only contains the new Tags
* field
*
* @param {object} [tagsParameter.tags] Tags field of the HANA instance.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {HanaInstance} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {HanaInstance} [result] - The deserialized result object if an error did not occur.
* See {@link HanaInstance} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
update(resourceGroupName: string, hanaInstanceName: string, tagsParameter: models.Tags, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.HanaInstance>;
update(resourceGroupName: string, hanaInstanceName: string, tagsParameter: models.Tags, callback: ServiceCallback<models.HanaInstance>): void;
update(resourceGroupName: string, hanaInstanceName: string, tagsParameter: models.Tags, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.HanaInstance>): void;
/**
* The operation to restart a SAP HANA instance.
*
* @param {string} resourceGroupName Name of the resource group.
*
* @param {string} hanaInstanceName Name of the SAP HANA on Azure instance.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
restartWithHttpOperationResponse(resourceGroupName: string, hanaInstanceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>;
/**
* The operation to restart a SAP HANA instance.
*
* @param {string} resourceGroupName Name of the resource group.
*
* @param {string} hanaInstanceName Name of the SAP HANA on Azure instance.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
restart(resourceGroupName: string, hanaInstanceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>;
restart(resourceGroupName: string, hanaInstanceName: string, callback: ServiceCallback<void>): void;
restart(resourceGroupName: string, hanaInstanceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void;
/**
* The operation to add a monitor to an SAP HANA instance.
*
* @param {string} resourceGroupName Name of the resource group.
*
* @param {string} hanaInstanceName Name of the SAP HANA on Azure instance.
*
* @param {object} monitoringParameter Request body that only contains
* monitoring attributes
*
* @param {string} [monitoringParameter.hanaVnet] ARM ID of an Azure Vnet with
* access to the HANA instance.
*
* @param {string} [monitoringParameter.hanaHostname] Hostname of the HANA
* Instance blade.
*
* @param {string} [monitoringParameter.hanaInstanceNum] A number between 00
* and 99, stored as a string to maintain leading zero.
*
* @param {string} [monitoringParameter.dbContainer] Either single or multiple
* depending on the use of MDC(Multiple Database Containers). Possible values
* include: 'single', 'multiple'
*
* @param {string} [monitoringParameter.hanaDatabase] Name of the database
* itself. It only needs to be specified if using MDC
*
* @param {string} [monitoringParameter.hanaDbUsername] Username for the HANA
* database to login to for monitoring
*
* @param {string} [monitoringParameter.hanaDbPassword] Password for the HANA
* database to login for monitoring
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
enableMonitoringWithHttpOperationResponse(resourceGroupName: string, hanaInstanceName: string, monitoringParameter: models.MonitoringDetails, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>;
/**
* The operation to add a monitor to an SAP HANA instance.
*
* @param {string} resourceGroupName Name of the resource group.
*
* @param {string} hanaInstanceName Name of the SAP HANA on Azure instance.
*
* @param {object} monitoringParameter Request body that only contains
* monitoring attributes
*
* @param {string} [monitoringParameter.hanaVnet] ARM ID of an Azure Vnet with
* access to the HANA instance.
*
* @param {string} [monitoringParameter.hanaHostname] Hostname of the HANA
* Instance blade.
*
* @param {string} [monitoringParameter.hanaInstanceNum] A number between 00
* and 99, stored as a string to maintain leading zero.
*
* @param {string} [monitoringParameter.dbContainer] Either single or multiple
* depending on the use of MDC(Multiple Database Containers). Possible values
* include: 'single', 'multiple'
*
* @param {string} [monitoringParameter.hanaDatabase] Name of the database
* itself. It only needs to be specified if using MDC
*
* @param {string} [monitoringParameter.hanaDbUsername] Username for the HANA
* database to login to for monitoring
*
* @param {string} [monitoringParameter.hanaDbPassword] Password for the HANA
* database to login for monitoring
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
enableMonitoring(resourceGroupName: string, hanaInstanceName: string, monitoringParameter: models.MonitoringDetails, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>;
enableMonitoring(resourceGroupName: string, hanaInstanceName: string, monitoringParameter: models.MonitoringDetails, callback: ServiceCallback<void>): void;
enableMonitoring(resourceGroupName: string, hanaInstanceName: string, monitoringParameter: models.MonitoringDetails, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void;
/**
* The operation to restart a SAP HANA instance.
*
* @param {string} resourceGroupName Name of the resource group.
*
* @param {string} hanaInstanceName Name of the SAP HANA on Azure instance.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
beginRestartWithHttpOperationResponse(resourceGroupName: string, hanaInstanceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>;
/**
* The operation to restart a SAP HANA instance.
*
* @param {string} resourceGroupName Name of the resource group.
*
* @param {string} hanaInstanceName Name of the SAP HANA on Azure instance.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
beginRestart(resourceGroupName: string, hanaInstanceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>;
beginRestart(resourceGroupName: string, hanaInstanceName: string, callback: ServiceCallback<void>): void;
beginRestart(resourceGroupName: string, hanaInstanceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void;
/**
* The operation to add a monitor to an SAP HANA instance.
*
* @param {string} resourceGroupName Name of the resource group.
*
* @param {string} hanaInstanceName Name of the SAP HANA on Azure instance.
*
* @param {object} monitoringParameter Request body that only contains
* monitoring attributes
*
* @param {string} [monitoringParameter.hanaVnet] ARM ID of an Azure Vnet with
* access to the HANA instance.
*
* @param {string} [monitoringParameter.hanaHostname] Hostname of the HANA
* Instance blade.
*
* @param {string} [monitoringParameter.hanaInstanceNum] A number between 00
* and 99, stored as a string to maintain leading zero.
*
* @param {string} [monitoringParameter.dbContainer] Either single or multiple
* depending on the use of MDC(Multiple Database Containers). Possible values
* include: 'single', 'multiple'
*
* @param {string} [monitoringParameter.hanaDatabase] Name of the database
* itself. It only needs to be specified if using MDC
*
* @param {string} [monitoringParameter.hanaDbUsername] Username for the HANA
* database to login to for monitoring
*
* @param {string} [monitoringParameter.hanaDbPassword] Password for the HANA
* database to login for monitoring
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
beginEnableMonitoringWithHttpOperationResponse(resourceGroupName: string, hanaInstanceName: string, monitoringParameter: models.MonitoringDetails, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>;
/**
* The operation to add a monitor to an SAP HANA instance.
*
* @param {string} resourceGroupName Name of the resource group.
*
* @param {string} hanaInstanceName Name of the SAP HANA on Azure instance.
*
* @param {object} monitoringParameter Request body that only contains
* monitoring attributes
*
* @param {string} [monitoringParameter.hanaVnet] ARM ID of an Azure Vnet with
* access to the HANA instance.
*
* @param {string} [monitoringParameter.hanaHostname] Hostname of the HANA
* Instance blade.
*
* @param {string} [monitoringParameter.hanaInstanceNum] A number between 00
* and 99, stored as a string to maintain leading zero.
*
* @param {string} [monitoringParameter.dbContainer] Either single or multiple
* depending on the use of MDC(Multiple Database Containers). Possible values
* include: 'single', 'multiple'
*
* @param {string} [monitoringParameter.hanaDatabase] Name of the database
* itself. It only needs to be specified if using MDC
*
* @param {string} [monitoringParameter.hanaDbUsername] Username for the HANA
* database to login to for monitoring
*
* @param {string} [monitoringParameter.hanaDbPassword] Password for the HANA
* database to login for monitoring
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
beginEnableMonitoring(resourceGroupName: string, hanaInstanceName: string, monitoringParameter: models.MonitoringDetails, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>;
beginEnableMonitoring(resourceGroupName: string, hanaInstanceName: string, monitoringParameter: models.MonitoringDetails, callback: ServiceCallback<void>): void;
beginEnableMonitoring(resourceGroupName: string, hanaInstanceName: string, monitoringParameter: models.MonitoringDetails, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void;
/**
* @summary Gets a list of SAP HANA instances in the specified subscription.
*
* Gets a list of SAP HANA instances in the specified subscription. The
* operations returns various properties of each SAP HANA on Azure instance.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<HanaInstancesListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.HanaInstancesListResult>>;
/**
* @summary Gets a list of SAP HANA instances in the specified subscription.
*
* Gets a list of SAP HANA instances in the specified subscription. The
* operations returns various properties of each SAP HANA on Azure instance.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {HanaInstancesListResult} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {HanaInstancesListResult} [result] - The deserialized result object if an error did not occur.
* See {@link HanaInstancesListResult} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.HanaInstancesListResult>;
listNext(nextPageLink: string, callback: ServiceCallback<models.HanaInstancesListResult>): void;
listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.HanaInstancesListResult>): void;
/**
* @summary Gets a list of SAP HANA instances in the specified subscription and
* the resource group.
*
* Gets a list of SAP HANA instances in the specified subscription and the
* resource group. The operations returns various properties of each SAP HANA
* on Azure instance.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<HanaInstancesListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listByResourceGroupNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.HanaInstancesListResult>>;
/**
* @summary Gets a list of SAP HANA instances in the specified subscription and
* the resource group.
*
* Gets a list of SAP HANA instances in the specified subscription and the
* resource group. The operations returns various properties of each SAP HANA
* on Azure instance.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {HanaInstancesListResult} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {HanaInstancesListResult} [result] - The deserialized result object if an error did not occur.
* See {@link HanaInstancesListResult} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listByResourceGroupNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.HanaInstancesListResult>;
listByResourceGroupNext(nextPageLink: string, callback: ServiceCallback<models.HanaInstancesListResult>): void;
listByResourceGroupNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.HanaInstancesListResult>): void;
} | the_stack |
import { inject, TestBed, waitForAsync } from '@angular/core/testing';
import {
ConfigService,
DEFAULT_CAROUSEL_BREAKPOINTS,
DEFAULT_CAROUSEL_DESCRIPTION,
DEFAULT_CAROUSEL_IMAGE_CONFIG,
DEFAULT_CAROUSEL_PREVIEWS_CONFIG,
DEFAULT_CURRENT_CAROUSEL_CONFIG,
DEFAULT_CURRENT_CAROUSEL_PLAY,
DEFAULT_CURRENT_IMAGE_CONFIG,
DEFAULT_DESCRIPTION,
DEFAULT_DESCRIPTION_STYLE,
DEFAULT_KEYBOARD_SERVICE_CONFIG,
DEFAULT_LAYOUT,
DEFAULT_LOADING,
DEFAULT_PLAIN_CONFIG,
DEFAULT_PREVIEW_CONFIG,
DEFAULT_PREVIEW_SIZE,
DEFAULT_SLIDE_CONFIG
} from './config.service';
import { LibConfig } from '../model/lib-config.interface';
import { ButtonsConfig, ButtonsStrategy, ButtonType } from '../model/buttons-config.interface';
import { AccessibilityConfig } from '../model/accessibility.interface';
import { KS_DEFAULT_ACCESSIBILITY_CONFIG } from '../components/accessibility-default';
import { Size } from '../model/size.interface';
import { DotsConfig } from '../model/dots-config.interface';
import { KeyboardConfig } from '../model/keyboard-config.interface';
import { CarouselConfig } from '../model/carousel-config.interface';
import { PlayConfig } from '../model/play-config.interface';
import { KeyboardServiceConfig } from '../model/keyboard-service-config.interface';
import { CarouselPreviewConfig } from '../model/carousel-preview-config.interface';
import { CarouselImageConfig } from '../model/carousel-image-config.interface';
import { Description, DescriptionStrategy, DescriptionStyle } from '../model/description.interface';
import { AdvancedConfig, AdvancedLayout, GridLayout, LineLayout, PlainGalleryConfig, PlainGalleryStrategy } from '../model/plain-gallery-config.interface';
import { CurrentImageConfig } from '../model/current-image-config.interface';
import { LoadingConfig, LoadingType } from '../model/loading-config.interface';
import { SidePreviewsConfig, SlideConfig } from '../model/slide-config.interface';
import { PreviewConfig } from '../model/preview-config.interface';
// tslint:disable:no-shadowed-variable
describe('ConfigService', () => {
beforeEach(
waitForAsync(() => {
TestBed.configureTestingModule({
providers: [ConfigService]
});
})
);
it('should instantiate service when inject service',
inject([ConfigService], (service: ConfigService) => {
expect(service instanceof ConfigService).toEqual(true);
})
);
describe('#setConfig()', () => {
describe('---YES---', () => {
describe('slideConfig', () => {
it(`should call setConfig to update the library configuration with an undefined slideConfig`,
inject([ConfigService], (service: ConfigService) => {
const inputConfig: LibConfig = {
slideConfig: undefined
};
service.setConfig(1, inputConfig);
const result: LibConfig | undefined = service.getConfig(1);
expect(result?.slideConfig).toEqual(DEFAULT_SLIDE_CONFIG);
})
);
it(`should call setConfig to update the library configuration with a custom slideConfig (playConfig and sidePreviews are undefined)`,
inject([ConfigService], (service: ConfigService) => {
const inputConfig: LibConfig = {
slideConfig: {
infinite: true,
playConfig: undefined,
sidePreviews: undefined
} as SlideConfig
};
service.setConfig(1, inputConfig);
const result: LibConfig | undefined = service.getConfig(1);
expect(result?.slideConfig?.infinite).toEqual(inputConfig.slideConfig?.infinite);
expect(result?.slideConfig?.playConfig).toEqual({autoPlay: false, interval: 5000, pauseOnHover: true} as PlayConfig);
expect(result?.slideConfig?.sidePreviews).toEqual({show: true, size: {width: '100px', height: 'auto'}} as SidePreviewsConfig);
})
);
it(`should call setConfig to update the library configuration with a custom slideConfig`,
inject([ConfigService], (service: ConfigService) => {
const inputConfig: LibConfig = {
slideConfig: {
infinite: true,
playConfig: {autoPlay: true, interval: 10000, pauseOnHover: false} as PlayConfig,
sidePreviews: {show: false, size: {width: '200px', height: '100px'}} as SidePreviewsConfig
} as SlideConfig
};
service.setConfig(1, inputConfig);
const result: LibConfig | undefined = service.getConfig(1);
expect(result?.slideConfig?.infinite).toEqual(inputConfig.slideConfig?.infinite);
expect(result?.slideConfig?.playConfig?.autoPlay).toEqual(inputConfig.slideConfig?.playConfig?.autoPlay);
expect(result?.slideConfig?.playConfig?.interval).toEqual(inputConfig.slideConfig?.playConfig?.interval);
expect(result?.slideConfig?.playConfig?.pauseOnHover).toEqual(inputConfig.slideConfig?.playConfig?.pauseOnHover);
expect(result?.slideConfig?.sidePreviews?.show).toEqual(inputConfig.slideConfig?.sidePreviews?.show);
expect(result?.slideConfig?.sidePreviews?.size?.width).toEqual(inputConfig.slideConfig?.sidePreviews?.size?.width);
expect(result?.slideConfig?.sidePreviews?.size?.height).toEqual(inputConfig.slideConfig?.sidePreviews?.size?.height);
})
);
});
describe('accessibilityConfig', () => {
it(`should call setConfig to update the library configuration with an undefined accessibilityConfig`,
inject([ConfigService], (service: ConfigService) => {
const inputConfig: LibConfig = {
accessibilityConfig: undefined
};
service.setConfig(1, inputConfig);
const result: LibConfig | undefined = service.getConfig(1);
expect(result?.accessibilityConfig).toEqual(KS_DEFAULT_ACCESSIBILITY_CONFIG);
})
);
it(`should call setConfig to update the library configuration with a custom accessibilityConfig`,
inject([ConfigService], (service: ConfigService) => {
const inputConfig: LibConfig = {
accessibilityConfig: {
backgroundAriaLabel: 'example-test'
} as AccessibilityConfig
};
service.setConfig(1, inputConfig);
const result: LibConfig | undefined = service.getConfig(1);
if (!result || !result.accessibilityConfig || !inputConfig || !inputConfig.accessibilityConfig) {
throw new Error('Interrupted test, because of some undefined values');
}
expect(result.accessibilityConfig.backgroundAriaLabel).toEqual(inputConfig.accessibilityConfig.backgroundAriaLabel);
})
);
});
describe('previewConfig', () => {
it(`should call setConfig to update the library configuration with an undefined previewConfig`,
inject([ConfigService], (service: ConfigService) => {
const inputConfig: LibConfig = {
previewConfig: undefined
};
service.setConfig(1, inputConfig);
const result: LibConfig | undefined = service.getConfig(1);
expect(result?.previewConfig).toEqual(DEFAULT_PREVIEW_CONFIG);
})
);
it(`should call setConfig to update the library configuration with a custom previewConfig`,
inject([ConfigService], (service: ConfigService) => {
const inputConfig: LibConfig = {
previewConfig: {
visible: false,
number: 2,
arrows: false,
clickable: false,
size: DEFAULT_PREVIEW_SIZE
} as PreviewConfig
};
service.setConfig(1, inputConfig);
const result: LibConfig | undefined = service.getConfig(1);
expect(result?.previewConfig?.visible).toEqual(inputConfig.previewConfig?.visible);
expect(result?.previewConfig?.number).toEqual(inputConfig.previewConfig?.number);
expect(result?.previewConfig?.arrows).toEqual(inputConfig.previewConfig?.arrows);
expect(result?.previewConfig?.clickable).toEqual(inputConfig.previewConfig?.clickable);
expect(result?.previewConfig?.size).toEqual(inputConfig.previewConfig?.size);
})
);
it(`should call setConfig to update the library configuration with a custom previewConfig (number < 0)`,
inject([ConfigService], (service: ConfigService) => {
const inputConfig: LibConfig = {
previewConfig: {
visible: false,
number: -1,
arrows: false,
clickable: false,
size: DEFAULT_PREVIEW_SIZE
} as PreviewConfig
};
service.setConfig(1, inputConfig);
const result: LibConfig | undefined = service.getConfig(1);
expect(result?.previewConfig?.visible).toEqual(inputConfig.previewConfig?.visible);
expect(result?.previewConfig?.number).toEqual(DEFAULT_PREVIEW_CONFIG.number);
expect(result?.previewConfig?.arrows).toEqual(inputConfig.previewConfig?.arrows);
expect(result?.previewConfig?.clickable).toEqual(inputConfig.previewConfig?.clickable);
expect(result?.previewConfig?.size).toEqual(inputConfig.previewConfig?.size);
})
);
it(`should call setConfig to update the library configuration with a custom previewConfig (number = 0)`,
inject([ConfigService], (service: ConfigService) => {
const inputConfig: LibConfig = {
previewConfig: {
visible: false,
number: 0,
arrows: false,
clickable: false,
size: DEFAULT_PREVIEW_SIZE
} as PreviewConfig
};
service.setConfig(1, inputConfig);
const result: LibConfig | undefined = service.getConfig(1);
expect(result?.previewConfig?.visible).toEqual(inputConfig.previewConfig?.visible);
expect(result?.previewConfig?.number).toEqual(DEFAULT_PREVIEW_CONFIG.number);
expect(result?.previewConfig?.arrows).toEqual(inputConfig.previewConfig?.arrows);
expect(result?.previewConfig?.clickable).toEqual(inputConfig.previewConfig?.clickable);
expect(result?.previewConfig?.size).toEqual(inputConfig.previewConfig?.size);
})
);
});
describe('buttonsConfig', () => {
it(`should call setConfig to update the library configuration with an undefined buttonsConfig`,
inject([ConfigService], (service: ConfigService) => {
const inputConfig: LibConfig = {
buttonsConfig: undefined
};
service.setConfig(1, inputConfig);
const result: LibConfig | undefined = service.getConfig(1);
expect(result?.buttonsConfig).toEqual({visible: true, strategy: ButtonsStrategy.DEFAULT});
})
);
it(`should call setConfig to update the library configuration with a custom buttonsConfig`,
inject([ConfigService], (service: ConfigService) => {
const customConfig: ButtonsConfig = {
visible: false,
strategy: ButtonsStrategy.CUSTOM,
buttons: [{
className: 'fake',
size: {height: '100px', width: '200px'} as Size,
fontSize: '12px',
type: ButtonType.CUSTOM,
title: 'fake title',
ariaLabel: 'fake aria label',
extUrlInNewTab: false
}]
};
const inputConfig: LibConfig = {
buttonsConfig: customConfig
};
service.setConfig(1, inputConfig);
const result: LibConfig | undefined = service.getConfig(1);
expect(result?.buttonsConfig?.visible).toEqual(inputConfig.buttonsConfig?.visible);
expect(result?.buttonsConfig?.strategy).toEqual(inputConfig.buttonsConfig?.strategy);
expect(result?.buttonsConfig?.buttons).toEqual(inputConfig.buttonsConfig?.buttons);
})
);
});
describe('dotsConfig', () => {
it(`should call setConfig to update the library configuration with an undefined dotsConfig`,
inject([ConfigService], (service: ConfigService) => {
const inputConfig: LibConfig = {
dotsConfig: undefined
};
service.setConfig(1, inputConfig);
const result: LibConfig | undefined = service.getConfig(1);
expect(result?.dotsConfig).toEqual({visible: true} as DotsConfig);
})
);
it(`should call setConfig to update the library configuration with a custom dotsConfig`,
inject([ConfigService], (service: ConfigService) => {
const inputConfig: LibConfig = {
dotsConfig: {visible: false} as DotsConfig
};
service.setConfig(1, inputConfig);
const result: LibConfig | undefined = service.getConfig(1);
expect(result?.dotsConfig?.visible).toEqual(inputConfig.dotsConfig?.visible);
})
);
});
describe('plainGalleryConfig', () => {
it(`should call setConfig to update the library configuration with an undefined plainGalleryConfig`,
inject([ConfigService], (service: ConfigService) => {
const inputConfig: LibConfig = {
plainGalleryConfig: undefined
};
service.setConfig(1, inputConfig);
const result: LibConfig | undefined = service.getConfig(1);
expect(result?.plainGalleryConfig).toEqual(DEFAULT_PLAIN_CONFIG);
})
);
it(`should call setConfig to update the library configuration with a custom plainGalleryConfig`,
inject([ConfigService], (service: ConfigService) => {
const inputConfig: LibConfig = {
plainGalleryConfig: {
strategy: PlainGalleryStrategy.ROW,
layout: DEFAULT_LAYOUT,
advanced: undefined
} as PlainGalleryConfig
};
service.setConfig(1, inputConfig);
const result: LibConfig | undefined = service.getConfig(1);
expect(result?.plainGalleryConfig?.strategy).toEqual(inputConfig.plainGalleryConfig?.strategy);
expect(result?.plainGalleryConfig?.layout).toEqual(inputConfig.plainGalleryConfig?.layout);
expect(result?.plainGalleryConfig?.advanced).toEqual({aTags: false, additionalBackground: '50% 50%/cover'} as AdvancedConfig);
})
);
it(`should call setConfig to update the library configuration with a custom plainGalleryConfig with custom advanced`,
inject([ConfigService], (service: ConfigService) => {
const inputConfig: LibConfig = {
plainGalleryConfig: {
strategy: PlainGalleryStrategy.ROW,
layout: DEFAULT_LAYOUT,
advanced: {aTags: true, additionalBackground: '10% 10%/cover'} as AdvancedConfig
} as PlainGalleryConfig
};
service.setConfig(1, inputConfig);
const result: LibConfig | undefined = service.getConfig(1);
expect(result?.plainGalleryConfig?.strategy).toEqual(inputConfig.plainGalleryConfig?.strategy);
expect(result?.plainGalleryConfig?.layout).toEqual(inputConfig.plainGalleryConfig?.layout);
expect(result?.plainGalleryConfig?.advanced?.aTags).toEqual(inputConfig.plainGalleryConfig?.advanced?.aTags);
expect(result?.plainGalleryConfig?.advanced?.additionalBackground).toEqual(inputConfig.plainGalleryConfig?.advanced?.additionalBackground);
})
);
it(`should call setConfig to update the library configuration with a custom plainGalleryConfig`,
inject([ConfigService], (service: ConfigService) => {
const inputConfig: LibConfig = {
plainGalleryConfig: {
strategy: PlainGalleryStrategy.GRID,
layout: new GridLayout(DEFAULT_PREVIEW_SIZE, {length: -1, wrap: false}),
advanced: {aTags: true, additionalBackground: '10% 10%/cover'} as AdvancedConfig
} as PlainGalleryConfig
};
service.setConfig(1, inputConfig);
const result: LibConfig | undefined = service.getConfig(1);
// wrap is forced to true in case of GridLayout
expect((result?.plainGalleryConfig?.layout as GridLayout).breakConfig?.wrap).toEqual(true);
})
);
});
describe('currentImageConfig', () => {
it(`should call setConfig to update the library configuration with an undefined currentImageConfig`,
inject([ConfigService], (service: ConfigService) => {
const inputConfig: LibConfig = {
currentImageConfig: undefined
};
service.setConfig(1, inputConfig);
const result: LibConfig | undefined = service.getConfig(1);
expect(result?.currentImageConfig).toEqual(DEFAULT_CURRENT_IMAGE_CONFIG);
})
);
it(`should call setConfig to update the library configuration with a custom currentImageConfig (loadingConfig and description are undefined)`,
inject([ConfigService], (service: ConfigService) => {
const inputConfig: LibConfig = {
currentImageConfig: {
navigateOnClick: false,
loadingConfig: undefined,
description: undefined,
downloadable: true,
invertSwipe: true
} as CurrentImageConfig
};
service.setConfig(1, inputConfig);
const result: LibConfig | undefined = service.getConfig(1);
expect(result?.currentImageConfig?.navigateOnClick).toEqual(inputConfig.currentImageConfig?.navigateOnClick);
expect(result?.currentImageConfig?.downloadable).toEqual(inputConfig.currentImageConfig?.downloadable);
expect(result?.currentImageConfig?.invertSwipe).toEqual(inputConfig.currentImageConfig?.invertSwipe);
expect(result?.currentImageConfig?.loadingConfig).toEqual(DEFAULT_LOADING);
expect(result?.currentImageConfig?.description).toEqual(DEFAULT_DESCRIPTION);
})
);
it(`should call setConfig to update the library configuration with a custom currentImageConfig (custom loadingConfig)`,
inject([ConfigService], (service: ConfigService) => {
const inputConfig: LibConfig = {
currentImageConfig: {
navigateOnClick: false,
loadingConfig: {enable: false, type: LoadingType.CIRCLES} as LoadingConfig,
description: undefined,
downloadable: true,
invertSwipe: true
} as CurrentImageConfig
};
service.setConfig(1, inputConfig);
const result: LibConfig | undefined = service.getConfig(1);
expect(result?.currentImageConfig?.navigateOnClick).toEqual(inputConfig.currentImageConfig?.navigateOnClick);
expect(result?.currentImageConfig?.downloadable).toEqual(inputConfig.currentImageConfig?.downloadable);
expect(result?.currentImageConfig?.invertSwipe).toEqual(inputConfig.currentImageConfig?.invertSwipe);
expect(result?.currentImageConfig?.loadingConfig?.enable).toEqual(inputConfig.currentImageConfig?.loadingConfig?.enable);
expect(result?.currentImageConfig?.loadingConfig?.type).toEqual(inputConfig.currentImageConfig?.loadingConfig?.type);
expect(result?.currentImageConfig?.description).toEqual(DEFAULT_DESCRIPTION);
})
);
it(`should call setConfig to update the library configuration with a custom currentImageConfig (custom description)`,
inject([ConfigService], (service: ConfigService) => {
const inputConfig: LibConfig = {
currentImageConfig: {
navigateOnClick: false,
loadingConfig: undefined,
description: {
strategy: DescriptionStrategy.HIDE_IF_EMPTY,
imageText: 'Img ',
numberSeparator: ' of ',
beforeTextDescription: ' * ',
style: DEFAULT_DESCRIPTION_STYLE
} as Description,
downloadable: true,
invertSwipe: true
} as CurrentImageConfig
};
service.setConfig(1, inputConfig);
const result: LibConfig | undefined = service.getConfig(1);
expect(result?.currentImageConfig?.navigateOnClick).toEqual(inputConfig.currentImageConfig?.navigateOnClick);
expect(result?.currentImageConfig?.downloadable).toEqual(inputConfig.currentImageConfig?.downloadable);
expect(result?.currentImageConfig?.invertSwipe).toEqual(inputConfig.currentImageConfig?.invertSwipe);
expect(result?.currentImageConfig?.loadingConfig).toEqual(DEFAULT_LOADING);
expect(result?.currentImageConfig?.description?.strategy).toEqual(inputConfig.currentImageConfig?.description?.strategy);
expect(result?.currentImageConfig?.description?.imageText).toEqual(inputConfig.currentImageConfig?.description?.imageText);
expect(result?.currentImageConfig?.description?.numberSeparator).toEqual(inputConfig.currentImageConfig?.description?.numberSeparator);
expect(result?.currentImageConfig?.description?.beforeTextDescription).toEqual(inputConfig.currentImageConfig?.description?.beforeTextDescription);
expect(result?.currentImageConfig?.description?.style).toEqual(inputConfig.currentImageConfig?.description?.style);
})
);
it(`should call setConfig to update the library configuration with a custom currentImageConfig (custom description with style undefined)`,
inject([ConfigService], (service: ConfigService) => {
const inputConfig: LibConfig = {
currentImageConfig: {
navigateOnClick: false,
loadingConfig: undefined,
description: {
strategy: DescriptionStrategy.ALWAYS_VISIBLE,
imageText: 'Img ',
numberSeparator: ' of ',
beforeTextDescription: ' * ',
style: undefined
} as Description,
downloadable: true,
invertSwipe: true
} as CurrentImageConfig
};
service.setConfig(1, inputConfig);
const result: LibConfig | undefined = service.getConfig(1);
expect(result?.currentImageConfig?.navigateOnClick).toEqual(inputConfig.currentImageConfig?.navigateOnClick);
expect(result?.currentImageConfig?.downloadable).toEqual(inputConfig.currentImageConfig?.downloadable);
expect(result?.currentImageConfig?.invertSwipe).toEqual(inputConfig.currentImageConfig?.invertSwipe);
expect(result?.currentImageConfig?.loadingConfig).toEqual(DEFAULT_LOADING);
expect(result?.currentImageConfig?.description?.strategy).toEqual(inputConfig.currentImageConfig?.description?.strategy);
expect(result?.currentImageConfig?.description?.imageText).toEqual(inputConfig.currentImageConfig?.description?.imageText);
expect(result?.currentImageConfig?.description?.numberSeparator).toEqual(inputConfig.currentImageConfig?.description?.numberSeparator);
expect(result?.currentImageConfig?.description?.beforeTextDescription).toEqual(inputConfig.currentImageConfig?.description?.beforeTextDescription);
expect(result?.currentImageConfig?.description?.style).toEqual(DEFAULT_DESCRIPTION_STYLE);
})
);
});
describe('keyboardConfig', () => {
it(`should call setConfig to update the library configuration with an undefined keyboardConfig`,
inject([ConfigService], (service: ConfigService) => {
const inputConfig: LibConfig = {
keyboardConfig: undefined
};
service.setConfig(1, inputConfig);
const result: LibConfig | undefined = service.getConfig(1);
expect(result?.keyboardConfig).toEqual(undefined);
})
);
it(`should call setConfig to update the library configuration with a custom keyboardConfig`,
inject([ConfigService], (service: ConfigService) => {
const inputConfig: LibConfig = {
keyboardConfig: {
esc: 10,
right: 11,
left: 12
} as KeyboardConfig
};
service.setConfig(1, inputConfig);
const result: LibConfig | undefined = service.getConfig(1);
expect(result?.keyboardConfig).toEqual(inputConfig.keyboardConfig);
})
);
});
describe('carouselImageConfig', () => {
it(`should call setConfig to update the library configuration with an undefined carouselImageConfig`,
inject([ConfigService], (service: ConfigService) => {
const inputConfig: LibConfig = {
carouselImageConfig: undefined
};
service.setConfig(1, inputConfig);
const result: LibConfig | undefined = service.getConfig(1);
expect(result?.carouselImageConfig).toEqual(DEFAULT_CAROUSEL_IMAGE_CONFIG);
})
);
it(`should call setConfig to update the library configuration with a custom carouselImageConfig (description undefined)`,
inject([ConfigService], (service: ConfigService) => {
const inputConfig: LibConfig = {
carouselImageConfig: {
description: undefined,
invertSwipe: true
} as CarouselImageConfig
};
service.setConfig(1, inputConfig);
const result: LibConfig | undefined = service.getConfig(1);
expect(result?.carouselImageConfig?.invertSwipe).toEqual(inputConfig.carouselImageConfig?.invertSwipe);
expect(result?.carouselImageConfig?.description).toEqual(DEFAULT_CAROUSEL_DESCRIPTION);
})
);
it(`should call setConfig to update the library configuration with a custom carouselImageConfig (description.style undefined)`,
inject([ConfigService], (service: ConfigService) => {
const inputConfig: LibConfig = {
carouselImageConfig: {
description: {
strategy: DescriptionStrategy.ALWAYS_HIDDEN,
imageText: 'Img ',
numberSeparator: ' of ',
beforeTextDescription: ' * ',
style: undefined
},
invertSwipe: true
} as CarouselImageConfig
};
service.setConfig(1, inputConfig);
const result: LibConfig | undefined = service.getConfig(1);
expect(result?.carouselImageConfig?.invertSwipe).toEqual(inputConfig.carouselImageConfig?.invertSwipe);
expect(result?.carouselImageConfig?.description?.strategy).toEqual(inputConfig.carouselImageConfig?.description?.strategy);
expect(result?.carouselImageConfig?.description?.imageText).toEqual(inputConfig.carouselImageConfig?.description?.imageText);
expect(result?.carouselImageConfig?.description?.numberSeparator).toEqual(inputConfig.carouselImageConfig?.description?.numberSeparator);
expect(result?.carouselImageConfig?.description?.beforeTextDescription).toEqual(inputConfig.carouselImageConfig?.description?.beforeTextDescription);
expect(result?.carouselImageConfig?.description?.style).toEqual(DEFAULT_DESCRIPTION_STYLE);
})
);
it(`should call setConfig to update the library configuration with a custom carouselImageConfig (custom description.style)`,
inject([ConfigService], (service: ConfigService) => {
const inputConfig: LibConfig = {
carouselImageConfig: {
description: {
strategy: DescriptionStrategy.ALWAYS_HIDDEN,
imageText: 'Img ',
numberSeparator: ' of ',
beforeTextDescription: ' * ',
style: {
bgColor: 'rgba(200, 0, 120, .5)',
textColor: 'black',
marginTop: '5px',
marginBottom: '10px',
marginLeft: '10px',
marginRight: '10px'
} as DescriptionStyle
},
invertSwipe: true
} as CarouselImageConfig
};
service.setConfig(1, inputConfig);
const result: LibConfig | undefined = service.getConfig(1);
expect(result?.carouselImageConfig?.invertSwipe).toEqual(inputConfig.carouselImageConfig?.invertSwipe);
expect(result?.carouselImageConfig?.description?.strategy).toEqual(inputConfig.carouselImageConfig?.description?.strategy);
expect(result?.carouselImageConfig?.description?.imageText).toEqual(inputConfig.carouselImageConfig?.description?.imageText);
expect(result?.carouselImageConfig?.description?.numberSeparator).toEqual(inputConfig.carouselImageConfig?.description?.numberSeparator);
expect(result?.carouselImageConfig?.description?.beforeTextDescription).toEqual(inputConfig.carouselImageConfig?.description?.beforeTextDescription);
expect(result?.carouselImageConfig?.description?.style?.bgColor).toEqual(inputConfig.carouselImageConfig?.description?.style?.bgColor);
expect(result?.carouselImageConfig?.description?.style?.textColor).toEqual(inputConfig.carouselImageConfig?.description?.style?.textColor);
expect(result?.carouselImageConfig?.description?.style?.marginTop).toEqual(inputConfig.carouselImageConfig?.description?.style?.marginTop);
expect(result?.carouselImageConfig?.description?.style?.marginBottom).toEqual(inputConfig.carouselImageConfig?.description?.style?.marginBottom);
expect(result?.carouselImageConfig?.description?.style?.marginLeft).toEqual(inputConfig.carouselImageConfig?.description?.style?.marginLeft);
expect(result?.carouselImageConfig?.description?.style?.marginRight).toEqual(inputConfig.carouselImageConfig?.description?.style?.marginRight);
})
);
});
describe('carouselConfig', () => {
it(`should call setConfig to update the library configuration with an undefined carouselConfig`,
inject([ConfigService], (service: ConfigService) => {
const inputConfig: LibConfig = {
carouselConfig: undefined
};
service.setConfig(1, inputConfig);
const result: LibConfig | undefined = service.getConfig(1);
expect(result?.carouselConfig).toEqual(DEFAULT_CURRENT_CAROUSEL_CONFIG);
})
);
it(`should call setConfig to update the library configuration with a custom carouselConfig`,
inject([ConfigService], (service: ConfigService) => {
const inputConfig: LibConfig = {
carouselConfig: {
maxWidth: '80%',
maxHeight: '200px',
showArrows: false,
objectFit: 'cover',
keyboardEnable: false,
modalGalleryEnable: false,
legacyIE11Mode: true
} as CarouselConfig
};
service.setConfig(1, inputConfig);
const result: LibConfig | undefined = service.getConfig(1);
expect(result?.carouselConfig).toEqual(inputConfig.carouselConfig);
})
);
});
describe('carouselPlayConfig', () => {
it(`should call setConfig to update the library configuration with an undefined carouselPlayConfig`,
inject([ConfigService], (service: ConfigService) => {
const inputConfig: LibConfig = {
carouselPlayConfig: undefined
};
service.setConfig(1, inputConfig);
const result: LibConfig | undefined = service.getConfig(1);
expect(result?.carouselPlayConfig).toEqual(DEFAULT_CURRENT_CAROUSEL_PLAY);
})
);
it(`should call setConfig to update the library configuration with a custom carouselPlayConfig`,
inject([ConfigService], (service: ConfigService) => {
const inputConfig: LibConfig = {
carouselPlayConfig: {
autoPlay: false,
interval: 1000,
pauseOnHover: false
} as PlayConfig
};
service.setConfig(1, inputConfig);
const result: LibConfig | undefined = service.getConfig(1);
expect(result?.carouselPlayConfig).toEqual(inputConfig.carouselPlayConfig);
})
);
});
describe('carouselPreviewsConfig', () => {
it(`should call setConfig to update the library configuration with an undefined carouselPreviewsConfig`,
inject([ConfigService], (service: ConfigService) => {
const inputConfig: LibConfig = {
carouselPreviewsConfig: undefined
};
service.setConfig(1, inputConfig);
const result: LibConfig | undefined = service.getConfig(1);
expect(result?.carouselPreviewsConfig).toEqual(DEFAULT_CAROUSEL_PREVIEWS_CONFIG);
})
);
it(`should call setConfig to update the library configuration with an undefined carouselPreviewsConfig without 'breakpoints'`,
inject([ConfigService], (service: ConfigService) => {
const inputConfig: LibConfig = {
carouselPreviewsConfig: {
visible: true,
number: 4,
arrows: true,
clickable: true,
width: 100 / 4 + '%',
maxHeight: '200px'
} as CarouselPreviewConfig
};
service.setConfig(1, inputConfig);
const result: LibConfig | undefined = service.getConfig(1);
expect(result?.carouselPreviewsConfig).toEqual(DEFAULT_CAROUSEL_PREVIEWS_CONFIG);
})
);
[0, -1].forEach((item: number, index: number) => {
it(`should call setConfig to update the library configuration with a custom carouselPreviewsConfig with invalid 'number'. Test i = ${index}`,
inject([ConfigService], (service: ConfigService) => {
const inputConfig: LibConfig = {
carouselPreviewsConfig: {
visible: false,
number: item,
arrows: false,
clickable: false,
width: 100 / 2 + '%',
maxHeight: '100px',
breakpoints: DEFAULT_CAROUSEL_BREAKPOINTS
} as CarouselPreviewConfig
};
service.setConfig(1, inputConfig);
const result: LibConfig | undefined = service.getConfig(1);
const numberVal: number = DEFAULT_CAROUSEL_PREVIEWS_CONFIG.number as number;
const widthVal: number = 100 / numberVal;
expect(result?.carouselPreviewsConfig?.visible).toEqual(inputConfig.carouselPreviewsConfig?.visible);
expect(result?.carouselPreviewsConfig?.number).toEqual(numberVal);
expect(result?.carouselPreviewsConfig?.arrows).toEqual(inputConfig.carouselPreviewsConfig?.arrows);
expect(result?.carouselPreviewsConfig?.clickable).toEqual(inputConfig.carouselPreviewsConfig?.clickable);
expect(result?.carouselPreviewsConfig?.width).toEqual(`${widthVal}%`);
expect(result?.carouselPreviewsConfig?.maxHeight).toEqual(inputConfig.carouselPreviewsConfig?.maxHeight);
expect(result?.carouselPreviewsConfig?.breakpoints).toEqual(inputConfig.carouselPreviewsConfig?.breakpoints);
})
);
});
});
describe('carouselDotsConfig', () => {
it(`should call setConfig to update the library configuration with an undefined carouselDotsConfig`,
inject([ConfigService], (service: ConfigService) => {
const inputConfig: LibConfig = {
carouselDotsConfig: undefined
};
service.setConfig(1, inputConfig);
const result: LibConfig | undefined = service.getConfig(1);
expect(result?.carouselDotsConfig).toEqual({visible: true} as DotsConfig);
})
);
it(`should call setConfig to update the library configuration with a custom carouselDotsConfig`,
inject([ConfigService], (service: ConfigService) => {
const inputConfig: LibConfig = {
carouselDotsConfig: {visible: false} as DotsConfig
};
service.setConfig(1, inputConfig);
const result: LibConfig | undefined = service.getConfig(1);
expect(result?.carouselDotsConfig).toEqual(inputConfig.carouselDotsConfig);
})
);
});
describe('keyboardServiceConfig', () => {
it(`should call setConfig to update the library configuration with an undefined keyboardServiceConfig`,
inject([ConfigService], (service: ConfigService) => {
const inputConfig: LibConfig = {
keyboardServiceConfig: undefined
};
service.setConfig(1, inputConfig);
const result: LibConfig | undefined = service.getConfig(1);
expect(result?.keyboardServiceConfig).toEqual(DEFAULT_KEYBOARD_SERVICE_CONFIG);
})
);
it(`should call setConfig to update the library configuration with a custom keyboardServiceConfig`,
inject([ConfigService], (service: ConfigService) => {
const inputConfig: LibConfig = {
keyboardServiceConfig: {
shortcuts: ['ctrl+s'],
disableSsrWorkaround: true
} as KeyboardServiceConfig
};
service.setConfig(1, inputConfig);
const result: LibConfig | undefined = service.getConfig(1);
expect(result?.keyboardServiceConfig).toEqual(inputConfig.keyboardServiceConfig);
})
);
});
describe('enableCloseOutside', () => {
it(`should call setConfig to update the library configuration with an undefined enableCloseOutside`,
inject([ConfigService], (service: ConfigService) => {
const inputConfig: LibConfig = {
enableCloseOutside: undefined
};
service.setConfig(1, inputConfig);
const result: LibConfig | undefined = service.getConfig(1);
expect(result?.enableCloseOutside).toEqual(true);
})
);
it(`should call setConfig to update the library configuration with a custom enableCloseOutside`,
inject([ConfigService], (service: ConfigService) => {
const inputConfig: LibConfig = {
enableCloseOutside: false
};
service.setConfig(1, inputConfig);
const result: LibConfig | undefined = service.getConfig(1);
expect(result?.enableCloseOutside).toEqual(inputConfig.enableCloseOutside);
})
);
});
it(`should call setConfig with an undefined configuration object.`,
inject([ConfigService], (service: ConfigService) => {
service.setConfig(1, undefined);
const result: LibConfig | undefined = service.getConfig(1);
// console.log('result', result);
})
);
});
describe('---NO---', () => {
describe('carouselPlayConfig', () => {
it(`should throw an error if carouselPlayConfig.interval is < 0`,
inject([ConfigService], (service: ConfigService) => {
const inputConfig: LibConfig = {
carouselPlayConfig: {
autoPlay: false,
interval: -1,
pauseOnHover: false
} as PlayConfig
};
expect(() => service.setConfig(1, inputConfig)).toThrowError(`Carousel's interval must be a number >= 0`);
})
);
});
describe('plainGalleryConfig', () => {
[PlainGalleryStrategy.GRID, PlainGalleryStrategy.CUSTOM].forEach((item: PlainGalleryStrategy) => {
it(`should throw an error because 'LineLayout requires either ROW or COLUMN strategy'`,
inject([ConfigService], (service: ConfigService) => {
const inputConfig: LibConfig = {
plainGalleryConfig: {
strategy: item,
layout: new LineLayout(DEFAULT_PREVIEW_SIZE, {length: -1, wrap: false}, 'flex-start'),
advanced: {aTags: true, additionalBackground: '10% 10%/cover'} as AdvancedConfig
} as PlainGalleryConfig
};
expect(() => service.setConfig(1, inputConfig)).toThrowError('LineLayout requires either ROW or COLUMN strategy');
})
);
});
it(`should throw an error because 'GridLayout requires GRID strategy'`,
inject([ConfigService], (service: ConfigService) => {
const inputConfig: LibConfig = {
plainGalleryConfig: {
strategy: PlainGalleryStrategy.ROW,
layout: new GridLayout(DEFAULT_PREVIEW_SIZE, {length: -1, wrap: false}),
advanced: {aTags: true, additionalBackground: '10% 10%/cover'} as AdvancedConfig
} as PlainGalleryConfig
};
expect(() => service.setConfig(1, inputConfig)).toThrowError('GridLayout requires GRID strategy');
})
);
it(`should throw an error because 'AdvancedLayout requires CUSTOM strategy'`,
inject([ConfigService], (service: ConfigService) => {
const inputConfig: LibConfig = {
plainGalleryConfig: {
strategy: PlainGalleryStrategy.GRID,
layout: new AdvancedLayout(1, false),
advanced: {aTags: true, additionalBackground: '10% 10%/cover'} as AdvancedConfig
} as PlainGalleryConfig
};
expect(() => service.setConfig(1, inputConfig)).toThrowError('AdvancedLayout requires CUSTOM strategy');
})
);
});
});
});
}); | the_stack |
* @module OrbitGT
*/
//package orbitgt.spatial.ecrs;
type int8 = number;
type int16 = number;
type int32 = number;
type float32 = number;
type float64 = number;
import { AList } from "../../system/collection/AList";
import { Message } from "../../system/runtime/Message";
import { Strings } from "../../system/runtime/Strings";
import { Coordinate } from "../geom/Coordinate";
import { Axis } from "./Axis";
import { CRS } from "./CRS";
import { Registry } from "./Registry";
import { Unit } from "./Unit";
/**
* Class CoordinateSystem manages the different coordinate systems.
*
* @version 1.0 October 2014
*/
/** @internal */
export class CoordinateSystem {
/** The name of this module */
private static readonly MODULE: string = "CoordinateSystem";
/** The type of coordinate reference system (PROJECTED,GEOGRAPHIC_2D,...) */
private _type: int32;
/** The coordinate-system code */
private _csCode: int32;
/** The coordinate axes (defined by the csCode) */
private _axes: AList<Axis>;
/** The X axis (derived) */
private _xAxis: Axis;
/** The Y axis (derived) */
private _yAxis: Axis;
/** The Z axis (derived) */
private _zAxis: Axis;
/** The X unit (derived) */
private _xUnit: Unit;
/** The Y unit (derived) */
private _yUnit: Unit;
/** The Z unit (derived) */
private _zUnit: Unit;
/**
* Check if easting-northing axis order is swapped?
* @param csCode the code of the coordinate-system.
* @return true for swapped CRS.
*/
public static isSwappedEN(csCode: int32): boolean {
if (csCode == 1029) return true;
// if (csCode==4400) return true; // this used to be swapped in the EPSG database, but not anymore
if (csCode == 4498) return true;
if (csCode == 4500) return true;
if (csCode == 4532) return true;
return false;
}
/**
* Create a coordinate system.
* @param type the type of coordinate reference system (PROJECTED,GEOGRAPHIC_2D,...).
* @param csCode the coordinate-system code.
* @param axes the (sorted on order) coordinate axes.
* @return the coordinate system (null for an identify system).
*/
public static create(type: int32, csCode: int32, axes: AList<Axis>): CoordinateSystem {
let coordinateSystem: CoordinateSystem = new CoordinateSystem(type, csCode, axes);
if (coordinateSystem.isIdentity()) return null;
return coordinateSystem;
}
/**
* Create a new coordinate system.
* @param type the type of coordinate reference system (PROJECTED,GEOGRAPHIC_2D,...).
* @param csCode the coordinate-system code.
* @param axes the (sorted on order) coordinate axes.
*/
public constructor(type: int32, csCode: int32, axes: AList<Axis>) {
/* Store the parameters */
this._type = type;
this._csCode = csCode;
this._axes = axes;
/* Clear */
this._xAxis = null;
this._yAxis = null;
this._zAxis = null;
this._xUnit = null;
this._yUnit = null;
this._zUnit = null;
/* Projection? */
if (type == CRS.PROJECTED) this.parseProjection();
/* Log? */
if (this.isIdentity() == false) {
/* Log */
Message.print(CoordinateSystem.MODULE, "Created coordinate system " + this._csCode);
if (this._xAxis != null) Message.print(CoordinateSystem.MODULE, "X axis '" + this._xAxis.getAbbreviation() + "'/'" + this._xAxis.getAxisName() + "' (" + this._xAxis.getOrder() + ")");
if (this._yAxis != null) Message.print(CoordinateSystem.MODULE, "Y axis '" + this._yAxis.getAbbreviation() + "'/'" + this._yAxis.getAxisName() + "' (" + this._yAxis.getOrder() + ")");
if (this._zAxis != null) Message.print(CoordinateSystem.MODULE, "Z axis '" + this._zAxis.getAbbreviation() + "'/'" + this._zAxis.getAxisName() + "' (" + this._zAxis.getOrder() + ")");
if (this._xUnit != null) Message.print(CoordinateSystem.MODULE, "X unit '" + this._xUnit.getName() + "'");
if (this._yUnit != null) Message.print(CoordinateSystem.MODULE, "Y unit '" + this._yUnit.getName() + "'");
if (this._zUnit != null) Message.print(CoordinateSystem.MODULE, "Z unit '" + this._zUnit.getName() + "'");
}
}
/**
* Get the type of coordinate reference system (PROJECTED,GEOGRAPHIC_2D,...).
* @return the type.
*/
public getType(): int32 {
return this._type;
}
/**
* Get the code of the coordinate system.
* @return the code of the coordinate system.
*/
public getCode(): int32 {
return this._csCode;
}
/**
* Get the coordinate axes.
* @return the coordinate axes.
*/
public getAxes(): AList<Axis> {
return this._axes;
}
/**
* Do we have an identity transformation between local and standard forms?
* @return true for an identity transform.
*/
public isIdentity(): boolean {
/* Check the axis */
if ((this._xAxis != null) && (this._xAxis.getOrder() != 1)) return false;
if ((this._yAxis != null) && (this._yAxis.getOrder() != 2)) return false;
if ((this._zAxis != null) && (this._zAxis.getOrder() != 3)) return false;
/* Check the units */
if (this._xUnit != null) return false;
if (this._yUnit != null) return false;
if (this._zUnit != null) return false;
/* We have identity */
return true;
}
/**
* Get the X axis.
* @return the X axis.
*/
public getXAxis(): Axis {
return this._xAxis;
}
/**
* Get the Y axis.
* @return the Y axis.
*/
public getYAxis(): Axis {
return this._yAxis;
}
/**
* Get the Z axis.
* @return the Z axis.
*/
public getZAxis(): Axis {
return this._zAxis;
}
/**
* Get the unit of the first axis.
* @return the unit of the first axis (null for the default unit).
*/
public getXUnit(): Unit {
return this._xUnit;
}
/**
* Get the unit of the second axis.
* @return the unit of the second axis (null for the default unit).
*/
public getYUnit(): Unit {
return this._yUnit;
}
/**
* Get the unit of the third axis.
* @return the unit of the third axis (null for the default unit).
*/
public getZUnit(): Unit {
return this._zUnit;
}
/**
* Parse a projection type coordinate system.
*/
private parseProjection(): void {
/* Get the abbreviations */
let name1: string = this._axes.get(0).getAbbreviation();
let name2: string = this._axes.get(1).getAbbreviation();
// /* Get the axis names */
// String aname1 = this._axis[0].getAxisName();
// String aname2 = this._axis[1].getAxisName();
// /* Special cases */
// if (aname1.equalsIgnoreCase("Northing") && aname2.equalsIgnoreCase("Easting"))
// {
// /* Coordinate system 4531, used by CRS 2180: ETRS89 / Poland CS92 */
// name1 = "N";
// name2 = "E";
// }
/* Check the various combinations */
let xy1: boolean = (Strings.equalsIgnoreCase(name1, "X") && Strings.equalsIgnoreCase(name2, "Y"));
let xy2: boolean = (Strings.equalsIgnoreCase(name1, "E") && Strings.equalsIgnoreCase(name2, "N"));
let xy3: boolean = (Strings.equalsIgnoreCase(name1, "E(X)") && Strings.equalsIgnoreCase(name2, "N(Y)"));
let xy4: boolean = (Strings.equalsIgnoreCase(name1, "M") && Strings.equalsIgnoreCase(name2, "P")); // csCode 1024, Portuguese
let yx1: boolean = (Strings.equalsIgnoreCase(name1, "Y") && Strings.equalsIgnoreCase(name2, "X"));
let yx2: boolean = (Strings.equalsIgnoreCase(name1, "N") && Strings.equalsIgnoreCase(name2, "E"));
/* XY sequence? */
if (xy1 || xy2 || xy3 || xy4) {
this._xAxis = this._axes.get(0);
this._yAxis = this._axes.get(1);
}
/* YX sequence */
else if (yx1 || yx2) {
this._xAxis = this._axes.get(1);
this._yAxis = this._axes.get(0);
}
/* Default */
else {
this._xAxis = this._axes.get(0);
this._yAxis = this._axes.get(1);
/* Log */
Message.printWarning(CoordinateSystem.MODULE, "Invalid projected axis '" + name1 + "','" + name2 + "'");
}
/* Do we have a Z axis? */
if (this._axes.size() >= 3) {
this._zAxis = this._axes.get(2);
}
/* Get the units */
if ((this._xAxis != null) && this._xAxis.getUnitCode() != Unit.METER) this._xUnit = Registry.getUnit(this._xAxis.getUnitCode());
if ((this._yAxis != null) && this._yAxis.getUnitCode() != Unit.METER) this._yUnit = Registry.getUnit(this._yAxis.getUnitCode());
if ((this._zAxis != null) && this._zAxis.getUnitCode() != Unit.METER) this._zUnit = Registry.getUnit(this._zAxis.getUnitCode());
}
/**
* Get a local coordinate.
* @param local the coordinate.
* @param axis the standard axis to retrieve.
* @param order the default order.
* @return the coordinate.
*/
private static getLocalCoordinate(local: Coordinate, axis: Axis, order: int32): float64 {
/* Do we have an axis? */
if (axis != null) order = axis.getOrder();
/* Return the request coordinate */
if (order == 1) return local.getX();
if (order == 2) return local.getY();
if (order == 3) return local.getZ();
return 0.0;
}
/**
* Convert a coordinate from the local to the standard form.
* @param local the local coordinate (input).
* @param standard the standard coordinate (can be same as local) (output).
*/
public localToStandard(local: Coordinate, standard: Coordinate): void {
/* Get X */
let x: float64 = CoordinateSystem.getLocalCoordinate(local, this._xAxis, 1);
if (this._xUnit != null) x = this._xUnit.toStandard(x);
/* Get Y */
let y: float64 = CoordinateSystem.getLocalCoordinate(local, this._yAxis, 2);
if (this._yUnit != null) y = this._yUnit.toStandard(y);
/* Get Z */
let z: float64 = CoordinateSystem.getLocalCoordinate(local, this._zAxis, 3);
if (this._zUnit != null) z = this._zUnit.toStandard(z);
/* Set */
standard.setX(x);
standard.setY(y);
standard.setZ(z);
}
/**
* Get a standard coordinate.
* @param x the standard x coordinate.
* @param y the standard y coordinate.
* @param z the standard z coordinate.
* @param axis the local axis to consider.
* @param index the default index.
* @return the coordinate.
*/
private getStandardCoordinate(x: float64, y: float64, z: float64, axis: Axis, index: int32): float64 {
/* Check the standard index of the axis */
if (axis == this._xAxis) index = 1;
else if (axis == this._yAxis) index = 2;
else if (axis == this._zAxis) index = 3;
/* Return the coordinate */
if (index == 1) return x;
if (index == 2) return y;
if (index == 3) return z;
return 0.0;
}
/**
* Convert a coordinate from the standard to the local form.
* @param standard the standard coordinate (input).
* @param local the local coordinate (can be same as standard) (output).
*/
public standardToLocal(standard: Coordinate, local: Coordinate): void {
/* Get X */
let x: float64 = standard.getX();
if (this._xUnit != null) x = this._xUnit.fromStandard(x);
/* Get Y */
let y: float64 = standard.getY();
if (this._yUnit != null) y = this._yUnit.fromStandard(y);
/* Get Z */
let z: float64 = standard.getZ();
if (this._zUnit != null) z = this._zUnit.fromStandard(z);
/* Set */
local.setX(this.getStandardCoordinate(x, y, z, this._axes.get(0), 1));
local.setY(this.getStandardCoordinate(x, y, z, this._axes.get(1), 2));
if (this._axes.size() >= 3) local.setZ(this.getStandardCoordinate(x, y, z, this._axes.get(2), 3));
}
} | the_stack |
import { DataProvider } from '../ojdataprovider';
import { dvtBaseComponent, dvtBaseComponentEventMap, dvtBaseComponentSettableProperties } from '../ojdvt-base';
import { JetElement, JetSettableProperties, JetElementCustomEvent, JetSetPropertyType } from '..';
export interface ojTreemap<K, D> extends dvtBaseComponent<ojTreemapSettableProperties<K, D>> {
animationDuration: number;
animationOnDataChange: 'auto' | 'none';
animationOnDisplay: 'auto' | 'none';
animationUpdateColor: string;
as: string;
colorLabel: string;
data: DataProvider<K, D> | null;
displayLevels: number;
drilling: 'on' | 'off';
groupGaps: 'all' | 'none' | 'outer';
hiddenCategories: string[];
highlightMatch: 'any' | 'all';
highlightedCategories: string[];
hoverBehavior: 'dim' | 'none';
hoverBehaviorDelay: number;
isolatedNode: any;
layout: 'sliceAndDiceHorizontal' | 'sliceAndDiceVertical' | 'squarified';
nodeContent: {
renderer: ((context: ojTreemap.NodeContentContext<K, D>) => ({
insert: Element | string;
}));
};
nodeDefaults: {
groupLabelDisplay: 'node' | 'off' | 'header';
header: {
backgroundColor: string;
borderColor: string;
hoverBackgroundColor: string;
hoverInnerColor: string;
hoverOuterColor: string;
isolate: 'off' | 'on';
labelHalign: 'center' | 'end' | 'start';
labelStyle: object;
selectedBackgroundColor: string;
selectedInnerColor: string;
selectedOuterColor: string;
useNodeColor: 'on' | 'off';
};
hoverColor: string;
labelDisplay: 'off' | 'node';
labelHalign: 'start' | 'end' | 'center';
labelMinLength: number;
labelStyle: object;
labelValign: 'top' | 'bottom' | 'center';
selectedInnerColor: string;
selectedOuterColor: string;
};
nodeSeparators: 'bevels' | 'gaps';
rootNode: any;
selection: any[];
selectionMode: 'none' | 'single' | 'multiple';
sizeLabel: string;
sorting: 'on' | 'off';
tooltip: {
renderer: ((context: ojTreemap.TooltipContext<K, D>) => ({
insert: Element | string;
} | {
preventDefault: boolean;
}));
};
touchResponse: 'touchStart' | 'auto';
translations: {
componentName?: string | undefined;
labelAndValue?: string | undefined;
labelClearSelection?: string | undefined;
labelColor?: string | undefined;
labelCountWithTotal?: string | undefined;
labelDataVisualization?: string | undefined;
labelInvalidData?: string | undefined;
labelNoData?: string | undefined;
labelSize?: string | undefined;
stateCollapsed?: string | undefined;
stateDrillable?: string | undefined;
stateExpanded?: string | undefined;
stateHidden?: string | undefined;
stateIsolated?: string | undefined;
stateMaximized?: string | undefined;
stateMinimized?: string | undefined;
stateSelected?: string | undefined;
stateUnselected?: string | undefined;
stateVisible?: string | undefined;
tooltipIsolate?: string | undefined;
tooltipRestore?: string | undefined;
};
onAnimationDurationChanged: ((event: JetElementCustomEvent<ojTreemap<K, D>["animationDuration"]>) => any) | null;
onAnimationOnDataChangeChanged: ((event: JetElementCustomEvent<ojTreemap<K, D>["animationOnDataChange"]>) => any) | null;
onAnimationOnDisplayChanged: ((event: JetElementCustomEvent<ojTreemap<K, D>["animationOnDisplay"]>) => any) | null;
onAnimationUpdateColorChanged: ((event: JetElementCustomEvent<ojTreemap<K, D>["animationUpdateColor"]>) => any) | null;
onAsChanged: ((event: JetElementCustomEvent<ojTreemap<K, D>["as"]>) => any) | null;
onColorLabelChanged: ((event: JetElementCustomEvent<ojTreemap<K, D>["colorLabel"]>) => any) | null;
onDataChanged: ((event: JetElementCustomEvent<ojTreemap<K, D>["data"]>) => any) | null;
onDisplayLevelsChanged: ((event: JetElementCustomEvent<ojTreemap<K, D>["displayLevels"]>) => any) | null;
onDrillingChanged: ((event: JetElementCustomEvent<ojTreemap<K, D>["drilling"]>) => any) | null;
onGroupGapsChanged: ((event: JetElementCustomEvent<ojTreemap<K, D>["groupGaps"]>) => any) | null;
onHiddenCategoriesChanged: ((event: JetElementCustomEvent<ojTreemap<K, D>["hiddenCategories"]>) => any) | null;
onHighlightMatchChanged: ((event: JetElementCustomEvent<ojTreemap<K, D>["highlightMatch"]>) => any) | null;
onHighlightedCategoriesChanged: ((event: JetElementCustomEvent<ojTreemap<K, D>["highlightedCategories"]>) => any) | null;
onHoverBehaviorChanged: ((event: JetElementCustomEvent<ojTreemap<K, D>["hoverBehavior"]>) => any) | null;
onHoverBehaviorDelayChanged: ((event: JetElementCustomEvent<ojTreemap<K, D>["hoverBehaviorDelay"]>) => any) | null;
onIsolatedNodeChanged: ((event: JetElementCustomEvent<ojTreemap<K, D>["isolatedNode"]>) => any) | null;
onLayoutChanged: ((event: JetElementCustomEvent<ojTreemap<K, D>["layout"]>) => any) | null;
onNodeContentChanged: ((event: JetElementCustomEvent<ojTreemap<K, D>["nodeContent"]>) => any) | null;
onNodeDefaultsChanged: ((event: JetElementCustomEvent<ojTreemap<K, D>["nodeDefaults"]>) => any) | null;
onNodeSeparatorsChanged: ((event: JetElementCustomEvent<ojTreemap<K, D>["nodeSeparators"]>) => any) | null;
onRootNodeChanged: ((event: JetElementCustomEvent<ojTreemap<K, D>["rootNode"]>) => any) | null;
onSelectionChanged: ((event: JetElementCustomEvent<ojTreemap<K, D>["selection"]>) => any) | null;
onSelectionModeChanged: ((event: JetElementCustomEvent<ojTreemap<K, D>["selectionMode"]>) => any) | null;
onSizeLabelChanged: ((event: JetElementCustomEvent<ojTreemap<K, D>["sizeLabel"]>) => any) | null;
onSortingChanged: ((event: JetElementCustomEvent<ojTreemap<K, D>["sorting"]>) => any) | null;
onTooltipChanged: ((event: JetElementCustomEvent<ojTreemap<K, D>["tooltip"]>) => any) | null;
onTouchResponseChanged: ((event: JetElementCustomEvent<ojTreemap<K, D>["touchResponse"]>) => any) | null;
onOjBeforeDrill: ((event: ojTreemap.ojBeforeDrill) => any) | null;
onOjDrill: ((event: ojTreemap.ojDrill) => any) | null;
addEventListener<T extends keyof ojTreemapEventMap<K, D>>(type: T, listener: (this: HTMLElement, ev: ojTreemapEventMap<K, D>[T]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
getProperty<T extends keyof ojTreemapSettableProperties<K, D>>(property: T): ojTreemap<K, D>[T];
getProperty(property: string): any;
setProperty<T extends keyof ojTreemapSettableProperties<K, D>>(property: T, value: ojTreemapSettableProperties<K, D>[T]): void;
setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojTreemapSettableProperties<K, D>>): void;
setProperties(properties: ojTreemapSettablePropertiesLenient<K, D>): void;
getContextByNode(node: Element): ojTreemap.NodeContext | null;
getNode(subIdPath: any[]): ojTreemap.DataContext | null;
}
export namespace ojTreemap {
interface ojBeforeDrill extends CustomEvent<{
id: any;
data: object;
itemData: object;
[propName: string]: any;
}> {
}
interface ojDrill extends CustomEvent<{
id: any;
data: object;
itemData: object;
[propName: string]: any;
}> {
}
// tslint:disable-next-line interface-over-type-literal
type DataContext = {
color: string;
label: string;
selected: boolean;
size: number;
tooltip: string;
};
// tslint:disable-next-line interface-over-type-literal
type NodeContentContext<K, D> = {
bounds: {
x: number;
y: number;
width: number;
height: number;
};
id: K;
data: object;
itemData: D;
componentElement: Element;
};
// tslint:disable-next-line interface-over-type-literal
type NodeContext = {
subId: string;
indexPath: number[];
};
// tslint:disable-next-line interface-over-type-literal
type TooltipContext<K, D> = {
parentElement: Element;
id: K;
label: string;
value: number;
color: string;
data: object;
itemData: D;
componentElement: Element;
};
}
export interface ojTreemapEventMap<K, D> extends dvtBaseComponentEventMap<ojTreemapSettableProperties<K, D>> {
'ojBeforeDrill': ojTreemap.ojBeforeDrill;
'ojDrill': ojTreemap.ojDrill;
'animationDurationChanged': JetElementCustomEvent<ojTreemap<K, D>["animationDuration"]>;
'animationOnDataChangeChanged': JetElementCustomEvent<ojTreemap<K, D>["animationOnDataChange"]>;
'animationOnDisplayChanged': JetElementCustomEvent<ojTreemap<K, D>["animationOnDisplay"]>;
'animationUpdateColorChanged': JetElementCustomEvent<ojTreemap<K, D>["animationUpdateColor"]>;
'asChanged': JetElementCustomEvent<ojTreemap<K, D>["as"]>;
'colorLabelChanged': JetElementCustomEvent<ojTreemap<K, D>["colorLabel"]>;
'dataChanged': JetElementCustomEvent<ojTreemap<K, D>["data"]>;
'displayLevelsChanged': JetElementCustomEvent<ojTreemap<K, D>["displayLevels"]>;
'drillingChanged': JetElementCustomEvent<ojTreemap<K, D>["drilling"]>;
'groupGapsChanged': JetElementCustomEvent<ojTreemap<K, D>["groupGaps"]>;
'hiddenCategoriesChanged': JetElementCustomEvent<ojTreemap<K, D>["hiddenCategories"]>;
'highlightMatchChanged': JetElementCustomEvent<ojTreemap<K, D>["highlightMatch"]>;
'highlightedCategoriesChanged': JetElementCustomEvent<ojTreemap<K, D>["highlightedCategories"]>;
'hoverBehaviorChanged': JetElementCustomEvent<ojTreemap<K, D>["hoverBehavior"]>;
'hoverBehaviorDelayChanged': JetElementCustomEvent<ojTreemap<K, D>["hoverBehaviorDelay"]>;
'isolatedNodeChanged': JetElementCustomEvent<ojTreemap<K, D>["isolatedNode"]>;
'layoutChanged': JetElementCustomEvent<ojTreemap<K, D>["layout"]>;
'nodeContentChanged': JetElementCustomEvent<ojTreemap<K, D>["nodeContent"]>;
'nodeDefaultsChanged': JetElementCustomEvent<ojTreemap<K, D>["nodeDefaults"]>;
'nodeSeparatorsChanged': JetElementCustomEvent<ojTreemap<K, D>["nodeSeparators"]>;
'rootNodeChanged': JetElementCustomEvent<ojTreemap<K, D>["rootNode"]>;
'selectionChanged': JetElementCustomEvent<ojTreemap<K, D>["selection"]>;
'selectionModeChanged': JetElementCustomEvent<ojTreemap<K, D>["selectionMode"]>;
'sizeLabelChanged': JetElementCustomEvent<ojTreemap<K, D>["sizeLabel"]>;
'sortingChanged': JetElementCustomEvent<ojTreemap<K, D>["sorting"]>;
'tooltipChanged': JetElementCustomEvent<ojTreemap<K, D>["tooltip"]>;
'touchResponseChanged': JetElementCustomEvent<ojTreemap<K, D>["touchResponse"]>;
}
export interface ojTreemapSettableProperties<K, D> extends dvtBaseComponentSettableProperties {
animationDuration: number;
animationOnDataChange: 'auto' | 'none';
animationOnDisplay: 'auto' | 'none';
animationUpdateColor: string;
as: string;
colorLabel: string;
data: DataProvider<K, D> | null;
displayLevels: number;
drilling: 'on' | 'off';
groupGaps: 'all' | 'none' | 'outer';
hiddenCategories: string[];
highlightMatch: 'any' | 'all';
highlightedCategories: string[];
hoverBehavior: 'dim' | 'none';
hoverBehaviorDelay: number;
isolatedNode: any;
layout: 'sliceAndDiceHorizontal' | 'sliceAndDiceVertical' | 'squarified';
nodeContent: {
renderer: ((context: ojTreemap.NodeContentContext<K, D>) => ({
insert: Element | string;
}));
};
nodeDefaults: {
groupLabelDisplay: 'node' | 'off' | 'header';
header: {
backgroundColor: string;
borderColor: string;
hoverBackgroundColor: string;
hoverInnerColor: string;
hoverOuterColor: string;
isolate: 'off' | 'on';
labelHalign: 'center' | 'end' | 'start';
labelStyle: object;
selectedBackgroundColor: string;
selectedInnerColor: string;
selectedOuterColor: string;
useNodeColor: 'on' | 'off';
};
hoverColor: string;
labelDisplay: 'off' | 'node';
labelHalign: 'start' | 'end' | 'center';
labelMinLength: number;
labelStyle: object;
labelValign: 'top' | 'bottom' | 'center';
selectedInnerColor: string;
selectedOuterColor: string;
};
nodeSeparators: 'bevels' | 'gaps';
rootNode: any;
selection: any[];
selectionMode: 'none' | 'single' | 'multiple';
sizeLabel: string;
sorting: 'on' | 'off';
tooltip: {
renderer: ((context: ojTreemap.TooltipContext<K, D>) => ({
insert: Element | string;
} | {
preventDefault: boolean;
}));
};
touchResponse: 'touchStart' | 'auto';
translations: {
componentName?: string | undefined;
labelAndValue?: string | undefined;
labelClearSelection?: string | undefined;
labelColor?: string | undefined;
labelCountWithTotal?: string | undefined;
labelDataVisualization?: string | undefined;
labelInvalidData?: string | undefined;
labelNoData?: string | undefined;
labelSize?: string | undefined;
stateCollapsed?: string | undefined;
stateDrillable?: string | undefined;
stateExpanded?: string | undefined;
stateHidden?: string | undefined;
stateIsolated?: string | undefined;
stateMaximized?: string | undefined;
stateMinimized?: string | undefined;
stateSelected?: string | undefined;
stateUnselected?: string | undefined;
stateVisible?: string | undefined;
tooltipIsolate?: string | undefined;
tooltipRestore?: string | undefined;
};
}
export interface ojTreemapSettablePropertiesLenient<K, D> extends Partial<ojTreemapSettableProperties<K, D>> {
[key: string]: any;
}
export interface ojTreemapNode extends JetElement<ojTreemapNodeSettableProperties> {
categories?: string[] | undefined;
color?: string | undefined;
drilling?: 'on' | 'off' | 'inherit' | undefined;
groupLabelDisplay?: 'node' | 'off' | 'header' | undefined;
header?: {
isolate?: 'off' | 'on' | undefined;
labelHalign?: 'center' | 'end' | 'start' | undefined;
labelStyle?: object | undefined;
useNodeColor?: 'on' | 'off' | undefined;
} | undefined;
label?: string | undefined;
labelDisplay?: 'off' | 'node' | undefined;
labelHalign?: 'start' | 'end' | 'center' | undefined;
labelStyle?: object | undefined;
labelValign?: 'top' | 'bottom' | 'center' | undefined;
pattern?: 'smallChecker' | 'smallCrosshatch' | 'smallDiagonalLeft' | 'smallDiagonalRight' | 'smallDiamond' | 'smallTriangle' | 'largeChecker' | 'largeCrosshatch' | 'largeDiagonalLeft' |
'largeDiagonalRight' | 'largeDiamond' | 'largeTriangle' | 'none' | undefined;
selectable?: 'off' | 'auto' | undefined;
shortDesc?: string | undefined;
svgClassName?: string | undefined;
svgStyle?: object | undefined;
value: number;
onCategoriesChanged: ((event: JetElementCustomEvent<ojTreemapNode["categories"]>) => any) | null;
onColorChanged: ((event: JetElementCustomEvent<ojTreemapNode["color"]>) => any) | null;
onDrillingChanged: ((event: JetElementCustomEvent<ojTreemapNode["drilling"]>) => any) | null;
onGroupLabelDisplayChanged: ((event: JetElementCustomEvent<ojTreemapNode["groupLabelDisplay"]>) => any) | null;
onHeaderChanged: ((event: JetElementCustomEvent<ojTreemapNode["header"]>) => any) | null;
onLabelChanged: ((event: JetElementCustomEvent<ojTreemapNode["label"]>) => any) | null;
onLabelDisplayChanged: ((event: JetElementCustomEvent<ojTreemapNode["labelDisplay"]>) => any) | null;
onLabelHalignChanged: ((event: JetElementCustomEvent<ojTreemapNode["labelHalign"]>) => any) | null;
onLabelStyleChanged: ((event: JetElementCustomEvent<ojTreemapNode["labelStyle"]>) => any) | null;
onLabelValignChanged: ((event: JetElementCustomEvent<ojTreemapNode["labelValign"]>) => any) | null;
onPatternChanged: ((event: JetElementCustomEvent<ojTreemapNode["pattern"]>) => any) | null;
onSelectableChanged: ((event: JetElementCustomEvent<ojTreemapNode["selectable"]>) => any) | null;
onShortDescChanged: ((event: JetElementCustomEvent<ojTreemapNode["shortDesc"]>) => any) | null;
onSvgClassNameChanged: ((event: JetElementCustomEvent<ojTreemapNode["svgClassName"]>) => any) | null;
onSvgStyleChanged: ((event: JetElementCustomEvent<ojTreemapNode["svgStyle"]>) => any) | null;
onValueChanged: ((event: JetElementCustomEvent<ojTreemapNode["value"]>) => any) | null;
addEventListener<T extends keyof ojTreemapNodeEventMap>(type: T, listener: (this: HTMLElement, ev: ojTreemapNodeEventMap[T]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
getProperty<T extends keyof ojTreemapNodeSettableProperties>(property: T): ojTreemapNode[T];
getProperty(property: string): any;
setProperty<T extends keyof ojTreemapNodeSettableProperties>(property: T, value: ojTreemapNodeSettableProperties[T]): void;
setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojTreemapNodeSettableProperties>): void;
setProperties(properties: ojTreemapNodeSettablePropertiesLenient): void;
}
export interface ojTreemapNodeEventMap extends HTMLElementEventMap {
'categoriesChanged': JetElementCustomEvent<ojTreemapNode["categories"]>;
'colorChanged': JetElementCustomEvent<ojTreemapNode["color"]>;
'drillingChanged': JetElementCustomEvent<ojTreemapNode["drilling"]>;
'groupLabelDisplayChanged': JetElementCustomEvent<ojTreemapNode["groupLabelDisplay"]>;
'headerChanged': JetElementCustomEvent<ojTreemapNode["header"]>;
'labelChanged': JetElementCustomEvent<ojTreemapNode["label"]>;
'labelDisplayChanged': JetElementCustomEvent<ojTreemapNode["labelDisplay"]>;
'labelHalignChanged': JetElementCustomEvent<ojTreemapNode["labelHalign"]>;
'labelStyleChanged': JetElementCustomEvent<ojTreemapNode["labelStyle"]>;
'labelValignChanged': JetElementCustomEvent<ojTreemapNode["labelValign"]>;
'patternChanged': JetElementCustomEvent<ojTreemapNode["pattern"]>;
'selectableChanged': JetElementCustomEvent<ojTreemapNode["selectable"]>;
'shortDescChanged': JetElementCustomEvent<ojTreemapNode["shortDesc"]>;
'svgClassNameChanged': JetElementCustomEvent<ojTreemapNode["svgClassName"]>;
'svgStyleChanged': JetElementCustomEvent<ojTreemapNode["svgStyle"]>;
'valueChanged': JetElementCustomEvent<ojTreemapNode["value"]>;
}
export interface ojTreemapNodeSettableProperties extends JetSettableProperties {
categories?: string[] | undefined;
color?: string | undefined;
drilling?: 'on' | 'off' | 'inherit' | undefined;
groupLabelDisplay?: 'node' | 'off' | 'header' | undefined;
header?: {
isolate?: 'off' | 'on' | undefined;
labelHalign?: 'center' | 'end' | 'start' | undefined;
labelStyle?: object | undefined;
useNodeColor?: 'on' | 'off' | undefined;
} | undefined;
label?: string | undefined;
labelDisplay?: 'off' | 'node' | undefined;
labelHalign?: 'start' | 'end' | 'center' | undefined;
labelStyle?: object | undefined;
labelValign?: 'top' | 'bottom' | 'center' | undefined;
pattern?: 'smallChecker' | 'smallCrosshatch' | 'smallDiagonalLeft' | 'smallDiagonalRight' | 'smallDiamond' | 'smallTriangle' | 'largeChecker' | 'largeCrosshatch' | 'largeDiagonalLeft' |
'largeDiagonalRight' | 'largeDiamond' | 'largeTriangle' | 'none' | undefined;
selectable?: 'off' | 'auto' | undefined;
shortDesc?: string | undefined;
svgClassName?: string | undefined;
svgStyle?: object | undefined;
value: number;
}
export interface ojTreemapNodeSettablePropertiesLenient extends Partial<ojTreemapNodeSettableProperties> {
[key: string]: any;
} | the_stack |
module android.widget {
import Canvas = android.graphics.Canvas;
import Rect = android.graphics.Rect;
import Drawable = android.graphics.drawable.Drawable;
import InputType = android.text.InputType;
import TextUtils = android.text.TextUtils;
import Log = android.util.Log;
import LongSparseArray = android.util.LongSparseArray;
import SparseArray = android.util.SparseArray;
import SparseBooleanArray = android.util.SparseBooleanArray;
import StateSet = android.util.StateSet;
import Gravity = android.view.Gravity;
import HapticFeedbackConstants = android.view.HapticFeedbackConstants;
import KeyEvent = android.view.KeyEvent;
import MotionEvent = android.view.MotionEvent;
import VelocityTracker = android.view.VelocityTracker;
import View = android.view.View;
import ViewConfiguration = android.view.ViewConfiguration;
import ViewGroup = android.view.ViewGroup;
import ViewParent = android.view.ViewParent;
import ViewTreeObserver = android.view.ViewTreeObserver;
import Interpolator = android.view.animation.Interpolator;
import LinearInterpolator = android.view.animation.LinearInterpolator;
import ArrayList = java.util.ArrayList;
import List = java.util.List;
import Integer = java.lang.Integer;
import Runnable = java.lang.Runnable;
import System = java.lang.System;
import Adapter = android.widget.Adapter;
import AdapterView = android.widget.AdapterView;
import Button = android.widget.Button;
import Checkable = android.widget.Checkable;
import ListAdapter = android.widget.ListAdapter;
import OverScroller = android.widget.OverScroller;
import AttrBinder = androidui.attr.AttrBinder;
/**
* Base class that can be used to implement virtualized lists of items. A list does
* not have a spatial definition here. For instance, subclases of this class can
* display the content of the list in a grid, in a carousel, as stack, etc.
*
* @attr ref android.R.styleable#AbsListView_listSelector
* @attr ref android.R.styleable#AbsListView_drawSelectorOnTop
* @attr ref android.R.styleable#AbsListView_stackFromBottom
* @attr ref android.R.styleable#AbsListView_scrollingCache
* @attr ref android.R.styleable#AbsListView_textFilterEnabled
* @attr ref android.R.styleable#AbsListView_transcriptMode
* @attr ref android.R.styleable#AbsListView_cacheColorHint
* @attr ref android.R.styleable#AbsListView_fastScrollEnabled
* @attr ref android.R.styleable#AbsListView_smoothScrollbar
* @attr ref android.R.styleable#AbsListView_choiceMode
*/
export abstract class AbsListView extends AdapterView<ListAdapter> implements ViewTreeObserver.OnGlobalLayoutListener,
ViewTreeObserver.OnTouchModeChangeListener {
static TAG_AbsListView:string = "AbsListView";
/**
* Disables the transcript mode.
*
* @see #setTranscriptMode(int)
*/
static TRANSCRIPT_MODE_DISABLED:number = 0;
/**
* The list will automatically scroll to the bottom when a data set change
* notification is received and only if the last item is already visible
* on screen.
*
* @see #setTranscriptMode(int)
*/
static TRANSCRIPT_MODE_NORMAL:number = 1;
/**
* The list will automatically scroll to the bottom, no matter what items
* are currently visible.
*
* @see #setTranscriptMode(int)
*/
static TRANSCRIPT_MODE_ALWAYS_SCROLL:number = 2;
/**
* Indicates that we are not in the middle of a touch gesture
*/
static TOUCH_MODE_REST:number = -1;
/**
* Indicates we just received the touch event and we are waiting to see if the it is a tap or a
* scroll gesture.
*/
static TOUCH_MODE_DOWN:number = 0;
/**
* Indicates the touch has been recognized as a tap and we are now waiting to see if the touch
* is a longpress
*/
static TOUCH_MODE_TAP:number = 1;
/**
* Indicates we have waited for everything we can wait for, but the user's finger is still down
*/
static TOUCH_MODE_DONE_WAITING:number = 2;
/**
* Indicates the touch gesture is a scroll
*/
static TOUCH_MODE_SCROLL:number = 3;
/**
* Indicates the view is in the process of being flung
*/
static TOUCH_MODE_FLING:number = 4;
/**
* Indicates the touch gesture is an overscroll - a scroll beyond the beginning or end.
*/
private static TOUCH_MODE_OVERSCROLL:number = 5;
/**
* Indicates the view is being flung outside of normal content bounds
* and will spring back.
*/
static TOUCH_MODE_OVERFLING:number = 6;
/**
* Regular layout - usually an unsolicited layout from the view system
*/
static LAYOUT_NORMAL:number = 0;
/**
* Show the first item
*/
static LAYOUT_FORCE_TOP:number = 1;
/**
* Force the selected item to be on somewhere on the screen
*/
static LAYOUT_SET_SELECTION:number = 2;
/**
* Show the last item
*/
static LAYOUT_FORCE_BOTTOM:number = 3;
/**
* Make a mSelectedItem appear in a specific location and build the rest of
* the views from there. The top is specified by mSpecificTop.
*/
static LAYOUT_SPECIFIC:number = 4;
/**
* Layout to sync as a result of a data change. Restore mSyncPosition to have its top
* at mSpecificTop
*/
static LAYOUT_SYNC:number = 5;
/**
* Layout as a result of using the navigation keys
*/
static LAYOUT_MOVE_SELECTION:number = 6;
/**
* Normal list that does not indicate choices
*/
static CHOICE_MODE_NONE:number = 0;
/**
* The list allows up to one choice
*/
static CHOICE_MODE_SINGLE:number = 1;
/**
* The list allows multiple choices
*/
static CHOICE_MODE_MULTIPLE:number = 2;
/**
* The list allows multiple choices in a modal selection mode
* !!not impl this mode
*/
static CHOICE_MODE_MULTIPLE_MODAL:number = 3;
/**
* Controls if/how the user may choose/check items in the list
*/
mChoiceMode:number = AbsListView.CHOICE_MODE_NONE;
/**
* Controls CHOICE_MODE_MULTIPLE_MODAL. null when inactive.
* !!not impl current
*/
private mChoiceActionMode;
/**
* Wrapper for the multiple choice mode callback; AbsListView needs to perform
* a few extra actions around what application code does.
*/
//private mMultiChoiceModeCallback:AbsListView.MultiChoiceModeWrapper;
/**
* Running count of how many items are currently checked
*/
private mCheckedItemCount:number = 0;
/**
* Running state of which positions are currently checked
*/
mCheckStates:SparseBooleanArray;
/**
* Running state of which IDs are currently checked.
* If there is a value for a given key, the checked state for that ID is true
* and the value holds the last known position in the adapter for that id.
*/
private mCheckedIdStates:LongSparseArray<number>;
/**
* Controls how the next layout will happen
*/
//mLayoutMode:number = AbsListView.LAYOUT_NORMAL;
/**
* Should be used by subclasses to listen to changes in the dataset
*/
mDataSetObserver:AbsListView.AdapterDataSetObserver;
/**
* The adapter containing the data to be displayed by this view
*/
mAdapter:ListAdapter;
/**
* If mAdapter != null, whenever this is true the adapter has stable IDs.
*/
private mAdapterHasStableIds:boolean;
/**
* This flag indicates the a full notify is required when the RemoteViewsAdapter connects
*/
private mDeferNotifyDataSetChanged:boolean = false;
/**
* Indicates whether the list selector should be drawn on top of the children or behind
*/
private mDrawSelectorOnTop:boolean = false;
/**
* The drawable used to draw the selector
*/
private mSelector:Drawable;
/**
* The current position of the selector in the list.
*/
private mSelectorPosition:number = AbsListView.INVALID_POSITION;
/**
* Defines the selector's location and dimension at drawing time
*/
mSelectorRect:Rect = new Rect();
/**
* The data set used to store unused views that should be reused during the next layout
* to avoid creating new ones
*/
mRecycler:AbsListView.RecycleBin = new AbsListView.RecycleBin(this);
/**
* The selection's left padding
*/
private mSelectionLeftPadding:number = 0;
/**
* The selection's top padding
*/
private mSelectionTopPadding:number = 0;
/**
* The selection's right padding
*/
private mSelectionRightPadding:number = 0;
/**
* The selection's bottom padding
*/
private mSelectionBottomPadding:number = 0;
/**
* This view's padding
*/
mListPadding:Rect = new Rect();
/**
* Subclasses must retain their measure spec from onMeasure() into this member
*/
mWidthMeasureSpec:number = 0;
/**
* The top scroll indicator
*/
private mScrollUp:View;
/**
* The down scroll indicator
*/
private mScrollDown:View;
/**
* When the view is scrolling, this flag is set to true to indicate subclasses that
* the drawing cache was enabled on the children
*/
mCachingStarted:boolean;
mCachingActive:boolean;
/**
* The position of the view that received the down motion event
*/
mMotionPosition:number = 0;
/**
* The offset to the top of the mMotionPosition view when the down motion event was received
*/
private mMotionViewOriginalTop:number = 0;
/**
* The desired offset to the top of the mMotionPosition view after a scroll
*/
private mMotionViewNewTop:number = 0;
/**
* The X value associated with the the down motion event
*/
private mMotionX:number = 0;
/**
* The Y value associated with the the down motion event
*/
private mMotionY:number = 0;
/**
* One of TOUCH_MODE_REST, TOUCH_MODE_DOWN, TOUCH_MODE_TAP, TOUCH_MODE_SCROLL, or
* TOUCH_MODE_DONE_WAITING
*/
mTouchMode:number = AbsListView.TOUCH_MODE_REST;
/**
* Y value from on the previous motion event (if any)
*/
private mLastY:number = 0;
/**
* How far the finger moved before we started scrolling
*/
private mMotionCorrection:number = 0;
/**
* Determines speed during touch scrolling
*/
private mVelocityTracker:VelocityTracker;
/**
* Handles one frame of a fling
*/
mFlingRunnable:AbsListView.FlingRunnable;
/**
* Handles scrolling between positions within the list.
*/
mPositionScroller:AbsListView.PositionScroller;
/**
* The offset in pixels form the top of the AdapterView to the top
* of the currently selected view. Used to save and restore state.
*/
mSelectedTop:number = 0;
/**
* Indicates whether the list is stacked from the bottom edge or
* the top edge.
*/
mStackFromBottom:boolean;
/**
* When set to true, the list automatically discards the children's
* bitmap cache after scrolling.
*/
private mScrollingCacheEnabled:boolean;
/**
* Whether or not to enable the fast scroll feature on this list
*/
private mFastScrollEnabled:boolean;
/**
* Whether or not to always show the fast scroll feature on this list
*/
private mFastScrollAlwaysVisible:boolean;
/**
* Optional callback to notify client when scroll position has changed
*/
private mOnScrollListener:AbsListView.OnScrollListener;
/**
* Indicates whether to use pixels-based or position-based scrollbar
* properties.
*/
private mSmoothScrollbarEnabled:boolean = true;
/**
* Indicates that this view supports filtering
*/
private mTextFilterEnabled:boolean;
/**
* Indicates that this view is currently displaying a filtered view of the data
*/
private mFiltered:boolean;
/**
* Rectangle used for hit testing children
*/
private mTouchFrame:Rect;
/**
* The position to resurrect the selected position to.
*/
mResurrectToPosition:number = AbsListView.INVALID_POSITION;
/**
* Maximum distance to record overscroll
*/
private mOverscrollMax:number = 0;
/**
* Content height divided by this is the overscroll limit.
*/
private static OVERSCROLL_LIMIT_DIVISOR:number = 3;
/**
* How many positions in either direction we will search to try to
* find a checked item with a stable ID that moved position across
* a data set change. If the item isn't found it will be unselected.
*/
private static CHECK_POSITION_SEARCH_DISTANCE:number = 20;
/**
* Used to request a layout when we changed touch mode
*/
private static TOUCH_MODE_UNKNOWN:number = -1;
private static TOUCH_MODE_ON:number = 0;
private static TOUCH_MODE_OFF:number = 1;
private mLastTouchMode:number = AbsListView.TOUCH_MODE_UNKNOWN;
private static PROFILE_SCROLLING:boolean = false;
private mScrollProfilingStarted:boolean = false;
static PROFILE_FLINGING:boolean = false;
private mFlingProfilingStarted:boolean = false;
/**
* The last CheckForLongPress runnable we posted, if any
*/
private mPendingCheckForLongPress_List:AbsListView.CheckForLongPress;
/**
* The last CheckForTap runnable we posted, if any
*/
private mPendingCheckForTap_:Runnable;
/**
* The last CheckForKeyLongPress runnable we posted, if any
*/
private mPendingCheckForKeyLongPress:AbsListView.CheckForKeyLongPress;
/**
* Acts upon click
*/
private mPerformClick_:AbsListView.PerformClick;
/**
* Delayed action for touch mode.
*/
mTouchModeReset:Runnable;
/**
* This view is in transcript mode -- it shows the bottom of the list when the data
* changes
*/
private mTranscriptMode:number = 0;
/**
* Indicates that this list is always drawn on top of a solid, single-color, opaque
* background
*/
private mCacheColorHint:number = 0;
/**
* The select child's view (from the adapter's getView) is enabled.
*/
private mIsChildViewEnabled:boolean;
/**
* The last scroll state reported to clients through {@link OnScrollListener}.
*/
private mLastScrollState:number = AbsListView.OnScrollListener.SCROLL_STATE_IDLE;
/**
* Helper object that renders and controls the fast scroll thumb.
*/
//private mFastScroller:FastScroller;//TODO when fast scroll impl
private mGlobalLayoutListenerAddedFilter:boolean;
//private mTouchSlop:number = 0;
private mDensityScale:number = 0;
private mClearScrollingCache:Runnable;
mPositionScrollAfterLayout:Runnable;
private mMinimumVelocity:number = 0;
private mMaximumVelocity:number = 0;
private mVelocityScale:number = 1.0;
mIsScrap:boolean[] = new Array<boolean>(1);
// True when the popup should be hidden because of a call to
// dispatchDisplayHint()
private mPopupHidden:boolean;
/**
* ID of the active pointer. This is used to retain consistency during
* drags/flings if multiple pointers are used.
*/
private mActivePointerId:number = AbsListView.INVALID_POINTER;
/**
* Sentinel value for no current active pointer.
* Used by {@link #mActivePointerId}.
*/
static INVALID_POINTER:number = -1;
/**
* Maximum distance to overscroll by during edge effects
*/
private mOverscrollDistance:number = 0;
/**
* Maximum distance to overfling during edge effects
*/
private _mOverflingDistance:number = 0;
private get mOverflingDistance():number {
if(this.mScrollY <= 0){
if (this.mScrollY < -this._mOverflingDistance) return -this.mScrollY;
return this._mOverflingDistance;
}
let overDistance = this.mScrollY;
if (overDistance > this._mOverflingDistance) return overDistance;
return this._mOverflingDistance;
}
private set mOverflingDistance(value:number) {
this._mOverflingDistance = value;
}
// These two EdgeGlows are always set and used together.
// Checking one for null is as good as checking both.
/**
* Tracks the state of the top edge glow.
*/
//private mEdgeGlowTop:EdgeEffect;
/**
* Tracks the state of the bottom edge glow.
*/
//private mEdgeGlowBottom:EdgeEffect;
/**
* An estimate of how many pixels are between the top of the list and
* the top of the first position in the adapter, based on the last time
* we saw it. Used to hint where to draw edge glows.
*/
private mFirstPositionDistanceGuess:number = 0;
/**
* An estimate of how many pixels are between the bottom of the list and
* the bottom of the last position in the adapter, based on the last time
* we saw it. Used to hint where to draw edge glows.
*/
private mLastPositionDistanceGuess:number = 0;
/**
* Used for determining when to cancel out of overscroll.
*/
private mDirection:number = 0;
/**
* Tracked on measurement in transcript mode. Makes sure that we can still pin to
* the bottom correctly on resizes.
*/
private mForceTranscriptScroll:boolean;
private mGlowPaddingLeft:number = 0;
private mGlowPaddingRight:number = 0;
/**
* Used for interacting with list items from an accessibility service.
*/
//private mAccessibilityDelegate:AbsListView.ListItemAccessibilityDelegate;
//
//private mLastAccessibilityScrollEventFromIndex:number;
//
//private mLastAccessibilityScrollEventToIndex:number;
/**
* Track the item count from the last time we handled a data change.
*/
private mLastHandledItemCount:number = 0;
/**
* Used for smooth scrolling at a consistent rate
*/
static sLinearInterpolator:Interpolator = new LinearInterpolator();
/**
* The saved state that we will be restoring from when we next sync.
* Kept here so that if we happen to be asked to save our state before
* the sync happens, we can return this existing data rather than losing
* it.
*/
private mPendingSync;//:AbsListView.SavedState;
constructor(context:android.content.Context, bindElement?:HTMLElement, defStyle?:Map<string, string>) {
super(context, bindElement, defStyle);
this.initAbsListView();
// this.mOwnerThread = Thread.currentThread();
let a = context.obtainStyledAttributes(bindElement, defStyle);
let d:Drawable = a.getDrawable('listSelector');
if (d != null) {
this.setSelector(d);
}
this.mDrawSelectorOnTop = a.getBoolean('drawSelectorOnTop', false);
let stackFromBottom:boolean = a.getBoolean('stackFromBottom', false);
this.setStackFromBottom(stackFromBottom);
let scrollingCacheEnabled:boolean = a.getBoolean('scrollingCache', true);
this.setScrollingCacheEnabled(scrollingCacheEnabled);
let useTextFilter:boolean = a.getBoolean('textFilterEnabled', false);
this.setTextFilterEnabled(useTextFilter);
let transcriptModeValue = a.getAttrValue('transcriptMode');
let transcriptMode:number = AbsListView.TRANSCRIPT_MODE_DISABLED;
if (transcriptModeValue === "disabled") transcriptMode = AbsListView.TRANSCRIPT_MODE_DISABLED;
else if (transcriptModeValue === "normal") transcriptMode = AbsListView.TRANSCRIPT_MODE_NORMAL;
else if (transcriptModeValue === "alwaysScroll") transcriptMode = AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL;
this.setTranscriptMode(transcriptMode);
let color:number = a.getColor('cacheColorHint', 0);
this.setCacheColorHint(color);
let enableFastScroll:boolean = a.getBoolean('fastScrollEnabled', false);
this.setFastScrollEnabled(enableFastScroll);
let smoothScrollbar:boolean = a.getBoolean('smoothScrollbar', true);
this.setSmoothScrollbarEnabled(smoothScrollbar);
let choiceModeValue = a.getAttrValue('choiceMode');
let choiceMode = AbsListView.CHOICE_MODE_NONE;
if (choiceModeValue === "none") choiceMode = AbsListView.CHOICE_MODE_NONE;
else if (choiceModeValue === "singleChoice") choiceMode = AbsListView.CHOICE_MODE_SINGLE;
else if (choiceModeValue === "multipleChoice") choiceMode = AbsListView.CHOICE_MODE_MULTIPLE;
this.setChoiceMode(choiceMode);
this.setFastScrollAlwaysVisible(a.getBoolean('fastScrollAlwaysVisible', false));
a.recycle();
}
private initAbsListView():void {
// Setting focusable in touch mode will set the focusable property to true
this.setClickable(true);
this.setFocusableInTouchMode(true);
this.setWillNotDraw(false);
this.setAlwaysDrawnWithCacheEnabled(false);
this.setScrollingCacheEnabled(true);
const configuration:ViewConfiguration = ViewConfiguration.get();
this.mTouchSlop = configuration.getScaledTouchSlop();
this.mMinimumVelocity = configuration.getScaledMinimumFlingVelocity();
this.mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
this.mOverscrollDistance = configuration.getScaledOverscrollDistance();
this.mOverflingDistance = configuration.getScaledOverflingDistance();
this.mDensityScale = android.content.res.Resources.getDisplayMetrics().density;
this.mLayoutMode = AbsListView.LAYOUT_NORMAL;
}
protected createClassAttrBinder(): androidui.attr.AttrBinder.ClassBinderMap {
return super.createClassAttrBinder()
.set('listSelector', {
setter(v: AbsListView, value: any, attrBinder: AttrBinder) {
let d = attrBinder.parseDrawable(value);
if (d) v.setSelector(d);
}, getter(v: AbsListView) {
return v.getSelector();
}
})
.set('drawSelectorOnTop', {
setter(v: AbsListView, value: any, attrBinder: AttrBinder) {
v.setDrawSelectorOnTop(attrBinder.parseBoolean(value, false));
}, getter(v: AbsListView) {
return v.mDrawSelectorOnTop;
}
})
.set('stackFromBottom', {
setter(v: AbsListView, value: any, attrBinder: AttrBinder) {
v.setStackFromBottom(attrBinder.parseBoolean(value, false));
}, getter(v: AbsListView) {
return v.isStackFromBottom();
}
})
.set('scrollingCache', {
setter(v: AbsListView, value: any, attrBinder: AttrBinder) {
v.setScrollingCacheEnabled(attrBinder.parseBoolean(value, true));
}, getter(v: AbsListView) {
return v.isScrollingCacheEnabled();
}
})
.set('transcriptMode', {
setter(v: AbsListView, value: any, attrBinder: AttrBinder) {
v.setTranscriptMode(attrBinder.parseEnum(value, new Map<string, number>()
.set("disabled", AbsListView.TRANSCRIPT_MODE_DISABLED)
.set("normal", AbsListView.TRANSCRIPT_MODE_NORMAL)
.set("alwaysScroll", AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL),
AbsListView.TRANSCRIPT_MODE_DISABLED));
}, getter(v: AbsListView) {
return v.getTranscriptMode();
}
})
.set('cacheColorHint', {
setter(v: AbsListView, value: any, attrBinder: AttrBinder) {
let color: number = attrBinder.parseColor(value, 0);
v.setCacheColorHint(color);
}, getter(v: AbsListView) {
return v.getCacheColorHint();
}
})
.set('fastScrollEnabled', {
setter(v: AbsListView, value: any, attrBinder: AttrBinder) {
let enableFastScroll: boolean = attrBinder.parseBoolean(value, false);
v.setFastScrollEnabled(enableFastScroll);
}, getter(v: AbsListView) {
return v.isFastScrollEnabled();
}
})
.set('fastScrollAlwaysVisible', {
setter(v: AbsListView, value: any, attrBinder: AttrBinder) {
let fastScrollAlwaysVisible: boolean = attrBinder.parseBoolean(value, false);
v.setFastScrollAlwaysVisible(fastScrollAlwaysVisible);
}, getter(v: AbsListView) {
return v.isFastScrollAlwaysVisible();
}
})
.set('smoothScrollbar', {
setter(v: AbsListView, value: any, attrBinder: AttrBinder) {
let smoothScrollbar: boolean = attrBinder.parseBoolean(value, true);
v.setSmoothScrollbarEnabled(smoothScrollbar);
}, getter(v: AbsListView) {
return v.isSmoothScrollbarEnabled();
}
})
.set('choiceMode', {
setter(v: AbsListView, value: any, attrBinder: AttrBinder) {
v.setChoiceMode(attrBinder.parseEnum(value, new Map<string, number>()
.set("none", AbsListView.CHOICE_MODE_NONE)
.set("singleChoice", AbsListView.CHOICE_MODE_SINGLE)
.set("multipleChoice", AbsListView.CHOICE_MODE_MULTIPLE),
AbsListView.CHOICE_MODE_NONE));
}, getter(v: AbsListView) {
return v.getChoiceMode();
}
});
}
setOverScrollMode(mode:number):void {
if (mode != AbsListView.OVER_SCROLL_NEVER) {
//if (this.mEdgeGlowTop == null) {
// let context:Context = this.getContext();
// this.mEdgeGlowTop = new EdgeEffect(context);
// this.mEdgeGlowBottom = new EdgeEffect(context);
//}
} else {
//this.mEdgeGlowTop = null;
//this.mEdgeGlowBottom = null;
}
super.setOverScrollMode(mode);
}
/**
* {@inheritDoc}
*/
setAdapter(adapter:ListAdapter):void {
if (adapter != null) {
this.mAdapterHasStableIds = this.mAdapter.hasStableIds();
if (this.mChoiceMode != AbsListView.CHOICE_MODE_NONE && this.mAdapterHasStableIds && this.mCheckedIdStates == null) {
this.mCheckedIdStates = new LongSparseArray<number>();
}
}
if (this.mCheckStates != null) {
this.mCheckStates.clear();
}
if (this.mCheckedIdStates != null) {
this.mCheckedIdStates.clear();
}
}
/**
* Returns the number of items currently selected. This will only be valid
* if the choice mode is not {@link #CHOICE_MODE_NONE} (default).
*
* <p>To determine the specific items that are currently selected, use one of
* the <code>getChecked*</code> methods.
*
* @return The number of items currently selected
*
* @see #getCheckedItemPosition()
* @see #getCheckedItemPositions()
* @see #getCheckedItemIds()
*/
getCheckedItemCount():number {
return this.mCheckedItemCount;
}
/**
* Returns the checked state of the specified position. The result is only
* valid if the choice mode has been set to {@link #CHOICE_MODE_SINGLE}
* or {@link #CHOICE_MODE_MULTIPLE}.
*
* @param position The item whose checked state to return
* @return The item's checked state or <code>false</code> if choice mode
* is invalid
*
* @see #setChoiceMode(int)
*/
isItemChecked(position:number):boolean {
if (this.mChoiceMode != AbsListView.CHOICE_MODE_NONE && this.mCheckStates != null) {
return this.mCheckStates.get(position);
}
return false;
}
/**
* Returns the currently checked item. The result is only valid if the choice
* mode has been set to {@link #CHOICE_MODE_SINGLE}.
*
* @return The position of the currently checked item or
* {@link #INVALID_POSITION} if nothing is selected
*
* @see #setChoiceMode(int)
*/
getCheckedItemPosition():number {
if (this.mChoiceMode == AbsListView.CHOICE_MODE_SINGLE && this.mCheckStates != null && this.mCheckStates.size() == 1) {
return this.mCheckStates.keyAt(0);
}
return AbsListView.INVALID_POSITION;
}
/**
* Returns the set of checked items in the list. The result is only valid if
* the choice mode has not been set to {@link #CHOICE_MODE_NONE}.
*
* @return A SparseBooleanArray which will return true for each call to
* get(int position) where position is a checked position in the
* list and false otherwise, or <code>null</code> if the choice
* mode is set to {@link #CHOICE_MODE_NONE}.
*/
getCheckedItemPositions():SparseBooleanArray {
if (this.mChoiceMode != AbsListView.CHOICE_MODE_NONE) {
return this.mCheckStates;
}
return null;
}
/**
* Returns the set of checked items ids. The result is only valid if the
* choice mode has not been set to {@link #CHOICE_MODE_NONE} and the adapter
* has stable IDs. ({@link ListAdapter#hasStableIds()} == {@code true})
*
* @return A new array which contains the id of each checked item in the
* list.
*/
getCheckedItemIds():number[] {
if (this.mChoiceMode == AbsListView.CHOICE_MODE_NONE || this.mCheckedIdStates == null || this.mAdapter == null) {
return [0];
}
const idStates:LongSparseArray<Integer> = this.mCheckedIdStates;
const count:number = idStates.size();
const ids:number[] = [count];
for (let i:number = 0; i < count; i++) {
ids[i] = idStates.keyAt(i);
}
return ids;
}
/**
* Clear any choices previously set
*/
clearChoices():void {
if (this.mCheckStates != null) {
this.mCheckStates.clear();
}
if (this.mCheckedIdStates != null) {
this.mCheckedIdStates.clear();
}
this.mCheckedItemCount = 0;
}
/**
* Sets the checked state of the specified position. The is only valid if
* the choice mode has been set to {@link #CHOICE_MODE_SINGLE} or
* {@link #CHOICE_MODE_MULTIPLE}.
*
* @param position The item whose checked state is to be checked
* @param value The new checked state for the item
*/
setItemChecked(position:number, value:boolean):void {
if (this.mChoiceMode == AbsListView.CHOICE_MODE_NONE) {
return;
}
// Start selection mode if needed. We don't need to if we're unchecking something.
//if (value && this.mChoiceMode == AbsListView.CHOICE_MODE_MULTIPLE_MODAL && this.mChoiceActionMode == null) {
// if (this.mMultiChoiceModeCallback == null || !this.mMultiChoiceModeCallback.hasWrappedCallback()) {
// throw Error(`new IllegalStateException("AbsListView: attempted to start selection mode " + "for CHOICE_MODE_MULTIPLE_MODAL but no choice mode callback was " + "supplied. Call setMultiChoiceModeListener to set a callback.")`);
// }
// this.mChoiceActionMode = this.startActionMode(this.mMultiChoiceModeCallback);
//}
if (this.mChoiceMode == AbsListView.CHOICE_MODE_MULTIPLE || this.mChoiceMode == AbsListView.CHOICE_MODE_MULTIPLE_MODAL) {
let oldValue:boolean = this.mCheckStates.get(position);
this.mCheckStates.put(position, value);
if (this.mCheckedIdStates != null && this.mAdapter.hasStableIds()) {
if (value) {
this.mCheckedIdStates.put(this.mAdapter.getItemId(position), position);
} else {
this.mCheckedIdStates.delete(this.mAdapter.getItemId(position));
}
}
if (oldValue != value) {
if (value) {
this.mCheckedItemCount++;
} else {
this.mCheckedItemCount--;
}
}
//if (this.mChoiceActionMode != null) {
// const id:number = this.mAdapter.getItemId(position);
// this.mMultiChoiceModeCallback.onItemCheckedStateChanged(this.mChoiceActionMode, position, id, value);
//}
} else {
let updateIds:boolean = this.mCheckedIdStates != null && this.mAdapter.hasStableIds();
// selected item
if (value || this.isItemChecked(position)) {
this.mCheckStates.clear();
if (updateIds) {
this.mCheckedIdStates.clear();
}
}
// we ensure length of mCheckStates is 1, a fact getCheckedItemPosition relies on
if (value) {
this.mCheckStates.put(position, true);
if (updateIds) {
this.mCheckedIdStates.put(this.mAdapter.getItemId(position), position);
}
this.mCheckedItemCount = 1;
} else if (this.mCheckStates.size() == 0 || !this.mCheckStates.valueAt(0)) {
this.mCheckedItemCount = 0;
}
}
// Do not generate a data change while we are in the layout phase
if (!this.mInLayout && !this.mBlockLayoutRequests) {
this.mDataChanged = true;
this.rememberSyncState();
this.requestLayout();
}
}
performItemClick(view:View, position:number, id:number):boolean {
let handled:boolean = false;
let dispatchItemClick:boolean = true;
if (this.mChoiceMode != AbsListView.CHOICE_MODE_NONE) {
handled = true;
let checkedStateChanged:boolean = false;
if (this.mChoiceMode == AbsListView.CHOICE_MODE_MULTIPLE || (this.mChoiceMode == AbsListView.CHOICE_MODE_MULTIPLE_MODAL && this.mChoiceActionMode != null)) {
let checked:boolean = !this.mCheckStates.get(position, false);
this.mCheckStates.put(position, checked);
if (this.mCheckedIdStates != null && this.mAdapter.hasStableIds()) {
if (checked) {
this.mCheckedIdStates.put(this.mAdapter.getItemId(position), position);
} else {
this.mCheckedIdStates.delete(this.mAdapter.getItemId(position));
}
}
if (checked) {
this.mCheckedItemCount++;
} else {
this.mCheckedItemCount--;
}
//if (this.mChoiceActionMode != null) {
// this.mMultiChoiceModeCallback.onItemCheckedStateChanged(this.mChoiceActionMode, position, id, checked);
// dispatchItemClick = false;
//}
checkedStateChanged = true;
} else if (this.mChoiceMode == AbsListView.CHOICE_MODE_SINGLE) {
let checked:boolean = !this.mCheckStates.get(position, false);
if (checked) {
this.mCheckStates.clear();
this.mCheckStates.put(position, true);
if (this.mCheckedIdStates != null && this.mAdapter.hasStableIds()) {
this.mCheckedIdStates.clear();
this.mCheckedIdStates.put(this.mAdapter.getItemId(position), position);
}
this.mCheckedItemCount = 1;
} else if (this.mCheckStates.size() == 0 || !this.mCheckStates.valueAt(0)) {
this.mCheckedItemCount = 0;
}
checkedStateChanged = true;
}
if (checkedStateChanged) {
this.updateOnScreenCheckedViews();
}
}
if (dispatchItemClick) {
handled = super.performItemClick(view, position, id) || handled;
}
return handled;
}
/**
* Perform a quick, in-place update of the checked or activated state
* on all visible item views. This should only be called when a valid
* choice mode is active.
*/
private updateOnScreenCheckedViews():void {
const firstPos:number = this.mFirstPosition;
const count:number = this.getChildCount();
const useActivated:boolean = true;
for (let i:number = 0; i < count; i++) {
const child:View = this.getChildAt(i);
const position:number = firstPos + i;
if (child['setChecked']) {//child instanceof Checkable
(<Checkable><any>child).setChecked(this.mCheckStates.get(position));
} else if (useActivated) {
child.setActivated(this.mCheckStates.get(position));
}
}
}
/**
* @see #setChoiceMode(int)
*
* @return The current choice mode
*/
getChoiceMode():number {
return this.mChoiceMode;
}
/**
* Defines the choice behavior for the List. By default, Lists do not have any choice behavior
* ({@link #CHOICE_MODE_NONE}). By setting the choiceMode to {@link #CHOICE_MODE_SINGLE}, the
* List allows up to one item to be in a chosen state. By setting the choiceMode to
* {@link #CHOICE_MODE_MULTIPLE}, the list allows any number of items to be chosen.
*
* @param choiceMode One of {@link #CHOICE_MODE_NONE}, {@link #CHOICE_MODE_SINGLE}, or
* {@link #CHOICE_MODE_MULTIPLE}
*/
setChoiceMode(choiceMode:number):void {
this.mChoiceMode = choiceMode;
if (this.mChoiceActionMode != null) {
this.mChoiceActionMode.finish();
this.mChoiceActionMode = null;
}
if (this.mChoiceMode != AbsListView.CHOICE_MODE_NONE) {
if (this.mCheckStates == null) {
this.mCheckStates = new SparseBooleanArray(0);
}
if (this.mCheckedIdStates == null && this.mAdapter != null && this.mAdapter.hasStableIds()) {
this.mCheckedIdStates = new LongSparseArray<number>(0);
}
// Modal multi-choice mode only has choices when the mode is active. Clear them.
if (this.mChoiceMode == AbsListView.CHOICE_MODE_MULTIPLE_MODAL) {
this.clearChoices();
this.setLongClickable(true);
}
}
}
/**
* Set a {@link MultiChoiceModeListener} that will manage the lifecycle of the
* selection {@link ActionMode}. Only used when the choice mode is set to
* {@link #CHOICE_MODE_MULTIPLE_MODAL}.
*
* @param listener Listener that will manage the selection mode
*
* @see #setChoiceMode(int)
*/
//setMultiChoiceModeListener(listener:AbsListView.MultiChoiceModeListener):void {
// if (this.mMultiChoiceModeCallback == null) {
// this.mMultiChoiceModeCallback = new AbsListView.MultiChoiceModeWrapper(this);
// }
// this.mMultiChoiceModeCallback.setWrapped(listener);
//}
/**
* @return true if all list content currently fits within the view boundaries
*/
private contentFits():boolean {
const childCount:number = this.getChildCount();
if (childCount == 0)
return true;
if (childCount != this.mItemCount)
return false;
return this.getChildAt(0).getTop() >= this.mListPadding.top && this.getChildAt(childCount - 1).getBottom() <= this.getHeight() - this.mListPadding.bottom;
}
/**
* Specifies whether fast scrolling is enabled or disabled.
* <p>
* When fast scrolling is enabled, the user can quickly scroll through lists
* by dragging the fast scroll thumb.
* <p>
* If the adapter backing this list implements {@link SectionIndexer}, the
* fast scroller will display section header previews as the user scrolls.
* Additionally, the user will be able to quickly jump between sections by
* tapping along the length of the scroll bar.
*
* @see SectionIndexer
* @see #isFastScrollEnabled()
* @param enabled true to enable fast scrolling, false otherwise
*/
setFastScrollEnabled(enabled:boolean):void {
if (this.mFastScrollEnabled != enabled) {
this.mFastScrollEnabled = enabled;
this.setFastScrollerEnabledUiThread(enabled);
}
}
private setFastScrollerEnabledUiThread(enabled:boolean):void {
//TODO when fastScroller impl
//if (this.mFastScroller != null) {
// this.mFastScroller.setEnabled(enabled);
//} else if (enabled) {
// this.mFastScroller = new FastScroller(this);
// this.mFastScroller.setEnabled(true);
//}
//this.resolvePadding();
//if (this.mFastScroller != null) {
// this.mFastScroller.updateLayout();
//}
}
/**
* Set whether or not the fast scroller should always be shown in place of
* the standard scroll bars. This will enable fast scrolling if it is not
* already enabled.
* <p>
* Fast scrollers shown in this way will not fade out and will be a
* permanent fixture within the list. This is best combined with an inset
* scroll bar style to ensure the scroll bar does not overlap content.
*
* @param alwaysShow true if the fast scroller should always be displayed,
* false otherwise
* @see #setScrollBarStyle(int)
* @see #setFastScrollEnabled(boolean)
*/
setFastScrollAlwaysVisible(alwaysShow:boolean):void {
if (this.mFastScrollAlwaysVisible != alwaysShow) {
if (alwaysShow && !this.mFastScrollEnabled) {
this.setFastScrollEnabled(true);
}
this.mFastScrollAlwaysVisible = alwaysShow;
this.setFastScrollerAlwaysVisibleUiThread(alwaysShow);
}
}
private setFastScrollerAlwaysVisibleUiThread(alwaysShow:boolean):void {
//TODO when fastScroller impl
//if (this.mFastScroller != null) {
// this.mFastScroller.setAlwaysShow(alwaysShow);
//}
}
/**
* @return whether the current thread is the one that created the view
*/
private isOwnerThread():boolean {
return true;//one thread is js
}
/**
* Returns true if the fast scroller is set to always show on this view.
*
* @return true if the fast scroller will always show
* @see #setFastScrollAlwaysVisible(boolean)
*/
isFastScrollAlwaysVisible():boolean {
//TODO when fastScroller impl
return false;
//if (this.mFastScroller == null) {
// return this.mFastScrollEnabled && this.mFastScrollAlwaysVisible;
//} else {
// return this.mFastScroller.isEnabled() && this.mFastScroller.isAlwaysShowEnabled();
//}
}
getVerticalScrollbarWidth():number {
//TODO when fastScroller impl
//if (this.mFastScroller != null && this.mFastScroller.isEnabled()) {
// return Math.max(super.getVerticalScrollbarWidth(), this.mFastScroller.getWidth());
//}
return super.getVerticalScrollbarWidth();
}
/**
* Returns true if the fast scroller is enabled.
*
* @see #setFastScrollEnabled(boolean)
* @return true if fast scroll is enabled, false otherwise
*/
isFastScrollEnabled():boolean {
//TODO when fastScroller impl
return false;
//if (this.mFastScroller == null) {
// return this.mFastScrollEnabled;
//} else {
// return this.mFastScroller.isEnabled();
//}
}
setVerticalScrollbarPosition(position:number):void {
super.setVerticalScrollbarPosition(position);
//TODO when fastScroller impl
//if (this.mFastScroller != null) {
// this.mFastScroller.setScrollbarPosition(position);
//}
}
setScrollBarStyle(style:number):void {
super.setScrollBarStyle(style);
//TODO when fastScroller impl
//if (this.mFastScroller != null) {
// this.mFastScroller.setScrollBarStyle(style);
//}
}
/**
* If fast scroll is enabled, then don't draw the vertical scrollbar.
* @hide
*/
isVerticalScrollBarHidden():boolean {
return this.isFastScrollEnabled();
}
/**
* When smooth scrollbar is enabled, the position and size of the scrollbar thumb
* is computed based on the number of visible pixels in the visible items. This
* however assumes that all list items have the same height. If you use a list in
* which items have different heights, the scrollbar will change appearance as the
* user scrolls through the list. To avoid this issue, you need to disable this
* property.
*
* When smooth scrollbar is disabled, the position and size of the scrollbar thumb
* is based solely on the number of items in the adapter and the position of the
* visible items inside the adapter. This provides a stable scrollbar as the user
* navigates through a list of items with varying heights.
*
* @param enabled Whether or not to enable smooth scrollbar.
*
* @see #setSmoothScrollbarEnabled(boolean)
* @attr ref android.R.styleable#AbsListView_smoothScrollbar
*/
setSmoothScrollbarEnabled(enabled:boolean):void {
this.mSmoothScrollbarEnabled = enabled;
}
/**
* Returns the current state of the fast scroll feature.
*
* @return True if smooth scrollbar is enabled is enabled, false otherwise.
*
* @see #setSmoothScrollbarEnabled(boolean)
*/
isSmoothScrollbarEnabled():boolean {
return this.mSmoothScrollbarEnabled;
}
/**
* Set the listener that will receive notifications every time the list scrolls.
*
* @param l the scroll listener
*/
setOnScrollListener(l:AbsListView.OnScrollListener):void {
this.mOnScrollListener = l;
this.invokeOnItemScrollListener();
}
/**
* Notify our scroll listener (if there is one) of a change in scroll state
*/
invokeOnItemScrollListener():void {
//TODO when fastScroller impl
//if (this.mFastScroller != null) {
// this.mFastScroller.onScroll(this.mFirstPosition, this.getChildCount(), this.mItemCount);
//}
if (this.mOnScrollListener != null) {
this.mOnScrollListener.onScroll(this, this.mFirstPosition, this.getChildCount(), this.mItemCount);
}
// dummy values, View's implementation does not use these.
this.onScrollChanged(0, 0, 0, 0);
}
//sendAccessibilityEvent(eventType:number):void {
// // events.
// if (eventType == AccessibilityEvent.TYPE_VIEW_SCROLLED) {
// const firstVisiblePosition:number = this.getFirstVisiblePosition();
// const lastVisiblePosition:number = this.getLastVisiblePosition();
// if (this.mLastAccessibilityScrollEventFromIndex == firstVisiblePosition && this.mLastAccessibilityScrollEventToIndex == lastVisiblePosition) {
// return;
// } else {
// this.mLastAccessibilityScrollEventFromIndex = firstVisiblePosition;
// this.mLastAccessibilityScrollEventToIndex = lastVisiblePosition;
// }
// }
// super.sendAccessibilityEvent(eventType);
//}
//
//onInitializeAccessibilityEvent(event:AccessibilityEvent):void {
// super.onInitializeAccessibilityEvent(event);
// event.setClassName(AbsListView.class.getName());
//}
//
//onInitializeAccessibilityNodeInfo(info:AccessibilityNodeInfo):void {
// super.onInitializeAccessibilityNodeInfo(info);
// info.setClassName(AbsListView.class.getName());
// if (this.isEnabled()) {
// if (this.getFirstVisiblePosition() > 0) {
// info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD);
// info.setScrollable(true);
// }
// if (this.getLastVisiblePosition() < this.getCount() - 1) {
// info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
// info.setScrollable(true);
// }
// }
//}
//
//performAccessibilityAction(action:number, arguments:Bundle):boolean {
// if (super.performAccessibilityAction(action, arguments)) {
// return true;
// }
// switch (action) {
// case AccessibilityNodeInfo.ACTION_SCROLL_FORWARD:
// {
// if (this.isEnabled() && this.getLastVisiblePosition() < this.getCount() - 1) {
// const viewportHeight:number = this.getHeight() - this.mListPadding.top - this.mListPadding.bottom;
// this.smoothScrollBy(viewportHeight, PositionScroller.SCROLL_DURATION);
// return true;
// }
// }
// return false;
// case AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD:
// {
// if (this.isEnabled() && mFirstPosition > 0) {
// const viewportHeight:number = this.getHeight() - this.mListPadding.top - this.mListPadding.bottom;
// this.smoothScrollBy(-viewportHeight, PositionScroller.SCROLL_DURATION);
// return true;
// }
// }
// return false;
// }
// return false;
//}
//
///** @hide */
//findViewByAccessibilityIdTraversal(accessibilityId:number):View {
// if (accessibilityId == this.getAccessibilityViewId()) {
// return this;
// }
// // so a service will be able to re-fetch the views.
// if (mDataChanged) {
// return null;
// }
// return super.findViewByAccessibilityIdTraversal(accessibilityId);
//}
/**
* Indicates whether the children's drawing cache is used during a scroll.
* By default, the drawing cache is enabled but this will consume more memory.
*
* @return true if the scrolling cache is enabled, false otherwise
*
* @see #setScrollingCacheEnabled(boolean)
* @see View#setDrawingCacheEnabled(boolean)
*/
isScrollingCacheEnabled():boolean {
return this.mScrollingCacheEnabled;
}
/**
* Enables or disables the children's drawing cache during a scroll.
* By default, the drawing cache is enabled but this will use more memory.
*
* When the scrolling cache is enabled, the caches are kept after the
* first scrolling. You can manually clear the cache by calling
* {@link android.view.ViewGroup#setChildrenDrawingCacheEnabled(boolean)}.
*
* @param enabled true to enable the scroll cache, false otherwise
*
* @see #isScrollingCacheEnabled()
* @see View#setDrawingCacheEnabled(boolean)
*/
setScrollingCacheEnabled(enabled:boolean):void {
if (this.mScrollingCacheEnabled && !enabled) {
this.clearScrollingCache();
}
this.mScrollingCacheEnabled = enabled;
}
/**
* Enables or disables the type filter window. If enabled, typing when
* this view has focus will filter the children to match the users input.
* Note that the {@link Adapter} used by this view must implement the
* {@link Filterable} interface.
*
* @param textFilterEnabled true to enable type filtering, false otherwise
*
* @see Filterable
*/
setTextFilterEnabled(textFilterEnabled:boolean):void {
this.mTextFilterEnabled = textFilterEnabled;
}
/**
* Indicates whether type filtering is enabled for this view
*
* @return true if type filtering is enabled, false otherwise
*
* @see #setTextFilterEnabled(boolean)
* @see Filterable
*/
isTextFilterEnabled():boolean {
return this.mTextFilterEnabled;
}
getFocusedRect(r:Rect):void {
let view:View = this.getSelectedView();
if (view != null && view.getParent() == this) {
// the focused rectangle of the selected view offset into the
// coordinate space of this view.
view.getFocusedRect(r);
this.offsetDescendantRectToMyCoords(view, r);
} else {
// otherwise, just the norm
super.getFocusedRect(r);
}
}
private useDefaultSelector():void {
this.setSelector(R.drawable.list_selector_background);
}
/**
* Indicates whether the content of this view is pinned to, or stacked from,
* the bottom edge.
*
* @return true if the content is stacked from the bottom edge, false otherwise
*/
isStackFromBottom():boolean {
return this.mStackFromBottom;
}
/**
* When stack from bottom is set to true, the list fills its content starting from
* the bottom of the view.
*
* @param stackFromBottom true to pin the view's content to the bottom edge,
* false to pin the view's content to the top edge
*/
setStackFromBottom(stackFromBottom:boolean):void {
if (this.mStackFromBottom != stackFromBottom) {
this.mStackFromBottom = stackFromBottom;
this.requestLayoutIfNecessary();
}
}
private requestLayoutIfNecessary():void {
if (this.getChildCount() > 0) {
this.resetList();
this.requestLayout();
this.invalidate();
}
}
//private acceptFilter():boolean {
// return this.mTextFilterEnabled && this.getAdapter() instanceof Filterable && (<Filterable> this.getAdapter()).getFilter() != null;
//}
//
///**
// * Sets the initial value for the text filter.
// * @param filterText The text to use for the filter.
// *
// * @see #setTextFilterEnabled
// */
//setFilterText(filterText:string):void {
// // Should we check for acceptFilter()?
// if (this.mTextFilterEnabled && !TextUtils.isEmpty(filterText)) {
// this.createTextFilter(false);
// // This is going to call our listener onTextChanged, but we might not
// // be ready to bring up a window yet
// this.mTextFilter.setText(filterText);
// this.mTextFilter.setSelection(filterText.length());
// if (this.mAdapter instanceof Filterable) {
// // if mPopup is non-null, then onTextChanged will do the filtering
// if (this.mPopup == null) {
// let f:Filter = (<Filterable> this.mAdapter).getFilter();
// f.filter(filterText);
// }
// // Set filtered to true so we will display the filter window when our main
// // window is ready
// this.mFiltered = true;
// this.mDataSetObserver.clearSavedState();
// }
// }
//}
//
///**
// * Returns the list's text filter, if available.
// * @return the list's text filter or null if filtering isn't enabled
// */
//getTextFilter():CharSequence {
// if (this.mTextFilterEnabled && this.mTextFilter != null) {
// return this.mTextFilter.getText();
// }
// return null;
//}
protected onFocusChanged(gainFocus:boolean, direction:number, previouslyFocusedRect:Rect):void {
super.onFocusChanged(gainFocus, direction, previouslyFocusedRect);
if (gainFocus && this.mSelectedPosition < 0 && !this.isInTouchMode()) {
if (!this.isAttachedToWindow() && this.mAdapter != null) {
// Data may have changed while we were detached and it's valid
// to change focus while detached. Refresh so we don't die.
this.mDataChanged = true;
this.mOldItemCount = this.mItemCount;
this.mItemCount = this.mAdapter.getCount();
}
this.resurrectSelection();
}
}
requestLayout():void {
if (!this.mBlockLayoutRequests && !this.mInLayout) {
super.requestLayout();
}
}
/**
* The list is empty. Clear everything out.
*/
resetList():void {
this.removeAllViewsInLayout();
this.mFirstPosition = 0;
this.mDataChanged = false;
this.mPositionScrollAfterLayout = null;
this.mNeedSync = false;
this.mPendingSync = null;
this.mOldSelectedPosition = AbsListView.INVALID_POSITION;
this.mOldSelectedRowId = AbsListView.INVALID_ROW_ID;
this.setSelectedPositionInt(AbsListView.INVALID_POSITION);
this.setNextSelectedPositionInt(AbsListView.INVALID_POSITION);
this.mSelectedTop = 0;
this.mSelectorPosition = AbsListView.INVALID_POSITION;
this.mSelectorRect.setEmpty();
this.invalidate();
}
protected computeVerticalScrollExtent():number {
const count:number = this.getChildCount();
if (count > 0) {
if (this.mSmoothScrollbarEnabled) {
let extent:number = count * 100;
let view:View = this.getChildAt(0);
const top:number = view.getTop();
let height:number = view.getHeight();
if (height > 0) {
extent += (top * 100) / height;
}
view = this.getChildAt(count - 1);
const bottom:number = view.getBottom();
height = view.getHeight();
if (height > 0) {
extent -= ((bottom - this.getHeight()) * 100) / height;
}
return extent;
} else {
return 1;
}
}
return 0;
}
protected computeVerticalScrollOffset():number {
const firstPosition:number = this.mFirstPosition;
const childCount:number = this.getChildCount();
if (firstPosition >= 0 && childCount > 0) {
if (this.mSmoothScrollbarEnabled) {
const view:View = this.getChildAt(0);
const top:number = view.getTop();
let height:number = view.getHeight();
if (height > 0) {
return Math.max(firstPosition * 100 - (top * 100) / height + Math.floor((<number> this.mScrollY / this.getHeight() * this.mItemCount * 100)), 0);
}
} else {
let index:number;
const count:number = this.mItemCount;
if (firstPosition == 0) {
index = 0;
} else if (firstPosition + childCount == count) {
index = count;
} else {
index = firstPosition + childCount / 2;
}
return Math.floor((firstPosition + childCount * (index / <number> count)));
}
}
return 0;
}
protected computeVerticalScrollRange():number {
let result:number;
if (this.mSmoothScrollbarEnabled) {
result = Math.max(this.mItemCount * 100, 0);
if (this.mScrollY != 0) {
// Compensate for overscroll
result += Math.abs(Math.floor((<number> this.mScrollY / this.getHeight() * this.mItemCount * 100)));
}
} else {
result = this.mItemCount;
}
return result;
}
protected getTopFadingEdgeStrength():number {
const count:number = this.getChildCount();
const fadeEdge:number = super.getTopFadingEdgeStrength();
if (count == 0) {
return fadeEdge;
} else {
if (this.mFirstPosition > 0) {
return 1.0;
}
const top:number = this.getChildAt(0).getTop();
const fadeLength:number = this.getVerticalFadingEdgeLength();
return top < this.mPaddingTop ? -(top - this.mPaddingTop) / fadeLength : fadeEdge;
}
}
protected getBottomFadingEdgeStrength():number {
const count:number = this.getChildCount();
const fadeEdge:number = super.getBottomFadingEdgeStrength();
if (count == 0) {
return fadeEdge;
} else {
if (this.mFirstPosition + count - 1 < this.mItemCount - 1) {
return 1.0;
}
const bottom:number = this.getChildAt(count - 1).getBottom();
const height:number = this.getHeight();
const fadeLength:number = this.getVerticalFadingEdgeLength();
return bottom > height - this.mPaddingBottom ? (bottom - height + this.mPaddingBottom) / fadeLength : fadeEdge;
}
}
protected onMeasure(widthMeasureSpec:number, heightMeasureSpec:number):void {
if (this.mSelector == null) {
this.useDefaultSelector();
}
const listPadding:Rect = this.mListPadding;
listPadding.left = this.mSelectionLeftPadding + this.mPaddingLeft;
listPadding.top = this.mSelectionTopPadding + this.mPaddingTop;
listPadding.right = this.mSelectionRightPadding + this.mPaddingRight;
listPadding.bottom = this.mSelectionBottomPadding + this.mPaddingBottom;
// Check if our previous measured size was at a point where we should scroll later.
if (this.mTranscriptMode == AbsListView.TRANSCRIPT_MODE_NORMAL) {
const childCount:number = this.getChildCount();
const listBottom:number = this.getHeight() - this.getPaddingBottom();
const lastChild:View = this.getChildAt(childCount - 1);
const lastBottom:number = lastChild != null ? lastChild.getBottom() : listBottom;
this.mForceTranscriptScroll = this.mFirstPosition + childCount >= this.mLastHandledItemCount && lastBottom <= listBottom;
}
}
/**
* Subclasses should NOT override this method but
* {@link #layoutChildren()} instead.
*/
protected onLayout(changed:boolean, l:number, t:number, r:number, b:number):void {
super.onLayout(changed, l, t, r, b);
this.mInLayout = true;
if (changed) {
let childCount:number = this.getChildCount();
for (let i:number = 0; i < childCount; i++) {
this.getChildAt(i).forceLayout();
}
this.mRecycler.markChildrenDirty();
}
//TODO when fastScroller impl
//if (this.mFastScroller != null && (mItemCount != mOldItemCount || mDataChanged)) {
// this.mFastScroller.onItemCountChanged(mItemCount);
//}
this.layoutChildren();
this.mInLayout = false;
this.mOverscrollMax = (b - t) / AbsListView.OVERSCROLL_LIMIT_DIVISOR;
}
/**
* @hide
*/
protected setFrame(left:number, top:number, right:number, bottom:number):boolean {
const changed:boolean = super.setFrame(left, top, right, bottom);
if (changed) {
// Reposition the popup when the frame has changed. This includes
// translating the widget, not just changing its dimension. The
// filter popup needs to follow the widget.
const visible:boolean = this.getWindowVisibility() == View.VISIBLE;
//if (this.mFiltered && visible && this.mPopup != null && this.mPopup.isShowing()) {
// this.positionPopup();
//}
}
return changed;
}
/**
* Subclasses must override this method to layout their children.
*/
protected layoutChildren():void {
}
updateScrollIndicators():void {
if (this.mScrollUp != null) {
let canScrollUp:boolean;
// 0th element is not visible
canScrollUp = this.mFirstPosition > 0;
// ... Or top of 0th element is not visible
if (!canScrollUp) {
if (this.getChildCount() > 0) {
let child:View = this.getChildAt(0);
canScrollUp = child.getTop() < this.mListPadding.top;
}
}
this.mScrollUp.setVisibility(canScrollUp ? View.VISIBLE : View.INVISIBLE);
}
if (this.mScrollDown != null) {
let canScrollDown:boolean;
let count:number = this.getChildCount();
// Last item is not visible
canScrollDown = (this.mFirstPosition + count) < this.mItemCount;
// ... Or bottom of the last element is not visible
if (!canScrollDown && count > 0) {
let child:View = this.getChildAt(count - 1);
canScrollDown = child.getBottom() > this.mBottom - this.mListPadding.bottom;
}
this.mScrollDown.setVisibility(canScrollDown ? View.VISIBLE : View.INVISIBLE);
}
}
getSelectedView():View {
if (this.mItemCount > 0 && this.mSelectedPosition >= 0) {
return this.getChildAt(this.mSelectedPosition - this.mFirstPosition);
} else {
return null;
}
}
/**
* List padding is the maximum of the normal view's padding and the padding of the selector.
*
* @see android.view.View#getPaddingTop()
* @see #getSelector()
*
* @return The top list padding.
*/
getListPaddingTop():number {
return this.mListPadding.top;
}
/**
* List padding is the maximum of the normal view's padding and the padding of the selector.
*
* @see android.view.View#getPaddingBottom()
* @see #getSelector()
*
* @return The bottom list padding.
*/
getListPaddingBottom():number {
return this.mListPadding.bottom;
}
/**
* List padding is the maximum of the normal view's padding and the padding of the selector.
*
* @see android.view.View#getPaddingLeft()
* @see #getSelector()
*
* @return The left list padding.
*/
getListPaddingLeft():number {
return this.mListPadding.left;
}
/**
* List padding is the maximum of the normal view's padding and the padding of the selector.
*
* @see android.view.View#getPaddingRight()
* @see #getSelector()
*
* @return The right list padding.
*/
getListPaddingRight():number {
return this.mListPadding.right;
}
/**
* Get a view and have it show the data associated with the specified
* position. This is called when we have already discovered that the view is
* not available for reuse in the recycle bin. The only choices left are
* converting an old view or making a new one.
*
* @param position The position to display
* @param isScrap Array of at least 1 boolean, the first entry will become true if
* the returned view was taken from the scrap heap, false if otherwise.
*
* @return A view displaying the data associated with the specified position
*/
obtainView(position:number, isScrap:boolean[]):View {
//Trace.traceBegin(Trace.TRACE_TAG_VIEW, "obtainView");
isScrap[0] = false;
let scrapView:View;
scrapView = this.mRecycler.getTransientStateView(position);
if (scrapView == null) {
scrapView = this.mRecycler.getScrapView(position);
}
let child:View;
if (scrapView != null) {
child = this.mAdapter.getView(position, scrapView, this);
//if (child.getImportantForAccessibility() == AbsListView.IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
// child.setImportantForAccessibility(AbsListView.IMPORTANT_FOR_ACCESSIBILITY_YES);
//}
if (child != scrapView) {
this.mRecycler.addScrapView(scrapView, position);
if (this.mCacheColorHint != 0) {
child.setDrawingCacheBackgroundColor(this.mCacheColorHint);
}
} else {
isScrap[0] = true;
// recycle this view and bind it to different data.
//if (child.isAccessibilityFocused()) {
// child.clearAccessibilityFocus();
//}
child.dispatchFinishTemporaryDetach();
}
} else {
child = this.mAdapter.getView(position, null, this);
//if (child.getImportantForAccessibility() == AbsListView.IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
// child.setImportantForAccessibility(AbsListView.IMPORTANT_FOR_ACCESSIBILITY_YES);
//}
if (this.mCacheColorHint != 0) {
child.setDrawingCacheBackgroundColor(this.mCacheColorHint);
}
}
if (this.mAdapterHasStableIds) {
const vlp:ViewGroup.LayoutParams = child.getLayoutParams();
let lp:AbsListView.LayoutParams;
if (vlp == null) {
lp = <AbsListView.LayoutParams> this.generateDefaultLayoutParams();
} else if (!this.checkLayoutParams(vlp)) {
lp = <AbsListView.LayoutParams> this.generateLayoutParams(vlp);
} else {
lp = <AbsListView.LayoutParams> vlp;
}
lp.itemId = this.mAdapter.getItemId(position);
child.setLayoutParams(lp);
}
//if (AccessibilityManager.getInstance(this.mContext).isEnabled()) {
// if (this.mAccessibilityDelegate == null) {
// this.mAccessibilityDelegate = new AbsListView.ListItemAccessibilityDelegate(this);
// }
// if (child.getAccessibilityDelegate() == null) {
// child.setAccessibilityDelegate(this.mAccessibilityDelegate);
// }
//}
//Trace.traceEnd(Trace.TRACE_TAG_VIEW);
return child;
}
/**
* Initializes an {@link AccessibilityNodeInfo} with information about a
* particular item in the list.
*
* @param view View representing the list item.
* @param position Position of the list item within the adapter.
* @param info Node info to populate.
*/
//onInitializeAccessibilityNodeInfoForItem(view:View, position:number, info:AccessibilityNodeInfo):void {
// const adapter:ListAdapter = this.getAdapter();
// if (position == AbsListView.INVALID_POSITION || adapter == null) {
// // The item doesn't exist, so there's not much we can do here.
// return;
// }
// if (!this.isEnabled() || !adapter.isEnabled(position)) {
// info.setEnabled(false);
// return;
// }
// if (position == this.getSelectedItemPosition()) {
// info.setSelected(true);
// info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
// } else {
// info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
// }
// if (this.isClickable()) {
// info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
// info.setClickable(true);
// }
// if (this.isLongClickable()) {
// info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
// info.setLongClickable(true);
// }
//}
positionSelector(l:number, t:number, r:number, b:number):void;
positionSelector(position:number, sel:View):void;
positionSelector(...args):void {
if(args.length===4){
let [l, t, r, b] = args;
this.mSelectorRect.set(l - this.mSelectionLeftPadding, t - this.mSelectionTopPadding,
r + this.mSelectionRightPadding, b + this.mSelectionBottomPadding);
}else {
let position:number = args[0];
let sel:View = args[1];
if (position != AbsListView.INVALID_POSITION) {
this.mSelectorPosition = position;
}
const selectorRect:Rect = this.mSelectorRect;
selectorRect.set(sel.getLeft(), sel.getTop(), sel.getRight(), sel.getBottom());
if (sel['adjustListItemSelectionBounds']) {
(<AbsListView.SelectionBoundsAdjuster><any>sel).adjustListItemSelectionBounds(selectorRect);
}
this.positionSelector(selectorRect.left, selectorRect.top, selectorRect.right, selectorRect.bottom);
const isChildViewEnabled:boolean = this.mIsChildViewEnabled;
if (sel.isEnabled() != isChildViewEnabled) {
this.mIsChildViewEnabled = !isChildViewEnabled;
if (this.getSelectedItemPosition() != AbsListView.INVALID_POSITION) {
this.refreshDrawableState();
}
}
}
}
protected dispatchDraw(canvas:Canvas):void {
let saveCount:number = 0;
const clipToPadding:boolean = (this.mGroupFlags & AbsListView.CLIP_TO_PADDING_MASK) == AbsListView.CLIP_TO_PADDING_MASK;
if (clipToPadding) {
saveCount = canvas.save();
const scrollX:number = this.mScrollX;
const scrollY:number = this.mScrollY;
canvas.clipRect(scrollX + this.mPaddingLeft, scrollY + this.mPaddingTop, scrollX + this.mRight - this.mLeft - this.mPaddingRight, scrollY + this.mBottom - this.mTop - this.mPaddingBottom);
this.mGroupFlags &= ~AbsListView.CLIP_TO_PADDING_MASK;
}
const drawSelectorOnTop:boolean = this.mDrawSelectorOnTop;
if (!drawSelectorOnTop) {
this.drawSelector(canvas);
}
super.dispatchDraw(canvas);
if (drawSelectorOnTop) {
this.drawSelector(canvas);
}
if (clipToPadding) {
canvas.restoreToCount(saveCount);
this.mGroupFlags |= AbsListView.CLIP_TO_PADDING_MASK;
}
}
isPaddingOffsetRequired():boolean {
return (this.mGroupFlags & AbsListView.CLIP_TO_PADDING_MASK) != AbsListView.CLIP_TO_PADDING_MASK;
}
getLeftPaddingOffset():number {
return (this.mGroupFlags & AbsListView.CLIP_TO_PADDING_MASK) == AbsListView.CLIP_TO_PADDING_MASK ? 0 : -this.mPaddingLeft;
}
getTopPaddingOffset():number {
return (this.mGroupFlags & AbsListView.CLIP_TO_PADDING_MASK) == AbsListView.CLIP_TO_PADDING_MASK ? 0 : -this.mPaddingTop;
}
getRightPaddingOffset():number {
return (this.mGroupFlags & AbsListView.CLIP_TO_PADDING_MASK) == AbsListView.CLIP_TO_PADDING_MASK ? 0 : this.mPaddingRight;
}
getBottomPaddingOffset():number {
return (this.mGroupFlags & AbsListView.CLIP_TO_PADDING_MASK) == AbsListView.CLIP_TO_PADDING_MASK ? 0 : this.mPaddingBottom;
}
protected onSizeChanged(w:number, h:number, oldw:number, oldh:number):void {
if (this.getChildCount() > 0) {
this.mDataChanged = true;
this.rememberSyncState();
}
//TODO when fast scroller impl
//if (this.mFastScroller != null) {
// this.mFastScroller.onSizeChanged(w, h, oldw, oldh);
//}
}
/**
* @return True if the current touch mode requires that we draw the selector in the pressed
* state.
*/
touchModeDrawsInPressedState():boolean {
// FIXME use isPressed for this
switch (this.mTouchMode) {
case AbsListView.TOUCH_MODE_TAP:
case AbsListView.TOUCH_MODE_DONE_WAITING:
return true;
default:
return false;
}
}
/**
* Indicates whether this view is in a state where the selector should be drawn. This will
* happen if we have focus but are not in touch mode, or we are in the middle of displaying
* the pressed state for an item.
*
* @return True if the selector should be shown
*/
shouldShowSelector():boolean {
return (!this.isInTouchMode()) || (this.touchModeDrawsInPressedState() && this.isPressed());
}
private drawSelector(canvas:Canvas):void {
if (!this.mSelectorRect.isEmpty()) {
const selector:Drawable = this.mSelector;
selector.setBounds(this.mSelectorRect);
selector.draw(canvas);
}
}
/**
* Controls whether the selection highlight drawable should be drawn on top of the item or
* behind it.
*
* @param onTop If true, the selector will be drawn on the item it is highlighting. The default
* is false.
*
* @attr ref android.R.styleable#AbsListView_drawSelectorOnTop
*/
setDrawSelectorOnTop(onTop:boolean):void {
this.mDrawSelectorOnTop = onTop;
}
/**
* Set a Drawable that should be used to highlight the currently selected item.
*
* @param resID A Drawable resource to use as the selection highlight.
*
* @attr ref android.R.styleable#AbsListView_listSelector
*/
//setSelector(resID:number):void {
// this.setSelector(this.getResources().getDrawable(resID));
//}
setSelector(sel:Drawable):void {
if (this.mSelector != null) {
this.mSelector.setCallback(null);
this.unscheduleDrawable(this.mSelector);
}
this.mSelector = sel;
let padding:Rect = new Rect();
sel.getPadding(padding);
this.mSelectionLeftPadding = padding.left;
this.mSelectionTopPadding = padding.top;
this.mSelectionRightPadding = padding.right;
this.mSelectionBottomPadding = padding.bottom;
sel.setCallback(this);
this.updateSelectorState();
}
/**
* Returns the selector {@link android.graphics.drawable.Drawable} that is used to draw the
* selection in the list.
*
* @return the drawable used to display the selector
*/
getSelector():Drawable {
return this.mSelector;
}
/**
* Sets the selector state to "pressed" and posts a CheckForKeyLongPress to see if
* this is a long press.
*/
keyPressed():void {
if (!this.isEnabled() || !this.isClickable()) {
return;
}
let selector:Drawable = this.mSelector;
let selectorRect:Rect = this.mSelectorRect;
if (selector != null && (this.isFocused() || this.touchModeDrawsInPressedState()) && !selectorRect.isEmpty()) {
const v:View = this.getChildAt(this.mSelectedPosition - this.mFirstPosition);
if (v != null) {
if (v.hasFocusable())
return;
v.setPressed(true);
}
this.setPressed(true);
const longClickable:boolean = this.isLongClickable();
let d:Drawable = selector.getCurrent();
//TODO when transition ok
//if (d != null && d instanceof TransitionDrawable) {
// if (longClickable) {
// (<TransitionDrawable> d).startTransition(ViewConfiguration.getLongPressTimeout());
// } else {
// (<TransitionDrawable> d).resetTransition();
// }
//}
if (longClickable && !this.mDataChanged) {
if (this.mPendingCheckForKeyLongPress == null) {
this.mPendingCheckForKeyLongPress = new AbsListView.CheckForKeyLongPress(this);
}
this.mPendingCheckForKeyLongPress.rememberWindowAttachCount();
this.postDelayed(this.mPendingCheckForKeyLongPress, ViewConfiguration.getLongPressTimeout());
}
}
}
setScrollIndicators(up:View, down:View):void {
this.mScrollUp = up;
this.mScrollDown = down;
}
private updateSelectorState():void {
if (this.mSelector != null) {
if (this.shouldShowSelector()) {
this.mSelector.setState(this.getDrawableState());
} else {
this.mSelector.setState(StateSet.NOTHING);
}
}
}
protected drawableStateChanged():void {
super.drawableStateChanged();
this.updateSelectorState();
}
protected onCreateDrawableState(extraSpace:number):number[] {
// If the child view is enabled then do the default behavior.
if (this.mIsChildViewEnabled) {
// Common case
return super.onCreateDrawableState(extraSpace);
}
// The selector uses this View's drawable state. The selected child view
// is disabled, so we need to remove the enabled state from the drawable
// states.
const enabledState:number = AbsListView.ENABLED_STATE_SET[0];
// If we don't have any extra space, it will return one of the static state arrays,
// and clearing the enabled state on those arrays is a bad thing! If we specify
// we need extra space, it will create+copy into a new array that safely mutable.
let state:number[] = super.onCreateDrawableState(extraSpace + 1);
let enabledPos:number = -1;
for (let i:number = state.length - 1; i >= 0; i--) {
if (state[i] == enabledState) {
enabledPos = i;
break;
}
}
// Remove the enabled state
if (enabledPos >= 0) {
System.arraycopy(state, enabledPos + 1, state, enabledPos, state.length - enabledPos - 1);
}
return state;
}
protected verifyDrawable(dr:Drawable):boolean {
return this.mSelector == dr || super.verifyDrawable(dr);
}
jumpDrawablesToCurrentState():void {
super.jumpDrawablesToCurrentState();
if (this.mSelector != null)
this.mSelector.jumpToCurrentState();
}
protected onAttachedToWindow():void {
super.onAttachedToWindow();
const treeObserver:ViewTreeObserver = this.getViewTreeObserver();
treeObserver.addOnTouchModeChangeListener(this);
//if (this.mTextFilterEnabled && this.mPopup != null && !this.mGlobalLayoutListenerAddedFilter) {
// treeObserver.addOnGlobalLayoutListener(this);
//}
if (this.mAdapter != null && this.mDataSetObserver == null) {
this.mDataSetObserver = new AbsListView.AdapterDataSetObserver(this);
this.mAdapter.registerDataSetObserver(this.mDataSetObserver);
// Data may have changed while we were detached. Refresh.
this.mDataChanged = true;
this.mOldItemCount = this.mItemCount;
this.mItemCount = this.mAdapter.getCount();
}
}
protected onDetachedFromWindow():void {
super.onDetachedFromWindow();
// Dismiss the popup in case onSaveInstanceState() was not invoked
this.dismissPopup();
// Detach any view left in the scrap heap
this.mRecycler.clear();
const treeObserver:ViewTreeObserver = this.getViewTreeObserver();
treeObserver.removeOnTouchModeChangeListener(this);
//if (this.mTextFilterEnabled && this.mPopup != null) {
// treeObserver.removeOnGlobalLayoutListener(this);
// this.mGlobalLayoutListenerAddedFilter = false;
//}
if (this.mAdapter != null && this.mDataSetObserver != null) {
this.mAdapter.unregisterDataSetObserver(this.mDataSetObserver);
this.mDataSetObserver = null;
}
//if (this.mScrollStrictSpan != null) {
// this.mScrollStrictSpan.finish();
// this.mScrollStrictSpan = null;
//}
//if (this.mFlingStrictSpan != null) {
// this.mFlingStrictSpan.finish();
// this.mFlingStrictSpan = null;
//}
if (this.mFlingRunnable != null) {
this.removeCallbacks(this.mFlingRunnable);
}
if (this.mPositionScroller != null) {
this.mPositionScroller.stop();
}
if (this.mClearScrollingCache != null) {
this.removeCallbacks(this.mClearScrollingCache);
}
if (this.mPerformClick_ != null) {
this.removeCallbacks(this.mPerformClick_);
}
if (this.mTouchModeReset != null) {
this.removeCallbacks(this.mTouchModeReset);
this.mTouchModeReset.run();
}
}
onWindowFocusChanged(hasWindowFocus:boolean):void {
super.onWindowFocusChanged(hasWindowFocus);
const touchMode:number = this.isInTouchMode() ? AbsListView.TOUCH_MODE_ON : AbsListView.TOUCH_MODE_OFF;
if (!hasWindowFocus) {
this.setChildrenDrawingCacheEnabled(false);
if (this.mFlingRunnable != null) {
this.removeCallbacks(this.mFlingRunnable);
// let the fling runnable report it's new state which
// should be idle
this.mFlingRunnable.endFling();
if (this.mPositionScroller != null) {
this.mPositionScroller.stop();
}
if (this.mScrollY != 0) {
this.mScrollY = 0;
this.invalidateParentCaches();
this.finishGlows();
this.invalidate();
}
}
// Always hide the type filter
this.dismissPopup();
if (touchMode == AbsListView.TOUCH_MODE_OFF) {
// Remember the last selected element
this.mResurrectToPosition = this.mSelectedPosition;
}
} else {
if (this.mFiltered && !this.mPopupHidden) {
// Show the type filter only if a filter is in effect
this.showPopup();
}
// If we changed touch mode since the last time we had focus
if (touchMode != this.mLastTouchMode && this.mLastTouchMode != AbsListView.TOUCH_MODE_UNKNOWN) {
// If we come back in trackball mode, we bring the selection back
if (touchMode == AbsListView.TOUCH_MODE_OFF) {
// This will trigger a layout
this.resurrectSelection();
// If we come back in touch mode, then we want to hide the selector
} else {
this.hideSelector();
this.mLayoutMode = AbsListView.LAYOUT_NORMAL;
this.layoutChildren();
}
}
}
this.mLastTouchMode = touchMode;
}
//onRtlPropertiesChanged(layoutDirection:number):void {
// super.onRtlPropertiesChanged(layoutDirection);
// if (this.mFastScroller != null) {
// this.mFastScroller.setScrollbarPosition(this.getVerticalScrollbarPosition());
// }
//}
/**
* Creates the ContextMenuInfo returned from {@link #getContextMenuInfo()}. This
* methods knows the view, position and ID of the item that received the
* long press.
*
* @param view The view that received the long press.
* @param position The position of the item that received the long press.
* @param id The ID of the item that received the long press.
* @return The extra information that should be returned by
* {@link #getContextMenuInfo()}.
*/
//private createContextMenuInfo(view:View, position:number, id:number):ContextMenuInfo {
// return new AdapterContextMenuInfo(view, position, id);
//}
onCancelPendingInputEvents():void {
super.onCancelPendingInputEvents();
if (this.mPerformClick_ != null) {
this.removeCallbacks(this.mPerformClick_);
}
if (this.mPendingCheckForTap_ != null) {
this.removeCallbacks(this.mPendingCheckForTap_);
}
if (this.mPendingCheckForLongPress_List != null) {
this.removeCallbacks(this.mPendingCheckForLongPress_List);
}
if (this.mPendingCheckForKeyLongPress != null) {
this.removeCallbacks(this.mPendingCheckForKeyLongPress);
}
}
private performLongPress(child:View, longPressPosition:number, longPressId:number):boolean {
// CHOICE_MODE_MULTIPLE_MODAL takes over long press.
//if (this.mChoiceMode == AbsListView.CHOICE_MODE_MULTIPLE_MODAL) {
// if (this.mChoiceActionMode == null && (this.mChoiceActionMode = this.startActionMode(this.mMultiChoiceModeCallback)) != null) {
// this.setItemChecked(longPressPosition, true);
// this.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
// }
// return true;
//}
let handled:boolean = false;
if (this.mOnItemLongClickListener != null) {
handled = this.mOnItemLongClickListener.onItemLongClick(<any>this, child, longPressPosition, longPressId);
}
//if (!handled) {
// this.mContextMenuInfo = this.createContextMenuInfo(child, longPressPosition, longPressId);
// handled = super.showContextMenuForChild(AbsListView.this);
//}
if (handled) {
this.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
}
return handled;
}
//getContextMenuInfo():ContextMenuInfo {
// return this.mContextMenuInfo;
//}
//
///** @hide */
//showContextMenu(x:number, y:number, metaState:number):boolean {
// const position:number = this.pointToPosition(Math.floor(x), Math.floor(y));
// if (position != AbsListView.INVALID_POSITION) {
// const id:number = this.mAdapter.getItemId(position);
// let child:View = this.getChildAt(position - mFirstPosition);
// if (child != null) {
// this.mContextMenuInfo = this.createContextMenuInfo(child, position, id);
// return super.showContextMenuForChild(AbsListView.this);
// }
// }
// return super.showContextMenu(x, y, metaState);
//}
//
//showContextMenuForChild(originalView:View):boolean {
// const longPressPosition:number = this.getPositionForView(originalView);
// if (longPressPosition >= 0) {
// const longPressId:number = this.mAdapter.getItemId(longPressPosition);
// let handled:boolean = false;
// if (mOnItemLongClickListener != null) {
// handled = mOnItemLongClickListener.onItemLongClick(AbsListView.this, originalView, longPressPosition, longPressId);
// }
// if (!handled) {
// this.mContextMenuInfo = this.createContextMenuInfo(this.getChildAt(longPressPosition - mFirstPosition), longPressPosition, longPressId);
// handled = super.showContextMenuForChild(originalView);
// }
// return handled;
// }
// return false;
//}
onKeyDown(keyCode:number, event:KeyEvent):boolean {
return false;
}
onKeyUp(keyCode:number, event:KeyEvent):boolean {
if (KeyEvent.isConfirmKey(keyCode)) {
if (!this.isEnabled()) {
return true;
}
if (this.isClickable() && this.isPressed() && this.mSelectedPosition >= 0
&& this.mAdapter != null && this.mSelectedPosition < this.mAdapter.getCount()) {
const view:View = this.getChildAt(this.mSelectedPosition - this.mFirstPosition);
if (view != null) {
this.performItemClick(view, this.mSelectedPosition, this.mSelectedRowId);
view.setPressed(false);
}
this.setPressed(false);
return true;
}
}
return super.onKeyUp(keyCode, event);
}
dispatchSetPressed(pressed:boolean):void {
// Don't dispatch setPressed to our children. We call setPressed on ourselves to
// get the selector in the right state, but we don't want to press each child.
}
/**
* Maps a point to a position in the list.
*
* @param x X in local coordinate
* @param y Y in local coordinate
* @return The position of the item which contains the specified point, or
* {@link #INVALID_POSITION} if the point does not intersect an item.
*/
pointToPosition(x:number, y:number):number {
let frame:Rect = this.mTouchFrame;
if (frame == null) {
this.mTouchFrame = new Rect();
frame = this.mTouchFrame;
}
const count:number = this.getChildCount();
for (let i:number = count - 1; i >= 0; i--) {
const child:View = this.getChildAt(i);
if (child.getVisibility() == View.VISIBLE) {
child.getHitRect(frame);
if (frame.contains(x, y)) {
return this.mFirstPosition + i;
}
}
}
return AbsListView.INVALID_POSITION;
}
/**
* Maps a point to a the rowId of the item which intersects that point.
*
* @param x X in local coordinate
* @param y Y in local coordinate
* @return The rowId of the item which contains the specified point, or {@link #INVALID_ROW_ID}
* if the point does not intersect an item.
*/
pointToRowId(x:number, y:number):number {
let position:number = this.pointToPosition(x, y);
if (position >= 0) {
return this.mAdapter.getItemId(position);
}
return AbsListView.INVALID_ROW_ID;
}
protected checkOverScrollStartScrollIfNeeded():boolean {
return this.mScrollY != 0;
}
private startScrollIfNeeded(y:number):boolean {
// Check if we have moved far enough that it looks more like a
// scroll than a tap
const deltaY:number = y - this.mMotionY;
const distance:number = Math.abs(deltaY);
const overscroll:boolean = this.checkOverScrollStartScrollIfNeeded();
if (overscroll || distance > this.mTouchSlop) {
this.createScrollingCache();
if (this.mScrollY != 0) {
this.mTouchMode = AbsListView.TOUCH_MODE_OVERSCROLL;
this.mMotionCorrection = 0;
} else {
this.mTouchMode = AbsListView.TOUCH_MODE_SCROLL;
this.mMotionCorrection = deltaY > 0 ? this.mTouchSlop : -this.mTouchSlop;
}
this.removeCallbacks(this.mPendingCheckForLongPress_List);
this.setPressed(false);
const motionView:View = this.getChildAt(this.mMotionPosition - this.mFirstPosition);
if (motionView != null) {
motionView.setPressed(false);
}
this.reportScrollStateChange(AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL);
// Time to start stealing events! Once we've stolen them, don't let anyone
// steal from us
const parent:ViewParent = this.getParent();
if (parent != null) {
parent.requestDisallowInterceptTouchEvent(true);
}
this.scrollIfNeeded(y);
return true;
}
return false;
}
private scrollIfNeeded(y:number):void {
const rawDeltaY:number = y - this.mMotionY;
const deltaY:number = rawDeltaY - this.mMotionCorrection;
let incrementalDeltaY:number = this.mLastY != Integer.MIN_VALUE ? y - this.mLastY : deltaY;
if (this.mTouchMode == AbsListView.TOUCH_MODE_SCROLL) {
if (AbsListView.PROFILE_SCROLLING) {
if (!this.mScrollProfilingStarted) {
//Debug.startMethodTracing("AbsListViewScroll");
this.mScrollProfilingStarted = true;
}
}
//if (this.mScrollStrictSpan == null) {
// // If it's non-null, we're already in a scroll.
// this.mScrollStrictSpan = StrictMode.enterCriticalSpan("AbsListView-scroll");
//}
if (y != this.mLastY) {
// Make sure that we do so in case we're in a parent that can intercept.
if ((this.mGroupFlags & AbsListView.FLAG_DISALLOW_INTERCEPT) == 0 && Math.abs(rawDeltaY) > this.mTouchSlop) {
const parent:ViewParent = this.getParent();
if (parent != null) {
parent.requestDisallowInterceptTouchEvent(true);
}
}
let motionIndex:number;
if (this.mMotionPosition >= 0) {
motionIndex = this.mMotionPosition - this.mFirstPosition;
} else {
// If we don't have a motion position that we can reliably track,
// pick something in the middle to make a best guess at things below.
motionIndex = this.getChildCount() / 2;
}
let motionViewPrevTop:number = 0;
let motionView:View = this.getChildAt(motionIndex);
if (motionView != null) {
motionViewPrevTop = motionView.getTop();
}
// No need to do all this work if we're not going to move anyway
let atEdge:boolean = false;
if (incrementalDeltaY != 0) {
atEdge = this.trackMotionScroll(deltaY, incrementalDeltaY);
}
// Check to see if we have bumped into the scroll limit
motionView = this.getChildAt(motionIndex);
if (motionView != null) {
// Check if the top of the motion view is where it is
// supposed to be
const motionViewRealTop:number = motionView.getTop();
if (atEdge) {
// Apply overscroll
let overscroll:number = -incrementalDeltaY - (motionViewRealTop - motionViewPrevTop);
this.overScrollBy(0, overscroll, 0, this.mScrollY, 0, 0, 0, this.mOverscrollDistance, true);
if (Math.abs(this.mOverscrollDistance) == Math.abs(this.mScrollY)) {
// Don't allow overfling if we're at the edge.
if (this.mVelocityTracker != null) {
this.mVelocityTracker.clear();
}
}
const overscrollMode:number = this.getOverScrollMode();
if (overscrollMode == AbsListView.OVER_SCROLL_ALWAYS || (overscrollMode == AbsListView.OVER_SCROLL_IF_CONTENT_SCROLLS && !this.contentFits())) {
// Reset when entering overscroll.
this.mDirection = 0;
this.mTouchMode = AbsListView.TOUCH_MODE_OVERSCROLL;
if (rawDeltaY > 0) {
//this.mEdgeGlowTop.onPull(<number> overscroll / this.getHeight());
//if (!this.mEdgeGlowBottom.isFinished()) {
// this.mEdgeGlowBottom.onRelease();
//}
//this.invalidate(this.mEdgeGlowTop.getBounds(false));
} else if (rawDeltaY < 0) {
//this.mEdgeGlowBottom.onPull(<number> overscroll / this.getHeight());
//if (!this.mEdgeGlowTop.isFinished()) {
// this.mEdgeGlowTop.onRelease();
//}
//this.invalidate(this.mEdgeGlowBottom.getBounds(true));
}
}
}
this.mMotionY = y;
}
this.mLastY = y;
}
} else if (this.mTouchMode == AbsListView.TOUCH_MODE_OVERSCROLL) {
if (y != this.mLastY) {
const oldScroll:number = this.mScrollY;
const newScroll:number = oldScroll - incrementalDeltaY;
let newDirection:number = y > this.mLastY ? 1 : -1;
if (this.mDirection == 0) {
this.mDirection = newDirection;
}
let overScrollDistance:number = -incrementalDeltaY;
if ((newScroll < 0 && oldScroll >= 0) || (newScroll > 0 && oldScroll <= 0)) {
overScrollDistance = -oldScroll;
incrementalDeltaY += overScrollDistance;
} else {
incrementalDeltaY = 0;
}
if (overScrollDistance != 0) {
this.overScrollBy(0, overScrollDistance, 0, this.mScrollY, 0, 0, 0, this.mOverscrollDistance, true);
//const overscrollMode:number = this.getOverScrollMode();
//if (overscrollMode == AbsListView.OVER_SCROLL_ALWAYS || (overscrollMode == AbsListView.OVER_SCROLL_IF_CONTENT_SCROLLS && !this.contentFits())) {
// if (rawDeltaY > 0) {
//this.mEdgeGlowTop.onPull(<number> overScrollDistance / this.getHeight());
//if (!this.mEdgeGlowBottom.isFinished()) {
// this.mEdgeGlowBottom.onRelease();
//}
//this.invalidate(this.mEdgeGlowTop.getBounds(false));
//} else if (rawDeltaY < 0) {
//this.mEdgeGlowBottom.onPull(<number> overScrollDistance / this.getHeight());
//if (!this.mEdgeGlowTop.isFinished()) {
// this.mEdgeGlowTop.onRelease();
//}
//this.invalidate(this.mEdgeGlowBottom.getBounds(true));
//}
//}
}
if (incrementalDeltaY != 0) {
// Coming back to 'real' list scrolling
if (this.mScrollY != 0) {
this.mScrollY = 0;
this.invalidateParentIfNeeded();
}
this.trackMotionScroll(incrementalDeltaY, incrementalDeltaY);
this.mTouchMode = AbsListView.TOUCH_MODE_SCROLL;
// We did not scroll the full amount. Treat this essentially like the
// start of a new touch scroll
const motionPosition:number = this.findClosestMotionRow(y);
this.mMotionCorrection = 0;
let motionView:View = this.getChildAt(motionPosition - this.mFirstPosition);
this.mMotionViewOriginalTop = motionView != null ? motionView.getTop() : 0;
this.mMotionY = y;
this.mMotionPosition = motionPosition;
}
this.mLastY = y;
this.mDirection = newDirection;
}
}
}
onTouchModeChanged(isInTouchMode:boolean):void {
if (isInTouchMode) {
// Get rid of the selection when we enter touch mode
this.hideSelector();
// state.)
if (this.getHeight() > 0 && this.getChildCount() > 0) {
// We do not lose focus initiating a touch (since AbsListView is focusable in
// touch mode). Force an initial layout to get rid of the selection.
this.layoutChildren();
}
this.updateSelectorState();
} else {
let touchMode:number = this.mTouchMode;
if (touchMode == AbsListView.TOUCH_MODE_OVERSCROLL || touchMode == AbsListView.TOUCH_MODE_OVERFLING) {
if (this.mFlingRunnable != null) {
this.mFlingRunnable.endFling();
}
if (this.mPositionScroller != null) {
this.mPositionScroller.stop();
}
if (this.mScrollY != 0) {
this.mScrollY = 0;
this.invalidateParentCaches();
this.finishGlows();
this.invalidate();
}
}
}
}
onTouchEvent(ev:MotionEvent):boolean {
if (!this.isEnabled()) {
// events, it just doesn't respond to them.
return this.isClickable() || this.isLongClickable();
}
if (this.mPositionScroller != null) {
this.mPositionScroller.stop();
}
if (!this.isAttachedToWindow()) {
// in a bogus state.
return false;
}
//TODO when fast scroller impl
//if (this.mFastScroller != null) {
// let intercepted:boolean = this.mFastScroller.onTouchEvent(ev);
// if (intercepted) {
// return true;
// }
//}
this.initVelocityTrackerIfNotExists();
this.mVelocityTracker.addMovement(ev);
const actionMasked:number = ev.getActionMasked();
switch (actionMasked) {
case MotionEvent.ACTION_DOWN:
{
this.onTouchDown(ev);
break;
}
case MotionEvent.ACTION_MOVE:
{
this.onTouchMove(ev);
break;
}
case MotionEvent.ACTION_UP:
{
this.onTouchUp(ev);
break;
}
case MotionEvent.ACTION_CANCEL:
{
this.onTouchCancel();
break;
}
case MotionEvent.ACTION_POINTER_UP:
{
this.onSecondaryPointerUp(ev);
const x:number = this.mMotionX;
const y:number = this.mMotionY;
const motionPosition:number = this.pointToPosition(x, y);
if (motionPosition >= 0) {
// Remember where the motion event started
const child:View = this.getChildAt(motionPosition - this.mFirstPosition);
this.mMotionViewOriginalTop = child.getTop();
this.mMotionPosition = motionPosition;
}
this.mLastY = y;
break;
}
case MotionEvent.ACTION_POINTER_DOWN:
{
// New pointers take over dragging duties
const index:number = ev.getActionIndex();
const id:number = ev.getPointerId(index);
const x:number = Math.floor(ev.getX(index));
const y:number = Math.floor(ev.getY(index));
this.mMotionCorrection = 0;
this.mActivePointerId = id;
this.mMotionX = x;
this.mMotionY = y;
const motionPosition:number = this.pointToPosition(x, y);
if (motionPosition >= 0) {
// Remember where the motion event started
const child:View = this.getChildAt(motionPosition - this.mFirstPosition);
this.mMotionViewOriginalTop = child.getTop();
this.mMotionPosition = motionPosition;
}
this.mLastY = y;
break;
}
}
return true;
}
private onTouchDown(ev:MotionEvent):void {
this.mActivePointerId = ev.getPointerId(0);
if (this.mTouchMode == AbsListView.TOUCH_MODE_OVERFLING) {
// Stopped the fling. It is a scroll.
this.mFlingRunnable.endFling();
if (this.mPositionScroller != null) {
this.mPositionScroller.stop();
}
this.mTouchMode = AbsListView.TOUCH_MODE_OVERSCROLL;
this.mMotionX = Math.floor(ev.getX());
this.mMotionY = Math.floor(ev.getY());
this.mLastY = this.mMotionY;
this.mMotionCorrection = 0;
this.mDirection = 0;
} else {
const x:number = Math.floor(ev.getX());
const y:number = Math.floor(ev.getY());
let motionPosition:number = this.pointToPosition(x, y);
if (!this.mDataChanged) {
if (this.mTouchMode == AbsListView.TOUCH_MODE_FLING) {
// Stopped a fling. It is a scroll.
this.createScrollingCache();
this.mTouchMode = AbsListView.TOUCH_MODE_SCROLL;
this.mMotionCorrection = 0;
motionPosition = this.findMotionRow(y);
this.mFlingRunnable.flywheelTouch();
} else if ((motionPosition >= 0) && this.getAdapter().isEnabled(motionPosition)) {
// User clicked on an actual view (and was not stopping a
// fling). It might be a click or a scroll. Assume it is a
// click until proven otherwise.
this.mTouchMode = AbsListView.TOUCH_MODE_DOWN;
// FIXME Debounce
if (this.mPendingCheckForTap_ == null) {
this.mPendingCheckForTap_ = new AbsListView.CheckForTap(this);
}
this.postDelayed(this.mPendingCheckForTap_, ViewConfiguration.getTapTimeout());
}
//AndroidUI added. so listView can drag even not touch on item (item count is less)
else if(motionPosition < 0){
this.mTouchMode = AbsListView.TOUCH_MODE_DOWN;
}
}
if (motionPosition >= 0) {
// Remember where the motion event started
const v:View = this.getChildAt(motionPosition - this.mFirstPosition);
this.mMotionViewOriginalTop = v.getTop();
}
this.mMotionX = x;
this.mMotionY = y;
this.mMotionPosition = motionPosition;
this.mLastY = Integer.MIN_VALUE;
}
if (this.mTouchMode == AbsListView.TOUCH_MODE_DOWN && this.mMotionPosition != AbsListView.INVALID_POSITION
&& this.performButtonActionOnTouchDown(ev)) {
this.removeCallbacks(this.mPendingCheckForTap_);
}
}
private onTouchMove(ev:MotionEvent):void {
let pointerIndex:number = ev.findPointerIndex(this.mActivePointerId);
if (pointerIndex == -1) {
pointerIndex = 0;
this.mActivePointerId = ev.getPointerId(pointerIndex);
}
if (this.mDataChanged) {
// Re-sync everything if data has been changed
// since the scroll operation can query the adapter.
this.layoutChildren();
}
const y:number = Math.floor(ev.getY(pointerIndex));
switch (this.mTouchMode) {
case AbsListView.TOUCH_MODE_DOWN:
case AbsListView.TOUCH_MODE_TAP:
case AbsListView.TOUCH_MODE_DONE_WAITING:
// scroll than a tap. If so, we'll enter scrolling mode.
if (this.startScrollIfNeeded(y)) {
break;
}
// Otherwise, check containment within list bounds. If we're
// outside bounds, cancel any active presses.
const x:number = ev.getX(pointerIndex);
if (!this.pointInView(x, y, this.mTouchSlop)) {
this.setPressed(false);
const motionView:View = this.getChildAt(this.mMotionPosition - this.mFirstPosition);
if (motionView != null) {
motionView.setPressed(false);
}
this.removeCallbacks(this.mTouchMode == AbsListView.TOUCH_MODE_DOWN ? this.mPendingCheckForTap_ : this.mPendingCheckForLongPress_List);
this.mTouchMode = AbsListView.TOUCH_MODE_DONE_WAITING;
this.updateSelectorState();
}
break;
case AbsListView.TOUCH_MODE_SCROLL:
case AbsListView.TOUCH_MODE_OVERSCROLL:
this.scrollIfNeeded(y);
break;
}
}
private onTouchUp(ev:MotionEvent):void {
switch (this.mTouchMode) {
case AbsListView.TOUCH_MODE_DOWN:
case AbsListView.TOUCH_MODE_TAP:
case AbsListView.TOUCH_MODE_DONE_WAITING:
const motionPosition:number = this.mMotionPosition;
const child:View = this.getChildAt(motionPosition - this.mFirstPosition);
if (child != null) {
if (this.mTouchMode != AbsListView.TOUCH_MODE_DOWN) {
child.setPressed(false);
}
const x:number = ev.getX();
const inList:boolean = x > this.mListPadding.left && x < this.getWidth() - this.mListPadding.right;
if (inList && !child.hasFocusable()) {
if (this.mPerformClick_ == null) {
this.mPerformClick_ = new AbsListView.PerformClick(this);
}
const performClick:AbsListView.PerformClick = this.mPerformClick_;
performClick.mClickMotionPosition = motionPosition;
performClick.rememberWindowAttachCount();
this.mResurrectToPosition = motionPosition;
if (this.mTouchMode == AbsListView.TOUCH_MODE_DOWN || this.mTouchMode == AbsListView.TOUCH_MODE_TAP) {
this.removeCallbacks(this.mTouchMode == AbsListView.TOUCH_MODE_DOWN ? this.mPendingCheckForTap_ : this.mPendingCheckForLongPress_List);
this.mLayoutMode = AbsListView.LAYOUT_NORMAL;
if (!this.mDataChanged && this.mAdapter.isEnabled(motionPosition)) {
this.mTouchMode = AbsListView.TOUCH_MODE_TAP;
this.setSelectedPositionInt(this.mMotionPosition);
this.layoutChildren();
child.setPressed(true);
this.positionSelector(this.mMotionPosition, child);
this.setPressed(true);
if (this.mSelector != null) {
let d:Drawable = this.mSelector.getCurrent();
//TODO when transition drawable impl
//if (d != null && d instanceof TransitionDrawable) {
// (<TransitionDrawable> d).resetTransition();
//}
}
if (this.mTouchModeReset != null) {
this.removeCallbacks(this.mTouchModeReset);
}
this.mTouchModeReset = (()=> {
const inner_this = this;
class _Inner implements Runnable {
run():void {
inner_this.mTouchModeReset = null;
inner_this.mTouchMode = AbsListView.TOUCH_MODE_REST;
child.setPressed(false);
inner_this.setPressed(false);
if (!inner_this.mDataChanged && inner_this.isAttachedToWindow()) {
performClick.run();
}
}
}
return new _Inner();
})();
this.postDelayed(this.mTouchModeReset, ViewConfiguration.getPressedStateDuration());
} else {
this.mTouchMode = AbsListView.TOUCH_MODE_REST;
this.updateSelectorState();
}
return;
} else if (!this.mDataChanged && this.mAdapter.isEnabled(motionPosition)) {
performClick.run();
}
}
}
this.mTouchMode = AbsListView.TOUCH_MODE_REST;
this.updateSelectorState();
break;
case AbsListView.TOUCH_MODE_SCROLL:
const childCount:number = this.getChildCount();
if (childCount > 0) {
const firstChildTop:number = this.getChildAt(0).getTop();
const lastChildBottom:number = this.getChildAt(childCount - 1).getBottom();
const contentTop:number = this.mListPadding.top;
const contentBottom:number = this.getHeight() - this.mListPadding.bottom;
if (this.mFirstPosition == 0 && firstChildTop >= contentTop && this.mFirstPosition + childCount < this.mItemCount
&& lastChildBottom <= this.getHeight() - contentBottom) {
this.mTouchMode = AbsListView.TOUCH_MODE_REST;
this.reportScrollStateChange(AbsListView.OnScrollListener.SCROLL_STATE_IDLE);
} else {
const velocityTracker:VelocityTracker = this.mVelocityTracker;
velocityTracker.computeCurrentVelocity(1000, this.mMaximumVelocity);
const initialVelocity:number = Math.floor((velocityTracker.getYVelocity(this.mActivePointerId) * this.mVelocityScale));
// fling further.
if (Math.abs(initialVelocity) > this.mMinimumVelocity
&& !( (this.mFirstPosition == 0 && firstChildTop == contentTop - this.mOverscrollDistance)
|| (this.mFirstPosition + childCount == this.mItemCount
&& lastChildBottom == contentBottom + this.mOverscrollDistance))) {
if (this.mFlingRunnable == null) {
this.mFlingRunnable = new AbsListView.FlingRunnable(this);
}
this.reportScrollStateChange(AbsListView.OnScrollListener.SCROLL_STATE_FLING);
this.mFlingRunnable.start(-initialVelocity);
} else {
this.mTouchMode = AbsListView.TOUCH_MODE_REST;
this.reportScrollStateChange(AbsListView.OnScrollListener.SCROLL_STATE_IDLE);
if (this.mFlingRunnable != null) {
this.mFlingRunnable.endFling();
}
if (this.mPositionScroller != null) {
this.mPositionScroller.stop();
}
}
}
} else {
this.mTouchMode = AbsListView.TOUCH_MODE_REST;
this.reportScrollStateChange(AbsListView.OnScrollListener.SCROLL_STATE_IDLE);
}
break;
case AbsListView.TOUCH_MODE_OVERSCROLL:
if (this.mFlingRunnable == null) {
this.mFlingRunnable = new AbsListView.FlingRunnable(this);
}
const velocityTracker:VelocityTracker = this.mVelocityTracker;
velocityTracker.computeCurrentVelocity(1000, this.mMaximumVelocity);
const initialVelocity:number = Math.floor(velocityTracker.getYVelocity(this.mActivePointerId));
this.reportScrollStateChange(AbsListView.OnScrollListener.SCROLL_STATE_FLING);
if (Math.abs(initialVelocity) > this.mMinimumVelocity) {
this.mFlingRunnable.startOverfling(-initialVelocity);
} else {
this.mFlingRunnable.startSpringback();
}
break;
}
this.setPressed(false);
//if (this.mEdgeGlowTop != null) {
// this.mEdgeGlowTop.onRelease();
// this.mEdgeGlowBottom.onRelease();
//}
// Need to redraw since we probably aren't drawing the selector anymore
this.invalidate();
this.removeCallbacks(this.mPendingCheckForLongPress_List);
this.recycleVelocityTracker();
this.mActivePointerId = AbsListView.INVALID_POINTER;
if (AbsListView.PROFILE_SCROLLING) {
if (this.mScrollProfilingStarted) {
//Debug.stopMethodTracing();
this.mScrollProfilingStarted = false;
}
}
//if (this.mScrollStrictSpan != null) {
// this.mScrollStrictSpan.finish();
// this.mScrollStrictSpan = null;
//}
}
private onTouchCancel():void {
switch (this.mTouchMode) {
case AbsListView.TOUCH_MODE_OVERSCROLL:
if (this.mFlingRunnable == null) {
this.mFlingRunnable = new AbsListView.FlingRunnable(this);
}
this.mFlingRunnable.startSpringback();
break;
case AbsListView.TOUCH_MODE_OVERFLING:
// Do nothing - let it play out.
break;
default:
this.mTouchMode = AbsListView.TOUCH_MODE_REST;
this.setPressed(false);
const motionView:View = this.getChildAt(this.mMotionPosition - this.mFirstPosition);
if (motionView != null) {
motionView.setPressed(false);
}
this.clearScrollingCache();
this.removeCallbacks(this.mPendingCheckForLongPress_List);
this.recycleVelocityTracker();
}
//if (this.mEdgeGlowTop != null) {
// this.mEdgeGlowTop.onRelease();
// this.mEdgeGlowBottom.onRelease();
//}
this.mActivePointerId = AbsListView.INVALID_POINTER;
}
protected onOverScrolled(scrollX:number, scrollY:number, clampedX:boolean, clampedY:boolean):void {
if (this.mScrollY != scrollY) {
this.onScrollChanged(this.mScrollX, scrollY, this.mScrollX, this.mScrollY);
this.mScrollY = scrollY;
this.invalidateParentIfNeeded();
this.awakenScrollBars();
}
}
onGenericMotionEvent(event:MotionEvent):boolean {
if (event.isPointerEvent()) {
switch (event.getAction()) {
case MotionEvent.ACTION_SCROLL:
{
if (this.mTouchMode == AbsListView.TOUCH_MODE_REST) {
const vscroll:number = event.getAxisValue(MotionEvent.AXIS_VSCROLL);
if (vscroll != 0) {
const delta:number = Math.floor((vscroll * this.getVerticalScrollFactor()));
if (!this.trackMotionScroll(delta, delta)) {
return true;
}
}
}
}
}
}
return super.onGenericMotionEvent(event);
}
draw(canvas:Canvas):void {
super.draw(canvas);
//if (this.mEdgeGlowTop != null) {
// const scrollY:number = this.mScrollY;
// if (!this.mEdgeGlowTop.isFinished()) {
// const restoreCount:number = canvas.save();
// const leftPadding:number = this.mListPadding.left + this.mGlowPaddingLeft;
// const rightPadding:number = this.mListPadding.right + this.mGlowPaddingRight;
// const width:number = this.getWidth() - leftPadding - rightPadding;
// let edgeY:number = Math.min(0, scrollY + this.mFirstPositionDistanceGuess);
// canvas.translate(leftPadding, edgeY);
// this.mEdgeGlowTop.setSize(width, this.getHeight());
// if (this.mEdgeGlowTop.draw(canvas)) {
// this.mEdgeGlowTop.setPosition(leftPadding, edgeY);
// this.invalidate(this.mEdgeGlowTop.getBounds(false));
// }
// canvas.restoreToCount(restoreCount);
// }
// if (!this.mEdgeGlowBottom.isFinished()) {
// const restoreCount:number = canvas.save();
// const leftPadding:number = this.mListPadding.left + this.mGlowPaddingLeft;
// const rightPadding:number = this.mListPadding.right + this.mGlowPaddingRight;
// const width:number = this.getWidth() - leftPadding - rightPadding;
// const height:number = this.getHeight();
// let edgeX:number = -width + leftPadding;
// let edgeY:number = Math.max(height, scrollY + this.mLastPositionDistanceGuess);
// canvas.translate(edgeX, edgeY);
// canvas.rotate(180, width, 0);
// this.mEdgeGlowBottom.setSize(width, height);
// if (this.mEdgeGlowBottom.draw(canvas)) {
// // Account for the rotation
// this.mEdgeGlowBottom.setPosition(edgeX + width, edgeY);
// this.invalidate(this.mEdgeGlowBottom.getBounds(true));
// }
// canvas.restoreToCount(restoreCount);
// }
//}
}
/**
* @hide
*/
setOverScrollEffectPadding(leftPadding:number, rightPadding:number):void {
this.mGlowPaddingLeft = leftPadding;
this.mGlowPaddingRight = rightPadding;
}
private initOrResetVelocityTracker():void {
if (this.mVelocityTracker == null) {
this.mVelocityTracker = VelocityTracker.obtain();
} else {
this.mVelocityTracker.clear();
}
}
private initVelocityTrackerIfNotExists():void {
if (this.mVelocityTracker == null) {
this.mVelocityTracker = VelocityTracker.obtain();
}
}
private recycleVelocityTracker():void {
if (this.mVelocityTracker != null) {
this.mVelocityTracker.recycle();
this.mVelocityTracker = null;
}
}
requestDisallowInterceptTouchEvent(disallowIntercept:boolean):void {
if (disallowIntercept) {
this.recycleVelocityTracker();
}
super.requestDisallowInterceptTouchEvent(disallowIntercept);
}
//TODO when hover impl
//onInterceptHoverEvent(event:MotionEvent):boolean {
// //TODO when fast scroller impl
// //if (this.mFastScroller != null && this.mFastScroller.onInterceptHoverEvent(event)) {
// // return true;
// //}
// return super.onInterceptHoverEvent(event);
//}
onInterceptTouchEvent(ev:MotionEvent):boolean {
let action:number = ev.getAction();
let v:View;
if (this.mPositionScroller != null) {
this.mPositionScroller.stop();
}
if (!this.isAttachedToWindow()) {
// in a bogus state.
return false;
}
//TODO when fast scroller impl
//if (this.mFastScroller != null && this.mFastScroller.onInterceptTouchEvent(ev)) {
// return true;
//}
switch (action & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
{
let touchMode:number = this.mTouchMode;
if (touchMode == AbsListView.TOUCH_MODE_OVERFLING || touchMode == AbsListView.TOUCH_MODE_OVERSCROLL) {
this.mMotionCorrection = 0;
return true;
}
const x:number = Math.floor(ev.getX());
const y:number = Math.floor(ev.getY());
this.mActivePointerId = ev.getPointerId(0);
let motionPosition:number = this.findMotionRow(y);
if (touchMode != AbsListView.TOUCH_MODE_FLING && motionPosition >= 0) {
// User clicked on an actual view (and was not stopping a fling).
// Remember where the motion event started
v = this.getChildAt(motionPosition - this.mFirstPosition);
this.mMotionViewOriginalTop = v.getTop();
this.mMotionX = x;
this.mMotionY = y;
this.mMotionPosition = motionPosition;
this.mTouchMode = AbsListView.TOUCH_MODE_DOWN;
this.clearScrollingCache();
}
this.mLastY = Integer.MIN_VALUE;
this.initOrResetVelocityTracker();
this.mVelocityTracker.addMovement(ev);
if (touchMode == AbsListView.TOUCH_MODE_FLING) {
return true;
}
break;
}
case MotionEvent.ACTION_MOVE:
{
switch (this.mTouchMode) {
case AbsListView.TOUCH_MODE_DOWN:
let pointerIndex:number = ev.findPointerIndex(this.mActivePointerId);
if (pointerIndex == -1) {
pointerIndex = 0;
this.mActivePointerId = ev.getPointerId(pointerIndex);
}
const y:number = Math.floor(ev.getY(pointerIndex));
this.initVelocityTrackerIfNotExists();
this.mVelocityTracker.addMovement(ev);
if (this.startScrollIfNeeded(y)) {
return true;
}
break;
}
break;
}
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
{
this.mTouchMode = AbsListView.TOUCH_MODE_REST;
this.mActivePointerId = AbsListView.INVALID_POINTER;
this.recycleVelocityTracker();
this.reportScrollStateChange(AbsListView.OnScrollListener.SCROLL_STATE_IDLE);
break;
}
case MotionEvent.ACTION_POINTER_UP:
{
this.onSecondaryPointerUp(ev);
break;
}
}
return false;
}
private onSecondaryPointerUp(ev:MotionEvent):void {
const pointerIndex:number = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
const pointerId:number = ev.getPointerId(pointerIndex);
if (pointerId == this.mActivePointerId) {
// This was our active pointer going up. Choose a new
// active pointer and adjust accordingly.
// TODO: Make this decision more intelligent.
const newPointerIndex:number = pointerIndex == 0 ? 1 : 0;
this.mMotionX = Math.floor(ev.getX(newPointerIndex));
this.mMotionY = Math.floor(ev.getY(newPointerIndex));
this.mMotionCorrection = 0;
this.mActivePointerId = ev.getPointerId(newPointerIndex);
}
}
/**
* {@inheritDoc}
*/
addTouchables(views:ArrayList<View>):void {
const count:number = this.getChildCount();
const firstPosition:number = this.mFirstPosition;
const adapter:ListAdapter = this.mAdapter;
if (adapter == null) {
return;
}
for (let i:number = 0; i < count; i++) {
const child:View = this.getChildAt(i);
if (adapter.isEnabled(firstPosition + i)) {
views.add(child);
}
child.addTouchables(views);
}
}
/**
* Fires an "on scroll state changed" event to the registered
* {@link android.widget.AbsListView.OnScrollListener}, if any. The state change
* is fired only if the specified state is different from the previously known state.
*
* @param newState The new scroll state.
*/
private reportScrollStateChange(newState:number):void {
if (newState != this.mLastScrollState) {
if (this.mOnScrollListener != null) {
this.mLastScrollState = newState;
this.mOnScrollListener.onScrollStateChanged(this, newState);
}
}
}
/**
* The amount of friction applied to flings. The default value
* is {@link ViewConfiguration#getScrollFriction}.
*/
setFriction(friction:number):void {
if (this.mFlingRunnable == null) {
this.mFlingRunnable = new AbsListView.FlingRunnable(this);
}
this.mFlingRunnable.mScroller.setFriction(friction);
}
/**
* Sets a scale factor for the fling velocity. The initial scale
* factor is 1.0.
*
* @param scale The scale factor to multiply the velocity by.
*/
setVelocityScale(scale:number):void {
this.mVelocityScale = scale;
}
/**
* Smoothly scroll to the specified adapter position. The view will scroll
* such that the indicated position is displayed <code>offset</code> pixels from
* the top edge of the view. If this is impossible, (e.g. the offset would scroll
* the first or last item beyond the boundaries of the list) it will get as close
* as possible. The scroll will take <code>duration</code> milliseconds to complete.
*
* @param position Position to scroll to
* @param offset Desired distance in pixels of <code>position</code> from the top
* of the view when scrolling is finished
* @param duration Number of milliseconds to use for the scroll
*/
smoothScrollToPositionFromTop(position:number, offset:number, duration?:number):void {
if (this.mPositionScroller == null) {
this.mPositionScroller = new AbsListView.PositionScroller(this);
}
this.mPositionScroller.startWithOffset(position, offset, duration);
}
/**
* Smoothly scroll to the specified adapter position. The view will
* scroll such that the indicated position is displayed, but it will
* stop early if scrolling further would scroll boundPosition out of
* view.
* @param position Scroll to this adapter position.
* @param boundPosition Do not scroll if it would move this adapter
* position out of view.
*/
smoothScrollToPosition(position:number, boundPosition?:number):void {
if (this.mPositionScroller == null) {
this.mPositionScroller = new AbsListView.PositionScroller(this);
}
this.mPositionScroller.start(position, boundPosition);
}
/**
* Smoothly scroll by distance pixels over duration milliseconds.
* @param distance Distance to scroll in pixels.
* @param duration Duration of the scroll animation in milliseconds.
*/
smoothScrollBy(distance:number, duration:number, linear:boolean=false):void {
if (this.mFlingRunnable == null) {
this.mFlingRunnable = new AbsListView.FlingRunnable(this);
}
// No sense starting to scroll if we're not going anywhere
const firstPos:number = this.mFirstPosition;
const childCount:number = this.getChildCount();
const lastPos:number = firstPos + childCount;
const topLimit:number = this.getPaddingTop();
const bottomLimit:number = this.getHeight() - this.getPaddingBottom();
if (distance == 0 || this.mItemCount == 0 || childCount == 0
|| (firstPos == 0 && this.getChildAt(0).getTop() == topLimit && distance < 0)
|| (lastPos == this.mItemCount && this.getChildAt(childCount - 1).getBottom() == bottomLimit && distance > 0)) {
this.mFlingRunnable.endFling();
if (this.mPositionScroller != null) {
this.mPositionScroller.stop();
}
} else {
this.reportScrollStateChange(AbsListView.OnScrollListener.SCROLL_STATE_FLING);
this.mFlingRunnable.startScroll(distance, duration, linear);
}
}
/**
* Allows RemoteViews to scroll relatively to a position.
*/
smoothScrollByOffset(position:number):void {
let index:number = -1;
if (position < 0) {
index = this.getFirstVisiblePosition();
} else if (position > 0) {
index = this.getLastVisiblePosition();
}
if (index > -1) {
let child:View = this.getChildAt(index - this.getFirstVisiblePosition());
if (child != null) {
let visibleRect:Rect = new Rect();
if (child.getGlobalVisibleRect(visibleRect)) {
// the child is partially visible
let childRectArea:number = child.getWidth() * child.getHeight();
let visibleRectArea:number = visibleRect.width() * visibleRect.height();
let visibleArea:number = (visibleRectArea / <number> childRectArea);
const visibleThreshold:number = 0.75;
if ((position < 0) && (visibleArea < visibleThreshold)) {
// the top index is not perceivably visible so offset
// to account for showing that top index as well
++index;
} else if ((position > 0) && (visibleArea < visibleThreshold)) {
// the bottom index is not perceivably visible so offset
// to account for showing that bottom index as well
--index;
}
}
this.smoothScrollToPosition(Math.max(0, Math.min(this.getCount(), index + position)));
}
}
}
private createScrollingCache():void {
if (this.mScrollingCacheEnabled && !this.mCachingStarted && !this.isHardwareAccelerated()) {
this.setChildrenDrawnWithCacheEnabled(true);
this.setChildrenDrawingCacheEnabled(true);
this.mCachingStarted = this.mCachingActive = true;
}
}
private clearScrollingCache():void {
if (!this.isHardwareAccelerated()) {
if (this.mClearScrollingCache == null) {
this.mClearScrollingCache = (()=> {
const inner_this = this;
class _Inner implements Runnable {
run():void {
if (inner_this.mCachingStarted) {
inner_this.mCachingStarted = inner_this.mCachingActive = false;
inner_this.setChildrenDrawnWithCacheEnabled(false);
if ((inner_this.mPersistentDrawingCache & AbsListView.PERSISTENT_SCROLLING_CACHE) == 0) {
inner_this.setChildrenDrawingCacheEnabled(false);
}
if (!inner_this.isAlwaysDrawnWithCacheEnabled()) {
inner_this.invalidate();
}
}
}
}
return new _Inner();
})();
}
this.post(this.mClearScrollingCache);
}
}
/**
* Scrolls the list items within the view by a specified number of pixels.
*
* @param y the amount of pixels to scroll by vertically
* @see #canScrollList(int)
*/
scrollListBy(y:number):void {
this.trackMotionScroll(-y, -y);
}
/**
* Check if the items in the list can be scrolled in a certain direction.
*
* @param direction Negative to check scrolling up, positive to check
* scrolling down.
* @return true if the list can be scrolled in the specified direction,
* false otherwise.
* @see #scrollListBy(int)
*/
canScrollList(direction:number):boolean {
const childCount:number = this.getChildCount();
if (childCount == 0) {
return false;
}
const firstPosition:number = this.mFirstPosition;
const listPadding:Rect = this.mListPadding;
if (direction > 0) {
const lastBottom:number = this.getChildAt(childCount - 1).getBottom();
const lastPosition:number = firstPosition + childCount;
return lastPosition < this.mItemCount || lastBottom > this.getHeight() - listPadding.bottom;
} else {
const firstTop:number = this.getChildAt(0).getTop();
return firstPosition > 0 || firstTop < listPadding.top;
}
}
/**
* Track a motion scroll
*
* @param deltaY Amount to offset mMotionView. This is the accumulated delta since the motion
* began. Positive numbers mean the user's finger is moving down the screen.
* @param incrementalDeltaY Change in deltaY from the previous event.
* @return true if we're already at the beginning/end of the list and have nothing to do.
*/
private trackMotionScroll(deltaY:number, incrementalDeltaY:number):boolean {
const childCount:number = this.getChildCount();
if (childCount == 0) {
return true;
}
const firstTop:number = this.getChildAt(0).getTop();
const lastBottom:number = this.getChildAt(childCount - 1).getBottom();
const listPadding:Rect = this.mListPadding;
// "effective padding" In this case is the amount of padding that affects
// how much space should not be filled by items. If we don't clip to padding
// there is no effective padding.
let effectivePaddingTop:number = 0;
let effectivePaddingBottom:number = 0;
if ((this.mGroupFlags & AbsListView.CLIP_TO_PADDING_MASK) == AbsListView.CLIP_TO_PADDING_MASK) {
effectivePaddingTop = listPadding.top;
effectivePaddingBottom = listPadding.bottom;
}
// FIXME account for grid vertical spacing too?
const spaceAbove:number = effectivePaddingTop - firstTop;
const end:number = this.getHeight() - effectivePaddingBottom;
const spaceBelow:number = lastBottom - end;
const height:number = this.getHeight() - this.mPaddingBottom - this.mPaddingTop;
if (deltaY < 0) {
deltaY = Math.max(-(height - 1), deltaY);
} else {
deltaY = Math.min(height - 1, deltaY);
}
if (incrementalDeltaY < 0) {
incrementalDeltaY = Math.max(-(height - 1), incrementalDeltaY);
} else {
incrementalDeltaY = Math.min(height - 1, incrementalDeltaY);
}
const firstPosition:number = this.mFirstPosition;
// Update our guesses for where the first and last views are
if (firstPosition == 0) {
this.mFirstPositionDistanceGuess = firstTop - listPadding.top;
} else {
this.mFirstPositionDistanceGuess += incrementalDeltaY;
}
if (firstPosition + childCount == this.mItemCount) {
this.mLastPositionDistanceGuess = lastBottom + listPadding.bottom;
} else {
this.mLastPositionDistanceGuess += incrementalDeltaY;
}
const cannotScrollDown:boolean = (firstPosition == 0 && firstTop >= listPadding.top && incrementalDeltaY >= 0);
const cannotScrollUp:boolean = (firstPosition + childCount == this.mItemCount && lastBottom <= this.getHeight() - listPadding.bottom && incrementalDeltaY <= 0);
if (cannotScrollDown || cannotScrollUp) {
return incrementalDeltaY != 0;
}
const down:boolean = incrementalDeltaY < 0;
const inTouchMode:boolean = this.isInTouchMode();
if (inTouchMode) {
this.hideSelector();
}
const headerViewsCount:number = this.getHeaderViewsCount();
const footerViewsStart:number = this.mItemCount - this.getFooterViewsCount();
let start:number = 0;
let count:number = 0;
if (down) {
let top:number = -incrementalDeltaY;
if ((this.mGroupFlags & AbsListView.CLIP_TO_PADDING_MASK) == AbsListView.CLIP_TO_PADDING_MASK) {
top += listPadding.top;
}
for (let i:number = 0; i < childCount; i++) {
const child:View = this.getChildAt(i);
if (child.getBottom() >= top) {
break;
} else {
count++;
let position:number = firstPosition + i;
if (position >= headerViewsCount && position < footerViewsStart) {
// system-managed transient state.
//if (child.isAccessibilityFocused()) {
// child.clearAccessibilityFocus();
//}
this.mRecycler.addScrapView(child, position);
}
}
}
} else {
let bottom:number = this.getHeight() - incrementalDeltaY;
if ((this.mGroupFlags & AbsListView.CLIP_TO_PADDING_MASK) == AbsListView.CLIP_TO_PADDING_MASK) {
bottom -= listPadding.bottom;
}
for (let i:number = childCount - 1; i >= 0; i--) {
const child:View = this.getChildAt(i);
if (child.getTop() <= bottom) {
break;
} else {
start = i;
count++;
let position:number = firstPosition + i;
if (position >= headerViewsCount && position < footerViewsStart) {
// system-managed transient state.
//if (child.isAccessibilityFocused()) {
// child.clearAccessibilityFocus();
//}
this.mRecycler.addScrapView(child, position);
}
}
}
}
this.mMotionViewNewTop = this.mMotionViewOriginalTop + deltaY;
this.mBlockLayoutRequests = true;
if (count > 0) {
this.detachViewsFromParent(start, count);
this.mRecycler.removeSkippedScrap();
}
// calls to bubble up from the children all the way to the top
if (!this.awakenScrollBars()) {
this.invalidate();
}
this.offsetChildrenTopAndBottom(incrementalDeltaY);
if (down) {
this.mFirstPosition += count;
}
const absIncrementalDeltaY:number = Math.abs(incrementalDeltaY);
if (spaceAbove < absIncrementalDeltaY || spaceBelow < absIncrementalDeltaY) {
this.fillGap(down);
}
if (!inTouchMode && this.mSelectedPosition != AbsListView.INVALID_POSITION) {
const childIndex:number = this.mSelectedPosition - this.mFirstPosition;
if (childIndex >= 0 && childIndex < this.getChildCount()) {
this.positionSelector(this.mSelectedPosition, this.getChildAt(childIndex));
}
} else if (this.mSelectorPosition != AbsListView.INVALID_POSITION) {
const childIndex:number = this.mSelectorPosition - this.mFirstPosition;
if (childIndex >= 0 && childIndex < this.getChildCount()) {
this.positionSelector(AbsListView.INVALID_POSITION, this.getChildAt(childIndex));
}
} else {
this.mSelectorRect.setEmpty();
}
this.mBlockLayoutRequests = false;
this.invokeOnItemScrollListener();
return false;
}
/**
* Returns the number of header views in the list. Header views are special views
* at the top of the list that should not be recycled during a layout.
*
* @return The number of header views, 0 in the default implementation.
*/
getHeaderViewsCount():number {
return 0;
}
/**
* Returns the number of footer views in the list. Footer views are special views
* at the bottom of the list that should not be recycled during a layout.
*
* @return The number of footer views, 0 in the default implementation.
*/
getFooterViewsCount():number {
return 0;
}
/**
* Fills the gap left open by a touch-scroll. During a touch scroll, children that
* remain on screen are shifted and the other ones are discarded. The role of this
* method is to fill the gap thus created by performing a partial layout in the
* empty space.
*
* @param down true if the scroll is going down, false if it is going up
*/
abstract fillGap(down:boolean):void ;
hideSelector():void {
if (this.mSelectedPosition != AbsListView.INVALID_POSITION) {
if (this.mLayoutMode != AbsListView.LAYOUT_SPECIFIC) {
this.mResurrectToPosition = this.mSelectedPosition;
}
if (this.mNextSelectedPosition >= 0 && this.mNextSelectedPosition != this.mSelectedPosition) {
this.mResurrectToPosition = this.mNextSelectedPosition;
}
this.setSelectedPositionInt(AbsListView.INVALID_POSITION);
this.setNextSelectedPositionInt(AbsListView.INVALID_POSITION);
this.mSelectedTop = 0;
}
}
/**
* @return A position to select. First we try mSelectedPosition. If that has been clobbered by
* entering touch mode, we then try mResurrectToPosition. Values are pinned to the range
* of items available in the adapter
*/
reconcileSelectedPosition():number {
let position:number = this.mSelectedPosition;
if (position < 0) {
position = this.mResurrectToPosition;
}
position = Math.max(0, position);
position = Math.min(position, this.mItemCount - 1);
return position;
}
/**
* Find the row closest to y. This row will be used as the motion row when scrolling
*
* @param y Where the user touched
* @return The position of the first (or only) item in the row containing y
*/
abstract findMotionRow(y:number):number ;
/**
* Find the row closest to y. This row will be used as the motion row when scrolling.
*
* @param y Where the user touched
* @return The position of the first (or only) item in the row closest to y
*/
private findClosestMotionRow(y:number):number {
const childCount:number = this.getChildCount();
if (childCount == 0) {
return AbsListView.INVALID_POSITION;
}
const motionRow:number = this.findMotionRow(y);
return motionRow != AbsListView.INVALID_POSITION ? motionRow : this.mFirstPosition + childCount - 1;
}
/**
* Causes all the views to be rebuilt and redrawn.
*/
invalidateViews():void {
this.mDataChanged = true;
this.rememberSyncState();
this.requestLayout();
this.invalidate();
}
/**
* If there is a selection returns false.
* Otherwise resurrects the selection and returns true if resurrected.
*/
resurrectSelectionIfNeeded():boolean {
if (this.mSelectedPosition < 0 && this.resurrectSelection()) {
this.updateSelectorState();
return true;
}
return false;
}
/**
* Makes the item at the supplied position selected.
*
* @param position the position of the new selection
*/
abstract setSelectionInt(position:number):void ;
/**
* Attempt to bring the selection back if the user is switching from touch
* to trackball mode
* @return Whether selection was set to something.
*/
private resurrectSelection():boolean {
const childCount:number = this.getChildCount();
if (childCount <= 0) {
return false;
}
let selectedTop:number = 0;
let selectedPos:number;
let childrenTop:number = this.mListPadding.top;
let childrenBottom:number = this.mBottom - this.mTop - this.mListPadding.bottom;
const firstPosition:number = this.mFirstPosition;
const toPosition:number = this.mResurrectToPosition;
let down:boolean = true;
if (toPosition >= firstPosition && toPosition < firstPosition + childCount) {
selectedPos = toPosition;
const selected:View = this.getChildAt(selectedPos - this.mFirstPosition);
selectedTop = selected.getTop();
let selectedBottom:number = selected.getBottom();
// We are scrolled, don't get in the fade
if (selectedTop < childrenTop) {
selectedTop = childrenTop + this.getVerticalFadingEdgeLength();
} else if (selectedBottom > childrenBottom) {
selectedTop = childrenBottom - selected.getMeasuredHeight() - this.getVerticalFadingEdgeLength();
}
} else {
if (toPosition < firstPosition) {
// Default to selecting whatever is first
selectedPos = firstPosition;
for (let i:number = 0; i < childCount; i++) {
const v:View = this.getChildAt(i);
const top:number = v.getTop();
if (i == 0) {
// Remember the position of the first item
selectedTop = top;
// See if we are scrolled at all
if (firstPosition > 0 || top < childrenTop) {
// If we are scrolled, don't select anything that is
// in the fade region
childrenTop += this.getVerticalFadingEdgeLength();
}
}
if (top >= childrenTop) {
// Found a view whose top is fully visisble
selectedPos = firstPosition + i;
selectedTop = top;
break;
}
}
} else {
const itemCount:number = this.mItemCount;
down = false;
selectedPos = firstPosition + childCount - 1;
for (let i:number = childCount - 1; i >= 0; i--) {
const v:View = this.getChildAt(i);
const top:number = v.getTop();
const bottom:number = v.getBottom();
if (i == childCount - 1) {
selectedTop = top;
if (firstPosition + childCount < itemCount || bottom > childrenBottom) {
childrenBottom -= this.getVerticalFadingEdgeLength();
}
}
if (bottom <= childrenBottom) {
selectedPos = firstPosition + i;
selectedTop = top;
break;
}
}
}
}
this.mResurrectToPosition = AbsListView.INVALID_POSITION;
this.removeCallbacks(this.mFlingRunnable);
if (this.mPositionScroller != null) {
this.mPositionScroller.stop();
}
this.mTouchMode = AbsListView.TOUCH_MODE_REST;
this.clearScrollingCache();
this.mSpecificTop = selectedTop;
selectedPos = this.lookForSelectablePosition(selectedPos, down);
if (selectedPos >= firstPosition && selectedPos <= this.getLastVisiblePosition()) {
this.mLayoutMode = AbsListView.LAYOUT_SPECIFIC;
this.updateSelectorState();
this.setSelectionInt(selectedPos);
this.invokeOnItemScrollListener();
} else {
selectedPos = AbsListView.INVALID_POSITION;
}
this.reportScrollStateChange(AbsListView.OnScrollListener.SCROLL_STATE_IDLE);
return selectedPos >= 0;
}
private confirmCheckedPositionsById():void {
// Clear out the positional check states, we'll rebuild it below from IDs.
this.mCheckStates.clear();
let checkedCountChanged:boolean = false;
for (let checkedIndex:number = 0; checkedIndex < this.mCheckedIdStates.size(); checkedIndex++) {
const id:number = this.mCheckedIdStates.keyAt(checkedIndex);
const lastPos:number = this.mCheckedIdStates.valueAt(checkedIndex);
const lastPosId:number = this.mAdapter.getItemId(lastPos);
if (id != lastPosId) {
// Look around to see if the ID is nearby. If not, uncheck it.
const start:number = Math.max(0, lastPos - AbsListView.CHECK_POSITION_SEARCH_DISTANCE);
const end:number = Math.min(lastPos + AbsListView.CHECK_POSITION_SEARCH_DISTANCE, this.mItemCount);
let found:boolean = false;
for (let searchPos:number = start; searchPos < end; searchPos++) {
const searchId:number = this.mAdapter.getItemId(searchPos);
if (id == searchId) {
found = true;
this.mCheckStates.put(searchPos, true);
this.mCheckedIdStates.setValueAt(checkedIndex, searchPos);
break;
}
}
if (!found) {
this.mCheckedIdStates.delete(id);
checkedIndex--;
this.mCheckedItemCount--;
checkedCountChanged = true;
//if (this.mChoiceActionMode != null && this.mMultiChoiceModeCallback != null) {
// this.mMultiChoiceModeCallback.onItemCheckedStateChanged(this.mChoiceActionMode, lastPos, id, false);
//}
}
} else {
this.mCheckStates.put(lastPos, true);
}
}
if (checkedCountChanged && this.mChoiceActionMode != null) {
this.mChoiceActionMode.invalidate();
}
}
handleDataChanged():void {
let count:number = this.mItemCount;
let lastHandledItemCount:number = this.mLastHandledItemCount;
this.mLastHandledItemCount = this.mItemCount;
if (this.mChoiceMode != AbsListView.CHOICE_MODE_NONE && this.mAdapter != null && this.mAdapter.hasStableIds()) {
this.confirmCheckedPositionsById();
}
// TODO: In the future we can recycle these views based on stable ID instead.
this.mRecycler.clearTransientStateViews();
if (count > 0) {
let newPos:number;
let selectablePos:number;
// Find the row we are supposed to sync to
if (this.mNeedSync) {
// Update this first, since setNextSelectedPositionInt inspects it
this.mNeedSync = false;
this.mPendingSync = null;
if (this.mTranscriptMode == AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL) {
this.mLayoutMode = AbsListView.LAYOUT_FORCE_BOTTOM;
return;
} else if (this.mTranscriptMode == AbsListView.TRANSCRIPT_MODE_NORMAL) {
if (this.mForceTranscriptScroll) {
this.mForceTranscriptScroll = false;
this.mLayoutMode = AbsListView.LAYOUT_FORCE_BOTTOM;
return;
}
const childCount:number = this.getChildCount();
const listBottom:number = this.getHeight() - this.getPaddingBottom();
const lastChild:View = this.getChildAt(childCount - 1);
const lastBottom:number = lastChild != null ? lastChild.getBottom() : listBottom;
if (this.mFirstPosition + childCount >= lastHandledItemCount && lastBottom <= listBottom) {
this.mLayoutMode = AbsListView.LAYOUT_FORCE_BOTTOM;
return;
}
// Something new came in and we didn't scroll; give the user a clue that
// there's something new.
this.awakenScrollBars();
}
switch (this.mSyncMode) {
case AbsListView.SYNC_SELECTED_POSITION:
if (this.isInTouchMode()) {
// We saved our state when not in touch mode. (We know this because
// mSyncMode is SYNC_SELECTED_POSITION.) Now we are trying to
// restore in touch mode. Just leave mSyncPosition as it is (possibly
// adjusting if the available range changed) and return.
this.mLayoutMode = AbsListView.LAYOUT_SYNC;
this.mSyncPosition = Math.min(Math.max(0, this.mSyncPosition), count - 1);
return;
} else {
// See if we can find a position in the new data with the same
// id as the old selection. This will change mSyncPosition.
newPos = this.findSyncPosition();
if (newPos >= 0) {
// Found it. Now verify that new selection is still selectable
selectablePos = this.lookForSelectablePosition(newPos, true);
if (selectablePos == newPos) {
// Same row id is selected
this.mSyncPosition = newPos;
if (this.mSyncHeight == this.getHeight()) {
// If we are at the same height as when we saved state, try
// to restore the scroll position too.
this.mLayoutMode = AbsListView.LAYOUT_SYNC;
} else {
// We are not the same height as when the selection was saved, so
// don't try to restore the exact position
this.mLayoutMode = AbsListView.LAYOUT_SET_SELECTION;
}
// Restore selection
this.setNextSelectedPositionInt(newPos);
return;
}
}
}
break;
case AbsListView.SYNC_FIRST_POSITION:
// Leave mSyncPosition as it is -- just pin to available range
this.mLayoutMode = AbsListView.LAYOUT_SYNC;
this.mSyncPosition = Math.min(Math.max(0, this.mSyncPosition), count - 1);
return;
}
}
if (!this.isInTouchMode()) {
// We couldn't find matching data -- try to use the same position
newPos = this.getSelectedItemPosition();
// Pin position to the available range
if (newPos >= count) {
newPos = count - 1;
}
if (newPos < 0) {
newPos = 0;
}
// Make sure we select something selectable -- first look down
selectablePos = this.lookForSelectablePosition(newPos, true);
if (selectablePos >= 0) {
this.setNextSelectedPositionInt(selectablePos);
return;
} else {
// Looking down didn't work -- try looking up
selectablePos = this.lookForSelectablePosition(newPos, false);
if (selectablePos >= 0) {
this.setNextSelectedPositionInt(selectablePos);
return;
}
}
} else {
// We already know where we want to resurrect the selection
if (this.mResurrectToPosition >= 0) {
return;
}
}
}
// Nothing is selected. Give up and reset everything.
this.mLayoutMode = this.mStackFromBottom ? AbsListView.LAYOUT_FORCE_BOTTOM : AbsListView.LAYOUT_FORCE_TOP;
this.mSelectedPosition = AbsListView.INVALID_POSITION;
this.mSelectedRowId = AbsListView.INVALID_ROW_ID;
this.mNextSelectedPosition = AbsListView.INVALID_POSITION;
this.mNextSelectedRowId = AbsListView.INVALID_ROW_ID;
this.mNeedSync = false;
this.mPendingSync = null;
this.mSelectorPosition = AbsListView.INVALID_POSITION;
this.checkSelectionChanged();
}
onDisplayHint(hint:number):void {
super.onDisplayHint(hint);
//switch (hint) {
// case AbsListView.INVISIBLE:
// if (this.mPopup != null && this.mPopup.isShowing()) {
// this.dismissPopup();
// }
// break;
// case AbsListView.VISIBLE:
// if (this.mFiltered && this.mPopup != null && !this.mPopup.isShowing()) {
// this.showPopup();
// }
// break;
//}
this.mPopupHidden = hint == AbsListView.INVISIBLE;
}
/**
* Removes the filter window
*/
private dismissPopup():void {
//if (this.mPopup != null) {
// this.mPopup.dismiss();
//}
}
/**
* Shows the filter window
*/
private showPopup():void {
// Make sure we have a window before showing the popup
//if (this.getWindowVisibility() == View.VISIBLE) {
// this.createTextFilter(true);
// this.positionPopup();
// // Make sure we get focus if we are showing the popup
// this.checkFocus();
//}
}
private positionPopup():void {
//let screenHeight:number = Resources.getDisplayMetrics().heightPixels;
//const xy:number[] = [2];
//this.getLocationOnScreen(xy);
//// TODO: The 20 below should come from the theme
//// TODO: And the gravity should be defined in the theme as well
//const bottomGap:number = screenHeight - xy[1] - this.getHeight() + Math.floor((this.mDensityScale * 20));
//if (!this.mPopup.isShowing()) {
// this.mPopup.showAtLocation(this, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, xy[0], bottomGap);
//} else {
// this.mPopup.update(xy[0], bottomGap, -1, -1);
//}
}
/**
* What is the distance between the source and destination rectangles given the direction of
* focus navigation between them? The direction basically helps figure out more quickly what is
* self evident by the relationship between the rects...
*
* @param source the source rectangle
* @param dest the destination rectangle
* @param direction the direction
* @return the distance between the rectangles
*/
static getDistance(source:Rect, dest:Rect, direction:number):number {
// source x, y
let sX:number, sY:number;
// dest x, y
let dX:number, dY:number;
switch (direction) {
case View.FOCUS_RIGHT:
sX = source.right;
sY = source.top + source.height() / 2;
dX = dest.left;
dY = dest.top + dest.height() / 2;
break;
case View.FOCUS_DOWN:
sX = source.left + source.width() / 2;
sY = source.bottom;
dX = dest.left + dest.width() / 2;
dY = dest.top;
break;
case View.FOCUS_LEFT:
sX = source.left;
sY = source.top + source.height() / 2;
dX = dest.right;
dY = dest.top + dest.height() / 2;
break;
case View.FOCUS_UP:
sX = source.left + source.width() / 2;
sY = source.top;
dX = dest.left + dest.width() / 2;
dY = dest.bottom;
break;
case View.FOCUS_FORWARD:
case View.FOCUS_BACKWARD:
sX = source.right + source.width() / 2;
sY = source.top + source.height() / 2;
dX = dest.left + dest.width() / 2;
dY = dest.top + dest.height() / 2;
break;
default:
throw Error(`new IllegalArgumentException("direction must be one of " + "{FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, " + "FOCUS_FORWARD, FOCUS_BACKWARD}.")`);
}
let deltaX:number = dX - sX;
let deltaY:number = dY - sY;
return deltaY * deltaY + deltaX * deltaX;
}
isInFilterMode():boolean {
return this.mFiltered;
}
/**
* Sends a key to the text filter window
*
* @param keyCode The keycode for the event
* @param event The actual key event
*
* @return True if the text filter handled the event, false otherwise.
*/
//private sendToTextFilter(keyCode:number, count:number, event:KeyEvent):boolean {
// if (!this.acceptFilter()) {
// return false;
// }
// let handled:boolean = false;
// let okToSend:boolean = true;
// switch (keyCode) {
// case KeyEvent.KEYCODE_DPAD_UP:
// case KeyEvent.KEYCODE_DPAD_DOWN:
// case KeyEvent.KEYCODE_DPAD_LEFT:
// case KeyEvent.KEYCODE_DPAD_RIGHT:
// case KeyEvent.KEYCODE_DPAD_CENTER:
// case KeyEvent.KEYCODE_ENTER:
// okToSend = false;
// break;
// case KeyEvent.KEYCODE_BACK:
// if (this.mFiltered && this.mPopup != null && this.mPopup.isShowing()) {
// if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) {
// let state:KeyEvent.DispatcherState = this.getKeyDispatcherState();
// if (state != null) {
// state.startTracking(event, this);
// }
// handled = true;
// } else if (event.getAction() == KeyEvent.ACTION_UP && event.isTracking() && !event.isCanceled()) {
// handled = true;
// this.mTextFilter.setText("");
// }
// }
// okToSend = false;
// break;
// case KeyEvent.KEYCODE_SPACE:
// // Only send spaces once we are filtered
// okToSend = this.mFiltered;
// break;
// }
// if (okToSend) {
// this.createTextFilter(true);
// let forwardEvent:KeyEvent = event;
// if (forwardEvent.getRepeatCount() > 0) {
// forwardEvent = KeyEvent.changeTimeRepeat(event, event.getEventTime(), 0);
// }
// let action:number = event.getAction();
// switch (action) {
// case KeyEvent.ACTION_DOWN:
// handled = this.mTextFilter.onKeyDown(keyCode, forwardEvent);
// break;
// case KeyEvent.ACTION_UP:
// handled = this.mTextFilter.onKeyUp(keyCode, forwardEvent);
// break;
// case KeyEvent.ACTION_MULTIPLE:
// handled = this.mTextFilter.onKeyMultiple(keyCode, count, event);
// break;
// }
// }
// return handled;
//}
//
///**
// * Return an InputConnection for editing of the filter text.
// */
//onCreateInputConnection(outAttrs:EditorInfo):InputConnection {
// if (this.isTextFilterEnabled()) {
// if (this.mPublicInputConnection == null) {
// this.mDefInputConnection = new BaseInputConnection(this, false);
// this.mPublicInputConnection = new AbsListView.InputConnectionWrapper(outAttrs);
// }
// outAttrs.inputType = EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_FILTER;
// outAttrs.imeOptions = EditorInfo.IME_ACTION_DONE;
// return this.mPublicInputConnection;
// }
// return null;
//}
//
//
///**
// * For filtering we proxy an input connection to an internal text editor,
// * and this allows the proxying to happen.
// */
//checkInputConnectionProxy(view:View):boolean {
// return view == this.mTextFilter;
//}
//
///**
// * Creates the window for the text filter and populates it with an EditText field;
// *
// * @param animateEntrance true if the window should appear with an animation
// */
//private createTextFilter(animateEntrance:boolean):void {
// if (this.mPopup == null) {
// let p:PopupWindow = new PopupWindow(this.getContext());
// p.setFocusable(false);
// p.setTouchable(false);
// p.setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED);
// p.setContentView(this.getTextFilterInput());
// p.setWidth(LayoutParams.WRAP_CONTENT);
// p.setHeight(LayoutParams.WRAP_CONTENT);
// p.setBackgroundDrawable(null);
// this.mPopup = p;
// this.getViewTreeObserver().addOnGlobalLayoutListener(this);
// this.mGlobalLayoutListenerAddedFilter = true;
// }
// if (animateEntrance) {
// this.mPopup.setAnimationStyle(com.android.internal.R.style.Animation_TypingFilter);
// } else {
// this.mPopup.setAnimationStyle(com.android.internal.R.style.Animation_TypingFilterRestore);
// }
//}
//
//private getTextFilterInput():EditText {
// if (this.mTextFilter == null) {
// const layoutInflater:LayoutInflater = LayoutInflater.from(this.getContext());
// this.mTextFilter = <EditText> layoutInflater.inflate(com.android.internal.R.layout.typing_filter, null);
// // For some reason setting this as the "real" input type changes
// // the text view in some way that it doesn't work, and I don't
// // want to figure out why this is.
// this.mTextFilter.setRawInputType(EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_FILTER);
// this.mTextFilter.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI);
// this.mTextFilter.addTextChangedListener(this);
// }
// return this.mTextFilter;
//}
//
///**
// * Clear the text filter.
// */
//clearTextFilter():void {
// if (this.mFiltered) {
// this.getTextFilterInput().setText("");
// this.mFiltered = false;
// if (this.mPopup != null && this.mPopup.isShowing()) {
// this.dismissPopup();
// }
// }
//}
//
/**
* Returns if the ListView currently has a text filter.
*/
hasTextFilter():boolean {
return this.mFiltered;
}
onGlobalLayout():void {
if (this.isShown()) {
// Show the popup if we are filtered
//if (this.mFiltered && this.mPopup != null && !this.mPopup.isShowing() && !this.mPopupHidden) {
// this.showPopup();
//}
} else {
// Hide the popup when we are no longer visible
//if (this.mPopup != null && this.mPopup.isShowing()) {
// this.dismissPopup();
//}
}
}
//
///**
// * For our text watcher that is associated with the text filter. Does
// * nothing.
// */
//beforeTextChanged(s:string, start:number, count:number, after:number):void {
//}
//
///**
// * For our text watcher that is associated with the text filter. Performs
// * the actual filtering as the text changes, and takes care of hiding and
// * showing the popup displaying the currently entered filter text.
// */
//onTextChanged(s:string, start:number, before:number, count:number):void {
// if (this.isTextFilterEnabled()) {
// this.createTextFilter(true);
// let length:number = s.length();
// let showing:boolean = this.mPopup.isShowing();
// if (!showing && length > 0) {
// // Show the filter popup if necessary
// this.showPopup();
// this.mFiltered = true;
// } else if (showing && length == 0) {
// // Remove the filter popup if the user has cleared all text
// this.dismissPopup();
// this.mFiltered = false;
// }
// if (this.mAdapter instanceof Filterable) {
// let f:Filter = (<Filterable> this.mAdapter).getFilter();
// // Filter should not be null when we reach this part
// if (f != null) {
// f.filter(s, this);
// } else {
// throw Error(`new IllegalStateException("You cannot call onTextChanged with a non " + "filterable adapter")`);
// }
// }
// }
//}
//
///**
// * For our text watcher that is associated with the text filter. Does
// * nothing.
// */
//afterTextChanged(s):void {
//}
//
//onFilterComplete(count:number):void {
// if (mSelectedPosition < 0 && count > 0) {
// this.mResurrectToPosition = AbsListView.INVALID_POSITION;
// this.resurrectSelection();
// }
//}
protected generateDefaultLayoutParams():ViewGroup.LayoutParams {
return new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, 0);
}
protected generateLayoutParams(p:ViewGroup.LayoutParams):ViewGroup.LayoutParams {
return new AbsListView.LayoutParams(p);
}
generateLayoutParamsFromAttr(attrs:HTMLElement):ViewGroup.LayoutParams {
return new AbsListView.LayoutParams(this.getContext(), attrs);
}
protected checkLayoutParams(p:ViewGroup.LayoutParams):boolean {
return p instanceof AbsListView.LayoutParams;
}
/**
* Puts the list or grid into transcript mode. In this mode the list or grid will always scroll
* to the bottom to show new items.
*
* @param mode the transcript mode to set
*
* @see #TRANSCRIPT_MODE_DISABLED
* @see #TRANSCRIPT_MODE_NORMAL
* @see #TRANSCRIPT_MODE_ALWAYS_SCROLL
*/
setTranscriptMode(mode:number):void {
this.mTranscriptMode = mode;
}
/**
* Returns the current transcript mode.
*
* @return {@link #TRANSCRIPT_MODE_DISABLED}, {@link #TRANSCRIPT_MODE_NORMAL} or
* {@link #TRANSCRIPT_MODE_ALWAYS_SCROLL}
*/
getTranscriptMode():number {
return this.mTranscriptMode;
}
getSolidColor():number {
return this.mCacheColorHint;
}
/**
* When set to a non-zero value, the cache color hint indicates that this list is always drawn
* on top of a solid, single-color, opaque background.
*
* Zero means that what's behind this object is translucent (non solid) or is not made of a
* single color. This hint will not affect any existing background drawable set on this view (
* typically set via {@link #setBackgroundDrawable(Drawable)}).
*
* @param color The background color
*/
setCacheColorHint(color:number):void {
if (color != this.mCacheColorHint) {
this.mCacheColorHint = color;
let count:number = this.getChildCount();
for (let i:number = 0; i < count; i++) {
this.getChildAt(i).setDrawingCacheBackgroundColor(color);
}
this.mRecycler.setCacheColorHint(color);
}
}
/**
* When set to a non-zero value, the cache color hint indicates that this list is always drawn
* on top of a solid, single-color, opaque background
*
* @return The cache color hint
*/
getCacheColorHint():number {
return this.mCacheColorHint;
}
/**
* Move all views (excluding headers and footers) held by this AbsListView into the supplied
* List. This includes views displayed on the screen as well as views stored in AbsListView's
* internal view recycler.
*
* @param views A list into which to put the reclaimed views
*/
reclaimViews(views:List<View>):void {
let childCount:number = this.getChildCount();
let listener:AbsListView.RecyclerListener = this.mRecycler.mRecyclerListener;
// Reclaim views on screen
for (let i:number = 0; i < childCount; i++) {
let child:View = this.getChildAt(i);
let lp:AbsListView.LayoutParams = <AbsListView.LayoutParams> child.getLayoutParams();
// Don't reclaim header or footer views, or views that should be ignored
if (lp != null && this.mRecycler.shouldRecycleViewType(lp.viewType)) {
views.add(child);
//child.setAccessibilityDelegate(null);
if (listener != null) {
// Pretend they went through the scrap heap
listener.onMovedToScrapHeap(child);
}
}
}
this.mRecycler.reclaimScrapViews(views);
this.removeAllViewsInLayout();
}
private finishGlows():void {
//if (this.mEdgeGlowTop != null) {
// this.mEdgeGlowTop.finish();
// this.mEdgeGlowBottom.finish();
//}
}
///**
// * Sets up this AbsListView to use a remote views adapter which connects to a RemoteViewsService
// * through the specified intent.
// * @param intent the intent used to identify the RemoteViewsService for the adapter to connect to.
// */
//setRemoteViewsAdapter(intent:Intent):void {
// // service handling the specified intent.
// if (this.mRemoteAdapter != null) {
// let fcNew:Intent.FilterComparison = new Intent.FilterComparison(intent);
// let fcOld:Intent.FilterComparison = new Intent.FilterComparison(this.mRemoteAdapter.getRemoteViewsServiceIntent());
// if (fcNew.equals(fcOld)) {
// return;
// }
// }
// this.mDeferNotifyDataSetChanged = false;
// // Otherwise, create a new RemoteViewsAdapter for binding
// this.mRemoteAdapter = new RemoteViewsAdapter(this.getContext(), intent, this);
// if (this.mRemoteAdapter.isDataReady()) {
// this.setAdapter(this.mRemoteAdapter);
// }
//}
//
///**
// * Sets up the onClickHandler to be used by the RemoteViewsAdapter when inflating RemoteViews
// *
// * @param handler The OnClickHandler to use when inflating RemoteViews.
// *
// * @hide
// */
//setRemoteViewsOnClickHandler(handler:OnClickHandler):void {
// // service handling the specified intent.
// if (this.mRemoteAdapter != null) {
// this.mRemoteAdapter.setRemoteViewsOnClickHandler(handler);
// }
//}
//
///**
// * This defers a notifyDataSetChanged on the pending RemoteViewsAdapter if it has not
// * connected yet.
// */
//deferNotifyDataSetChanged():void {
// this.mDeferNotifyDataSetChanged = true;
//}
//
///**
// * Called back when the adapter connects to the RemoteViewsService.
// */
//onRemoteAdapterConnected():boolean {
// if (this.mRemoteAdapter != this.mAdapter) {
// this.setAdapter(this.mRemoteAdapter);
// if (this.mDeferNotifyDataSetChanged) {
// this.mRemoteAdapter.notifyDataSetChanged();
// this.mDeferNotifyDataSetChanged = false;
// }
// return false;
// } else if (this.mRemoteAdapter != null) {
// this.mRemoteAdapter.superNotifyDataSetChanged();
// return true;
// }
// return false;
//}
//
///**
// * Called back when the adapter disconnects from the RemoteViewsService.
// */
//onRemoteAdapterDisconnected():void {
// // If the remote adapter disconnects, we keep it around
// // since the currently displayed items are still cached.
// // Further, we want the service to eventually reconnect
// // when necessary, as triggered by this view requesting
// // items from the Adapter.
//}
//
///**
// * Hints the RemoteViewsAdapter, if it exists, about which views are currently
// * being displayed by the AbsListView.
// */
setVisibleRangeHint(start:number, end:number):void {
//if (this.mRemoteAdapter != null) {
// this.mRemoteAdapter.setVisibleRangeHint(start, end);
//}
}
/**
* Sets the recycler listener to be notified whenever a View is set aside in
* the recycler for later reuse. This listener can be used to free resources
* associated to the View.
*
* @param listener The recycler listener to be notified of views set aside
* in the recycler.
*
* @see android.widget.AbsListView.RecycleBin
* @see android.widget.AbsListView.RecyclerListener
*/
setRecyclerListener(listener:AbsListView.RecyclerListener):void {
this.mRecycler.mRecyclerListener = listener;
}
static retrieveFromScrap(scrapViews:ArrayList<View>, position:number):View {
let size:number = scrapViews.size();
if (size > 0) {
// See if we still have a view for this position.
for (let i:number = 0; i < size; i++) {
let view:View = scrapViews.get(i);
if ((<AbsListView.LayoutParams> view.getLayoutParams()).scrappedFromPosition == position) {
scrapViews.remove(i);
return view;
}
}
return scrapViews.remove(size - 1);
} else {
return null;
}
}
}
export module AbsListView {
/**
* Interface definition for a callback to be invoked when the list or grid
* has been scrolled.
*/
export interface OnScrollListener {
/**
* Callback method to be invoked while the list view or grid view is being scrolled. If the
* view is being scrolled, this method will be called before the next frame of the scroll is
* rendered. In particular, it will be called before any calls to
* {@link Adapter#getView(int, View, ViewGroup)}.
*
* @param view The view whose scroll state is being reported
*
* @param scrollState The current scroll state. One of {@link #SCROLL_STATE_IDLE},
* {@link #SCROLL_STATE_TOUCH_SCROLL} or {@link #SCROLL_STATE_IDLE}.
*/
onScrollStateChanged(view:AbsListView, scrollState:number):void ;
/**
* Callback method to be invoked when the list or grid has been scrolled. This will be
* called after the scroll has completed
* @param view The view whose scroll state is being reported
* @param firstVisibleItem the index of the first visible cell (ignore if
* visibleItemCount == 0)
* @param visibleItemCount the number of visible cells
* @param totalItemCount the number of items in the list adaptor
*/
onScroll(view:AbsListView, firstVisibleItem:number, visibleItemCount:number, totalItemCount:number):void ;
}
export module OnScrollListener {
/**
* The view is not scrolling. Note navigating the list using the trackball counts as
* being in the idle state since these transitions are not animated.
*/
export var SCROLL_STATE_IDLE:number = 0;
/**
* The user is scrolling using touch, and their finger is still on the screen
*/
export var SCROLL_STATE_TOUCH_SCROLL:number = 1;
/**
* The user had previously been scrolling using touch and had performed a fling. The
* animation is now coasting to a stop
*/
export var SCROLL_STATE_FLING:number = 2;
}
/**
* The top-level view of a list item can implement this interface to allow
* itself to modify the bounds of the selection shown for that item.
*/
export interface SelectionBoundsAdjuster {
/**
* Called to allow the list item to adjust the bounds shown for
* its selection.
*
* @param bounds On call, this contains the bounds the list has
* selected for the item (that is the bounds of the entire view). The
* values can be modified as desired.
*/
adjustListItemSelectionBounds(bounds:Rect):void ;
}
/**
* A base class for Runnables that will check that their view is still attached to
* the original window as when the Runnable was created.
*
*/
export class WindowRunnnable {
_AbsListView_this:AbsListView;
constructor(arg:AbsListView) {
this._AbsListView_this = arg;
}
private mOriginalAttachCount:number;
rememberWindowAttachCount():void {
this.mOriginalAttachCount = this._AbsListView_this.getWindowAttachCount();
}
sameWindow():boolean {
return this._AbsListView_this.getWindowAttachCount() == this.mOriginalAttachCount;
}
}
export class PerformClick extends AbsListView.WindowRunnnable implements Runnable {
_AbsListView_this:AbsListView;
constructor(arg:AbsListView) {
super(arg);
this._AbsListView_this = arg;
}
mClickMotionPosition:number = 0;
run():void {
// bail out before bad things happen
if (this._AbsListView_this.mDataChanged)
return;
const adapter:ListAdapter = this._AbsListView_this.mAdapter;
const motionPosition:number = this.mClickMotionPosition;
if (adapter != null && this._AbsListView_this.mItemCount > 0 && motionPosition != AbsListView.INVALID_POSITION
&& motionPosition < adapter.getCount() && this.sameWindow()) {
const view:View = this._AbsListView_this.getChildAt(motionPosition - this._AbsListView_this.mFirstPosition);
// screen, etc.) and we should cancel the click
if (view != null) {
this._AbsListView_this.performItemClick(view, motionPosition, adapter.getItemId(motionPosition));
}
}
}
}
export class CheckForLongPress extends AbsListView.WindowRunnnable implements Runnable {
_AbsListView_this:AbsListView;
constructor(arg:AbsListView) {
super(arg);
this._AbsListView_this = arg;
}
run():void {
const motionPosition:number = this._AbsListView_this.mMotionPosition;
const child:View = this._AbsListView_this.getChildAt(motionPosition - this._AbsListView_this.mFirstPosition);
if (child != null) {
const longPressPosition:number = this._AbsListView_this.mMotionPosition;
const longPressId:number = this._AbsListView_this.mAdapter.getItemId(this._AbsListView_this.mMotionPosition);
let handled:boolean = false;
if (this.sameWindow() && !this._AbsListView_this.mDataChanged) {
handled = this._AbsListView_this.performLongPress(child, longPressPosition, longPressId);
}
if (handled) {
this._AbsListView_this.mTouchMode = AbsListView.TOUCH_MODE_REST;
this._AbsListView_this.setPressed(false);
child.setPressed(false);
} else {
this._AbsListView_this.mTouchMode = AbsListView.TOUCH_MODE_DONE_WAITING;
}
}
}
}
export class CheckForKeyLongPress extends AbsListView.WindowRunnnable implements Runnable {
_AbsListView_this:AbsListView;
constructor(arg:AbsListView) {
super(arg);
this._AbsListView_this = arg;
}
run():void {
if (this._AbsListView_this.isPressed() && this._AbsListView_this.mSelectedPosition >= 0) {
let index:number = this._AbsListView_this.mSelectedPosition - this._AbsListView_this.mFirstPosition;
let v:View = this._AbsListView_this.getChildAt(index);
if (!this._AbsListView_this.mDataChanged) {
let handled:boolean = false;
if (this.sameWindow()) {
handled = this._AbsListView_this.performLongPress(v,
this._AbsListView_this.mSelectedPosition, this._AbsListView_this.mSelectedRowId);
}
if (handled) {
this._AbsListView_this.setPressed(false);
v.setPressed(false);
}
} else {
this._AbsListView_this.setPressed(false);
if (v != null)
v.setPressed(false);
}
}
}
}
export class CheckForTap implements Runnable {
_AbsListView_this:AbsListView;
constructor(arg:AbsListView) {
this._AbsListView_this = arg;
}
run():void {
if (this._AbsListView_this.mTouchMode == AbsListView.TOUCH_MODE_DOWN) {
this._AbsListView_this.mTouchMode = AbsListView.TOUCH_MODE_TAP;
const child:View = this._AbsListView_this.getChildAt(
this._AbsListView_this.mMotionPosition - this._AbsListView_this.mFirstPosition);
if (child != null && !child.hasFocusable()) {
this._AbsListView_this.mLayoutMode = AbsListView.LAYOUT_NORMAL;
if (!this._AbsListView_this.mDataChanged) {
child.setPressed(true);
this._AbsListView_this.setPressed(true);
this._AbsListView_this.layoutChildren();
this._AbsListView_this.positionSelector(this._AbsListView_this.mMotionPosition, child);
this._AbsListView_this.refreshDrawableState();
const longPressTimeout:number = ViewConfiguration.getLongPressTimeout();
const longClickable:boolean = this._AbsListView_this.isLongClickable();
if (this._AbsListView_this.mSelector != null) {
let d:Drawable = this._AbsListView_this.mSelector.getCurrent();
//TODO when transition drawable impl
//if (d != null && d instanceof TransitionDrawable) {
// if (longClickable) {
// (<TransitionDrawable> d).startTransition(longPressTimeout);
// } else {
// (<TransitionDrawable> d).resetTransition();
// }
//}
}
if (longClickable) {
if (this._AbsListView_this.mPendingCheckForLongPress_List == null) {
this._AbsListView_this.mPendingCheckForLongPress_List = new AbsListView.CheckForLongPress(this._AbsListView_this);
}
this._AbsListView_this.mPendingCheckForLongPress_List.rememberWindowAttachCount();
this._AbsListView_this.postDelayed(this._AbsListView_this.mPendingCheckForLongPress_List, longPressTimeout);
} else {
this._AbsListView_this.mTouchMode = AbsListView.TOUCH_MODE_DONE_WAITING;
}
} else {
this._AbsListView_this.mTouchMode = AbsListView.TOUCH_MODE_DONE_WAITING;
}
}
}
}
}
/**
* Responsible for fling behavior. Use {@link #start(int)} to
* initiate a fling. Each frame of the fling is handled in {@link #run()}.
* A FlingRunnable will keep re-posting itself until the fling is done.
*
*/
export class FlingRunnable implements Runnable {
_AbsListView_this:AbsListView;
constructor(arg:AbsListView) {
this._AbsListView_this = arg;
this.mScroller = new OverScroller();
}
/**
* Tracks the decay of a fling scroll
*/
mScroller:OverScroller;
/**
* Y value reported by mScroller on the previous fling
*/
private mLastFlingY:number = 0;
private mCheckFlywheel:Runnable = (()=> {
const inner_this = this;
class _Inner implements Runnable {
run():void {
const activeId:number = inner_this._AbsListView_this.mActivePointerId;
const vt:VelocityTracker = inner_this._AbsListView_this.mVelocityTracker;
const scroller:OverScroller = inner_this.mScroller;
if (vt == null || activeId == AbsListView.INVALID_POINTER) {
return;
}
vt.computeCurrentVelocity(1000, inner_this._AbsListView_this.mMaximumVelocity);
const yvel:number = -vt.getYVelocity(activeId);
if (Math.abs(yvel) >= inner_this._AbsListView_this.mMinimumVelocity && scroller.isScrollingInDirection(0, yvel)) {
// Keep the fling alive a little longer
inner_this._AbsListView_this.postDelayed(inner_this, FlingRunnable.FLYWHEEL_TIMEOUT);
} else {
inner_this.endFling();
inner_this._AbsListView_this.mTouchMode = AbsListView.TOUCH_MODE_SCROLL;
inner_this._AbsListView_this.reportScrollStateChange(OnScrollListener.SCROLL_STATE_TOUCH_SCROLL);
}
}
}
return new _Inner();
})();
// milliseconds
static FLYWHEEL_TIMEOUT:number = 40;
start(initialVelocity:number):void {
let initialY:number = initialVelocity < 0 ? Integer.MAX_VALUE : 0;
this.mLastFlingY = initialY;
this.mScroller.setInterpolator(null);
this.mScroller.fling(0, initialY, 0, initialVelocity, 0, Integer.MAX_VALUE, 0, Integer.MAX_VALUE);
this._AbsListView_this.mTouchMode = AbsListView.TOUCH_MODE_FLING;
this._AbsListView_this.postOnAnimation(this);
if (AbsListView.PROFILE_FLINGING) {
if (!this._AbsListView_this.mFlingProfilingStarted) {
//Debug.startMethodTracing("AbsListViewFling");
this._AbsListView_this.mFlingProfilingStarted = true;
}
}
//if (this._AbsListView_this.mFlingStrictSpan == null) {
// this._AbsListView_this.mFlingStrictSpan = StrictMode.enterCriticalSpan("AbsListView-fling");
//}
}
startSpringback():void {
if (this.mScroller.springBack(0, this._AbsListView_this.mScrollY, 0, 0, 0, 0)) {
this._AbsListView_this.mTouchMode = AbsListView.TOUCH_MODE_OVERFLING;
this._AbsListView_this.invalidate();
this._AbsListView_this.postOnAnimation(this);
} else {
this._AbsListView_this.mTouchMode = AbsListView.TOUCH_MODE_REST;
this._AbsListView_this.reportScrollStateChange(OnScrollListener.SCROLL_STATE_IDLE);
}
}
startOverfling(initialVelocity:number):void {
this.mScroller.setInterpolator(null);
let minY = Integer.MIN_VALUE, maxY = Integer.MAX_VALUE;
if(this._AbsListView_this.mScrollY < 0) minY = 0;
else if(this._AbsListView_this.mScrollY > 0) maxY = 0;
this.mScroller.fling(0, this._AbsListView_this.mScrollY, 0, initialVelocity, 0, 0, minY, maxY, 0, this._AbsListView_this.getHeight());
this._AbsListView_this.mTouchMode = AbsListView.TOUCH_MODE_OVERFLING;
this._AbsListView_this.invalidate();
this._AbsListView_this.postOnAnimation(this);
}
private edgeReached(delta:number):void {
this.mScroller.notifyVerticalEdgeReached(this._AbsListView_this.mScrollY, 0, this._AbsListView_this.mOverflingDistance);
const overscrollMode:number = this._AbsListView_this.getOverScrollMode();
if (overscrollMode == AbsListView.OVER_SCROLL_ALWAYS || (overscrollMode == AbsListView.OVER_SCROLL_IF_CONTENT_SCROLLS && !this._AbsListView_this.contentFits())) {
this._AbsListView_this.mTouchMode = AbsListView.TOUCH_MODE_OVERFLING;
//const vel:number = Math.floor(this.mScroller.getCurrVelocity());
//if (delta > 0) {
// this._AbsListView_this.mEdgeGlowTop.onAbsorb(vel);
//} else {
// this._AbsListView_this.mEdgeGlowBottom.onAbsorb(vel);
//}
} else {
this._AbsListView_this.mTouchMode = AbsListView.TOUCH_MODE_REST;
if (this._AbsListView_this.mPositionScroller != null) {
this._AbsListView_this.mPositionScroller.stop();
}
}
this._AbsListView_this.invalidate();
this._AbsListView_this.postOnAnimation(this);
}
startScroll(distance:number, duration:number, linear:boolean):void {
let initialY:number = distance < 0 ? Integer.MAX_VALUE : 0;
this.mLastFlingY = initialY;
this.mScroller.setInterpolator(linear ? AbsListView.sLinearInterpolator : null);
this.mScroller.startScroll(0, initialY, 0, distance, duration);
this._AbsListView_this.mTouchMode = AbsListView.TOUCH_MODE_FLING;
this._AbsListView_this.postOnAnimation(this);
}
endFling():void {
this._AbsListView_this.mTouchMode = AbsListView.TOUCH_MODE_REST;
this._AbsListView_this.removeCallbacks(this);
this._AbsListView_this.removeCallbacks(this.mCheckFlywheel);
this._AbsListView_this.reportScrollStateChange(OnScrollListener.SCROLL_STATE_IDLE);
this._AbsListView_this.clearScrollingCache();
this.mScroller.abortAnimation();
//if (this._AbsListView_this.mFlingStrictSpan != null) {
// this._AbsListView_this.mFlingStrictSpan.finish();
// this._AbsListView_this.mFlingStrictSpan = null;
//}
}
flywheelTouch():void {
this._AbsListView_this.postDelayed(this.mCheckFlywheel, FlingRunnable.FLYWHEEL_TIMEOUT);
}
run():void {
switch (this._AbsListView_this.mTouchMode) {
default:
this.endFling();
return;
case AbsListView.TOUCH_MODE_SCROLL:
if (this.mScroller.isFinished()) {
return;
}
// Fall through
case AbsListView.TOUCH_MODE_FLING:
{
if (this._AbsListView_this.mDataChanged) {
this._AbsListView_this.layoutChildren();
}
if (this._AbsListView_this.mItemCount == 0 || this._AbsListView_this.getChildCount() == 0) {
this.endFling();
return;
}
const scroller:OverScroller = this.mScroller;
let more:boolean = scroller.computeScrollOffset();
const y:number = scroller.getCurrY();
// Flip sign to convert finger direction to list items direction
// (e.g. finger moving down means list is moving towards the top)
let delta:number = this.mLastFlingY - y;
// Pretend that each frame of a fling scroll is a touch scroll
if (delta > 0) {
// List is moving towards the top. Use first view as mMotionPosition
this._AbsListView_this.mMotionPosition = this._AbsListView_this.mFirstPosition;
const firstView:View = this._AbsListView_this.getChildAt(0);
this._AbsListView_this.mMotionViewOriginalTop = firstView.getTop();
// Don't fling more than 1 screen
delta = Math.min(this._AbsListView_this.getHeight() - this._AbsListView_this.mPaddingBottom - this._AbsListView_this.mPaddingTop - 1, delta);
} else {
// List is moving towards the bottom. Use last view as mMotionPosition
let offsetToLast:number = this._AbsListView_this.getChildCount() - 1;
this._AbsListView_this.mMotionPosition = this._AbsListView_this.mFirstPosition + offsetToLast;
const lastView:View = this._AbsListView_this.getChildAt(offsetToLast);
this._AbsListView_this.mMotionViewOriginalTop = lastView.getTop();
// Don't fling more than 1 screen
delta = Math.max(-(this._AbsListView_this.getHeight() - this._AbsListView_this.mPaddingBottom - this._AbsListView_this.mPaddingTop - 1), delta);
}
// Check to see if we have bumped into the scroll limit
let motionView:View = this._AbsListView_this.getChildAt(this._AbsListView_this.mMotionPosition - this._AbsListView_this.mFirstPosition);
let oldTop:number = 0;
if (motionView != null) {
oldTop = motionView.getTop();
}
// Don't stop just because delta is zero (it could have been rounded)
const atEdge:boolean = this._AbsListView_this.trackMotionScroll(delta, delta);
const atEnd:boolean = atEdge && (delta != 0);
if (atEnd) {
if (motionView != null) {
// Tweak the scroll for how far we overshot
let overshoot:number = -(delta - (motionView.getTop() - oldTop));
this._AbsListView_this.overScrollBy(0, overshoot, 0, this._AbsListView_this.mScrollY, 0, 0, 0, this._AbsListView_this.mOverflingDistance, false);
}
if (more) {
this.edgeReached(delta);
}
break;
}
if (more && !atEnd) {
if (atEdge)
this._AbsListView_this.invalidate();
this.mLastFlingY = y;
this._AbsListView_this.postOnAnimation(this);
} else {
this.endFling();
if (AbsListView.PROFILE_FLINGING) {
if (this._AbsListView_this.mFlingProfilingStarted) {
//Debug.stopMethodTracing();
this._AbsListView_this.mFlingProfilingStarted = false;
}
//if (this._AbsListView_this.mFlingStrictSpan != null) {
// this._AbsListView_this.mFlingStrictSpan.finish();
// this._AbsListView_this.mFlingStrictSpan = null;
//}
}
}
break;
}
case AbsListView.TOUCH_MODE_OVERFLING:
{
const scroller:OverScroller = this.mScroller;
if (scroller.computeScrollOffset()) {
const scrollY:number = this._AbsListView_this.mScrollY;
const currY:number = scroller.getCurrY();
let deltaY:number = currY - scrollY;
//fix android bug: check cross scroll here, not in overScrollBy, it always false.
const crossDown:boolean = scrollY <= 0 && currY > 0;
const crossUp:boolean = scrollY >= 0 && currY < 0;
if (crossDown || crossUp) {
let velocity:number = Math.floor(scroller.getCurrVelocity());
if (crossUp) velocity = -velocity;
// Don't flywheel from this; we're just continuing things.
scroller.abortAnimation();
this.start(velocity);
deltaY = -scrollY;
}
if (this._AbsListView_this.overScrollBy(0, deltaY, 0, scrollY, 0, 0, 0, this._AbsListView_this.mOverflingDistance, false)) {
//const crossDown:boolean = scrollY <= 0 && currY > 0;
//const crossUp:boolean = scrollY >= 0 && currY < 0;
//if (crossDown || crossUp) {
// let velocity:number = Math.floor(scroller.getCurrVelocity());
// if (crossUp)
// velocity = -velocity;
// // Don't flywheel from this; we're just continuing things.
// scroller.abortAnimation();
// this.start(velocity);
//} else {
this.startSpringback();
//}
} else {
this._AbsListView_this.invalidate();
this._AbsListView_this.postOnAnimation(this);
}
} else {
this.endFling();
}
break;
}
}
}
}
export class PositionScroller implements Runnable {
_AbsListView_this:AbsListView;
constructor(arg:AbsListView) {
this._AbsListView_this = arg;
this.mExtraScroll = ViewConfiguration.get().getScaledFadingEdgeLength();
}
private static SCROLL_DURATION:number = 200;
private static MOVE_DOWN_POS:number = 1;
private static MOVE_UP_POS:number = 2;
private static MOVE_DOWN_BOUND:number = 3;
private static MOVE_UP_BOUND:number = 4;
private static MOVE_OFFSET:number = 5;
private mMode:number = 0;
private mTargetPos:number = 0;
private mBoundPos:number = 0;
private mLastSeenPos:number = 0;
private mScrollDuration:number = 0;
private mExtraScroll:number = 0;
private mOffsetFromTop:number = 0;
start(position:number, boundPosition?:number):void{
if(boundPosition==null) this._start_1(position);
else this._start_2(position, boundPosition);
}
private _start_1(position:number):void {
this.stop();
if (this._AbsListView_this.mDataChanged) {
// Wait until we're back in a stable state to try this.
this._AbsListView_this.mPositionScrollAfterLayout = (()=> {
const inner_this = this;
class _Inner implements Runnable {
run():void {
inner_this.start(position);
}
}
return new _Inner();
})();
return;
}
const childCount:number = this._AbsListView_this.getChildCount();
if (childCount == 0) {
// Can't scroll without children.
return;
}
const firstPos:number = this._AbsListView_this.mFirstPosition;
const lastPos:number = firstPos + childCount - 1;
let viewTravelCount:number;
let clampedPosition:number = Math.max(0, Math.min(this._AbsListView_this.getCount() - 1, position));
if (clampedPosition < firstPos) {
viewTravelCount = firstPos - clampedPosition + 1;
this.mMode = PositionScroller.MOVE_UP_POS;
} else if (clampedPosition > lastPos) {
viewTravelCount = clampedPosition - lastPos + 1;
this.mMode = PositionScroller.MOVE_DOWN_POS;
} else {
this.scrollToVisible(clampedPosition, AbsListView.INVALID_POSITION, PositionScroller.SCROLL_DURATION);
return;
}
if (viewTravelCount > 0) {
this.mScrollDuration = PositionScroller.SCROLL_DURATION / viewTravelCount;
} else {
this.mScrollDuration = PositionScroller.SCROLL_DURATION;
}
this.mTargetPos = clampedPosition;
this.mBoundPos = AbsListView.INVALID_POSITION;
this.mLastSeenPos = AbsListView.INVALID_POSITION;
this._AbsListView_this.postOnAnimation(this);
}
private _start_2(position:number, boundPosition:number):void {
this.stop();
if (boundPosition == AbsListView.INVALID_POSITION) {
this.start(position);
return;
}
if (this._AbsListView_this.mDataChanged) {
// Wait until we're back in a stable state to try this.
this._AbsListView_this.mPositionScrollAfterLayout = (()=> {
const inner_this = this;
class _Inner implements Runnable {
run():void {
inner_this.start(position, boundPosition);
}
}
return new _Inner();
})();
return;
}
const childCount:number = this._AbsListView_this.getChildCount();
if (childCount == 0) {
// Can't scroll without children.
return;
}
const firstPos:number = this._AbsListView_this.mFirstPosition;
const lastPos:number = firstPos + childCount - 1;
let viewTravelCount:number;
let clampedPosition:number = Math.max(0, Math.min(this._AbsListView_this.getCount() - 1, position));
if (clampedPosition < firstPos) {
const boundPosFromLast:number = lastPos - boundPosition;
if (boundPosFromLast < 1) {
// Moving would shift our bound position off the screen. Abort.
return;
}
const posTravel:number = firstPos - clampedPosition + 1;
const boundTravel:number = boundPosFromLast - 1;
if (boundTravel < posTravel) {
viewTravelCount = boundTravel;
this.mMode = PositionScroller.MOVE_UP_BOUND;
} else {
viewTravelCount = posTravel;
this.mMode = PositionScroller.MOVE_UP_POS;
}
} else if (clampedPosition > lastPos) {
const boundPosFromFirst:number = boundPosition - firstPos;
if (boundPosFromFirst < 1) {
// Moving would shift our bound position off the screen. Abort.
return;
}
const posTravel:number = clampedPosition - lastPos + 1;
const boundTravel:number = boundPosFromFirst - 1;
if (boundTravel < posTravel) {
viewTravelCount = boundTravel;
this.mMode = PositionScroller.MOVE_DOWN_BOUND;
} else {
viewTravelCount = posTravel;
this.mMode = PositionScroller.MOVE_DOWN_POS;
}
} else {
this.scrollToVisible(clampedPosition, boundPosition, PositionScroller.SCROLL_DURATION);
return;
}
if (viewTravelCount > 0) {
this.mScrollDuration = PositionScroller.SCROLL_DURATION / viewTravelCount;
} else {
this.mScrollDuration = PositionScroller.SCROLL_DURATION;
}
this.mTargetPos = clampedPosition;
this.mBoundPos = boundPosition;
this.mLastSeenPos = AbsListView.INVALID_POSITION;
this._AbsListView_this.postOnAnimation(this);
}
startWithOffset(position:number, offset:number, duration:number = PositionScroller.SCROLL_DURATION):void {
this.stop();
if (this._AbsListView_this.mDataChanged) {
// Wait until we're back in a stable state to try this.
const postOffset:number = offset;
this._AbsListView_this.mPositionScrollAfterLayout = (()=> {
const inner_this = this;
class _Inner implements Runnable {
run():void {
inner_this.startWithOffset(position, postOffset, duration);
}
}
return new _Inner();
})();
return;
}
const childCount:number = this._AbsListView_this.getChildCount();
if (childCount == 0) {
// Can't scroll without children.
return;
}
offset += this._AbsListView_this.getPaddingTop();
this.mTargetPos = Math.max(0, Math.min(this._AbsListView_this.getCount() - 1, position));
this.mOffsetFromTop = offset;
this.mBoundPos = AbsListView.INVALID_POSITION;
this.mLastSeenPos = AbsListView.INVALID_POSITION;
this.mMode = PositionScroller.MOVE_OFFSET;
const firstPos:number = this._AbsListView_this.mFirstPosition;
const lastPos:number = firstPos + childCount - 1;
let viewTravelCount:number;
if (this.mTargetPos < firstPos) {
viewTravelCount = firstPos - this.mTargetPos;
} else if (this.mTargetPos > lastPos) {
viewTravelCount = this.mTargetPos - lastPos;
} else {
// On-screen, just scroll.
const targetTop:number = this._AbsListView_this.getChildAt(this.mTargetPos - firstPos).getTop();
this._AbsListView_this.smoothScrollBy(targetTop - offset, duration, true);
return;
}
// Estimate how many screens we should travel
const screenTravelCount:number = <number> viewTravelCount / childCount;
this.mScrollDuration = screenTravelCount < 1 ? duration : Math.floor((duration / screenTravelCount));
this.mLastSeenPos = AbsListView.INVALID_POSITION;
this._AbsListView_this.postOnAnimation(this);
}
/**
* Scroll such that targetPos is in the visible padded region without scrolling
* boundPos out of view. Assumes targetPos is onscreen.
*/
private scrollToVisible(targetPos:number, boundPos:number, duration:number):void {
const firstPos:number = this._AbsListView_this.mFirstPosition;
const childCount:number = this._AbsListView_this.getChildCount();
const lastPos:number = firstPos + childCount - 1;
const paddedTop:number = this._AbsListView_this.mListPadding.top;
const paddedBottom:number = this._AbsListView_this.getHeight() - this._AbsListView_this.mListPadding.bottom;
if (targetPos < firstPos || targetPos > lastPos) {
Log.w(AbsListView.TAG_AbsListView, "scrollToVisible called with targetPos " + targetPos + " not visible [" + firstPos + ", " + lastPos + "]");
}
if (boundPos < firstPos || boundPos > lastPos) {
// boundPos doesn't matter, it's already offscreen.
boundPos = AbsListView.INVALID_POSITION;
}
const targetChild:View = this._AbsListView_this.getChildAt(targetPos - firstPos);
const targetTop:number = targetChild.getTop();
const targetBottom:number = targetChild.getBottom();
let scrollBy:number = 0;
if (targetBottom > paddedBottom) {
scrollBy = targetBottom - paddedBottom;
}
if (targetTop < paddedTop) {
scrollBy = targetTop - paddedTop;
}
if (scrollBy == 0) {
return;
}
if (boundPos >= 0) {
const boundChild:View = this._AbsListView_this.getChildAt(boundPos - firstPos);
const boundTop:number = boundChild.getTop();
const boundBottom:number = boundChild.getBottom();
const absScroll:number = Math.abs(scrollBy);
if (scrollBy < 0 && boundBottom + absScroll > paddedBottom) {
// Don't scroll the bound view off the bottom of the screen.
scrollBy = Math.max(0, boundBottom - paddedBottom);
} else if (scrollBy > 0 && boundTop - absScroll < paddedTop) {
// Don't scroll the bound view off the top of the screen.
scrollBy = Math.min(0, boundTop - paddedTop);
}
}
this._AbsListView_this.smoothScrollBy(scrollBy, duration);
}
stop():void {
this._AbsListView_this.removeCallbacks(this);
}
run():void {
const listHeight:number = this._AbsListView_this.getHeight();
const firstPos:number = this._AbsListView_this.mFirstPosition;
switch (this.mMode) {
case PositionScroller.MOVE_DOWN_POS:
{
const lastViewIndex:number = this._AbsListView_this.getChildCount() - 1;
const lastPos:number = firstPos + lastViewIndex;
if (lastViewIndex < 0) {
return;
}
if (lastPos == this.mLastSeenPos) {
// No new views, let things keep going.
this._AbsListView_this.postOnAnimation(this);
return;
}
const lastView:View = this._AbsListView_this.getChildAt(lastViewIndex);
const lastViewHeight:number = lastView.getHeight();
const lastViewTop:number = lastView.getTop();
const lastViewPixelsShowing:number = listHeight - lastViewTop;
const extraScroll:number = lastPos < this._AbsListView_this.mItemCount - 1 ? Math.max(this._AbsListView_this.mListPadding.bottom, this.mExtraScroll) : this._AbsListView_this.mListPadding.bottom;
const scrollBy:number = lastViewHeight - lastViewPixelsShowing + extraScroll;
this._AbsListView_this.smoothScrollBy(scrollBy, this.mScrollDuration, true);
this.mLastSeenPos = lastPos;
if (lastPos < this.mTargetPos) {
this._AbsListView_this.postOnAnimation(this);
}
break;
}
case PositionScroller.MOVE_DOWN_BOUND:
{
const nextViewIndex:number = 1;
const childCount:number = this._AbsListView_this.getChildCount();
if (firstPos == this.mBoundPos || childCount <= nextViewIndex || firstPos + childCount >= this._AbsListView_this.mItemCount) {
return;
}
const nextPos:number = firstPos + nextViewIndex;
if (nextPos == this.mLastSeenPos) {
// No new views, let things keep going.
this._AbsListView_this.postOnAnimation(this);
return;
}
const nextView:View = this._AbsListView_this.getChildAt(nextViewIndex);
const nextViewHeight:number = nextView.getHeight();
const nextViewTop:number = nextView.getTop();
const extraScroll:number = Math.max(this._AbsListView_this.mListPadding.bottom, this.mExtraScroll);
if (nextPos < this.mBoundPos) {
this._AbsListView_this.smoothScrollBy(Math.max(0, nextViewHeight + nextViewTop - extraScroll), this.mScrollDuration, true);
this.mLastSeenPos = nextPos;
this._AbsListView_this.postOnAnimation(this);
} else {
if (nextViewTop > extraScroll) {
this._AbsListView_this.smoothScrollBy(nextViewTop - extraScroll, this.mScrollDuration, true);
}
}
break;
}
case PositionScroller.MOVE_UP_POS:
{
if (firstPos == this.mLastSeenPos) {
// No new views, let things keep going.
this._AbsListView_this.postOnAnimation(this);
return;
}
const firstView:View = this._AbsListView_this.getChildAt(0);
if (firstView == null) {
return;
}
const firstViewTop:number = firstView.getTop();
const extraScroll:number = firstPos > 0 ? Math.max(this.mExtraScroll, this._AbsListView_this.mListPadding.top) : this._AbsListView_this.mListPadding.top;
this._AbsListView_this.smoothScrollBy(firstViewTop - extraScroll, this.mScrollDuration, true);
this.mLastSeenPos = firstPos;
if (firstPos > this.mTargetPos) {
this._AbsListView_this.postOnAnimation(this);
}
break;
}
case PositionScroller.MOVE_UP_BOUND:
{
const lastViewIndex:number = this._AbsListView_this.getChildCount() - 2;
if (lastViewIndex < 0) {
return;
}
const lastPos:number = firstPos + lastViewIndex;
if (lastPos == this.mLastSeenPos) {
// No new views, let things keep going.
this._AbsListView_this.postOnAnimation(this);
return;
}
const lastView:View = this._AbsListView_this.getChildAt(lastViewIndex);
const lastViewHeight:number = lastView.getHeight();
const lastViewTop:number = lastView.getTop();
const lastViewPixelsShowing:number = listHeight - lastViewTop;
const extraScroll:number = Math.max(this._AbsListView_this.mListPadding.top, this.mExtraScroll);
this.mLastSeenPos = lastPos;
if (lastPos > this.mBoundPos) {
this._AbsListView_this.smoothScrollBy(-(lastViewPixelsShowing - extraScroll), this.mScrollDuration, true);
this._AbsListView_this.postOnAnimation(this);
} else {
const bottom:number = listHeight - extraScroll;
const lastViewBottom:number = lastViewTop + lastViewHeight;
if (bottom > lastViewBottom) {
this._AbsListView_this.smoothScrollBy(-(bottom - lastViewBottom), this.mScrollDuration, true);
}
}
break;
}
case PositionScroller.MOVE_OFFSET:
{
if (this.mLastSeenPos == firstPos) {
// No new views, let things keep going.
this._AbsListView_this.postOnAnimation(this);
return;
}
this.mLastSeenPos = firstPos;
const childCount:number = this._AbsListView_this.getChildCount();
const position:number = this.mTargetPos;
const lastPos:number = firstPos + childCount - 1;
let viewTravelCount:number = 0;
if (position < firstPos) {
viewTravelCount = firstPos - position + 1;
} else if (position > lastPos) {
viewTravelCount = position - lastPos;
}
// Estimate how many screens we should travel
const screenTravelCount:number = <number> viewTravelCount / childCount;
const modifier:number = Math.min(Math.abs(screenTravelCount), 1.);
if (position < firstPos) {
const distance:number = Math.floor((-this._AbsListView_this.getHeight() * modifier));
const duration:number = Math.floor((this.mScrollDuration * modifier));
this._AbsListView_this.smoothScrollBy(distance, duration, true);
this._AbsListView_this.postOnAnimation(this);
} else if (position > lastPos) {
const distance:number = Math.floor((this._AbsListView_this.getHeight() * modifier));
const duration:number = Math.floor((this.mScrollDuration * modifier));
this._AbsListView_this.smoothScrollBy(distance, duration, true);
this._AbsListView_this.postOnAnimation(this);
} else {
// On-screen, just scroll.
const targetTop:number = this._AbsListView_this.getChildAt(position - firstPos).getTop();
const distance:number = targetTop - this.mOffsetFromTop;
const duration:number = Math.floor((this.mScrollDuration * (<number> Math.abs(distance) / this._AbsListView_this.getHeight())));
this._AbsListView_this.smoothScrollBy(distance, duration, true);
}
break;
}
default:
break;
}
}
}
export class AdapterDataSetObserver extends AdapterView.AdapterDataSetObserver {
_AbsListView_this:AbsListView;
constructor(arg:any) {
super(arg);
this._AbsListView_this = arg;
}
onChanged():void {
super.onChanged();
//TODO when fast scroller impl
//if (this._AbsListView_this.mFastScroller != null) {
// this._AbsListView_this.mFastScroller.onSectionsChanged();
//}
}
onInvalidated():void {
super.onInvalidated();
//TODO when fast scroller impl
//if (this._AbsListView_this.mFastScroller != null) {
// this._AbsListView_this.mFastScroller.onSectionsChanged();
//}
}
}
/**
* AbsListView extends LayoutParams to provide a place to hold the view type.
*/
export class LayoutParams extends ViewGroup.LayoutParams {
/**
* View type for this view, as returned by
* {@link android.widget.Adapter#getItemViewType(int) }
*/
viewType:number = 0;
/**
* When this boolean is set, the view has been added to the AbsListView
* at least once. It is used to know whether headers/footers have already
* been added to the list view and whether they should be treated as
* recycled views or not.
*/
recycledHeaderFooter:boolean;
/**
* When an AbsListView is measured with an AT_MOST measure spec, it needs
* to obtain children views to measure itself. When doing so, the children
* are not attached to the window, but put in the recycler which assumes
* they've been attached before. Setting this flag will force the reused
* view to be attached to the window rather than just attached to the
* parent.
*/
forceAdd:boolean;
/**
* The position the view was removed from when pulled out of the
* scrap heap.
* @hide
*/
scrappedFromPosition:number = 0;
/**
* The ID the view represents
*/
itemId:number = -1;
constructor(context:android.content.Context, attrs:HTMLElement);
constructor(w:number, h:number);
constructor(w:number, h:number, viewType:number);
constructor(source:ViewGroup.LayoutParams);
constructor(...args){
super(...(() => {
if (args[0] instanceof android.content.Context && args[1] instanceof HTMLElement) return [args[0], args[1]];
else if (typeof args[0] === 'number' && typeof args[1] === 'number' && typeof args[2] === 'number') return [args[0], args[1]];
else if (typeof args[0] === 'number' && typeof args[1] === 'number') return [args[0], args[1]];
else if (args[0] instanceof ViewGroup.LayoutParams) return [args[0]];
})());
if (args[0] instanceof android.content.Context && args[1] instanceof HTMLElement) {
} else if (typeof args[0] === 'number' && typeof args[1] === 'number' && typeof args[2] == 'number') {
this.viewType = args[2];
} else if (typeof args[0] === 'number' && typeof args[1] === 'number') {
} else if (args[0] instanceof ViewGroup.LayoutParams) {
}
}
}
/**
* A RecyclerListener is used to receive a notification whenever a View is placed
* inside the RecycleBin's scrap heap. This listener is used to free resources
* associated to Views placed in the RecycleBin.
*
* @see android.widget.AbsListView.RecycleBin
* @see android.widget.AbsListView#setRecyclerListener(android.widget.AbsListView.RecyclerListener)
*/
export interface RecyclerListener {
/**
* Indicates that the specified View was moved into the recycler's scrap heap.
* The view is not displayed on screen any more and any expensive resource
* associated with the view should be discarded.
*
* @param view
*/
onMovedToScrapHeap(view:View):void ;
}
/**
* The RecycleBin facilitates reuse of views across layouts. The RecycleBin has two levels of
* storage: ActiveViews and ScrapViews. ActiveViews are those views which were onscreen at the
* start of a layout. By construction, they are displaying current information. At the end of
* layout, all views in ActiveViews are demoted to ScrapViews. ScrapViews are old views that
* could potentially be used by the adapter to avoid allocating views unnecessarily.
*
* @see android.widget.AbsListView#setRecyclerListener(android.widget.AbsListView.RecyclerListener)
* @see android.widget.AbsListView.RecyclerListener
*/
export class RecycleBin {
_AbsListView_this:AbsListView;
constructor(arg:AbsListView) {
this._AbsListView_this = arg;
}
mRecyclerListener:AbsListView.RecyclerListener;
/**
* The position of the first view stored in mActiveViews.
*/
private mFirstActivePosition:number = 0;
/**
* Views that were on screen at the start of layout. This array is populated at the start of
* layout, and at the end of layout all view in mActiveViews are moved to mScrapViews.
* Views in mActiveViews represent a contiguous range of Views, with position of the first
* view store in mFirstActivePosition.
*/
mActiveViews:View[] = [];
/**
* Unsorted views that can be used by the adapter as a convert view.
*/
private mScrapViews:ArrayList<View>[];
private mViewTypeCount:number = 0;
private mCurrentScrap:ArrayList<View>;
private mSkippedScrap:ArrayList<View>;
private mTransientStateViews:SparseArray<View>;
private mTransientStateViewsById:LongSparseArray<View>;
setViewTypeCount(viewTypeCount:number):void {
if (viewTypeCount < 1) {
throw Error(`new IllegalArgumentException("Can't have a viewTypeCount < 1")`);
}
//noinspection unchecked
let scrapViews:ArrayList<View>[] = new Array<ArrayList<View>>(viewTypeCount);
for (let i:number = 0; i < viewTypeCount; i++) {
scrapViews[i] = new ArrayList<View>();
}
this.mViewTypeCount = viewTypeCount;
this.mCurrentScrap = scrapViews[0];
this.mScrapViews = scrapViews;
}
markChildrenDirty():void {
if (this.mViewTypeCount == 1) {
const scrap:ArrayList<View> = this.mCurrentScrap;
const scrapCount:number = scrap.size();
for (let i:number = 0; i < scrapCount; i++) {
scrap.get(i).forceLayout();
}
} else {
const typeCount:number = this.mViewTypeCount;
for (let i:number = 0; i < typeCount; i++) {
const scrap:ArrayList<View> = this.mScrapViews[i];
const scrapCount:number = scrap.size();
for (let j:number = 0; j < scrapCount; j++) {
scrap.get(j).forceLayout();
}
}
}
if (this.mTransientStateViews != null) {
const count:number = this.mTransientStateViews.size();
for (let i:number = 0; i < count; i++) {
this.mTransientStateViews.valueAt(i).forceLayout();
}
}
if (this.mTransientStateViewsById != null) {
const count:number = this.mTransientStateViewsById.size();
for (let i:number = 0; i < count; i++) {
this.mTransientStateViewsById.valueAt(i).forceLayout();
}
}
}
shouldRecycleViewType(viewType:number):boolean {
return viewType >= 0;
}
/**
* Clears the scrap heap.
*/
clear():void {
if (this.mViewTypeCount == 1) {
const scrap:ArrayList<View> = this.mCurrentScrap;
const scrapCount:number = scrap.size();
for (let i:number = 0; i < scrapCount; i++) {
this._AbsListView_this.removeDetachedView(scrap.remove(scrapCount - 1 - i), false);
}
} else {
const typeCount:number = this.mViewTypeCount;
for (let i:number = 0; i < typeCount; i++) {
const scrap:ArrayList<View> = this.mScrapViews[i];
const scrapCount:number = scrap.size();
for (let j:number = 0; j < scrapCount; j++) {
this._AbsListView_this.removeDetachedView(scrap.remove(scrapCount - 1 - j), false);
}
}
}
if (this.mTransientStateViews != null) {
this.mTransientStateViews.clear();
}
if (this.mTransientStateViewsById != null) {
this.mTransientStateViewsById.clear();
}
}
/**
* Fill ActiveViews with all of the children of the AbsListView.
*
* @param childCount The minimum number of views mActiveViews should hold
* @param firstActivePosition The position of the first view that will be stored in
* mActiveViews
*/
fillActiveViews(childCount:number, firstActivePosition:number):void {
if (this.mActiveViews.length < childCount) {
this.mActiveViews = new Array<View>(childCount);
}
this.mFirstActivePosition = firstActivePosition;
//noinspection MismatchedReadAndWriteOfArray
const activeViews:View[] = this.mActiveViews;
for (let i:number = 0; i < childCount; i++) {
let child:View = this._AbsListView_this.getChildAt(i);
let lp:AbsListView.LayoutParams = <AbsListView.LayoutParams> child.getLayoutParams();
// Don't put header or footer views into the scrap heap
if (lp != null && lp.viewType != AbsListView.ITEM_VIEW_TYPE_HEADER_OR_FOOTER) {
// Note: We do place AdapterView.ITEM_VIEW_TYPE_IGNORE in active views.
// However, we will NOT place them into scrap views.
activeViews[i] = child;
}
}
}
/**
* Get the view corresponding to the specified position. The view will be removed from
* mActiveViews if it is found.
*
* @param position The position to look up in mActiveViews
* @return The view if it is found, null otherwise
*/
getActiveView(position:number):View {
let index:number = position - this.mFirstActivePosition;
const activeViews:View[] = this.mActiveViews;
if (index >= 0 && index < activeViews.length) {
const match:View = activeViews[index];
activeViews[index] = null;
return match;
}
return null;
}
getTransientStateView(position:number):View {
if (this._AbsListView_this.mAdapter != null && this._AbsListView_this.mAdapterHasStableIds && this.mTransientStateViewsById != null) {
let id:number = this._AbsListView_this.mAdapter.getItemId(position);
let result:View = this.mTransientStateViewsById.get(id);
this.mTransientStateViewsById.remove(id);
return result;
}
if (this.mTransientStateViews != null) {
const index:number = this.mTransientStateViews.indexOfKey(position);
if (index >= 0) {
let result:View = this.mTransientStateViews.valueAt(index);
this.mTransientStateViews.removeAt(index);
return result;
}
}
return null;
}
/**
* Dump any currently saved views with transient state.
*/
clearTransientStateViews():void {
if (this.mTransientStateViews != null) {
this.mTransientStateViews.clear();
}
if (this.mTransientStateViewsById != null) {
this.mTransientStateViewsById.clear();
}
}
/**
* @return A view from the ScrapViews collection. These are unordered.
*/
getScrapView(position:number):View {
if (this.mViewTypeCount == 1) {
return AbsListView.retrieveFromScrap(this.mCurrentScrap, position);
} else {
let whichScrap:number = this._AbsListView_this.mAdapter.getItemViewType(position);
if (whichScrap >= 0 && whichScrap < this.mScrapViews.length) {
return AbsListView.retrieveFromScrap(this.mScrapViews[whichScrap], position);
}
}
return null;
}
/**
* Puts a view into the list of scrap views.
* <p>
* If the list data hasn't changed or the adapter has stable IDs, views
* with transient state will be preserved for later retrieval.
*
* @param scrap The view to add
* @param position The view's position within its parent
*/
addScrapView(scrap:View, position:number):void {
const lp:AbsListView.LayoutParams = <AbsListView.LayoutParams> scrap.getLayoutParams();
if (lp == null) {
return;
}
lp.scrappedFromPosition = position;
// Remove but don't scrap header or footer views, or views that
// should otherwise not be recycled.
const viewType:number = lp.viewType;
if (!this.shouldRecycleViewType(viewType)) {
return;
}
scrap.dispatchStartTemporaryDetach();
// The the accessibility state of the view may change while temporary
// detached and we do not allow detached views to fire accessibility
// events. So we are announcing that the subtree changed giving a chance
// to clients holding on to a view in this subtree to refresh it.
//this._AbsListView_this.notifyViewAccessibilityStateChangedIfNeeded(AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
// Don't scrap views that have transient state.
const scrapHasTransientState:boolean = scrap.hasTransientState();
if (scrapHasTransientState) {
if (this._AbsListView_this.mAdapter != null && this._AbsListView_this.mAdapterHasStableIds) {
// the same data.
if (this.mTransientStateViewsById == null) {
this.mTransientStateViewsById = new LongSparseArray<View>();
}
this.mTransientStateViewsById.put(lp.itemId, scrap);
} else if (!this._AbsListView_this.mDataChanged) {
// their old positions.
if (this.mTransientStateViews == null) {
this.mTransientStateViews = new SparseArray<View>();
}
this.mTransientStateViews.put(position, scrap);
} else {
// Otherwise, we'll have to remove the view and start over.
if (this.mSkippedScrap == null) {
this.mSkippedScrap = new ArrayList<View>();
}
this.mSkippedScrap.add(scrap);
}
} else {
if (this.mViewTypeCount == 1) {
this.mCurrentScrap.add(scrap);
} else {
this.mScrapViews[viewType].add(scrap);
}
// Clear any system-managed transient state.
//if (scrap.isAccessibilityFocused()) {
// scrap.clearAccessibilityFocus();
//}
//scrap.setAccessibilityDelegate(null);
if (this.mRecyclerListener != null) {
this.mRecyclerListener.onMovedToScrapHeap(scrap);
}
}
}
/**
* Finish the removal of any views that skipped the scrap heap.
*/
removeSkippedScrap():void {
if (this.mSkippedScrap == null) {
return;
}
const count:number = this.mSkippedScrap.size();
for (let i:number = 0; i < count; i++) {
this._AbsListView_this.removeDetachedView(this.mSkippedScrap.get(i), false);
}
this.mSkippedScrap.clear();
}
/**
* Move all views remaining in mActiveViews to mScrapViews.
*/
scrapActiveViews():void {
const activeViews:View[] = this.mActiveViews;
const hasListener:boolean = this.mRecyclerListener != null;
const multipleScraps:boolean = this.mViewTypeCount > 1;
let scrapViews:ArrayList<View> = this.mCurrentScrap;
const count:number = activeViews.length;
for (let i:number = count - 1; i >= 0; i--) {
const victim:View = activeViews[i];
if (victim != null) {
const lp:AbsListView.LayoutParams = <AbsListView.LayoutParams> victim.getLayoutParams();
let whichScrap:number = lp.viewType;
activeViews[i] = null;
const scrapHasTransientState:boolean = victim.hasTransientState();
if (!this.shouldRecycleViewType(whichScrap) || scrapHasTransientState) {
// Do not move views that should be ignored
if (whichScrap != AbsListView.ITEM_VIEW_TYPE_HEADER_OR_FOOTER && scrapHasTransientState) {
this._AbsListView_this.removeDetachedView(victim, false);
}
if (scrapHasTransientState) {
if (this._AbsListView_this.mAdapter != null && this._AbsListView_this.mAdapterHasStableIds) {
if (this.mTransientStateViewsById == null) {
this.mTransientStateViewsById = new LongSparseArray<View>();
}
let id:number = this._AbsListView_this.mAdapter.getItemId(this.mFirstActivePosition + i);
this.mTransientStateViewsById.put(id, victim);
} else {
if (this.mTransientStateViews == null) {
this.mTransientStateViews = new SparseArray<View>();
}
this.mTransientStateViews.put(this.mFirstActivePosition + i, victim);
}
}
continue;
}
if (multipleScraps) {
scrapViews = this.mScrapViews[whichScrap];
}
victim.dispatchStartTemporaryDetach();
lp.scrappedFromPosition = this.mFirstActivePosition + i;
scrapViews.add(victim);
//victim.setAccessibilityDelegate(null);
if (hasListener) {
this.mRecyclerListener.onMovedToScrapHeap(victim);
}
}
}
this.pruneScrapViews();
}
/**
* Makes sure that the size of mScrapViews does not exceed the size of mActiveViews.
* (This can happen if an adapter does not recycle its views).
*/
private pruneScrapViews():void {
const maxViews:number = this.mActiveViews.length;
const viewTypeCount:number = this.mViewTypeCount;
const scrapViews:ArrayList<View>[] = this.mScrapViews;
for (let i:number = 0; i < viewTypeCount; ++i) {
const scrapPile:ArrayList<View> = scrapViews[i];
let size:number = scrapPile.size();
const extras:number = size - maxViews;
size--;
for (let j:number = 0; j < extras; j++) {
this._AbsListView_this.removeDetachedView(scrapPile.remove(size--), false);
}
}
if (this.mTransientStateViews != null) {
for (let i:number = 0; i < this.mTransientStateViews.size(); i++) {
const v:View = this.mTransientStateViews.valueAt(i);
if (!v.hasTransientState()) {
this.mTransientStateViews.removeAt(i);
i--;
}
}
}
if (this.mTransientStateViewsById != null) {
for (let i:number = 0; i < this.mTransientStateViewsById.size(); i++) {
const v:View = this.mTransientStateViewsById.valueAt(i);
if (!v.hasTransientState()) {
this.mTransientStateViewsById.removeAt(i);
i--;
}
}
}
}
/**
* Puts all views in the scrap heap into the supplied list.
*/
reclaimScrapViews(views:List<View>):void {
if (this.mViewTypeCount == 1) {
views.addAll(this.mCurrentScrap);
} else {
const viewTypeCount:number = this.mViewTypeCount;
const scrapViews:ArrayList<View>[] = this.mScrapViews;
for (let i:number = 0; i < viewTypeCount; ++i) {
const scrapPile:ArrayList<View> = scrapViews[i];
views.addAll(scrapPile);
}
}
}
/**
* Updates the cache color hint of all known views.
*
* @param color The new cache color hint.
*/
setCacheColorHint(color:number):void {
if (this.mViewTypeCount == 1) {
const scrap:ArrayList<View> = this.mCurrentScrap;
const scrapCount:number = scrap.size();
for (let i:number = 0; i < scrapCount; i++) {
scrap.get(i).setDrawingCacheBackgroundColor(color);
}
} else {
const typeCount:number = this.mViewTypeCount;
for (let i:number = 0; i < typeCount; i++) {
const scrap:ArrayList<View> = this.mScrapViews[i];
const scrapCount:number = scrap.size();
for (let j:number = 0; j < scrapCount; j++) {
scrap.get(j).setDrawingCacheBackgroundColor(color);
}
}
}
// Just in case this is called during a layout pass
const activeViews:View[] = this.mActiveViews;
const count:number = activeViews.length;
for (let i:number = 0; i < count; ++i) {
const victim:View = activeViews[i];
if (victim != null) {
victim.setDrawingCacheBackgroundColor(color);
}
}
}
}
}
} | the_stack |
import "mocha";
import * as expect from "expect";
import { SimpleZ80Instruction, Z80AssemblyLine, Z80Instruction } from "../../src/z80lang/parser/tree-nodes";
import { InputStream } from "../../src/z80lang/parser/input-stream";
import { TokenStream } from "../../src/z80lang/parser/token-stream";
import { Z80AsmParser } from "../../src/z80lang/parser/z80-asm-parser";
describe("Parser - simple Z80 instructions", () => {
it("label-only #1", () => {
const parser = createParser("myLabel");
const parsed = parser.parseProgram();
expect(parser.hasErrors).toBe(false);
expect(parsed).not.toBeNull();
expect(parsed.assemblyLines.length).toBe(1);
expect(parsed.assemblyLines[0].type).toBe("LabelOnlyLine");
const line = parsed.assemblyLines[0] as Z80AssemblyLine;
expect(line.label.name).toBe("myLabel");
expect(line.startPosition).toBe(0);
expect(line.endPosition).toBe(7);
expect(line.line).toBe(1);
expect(line.startColumn).toBe(0);
expect(line.endColumn).toBe(7);
});
it("label-only #2", () => {
const parser = createParser("myLabel:");
const parsed = parser.parseProgram();
expect(parser.hasErrors).toBe(false);
expect(parsed).not.toBeNull();
expect(parsed.assemblyLines.length).toBe(1);
expect(parsed.assemblyLines[0].type).toBe("LabelOnlyLine");
const line = parsed.assemblyLines[0] as Z80AssemblyLine;
expect(line.label.name).toBe("myLabel");
expect(line.startPosition).toBe(0);
expect(line.endPosition).toBe(8);
expect(line.line).toBe(1);
expect(line.startColumn).toBe(0);
expect(line.endColumn).toBe(8);
});
it("label-only #3", () => {
const parser = createParser(" myLabel:");
const parsed = parser.parseProgram();
expect(parser.hasErrors).toBe(false);
expect(parsed).not.toBeNull();
expect(parsed.assemblyLines.length).toBe(1);
expect(parsed.assemblyLines[0].type).toBe("LabelOnlyLine");
const line = parsed.assemblyLines[0] as Z80AssemblyLine;
expect(line.label.name).toBe("myLabel");
expect(line.startPosition).toBe(2);
expect(line.endPosition).toBe(10);
expect(line.line).toBe(1);
expect(line.startColumn).toBe(2);
expect(line.endColumn).toBe(10);
});
it("label-only #4", () => {
const parser = createParser(" myLabel:\r\n");
const parsed = parser.parseProgram();
expect(parser.hasErrors).toBe(false);
expect(parsed).not.toBeNull();
expect(parsed.assemblyLines.length).toBe(1);
expect(parsed.assemblyLines[0].type).toBe("LabelOnlyLine");
const line = parsed.assemblyLines[0] as Z80AssemblyLine;
expect(line.label.name).toBe("myLabel");
expect(line.startPosition).toBe(2);
expect(line.endPosition).toBe(10);
expect(line.line).toBe(1);
expect(line.startColumn).toBe(2);
expect(line.endColumn).toBe(10);
});
const simpleInstructions = [
"nop",
"rlca",
"rrca",
"rla",
"rra",
"daa",
"cpl",
"scf",
"ccf",
"halt",
"exx",
"di",
"ei",
"neg",
"retn",
"reti",
"rld",
"rrd",
"ldi",
"cpi",
"ini",
"outi",
"ldd",
"cpd",
"ind",
"outd",
"ldir",
"cpir",
"inir",
"otir",
"lddr",
"cpdr",
"indr",
"otdr",
"ldix",
"ldws",
"ldirx",
"lddx",
"lddrx",
"ldpirx",
"outinb",
"swapnib",
"pixeldn",
"pixelad",
"setae",
];
simpleInstructions.forEach((instr) => {
it(`${instr}`, () => {
testInstruction(instr);
});
});
});
function testInstruction(source: string): void {
// --- Normal case
let parser = createParser(source);
let parsed = parser.parseProgram();
expect(parser.hasErrors).toBe(false);
expect(parsed).not.toBeNull();
expect(parsed.assemblyLines.length).toBe(1);
expect(parsed.assemblyLines[0].type).toBe("SimpleZ80Instruction");
let line = (parsed.assemblyLines[0] as unknown) as SimpleZ80Instruction;
expect(line.mnemonic).toBe(source.toUpperCase());
let asmLine = parsed.assemblyLines[0] as Z80AssemblyLine;
expect(asmLine.label).toBeNull();
expect(asmLine.startPosition).toBe(0);
expect(asmLine.endPosition).toBe(source.length);
expect(asmLine.line).toBe(1);
expect(asmLine.startColumn).toBe(0);
expect(asmLine.endColumn).toBe(source.length);
// --- Whitespaced case
parser = createParser(" " + source);
parsed = parser.parseProgram();
expect(parser.hasErrors).toBe(false);
expect(parsed).not.toBeNull();
expect(parsed.assemblyLines.length).toBe(1);
expect(parsed.assemblyLines[0].type).toBe("SimpleZ80Instruction");
line = (parsed.assemblyLines[0] as unknown) as SimpleZ80Instruction;
expect(line.mnemonic).toBe(source.toUpperCase());
asmLine = parsed.assemblyLines[0] as Z80AssemblyLine;
expect(asmLine.label).toBeNull();
expect(asmLine.startPosition).toBe(2);
expect(asmLine.endPosition).toBe(2 + source.length);
expect(asmLine.line).toBe(1);
expect(asmLine.startColumn).toBe(2);
expect(asmLine.endColumn).toBe(2 + source.length);
// --- New line before case #1
parser = createParser("\n" + source);
parsed = parser.parseProgram();
expect(parser.hasErrors).toBe(false);
expect(parsed).not.toBeNull();
expect(parsed.assemblyLines.length).toBe(1);
expect(parsed.assemblyLines[0].type).toBe("SimpleZ80Instruction");
line = (parsed.assemblyLines[0] as unknown) as SimpleZ80Instruction;
expect(line.mnemonic).toBe(source.toUpperCase());
asmLine = parsed.assemblyLines[0] as Z80AssemblyLine;
expect(asmLine.label).toBeNull();
expect(asmLine.startPosition).toBe(1);
expect(asmLine.endPosition).toBe(1 + source.length);
expect(asmLine.line).toBe(2);
expect(asmLine.startColumn).toBe(0);
expect(asmLine.endColumn).toBe(source.length);
// --- New line before case #2
parser = createParser("\r\n" + source);
parsed = parser.parseProgram();
expect(parser.hasErrors).toBe(false);
expect(parsed).not.toBeNull();
expect(parsed.assemblyLines.length).toBe(1);
expect(parsed.assemblyLines[0].type).toBe("SimpleZ80Instruction");
line = (parsed.assemblyLines[0] as unknown) as SimpleZ80Instruction;
expect(line.mnemonic).toBe(source.toUpperCase());
asmLine = parsed.assemblyLines[0] as Z80AssemblyLine;
expect(asmLine.label).toBeNull();
expect(asmLine.startPosition).toBe(2);
expect(asmLine.endPosition).toBe(2 + source.length);
expect(asmLine.line).toBe(2);
expect(asmLine.startColumn).toBe(0);
expect(asmLine.endColumn).toBe(source.length);
// --- New line after case #1
parser = createParser(source + "\n");
parsed = parser.parseProgram();
expect(parser.hasErrors).toBe(false);
expect(parsed).not.toBeNull();
expect(parsed.assemblyLines.length).toBe(1);
expect(parsed.assemblyLines[0].type).toBe("SimpleZ80Instruction");
line = (parsed.assemblyLines[0] as unknown) as SimpleZ80Instruction;
expect(line.mnemonic).toBe(source.toUpperCase());
asmLine = parsed.assemblyLines[0] as Z80AssemblyLine;
expect(asmLine.label).toBeNull();
expect(asmLine.startPosition).toBe(0);
expect(asmLine.endPosition).toBe(source.length);
expect(asmLine.line).toBe(1);
expect(asmLine.startColumn).toBe(0);
expect(asmLine.endColumn).toBe(source.length);
// --- New line after case #1
parser = createParser(source + "\n\r");
parsed = parser.parseProgram();
expect(parser.hasErrors).toBe(false);
expect(parsed).not.toBeNull();
expect(parsed.assemblyLines.length).toBe(1);
expect(parsed.assemblyLines[0].type).toBe("SimpleZ80Instruction");
line = (parsed.assemblyLines[0] as unknown) as SimpleZ80Instruction;
expect(line.mnemonic).toBe(source.toUpperCase());
asmLine = parsed.assemblyLines[0] as Z80AssemblyLine;
expect(asmLine.label).toBeNull();
expect(asmLine.startPosition).toBe(0);
expect(asmLine.endPosition).toBe(source.length);
expect(asmLine.line).toBe(1);
expect(asmLine.startColumn).toBe(0);
expect(asmLine.endColumn).toBe(source.length);
// --- Labeled case #1
parser = createParser("myLabel " + source);
parsed = parser.parseProgram();
expect(parser.hasErrors).toBe(false);
expect(parsed).not.toBeNull();
expect(parsed.assemblyLines.length).toBe(1);
expect(parsed.assemblyLines[0].type).toBe("SimpleZ80Instruction");
line = (parsed.assemblyLines[0] as unknown) as SimpleZ80Instruction;
expect(line.mnemonic).toBe(source.toUpperCase());
asmLine = parsed.assemblyLines[0] as Z80AssemblyLine;
expect(asmLine.label.name).toBe("myLabel");
expect(asmLine.startPosition).toBe(0);
expect(asmLine.endPosition).toBe(8 + source.length);
expect(asmLine.line).toBe(1);
expect(asmLine.startColumn).toBe(0);
expect(asmLine.endColumn).toBe(8 + source.length);
// --- Labeled case #2
parser = createParser("myLabel:" + source);
parsed = parser.parseProgram();
expect(parser.hasErrors).toBe(false);
expect(parsed).not.toBeNull();
expect(parsed.assemblyLines.length).toBe(1);
expect(parsed.assemblyLines[0].type).toBe("SimpleZ80Instruction");
line = (parsed.assemblyLines[0] as unknown) as SimpleZ80Instruction;
expect(line.mnemonic).toBe(source.toUpperCase());
asmLine = parsed.assemblyLines[0] as Z80AssemblyLine;
expect(asmLine.label.name).toBe("myLabel");
expect(asmLine.startPosition).toBe(0);
expect(asmLine.endPosition).toBe(8 + source.length);
expect(asmLine.line).toBe(1);
expect(asmLine.startColumn).toBe(0);
expect(asmLine.endColumn).toBe(8 + source.length);
// --- Labeled case #3
parser = createParser("myLabel: " + source);
parsed = parser.parseProgram();
expect(parser.hasErrors).toBe(false);
expect(parsed).not.toBeNull();
expect(parsed.assemblyLines.length).toBe(1);
expect(parsed.assemblyLines[0].type).toBe("SimpleZ80Instruction");
line = (parsed.assemblyLines[0] as unknown) as SimpleZ80Instruction;
expect(line.mnemonic).toBe(source.toUpperCase());
asmLine = parsed.assemblyLines[0] as Z80AssemblyLine;
expect(asmLine.label.name).toBe("myLabel");
expect(asmLine.startPosition).toBe(0);
expect(asmLine.endPosition).toBe(9 + source.length);
expect(asmLine.line).toBe(1);
expect(asmLine.startColumn).toBe(0);
expect(asmLine.endColumn).toBe(9 + source.length);
}
function createParser(source: string): Z80AsmParser {
const is = new InputStream(source);
const ts = new TokenStream(is);
return new Z80AsmParser(ts);
} | the_stack |
import $ from "jquery";
import { imageOutputBinding } from "../bindings/output/image";
import { shinySetInputValue } from "../shiny/initedMethods";
import { Debouncer, Throttler } from "../time";
import { createBrush } from "./createBrush";
import type { BoundsCss, Bounds, BrushOpts } from "./createBrush";
import type { Offset } from "./findbox";
import type { Coordmap } from "./initCoordmap";
import type { Panel } from "./initPanelScales";
// ----------------------------------------------------------
// Handler creators for click, hover, brush.
// Each of these returns an object with a few public members. These public
// members are callbacks that are meant to be bound to events on $el with
// the same name (like 'mousedown').
// ----------------------------------------------------------
type CreateHandler = {
mousemove?: (e: JQuery.MouseMoveEvent) => void;
mouseout?: (e: JQuery.MouseOutEvent) => void;
mousedown?: (e: JQuery.MouseDownEvent) => void;
onResetImg: () => void;
onResize?: () => void;
};
type BrushInfo = {
xmin: number;
xmax: number;
ymin: number;
ymax: number;
// eslint-disable-next-line @typescript-eslint/naming-convention
coords_css?: BoundsCss;
// eslint-disable-next-line @typescript-eslint/naming-convention
coords_img?: Bounds;
x?: number;
y?: number;
// eslint-disable-next-line @typescript-eslint/naming-convention
img_css_ratio?: Offset;
mapping?: Panel["mapping"];
domain?: Panel["domain"];
range?: Panel["range"];
log?: Panel["log"];
direction?: BrushOpts["brushDirection"];
brushId?: string;
outputId?: string;
};
type InputId = Parameters<Coordmap["mouseCoordinateSender"]>[0];
type Clip = Parameters<Coordmap["mouseCoordinateSender"]>[1];
type NullOutside = Parameters<Coordmap["mouseCoordinateSender"]>[2];
function createClickHandler(
inputId: InputId,
clip: Clip,
coordmap: Coordmap
): CreateHandler {
const clickInfoSender = coordmap.mouseCoordinateSender(inputId, clip);
return {
mousedown: function (e) {
// Listen for left mouse button only
if (e.which !== 1) return;
clickInfoSender(e);
},
onResetImg: function () {
clickInfoSender(null);
},
onResize: null,
};
}
function createHoverHandler(
inputId: InputId,
delay: number,
delayType: string | "throttle",
clip: Clip,
nullOutside: NullOutside,
coordmap: Coordmap
): CreateHandler {
const sendHoverInfo = coordmap.mouseCoordinateSender(
inputId,
clip,
nullOutside
);
let hoverInfoSender: Debouncer | Throttler;
if (delayType === "throttle")
hoverInfoSender = new Throttler(null, sendHoverInfo, delay);
else hoverInfoSender = new Debouncer(null, sendHoverInfo, delay);
// What to do when mouse exits the image
let mouseout: () => void;
if (nullOutside)
mouseout = function () {
hoverInfoSender.normalCall(null);
};
else
mouseout = function () {
// do nothing
};
return {
mousemove: function (e) {
hoverInfoSender.normalCall(e);
},
mouseout: mouseout,
onResetImg: function () {
hoverInfoSender.immediateCall(null);
},
onResize: null,
};
}
// Returns a brush handler object. This has three public functions:
// mousedown, mousemove, and onResetImg.
function createBrushHandler(
inputId: InputId,
$el: JQuery<HTMLElement>,
opts: BrushOpts,
coordmap: Coordmap,
outputId: BrushInfo["outputId"]
): CreateHandler {
// Parameter: expand the area in which a brush can be started, by this
// many pixels in all directions. (This should probably be a brush option)
const expandPixels = 20;
// Represents the state of the brush
const brush = createBrush($el, opts, coordmap, expandPixels);
// Brush IDs can span multiple image/plot outputs. When an output is brushed,
// if a brush with the same ID is active on a different image/plot, it must
// be dismissed (but without sending any data to the server). We implement
// this by sending the shiny-internal:brushed event to all plots, and letting
// each plot decide for itself what to do.
//
// The decision to have the event sent to each plot (as opposed to a single
// event triggered on, say, the document) was made to make cleanup easier;
// listening on an event on the document would prevent garbage collection
// of plot outputs that are removed from the document.
$el.on("shiny-internal:brushed.image_output", function (e, coords) {
// If the new brush shares our ID but not our output element ID, we
// need to clear our brush (if any).
if (coords.brushId === inputId && coords.outputId !== outputId) {
$el.data("mostRecentBrush", false);
brush.reset();
}
});
// Set cursor to one of 7 styles. We need to set the cursor on the whole
// el instead of the brush div, because the brush div has
// 'pointer-events:none' so that it won't intercept pointer events.
// If `style` is null, don't add a cursor style.
function setCursorStyle(style) {
$el.removeClass(
"crosshair grabbable grabbing ns-resize ew-resize nesw-resize nwse-resize"
);
if (style) $el.addClass(style);
}
function sendBrushInfo() {
const coords: BrushInfo = brush.boundsData();
// We're in a new or reset state
if (isNaN(coords.xmin)) {
shinySetInputValue(inputId, null);
// Must tell other brushes to clear.
imageOutputBinding
.find(document.documentElement)
.trigger("shiny-internal:brushed", {
brushId: inputId,
outputId: null,
});
return;
}
const panel = brush.getPanel();
// Add the panel (facet) variables, if present
$.extend(coords, panel.panel_vars);
// eslint-disable-next-line camelcase
coords.coords_css = brush.boundsCss();
// eslint-disable-next-line camelcase
coords.coords_img = coordmap.scaleCssToImg(coords.coords_css);
// eslint-disable-next-line camelcase
coords.img_css_ratio = coordmap.cssToImgScalingRatio();
// Add variable name mappings
coords.mapping = panel.mapping;
// Add scaling information
coords.domain = panel.domain;
coords.range = panel.range;
coords.log = panel.log;
coords.direction = opts.brushDirection;
coords.brushId = inputId;
coords.outputId = outputId;
// Send data to server
shinySetInputValue(inputId, coords);
$el.data("mostRecentBrush", true);
imageOutputBinding
.find(document.documentElement)
.trigger("shiny-internal:brushed", coords);
}
let brushInfoSender;
if (opts.brushDelayType === "throttle") {
brushInfoSender = new Throttler(null, sendBrushInfo, opts.brushDelay);
} else {
brushInfoSender = new Debouncer(null, sendBrushInfo, opts.brushDelay);
}
function mousedown(e: JQuery.MouseDownEvent) {
// This can happen when mousedown inside the graphic, then mouseup
// outside, then mousedown inside. Just ignore the second
// mousedown.
if (brush.isBrushing() || brush.isDragging() || brush.isResizing()) return;
// Listen for left mouse button only
if (e.which !== 1) return;
// In general, brush uses css pixels, and coordmap uses img pixels.
const offsetCss = coordmap.mouseOffsetCss(e);
// Ignore mousedown events outside of plotting region, expanded by
// a number of pixels specified in expandPixels.
if (opts.brushClip && !coordmap.isInPanelCss(offsetCss, expandPixels))
return;
brush.up({ x: NaN, y: NaN });
brush.down(offsetCss);
if (brush.isInResizeArea(offsetCss)) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error; TODO-barret; Remove the variable? it is not used
brush.startResizing(offsetCss);
// Attach the move and up handlers to the window so that they respond
// even when the mouse is moved outside of the image.
$(document)
.on("mousemove.image_brush", mousemoveResizing)
.on("mouseup.image_brush", mouseupResizing);
} else if (brush.isInsideBrush(offsetCss)) {
// @ts-expect-error; TODO-barret this variable is not respected
brush.startDragging(offsetCss);
setCursorStyle("grabbing");
// Attach the move and up handlers to the window so that they respond
// even when the mouse is moved outside of the image.
$(document)
.on("mousemove.image_brush", mousemoveDragging)
.on("mouseup.image_brush", mouseupDragging);
} else {
const panel = coordmap.getPanelCss(offsetCss, expandPixels);
// @ts-expect-error; TODO-barret start brushing does not take any args; Either change the function to ignore, or do not send to function;
brush.startBrushing(panel.clipImg(coordmap.scaleCssToImg(offsetCss)));
// Attach the move and up handlers to the window so that they respond
// even when the mouse is moved outside of the image.
$(document)
.on("mousemove.image_brush", mousemoveBrushing)
.on("mouseup.image_brush", mouseupBrushing);
}
}
// This sets the cursor style when it's in the el
function mousemove(e: JQuery.MouseMoveEvent) {
// In general, brush uses css pixels, and coordmap uses img pixels.
const offsetCss = coordmap.mouseOffsetCss(e);
if (!(brush.isBrushing() || brush.isDragging() || brush.isResizing())) {
// Set the cursor depending on where it is
if (brush.isInResizeArea(offsetCss)) {
const r = brush.whichResizeSides(offsetCss);
if ((r.left && r.top) || (r.right && r.bottom)) {
setCursorStyle("nwse-resize");
} else if ((r.left && r.bottom) || (r.right && r.top)) {
setCursorStyle("nesw-resize");
} else if (r.left || r.right) {
setCursorStyle("ew-resize");
} else if (r.top || r.bottom) {
setCursorStyle("ns-resize");
}
} else if (brush.isInsideBrush(offsetCss)) {
setCursorStyle("grabbable");
} else if (coordmap.isInPanelCss(offsetCss, expandPixels)) {
setCursorStyle("crosshair");
} else {
setCursorStyle(null);
}
}
}
// mousemove handlers while brushing or dragging
function mousemoveBrushing(e: JQuery.MouseMoveEvent) {
brush.brushTo(coordmap.mouseOffsetCss(e));
brushInfoSender.normalCall();
}
function mousemoveDragging(e: JQuery.MouseMoveEvent) {
brush.dragTo(coordmap.mouseOffsetCss(e));
brushInfoSender.normalCall();
}
function mousemoveResizing(e: JQuery.MouseMoveEvent) {
brush.resizeTo(coordmap.mouseOffsetCss(e));
brushInfoSender.normalCall();
}
// mouseup handlers while brushing or dragging
function mouseupBrushing(e: JQuery.MouseUpEvent) {
// Listen for left mouse button only
if (e.which !== 1) return;
$(document).off("mousemove.image_brush").off("mouseup.image_brush");
brush.up(coordmap.mouseOffsetCss(e));
brush.stopBrushing();
setCursorStyle("crosshair");
// If the brush didn't go anywhere, hide the brush, clear value,
// and return.
if (brush.down().x === brush.up().x && brush.down().y === brush.up().y) {
brush.reset();
brushInfoSender.immediateCall();
return;
}
// Send info immediately on mouseup, but only if needed. If we don't
// do the pending check, we might send the same data twice (with
// with difference nonce).
if (brushInfoSender.isPending()) brushInfoSender.immediateCall();
}
function mouseupDragging(e: JQuery.MouseUpEvent) {
// Listen for left mouse button only
if (e.which !== 1) return;
$(document).off("mousemove.image_brush").off("mouseup.image_brush");
brush.up(coordmap.mouseOffsetCss(e));
brush.stopDragging();
setCursorStyle("grabbable");
if (brushInfoSender.isPending()) brushInfoSender.immediateCall();
}
function mouseupResizing(e: JQuery.MouseUpEvent) {
// Listen for left mouse button only
if (e.which !== 1) return;
$(document).off("mousemove.image_brush").off("mouseup.image_brush");
brush.up(coordmap.mouseOffsetCss(e));
brush.stopResizing();
if (brushInfoSender.isPending()) brushInfoSender.immediateCall();
}
// Brush maintenance: When an image is re-rendered, the brush must either
// be removed (if brushResetOnNew) or imported (if !brushResetOnNew). The
// "mostRecentBrush" bit is to ensure that when multiple outputs share the
// same brush ID, inactive brushes don't send null values up to the server.
// This should be called when the img (not the el) is reset
function onResetImg() {
if (opts.brushResetOnNew) {
if ($el.data("mostRecentBrush")) {
brush.reset();
brushInfoSender.immediateCall();
}
}
}
if (!opts.brushResetOnNew) {
if ($el.data("mostRecentBrush")) {
// Importing an old brush must happen after the image data has loaded
// and the <img> DOM element has the updated size. If importOldBrush()
// is called before this happens, then the css-img coordinate mappings
// will give the wrong result, and the brush will have the wrong
// position.
//
// jcheng 09/26/2018: This used to happen in img.onLoad, but recently
// we moved to all brush initialization moving to img.onLoad so this
// logic can be executed inline.
brush.importOldBrush();
brushInfoSender.immediateCall();
}
}
function onResize() {
brush.onResize();
brushInfoSender.immediateCall();
}
return {
mousedown: mousedown,
mousemove: mousemove,
onResetImg: onResetImg,
onResize: onResize,
};
}
export { createClickHandler, createHoverHandler, createBrushHandler };
export type { BrushInfo }; | the_stack |
import { Template } from '@aws-cdk/assertions';
import * as autoscaling from '@aws-cdk/aws-autoscaling';
import * as ec2 from '@aws-cdk/aws-ec2';
import * as elbv2 from '@aws-cdk/aws-elasticloadbalancingv2';
import * as cloudmap from '@aws-cdk/aws-servicediscovery';
import * as cdk from '@aws-cdk/core';
import * as ecs from '../../lib';
import { LaunchType } from '../../lib/base/base-service';
import { addDefaultCapacityProvider } from '../util';
describe('external service', () => {
describe('When creating an External Service', () => {
test('with only required properties set, it correctly sets default properties', () => {
// GIVEN
const stack = new cdk.Stack();
const vpc = new ec2.Vpc(stack, 'MyVpc', {});
const cluster = new ecs.Cluster(stack, 'EcsCluster', { vpc });
addDefaultCapacityProvider(cluster, stack, vpc);
const taskDefinition = new ecs.ExternalTaskDefinition(stack, 'ExternalTaskDef');
taskDefinition.addContainer('web', {
image: ecs.ContainerImage.fromRegistry('amazon/amazon-ecs-sample'),
memoryLimitMiB: 512,
});
const service = new ecs.ExternalService(stack, 'ExternalService', {
cluster,
taskDefinition,
});
// THEN
Template.fromStack(stack).hasResourceProperties('AWS::ECS::Service', {
TaskDefinition: {
Ref: 'ExternalTaskDef6CCBDB87',
},
Cluster: {
Ref: 'EcsCluster97242B84',
},
DeploymentConfiguration: {
MaximumPercent: 100,
MinimumHealthyPercent: 0,
},
EnableECSManagedTags: false,
LaunchType: LaunchType.EXTERNAL,
});
expect(service.node.defaultChild).toBeDefined();
});
});
test('with all properties set', () => {
// GIVEN
const stack = new cdk.Stack();
const vpc = new ec2.Vpc(stack, 'MyVpc', {});
const cluster = new ecs.Cluster(stack, 'EcsCluster', { vpc });
addDefaultCapacityProvider(cluster, stack, vpc);
const taskDefinition = new ecs.ExternalTaskDefinition(stack, 'ExternalTaskDef');
taskDefinition.addContainer('web', {
image: ecs.ContainerImage.fromRegistry('amazon/amazon-ecs-sample'),
memoryLimitMiB: 512,
});
// WHEN
new ecs.ExternalService(stack, 'ExternalService', {
cluster,
taskDefinition,
desiredCount: 2,
healthCheckGracePeriod: cdk.Duration.seconds(60),
maxHealthyPercent: 150,
minHealthyPercent: 55,
securityGroups: [new ec2.SecurityGroup(stack, 'SecurityGroup1', {
allowAllOutbound: true,
description: 'Example',
securityGroupName: 'Bob',
vpc,
})],
serviceName: 'bonjour',
});
// THEN
Template.fromStack(stack).hasResourceProperties('AWS::ECS::Service', {
TaskDefinition: {
Ref: 'ExternalTaskDef6CCBDB87',
},
Cluster: {
Ref: 'EcsCluster97242B84',
},
DeploymentConfiguration: {
MaximumPercent: 150,
MinimumHealthyPercent: 55,
},
DesiredCount: 2,
LaunchType: LaunchType.EXTERNAL,
ServiceName: 'bonjour',
});
});
test('with cloudmap set on cluster, throw error', () => {
// GIVEN
const stack = new cdk.Stack();
const vpc = new ec2.Vpc(stack, 'MyVpc', {});
const cluster = new ecs.Cluster(stack, 'EcsCluster', { vpc });
addDefaultCapacityProvider(cluster, stack, vpc);
const taskDefinition = new ecs.ExternalTaskDefinition(stack, 'ExternalTaskDef');
cluster.addDefaultCloudMapNamespace({
name: 'foo.com',
type: cloudmap.NamespaceType.DNS_PRIVATE,
});
// THEN
expect(() => new ecs.ExternalService(stack, 'ExternalService', {
cluster,
taskDefinition,
desiredCount: 2,
healthCheckGracePeriod: cdk.Duration.seconds(60),
maxHealthyPercent: 150,
minHealthyPercent: 55,
securityGroups: [new ec2.SecurityGroup(stack, 'SecurityGroup1', {
allowAllOutbound: true,
description: 'Example',
securityGroupName: 'Bob',
vpc,
})],
serviceName: 'bonjour',
})).toThrow('Cloud map integration is not supported for External service' );
});
test('with multiple security groups, it correctly updates the cfn template', () => {
// GIVEN
const stack = new cdk.Stack();
const vpc = new ec2.Vpc(stack, 'MyVpc', {});
const cluster = new ecs.Cluster(stack, 'EcsCluster', { vpc });
addDefaultCapacityProvider(cluster, stack, vpc);
const taskDefinition = new ecs.ExternalTaskDefinition(stack, 'ExternalTaskDef');
taskDefinition.addContainer('web', {
image: ecs.ContainerImage.fromRegistry('amazon/amazon-ecs-sample'),
memoryLimitMiB: 512,
});
const securityGroup1 = new ec2.SecurityGroup(stack, 'SecurityGroup1', {
allowAllOutbound: true,
description: 'Example',
securityGroupName: 'Bingo',
vpc,
});
const securityGroup2 = new ec2.SecurityGroup(stack, 'SecurityGroup2', {
allowAllOutbound: false,
description: 'Example',
securityGroupName: 'Rolly',
vpc,
});
// WHEN
new ecs.ExternalService(stack, 'ExternalService', {
cluster,
taskDefinition,
desiredCount: 2,
securityGroups: [securityGroup1, securityGroup2],
serviceName: 'bonjour',
});
// THEN
Template.fromStack(stack).hasResourceProperties('AWS::ECS::Service', {
TaskDefinition: {
Ref: 'ExternalTaskDef6CCBDB87',
},
Cluster: {
Ref: 'EcsCluster97242B84',
},
DesiredCount: 2,
LaunchType: LaunchType.EXTERNAL,
ServiceName: 'bonjour',
});
Template.fromStack(stack).hasResourceProperties('AWS::EC2::SecurityGroup', {
GroupDescription: 'Example',
GroupName: 'Bingo',
SecurityGroupEgress: [
{
CidrIp: '0.0.0.0/0',
Description: 'Allow all outbound traffic by default',
IpProtocol: '-1',
},
],
});
Template.fromStack(stack).hasResourceProperties('AWS::EC2::SecurityGroup', {
GroupDescription: 'Example',
GroupName: 'Rolly',
SecurityGroupEgress: [
{
CidrIp: '255.255.255.255/32',
Description: 'Disallow all traffic',
FromPort: 252,
IpProtocol: 'icmp',
ToPort: 86,
},
],
});
});
test('throws when task definition is not External compatible', () => {
const stack = new cdk.Stack();
const vpc = new ec2.Vpc(stack, 'MyVpc', {});
const cluster = new ecs.Cluster(stack, 'EcsCluster', { vpc });
const taskDefinition = new ecs.TaskDefinition(stack, 'FargateTaskDef', {
compatibility: ecs.Compatibility.FARGATE,
cpu: '256',
memoryMiB: '512',
});
taskDefinition.addContainer('BaseContainer', {
image: ecs.ContainerImage.fromRegistry('test'),
memoryReservationMiB: 10,
});
expect(() => new ecs.ExternalService(stack, 'ExternalService', {
cluster,
taskDefinition,
})).toThrow('Supplied TaskDefinition is not configured for compatibility with ECS Anywhere cluster');
});
test('errors if minimum not less than maximum', () => {
// GIVEN
const stack = new cdk.Stack();
const vpc = new ec2.Vpc(stack, 'MyVpc', {});
const cluster = new ecs.Cluster(stack, 'EcsCluster', { vpc });
addDefaultCapacityProvider(cluster, stack, vpc);
const taskDefinition = new ecs.ExternalTaskDefinition(stack, 'ExternalTaskDef');
taskDefinition.addContainer('BaseContainer', {
image: ecs.ContainerImage.fromRegistry('test'),
memoryReservationMiB: 10,
});
// THEN
expect(() => new ecs.ExternalService(stack, 'ExternalService', {
cluster,
taskDefinition,
minHealthyPercent: 100,
maxHealthyPercent: 100,
})).toThrow('Minimum healthy percent must be less than maximum healthy percent.');
});
test('error if cloudmap options provided with external service', () => {
// GIVEN
const stack = new cdk.Stack();
const vpc = new ec2.Vpc(stack, 'MyVpc', {});
const cluster = new ecs.Cluster(stack, 'EcsCluster', { vpc });
addDefaultCapacityProvider(cluster, stack, vpc);
const taskDefinition = new ecs.ExternalTaskDefinition(stack, 'TaskDef');
taskDefinition.addContainer('web', {
image: ecs.ContainerImage.fromRegistry('amazon/amazon-ecs-sample'),
memoryLimitMiB: 512,
});
// THEN
expect(() => new ecs.ExternalService(stack, 'ExternalService', {
cluster,
taskDefinition,
cloudMapOptions: {
name: 'myApp',
},
})).toThrow('Cloud map options are not supported for External service');
// THEN
});
test('error if enableExecuteCommand options provided with external service', () => {
// GIVEN
const stack = new cdk.Stack();
const vpc = new ec2.Vpc(stack, 'MyVpc', {});
const cluster = new ecs.Cluster(stack, 'EcsCluster', { vpc });
addDefaultCapacityProvider(cluster, stack, vpc);
const taskDefinition = new ecs.ExternalTaskDefinition(stack, 'TaskDef');
taskDefinition.addContainer('web', {
image: ecs.ContainerImage.fromRegistry('amazon/amazon-ecs-sample'),
memoryLimitMiB: 512,
});
// THEN
expect(() => new ecs.ExternalService(stack, 'ExternalService', {
cluster,
taskDefinition,
enableExecuteCommand: true,
})).toThrow('Enable Execute Command options are not supported for External service');
// THEN
});
test('error if capacityProviderStrategies options provided with external service', () => {
// GIVEN
const stack = new cdk.Stack();
const vpc = new ec2.Vpc(stack, 'MyVpc', {});
const cluster = new ecs.Cluster(stack, 'EcsCluster', { vpc });
addDefaultCapacityProvider(cluster, stack, vpc);
const taskDefinition = new ecs.ExternalTaskDefinition(stack, 'TaskDef');
taskDefinition.addContainer('web', {
image: ecs.ContainerImage.fromRegistry('amazon/amazon-ecs-sample'),
memoryLimitMiB: 512,
});
// WHEN
const autoScalingGroup = new autoscaling.AutoScalingGroup(stack, 'asg', {
vpc,
instanceType: new ec2.InstanceType('bogus'),
machineImage: ecs.EcsOptimizedImage.amazonLinux2(),
});
const capacityProvider = new ecs.AsgCapacityProvider(stack, 'provider', {
autoScalingGroup,
enableManagedTerminationProtection: false,
});
// THEN
expect(() => new ecs.ExternalService(stack, 'ExternalService', {
cluster,
taskDefinition,
capacityProviderStrategies: [{
capacityProvider: capacityProvider.capacityProviderName,
}],
})).toThrow('Capacity Providers are not supported for External service');
// THEN
});
test('error when performing attachToApplicationTargetGroup to an external service', () => {
// GIVEN
const stack = new cdk.Stack();
const vpc = new ec2.Vpc(stack, 'MyVpc', {});
const cluster = new ecs.Cluster(stack, 'EcsCluster', { vpc });
addDefaultCapacityProvider(cluster, stack, vpc);
const taskDefinition = new ecs.ExternalTaskDefinition(stack, 'TaskDef');
taskDefinition.addContainer('web', {
image: ecs.ContainerImage.fromRegistry('amazon/amazon-ecs-sample'),
memoryLimitMiB: 512,
});
const service = new ecs.ExternalService(stack, 'ExternalService', {
cluster,
taskDefinition,
});
const lb = new elbv2.ApplicationLoadBalancer(stack, 'lb', { vpc });
const listener = lb.addListener('listener', { port: 80 });
const targetGroup = listener.addTargets('target', {
port: 80,
});
// THEN
expect(() => service.attachToApplicationTargetGroup(targetGroup)).toThrow('Application load balancer cannot be attached to an external service');
// THEN
});
test('error when performing loadBalancerTarget to an external service', () => {
// GIVEN
const stack = new cdk.Stack();
const vpc = new ec2.Vpc(stack, 'MyVpc', {});
const cluster = new ecs.Cluster(stack, 'EcsCluster', { vpc });
addDefaultCapacityProvider(cluster, stack, vpc);
const taskDefinition = new ecs.ExternalTaskDefinition(stack, 'TaskDef');
taskDefinition.addContainer('web', {
image: ecs.ContainerImage.fromRegistry('amazon/amazon-ecs-sample'),
memoryLimitMiB: 512,
});
const service = new ecs.ExternalService(stack, 'ExternalService', {
cluster,
taskDefinition,
});
// THEN
expect(() => service.loadBalancerTarget({
containerName: 'MainContainer',
})).toThrow('External service cannot be attached as load balancer targets');
// THEN
});
test('error when performing registerLoadBalancerTargets to an external service', () => {
// GIVEN
const stack = new cdk.Stack();
const vpc = new ec2.Vpc(stack, 'MyVpc', {});
const cluster = new ecs.Cluster(stack, 'EcsCluster', { vpc });
addDefaultCapacityProvider(cluster, stack, vpc);
const taskDefinition = new ecs.ExternalTaskDefinition(stack, 'TaskDef');
taskDefinition.addContainer('web', {
image: ecs.ContainerImage.fromRegistry('amazon/amazon-ecs-sample'),
memoryLimitMiB: 512,
});
const lb = new elbv2.ApplicationLoadBalancer(stack, 'lb', { vpc });
const listener = lb.addListener('listener', { port: 80 });
const service = new ecs.ExternalService(stack, 'ExternalService', {
cluster,
taskDefinition,
});
// THEN
expect(() => service.registerLoadBalancerTargets(
{
containerName: 'MainContainer',
containerPort: 8000,
listener: ecs.ListenerConfig.applicationListener(listener),
newTargetGroupId: 'target1',
},
)).toThrow('External service cannot be registered as load balancer targets');
// THEN
});
test('error when performing autoScaleTaskCount to an external service', () => {
// GIVEN
const stack = new cdk.Stack();
const vpc = new ec2.Vpc(stack, 'MyVpc', {});
const cluster = new ecs.Cluster(stack, 'EcsCluster', { vpc });
addDefaultCapacityProvider(cluster, stack, vpc);
const taskDefinition = new ecs.ExternalTaskDefinition(stack, 'TaskDef');
taskDefinition.addContainer('web', {
image: ecs.ContainerImage.fromRegistry('amazon/amazon-ecs-sample'),
memoryLimitMiB: 512,
});
const service = new ecs.ExternalService(stack, 'ExternalService', {
cluster,
taskDefinition,
});
// THEN
expect(() => service.autoScaleTaskCount({
maxCapacity: 2,
minCapacity: 1,
})).toThrow('Autoscaling not supported for external service');
// THEN
});
test('error when performing enableCloudMap to an external service', () => {
// GIVEN
const stack = new cdk.Stack();
const vpc = new ec2.Vpc(stack, 'MyVpc', {});
const cluster = new ecs.Cluster(stack, 'EcsCluster', { vpc });
addDefaultCapacityProvider(cluster, stack, vpc);
const taskDefinition = new ecs.ExternalTaskDefinition(stack, 'TaskDef');
taskDefinition.addContainer('web', {
image: ecs.ContainerImage.fromRegistry('amazon/amazon-ecs-sample'),
memoryLimitMiB: 512,
});
const service = new ecs.ExternalService(stack, 'ExternalService', {
cluster,
taskDefinition,
});
// THEN
expect(() => service.enableCloudMap({})).toThrow('Cloud map integration not supported for an external service');
// THEN
});
test('error when performing associateCloudMapService to an external service', () => {
// GIVEN
const stack = new cdk.Stack();
const vpc = new ec2.Vpc(stack, 'MyVpc', {});
const cluster = new ecs.Cluster(stack, 'EcsCluster', { vpc });
addDefaultCapacityProvider(cluster, stack, vpc);
const taskDefinition = new ecs.ExternalTaskDefinition(stack, 'TaskDef');
const container = taskDefinition.addContainer('web', {
image: ecs.ContainerImage.fromRegistry('amazon/amazon-ecs-sample'),
memoryLimitMiB: 512,
});
const service = new ecs.ExternalService(stack, 'ExternalService', {
cluster,
taskDefinition,
});
const cloudMapNamespace = new cloudmap.PrivateDnsNamespace(stack, 'TestCloudMapNamespace', {
name: 'scorekeep.com',
vpc,
});
const cloudMapService = new cloudmap.Service(stack, 'Service', {
name: 'service-name',
namespace: cloudMapNamespace,
dnsRecordType: cloudmap.DnsRecordType.SRV,
});
// THEN
expect(() => service.associateCloudMapService({
service: cloudMapService,
container: container,
containerPort: 8000,
})).toThrow('Cloud map service association is not supported for an external service');
// THEN
});
}); | the_stack |
import { Readable, Writable } from 'stream';
import { Config } from './config';
import { getContextForConfig } from './context';
import { ThemeColorName } from './themes';
import { transformContentsStreaming } from './transformContentsStreaming';
const TEST_THEME = Object.fromEntries(
Object.keys(ThemeColorName).map((name) => [name, {}])
);
const replaceColoredText = () => (text: string) => text.replace(/./g, '░');
const TEST_CONFIG: Config = {
// Provide a fake chalk implementation to make it easier to read snapshots
CHALK: {
// @ts-expect-error
rgb: replaceColoredText,
// @ts-expect-error
bgRgb: replaceColoredText,
},
SCREEN_WIDTH: 120,
MIN_LINE_WIDTH: 60,
WRAP_LINES: false,
HIGHLIGHT_LINE_CHANGES: false,
...TEST_THEME,
};
const CONFIG_OVERRIDES: Record<string, Partial<Config>> = {
splitWithoutWrapping: {
SCREEN_WIDTH: 80,
MIN_LINE_WIDTH: 40,
WRAP_LINES: false,
},
splitWithWrapping: {
SCREEN_WIDTH: 80,
MIN_LINE_WIDTH: 40,
WRAP_LINES: true,
},
unifiedWithWrapping: {
SCREEN_WIDTH: 80,
MIN_LINE_WIDTH: 80,
WRAP_LINES: true,
},
// This is in split mode
inlineChangesHighlighted: {
HIGHLIGHT_LINE_CHANGES: true,
DELETED_WORD_COLOR: { color: { r: 255, g: 0, b: 0, a: 255 } },
INSERTED_WORD_COLOR: { color: { r: 0, g: 255, b: 0, a: 255 } },
},
unifiedWithInlineChangesHighlighted: {
SCREEN_WIDTH: 80,
MIN_LINE_WIDTH: 80,
HIGHLIGHT_LINE_CHANGES: true,
DELETED_WORD_COLOR: { color: { r: 255, g: 0, b: 0, a: 255 } },
INSERTED_WORD_COLOR: { color: { r: 0, g: 255, b: 0, a: 255 } },
},
};
for (const [configName, configOverride] of Object.entries(CONFIG_OVERRIDES)) {
async function transform(input: string): Promise<string> {
const testConfig: Config = {
...TEST_CONFIG,
...configOverride,
};
const context = await getContextForConfig(testConfig);
let string = '';
await transformContentsStreaming(
context,
Readable.from(input),
new (class extends Writable {
write(chunk: Buffer) {
string += chunk.toString();
return true;
}
})()
);
return string;
}
describe(configName, () => {
test('empty', async function () {
expect(await transform(``)).toMatchSnapshot();
});
test('with ANSI color codes', async function () {
expect(
await transform(`
[1;32mcommit f735de7025c6d626c5ae1a291fe24f143dea0313[m
Author: Shrey Banga <banga.shrey@gmail.com>
Date: Sun Apr 11 15:25:34 2021 -0700
Add theme support
[1;33mdiff --git a/todo.md b/todo.md[m
[1;33mindex 9f14e96..eaf3730 100644[m
[1;33m--- a/todo.md[m
[1;33m+++ b/todo.md[m
[1;32m@@ -7,6 +7,7 @@[m
- [x] Handle file addition/deletion properly[m
- [x] Fix incorrect line positions when a hunk has discontinuous inserts and/or deletes[m
- [x] Organize code[m
[1;32m+[m[1;32m- [x] Move visual config to theme[m
- [ ] Handle empty diffs[m
- [ ] Handle moves and renames without diffs[m
- [ ] Highlight changes in lines[m
`)
).toMatchSnapshot();
});
test('commits without diffs', async function () {
expect(
await transform(`
commit e5f896655402f8cf2d947c528d45e1d56bbf5717 (HEAD -> main)
Author: Shrey Banga <banga.shrey@gmail.com>
Date: Sun Apr 11 16:23:54 2021 -0700
Small refactor to allow testing end-to-end
commit b637f38029f4a89c6a3b73b2b84a6a5b9e260730
Author: Shrey Banga <banga.shrey@gmail.com>
Date: Sun Apr 11 11:53:02 2021 -0700
Organize code
commit f323143e03af95fee5d38c21238a92ffd4461847
Author: Shrey Banga <banga.shrey@gmail.com>
Date: Sun Apr 11 10:39:17 2021 -0700
more todos
`)
).toMatchSnapshot();
});
test('commit with addition', async function () {
expect(
await transform(`
commit f735de7025c6d626c5ae1a291fe24f143dea0313
Author: Shrey Banga <banga.shrey@gmail.com>
Date: Sun Apr 11 15:25:34 2021 -0700
Add theme support
diff --git a/todo.md b/todo.md
index 9f14e96..eaf3730 100644
--- a/todo.md
+++ b/todo.md
@@ -9,2 +9,3 @@
- [x] Organize code
+- [x] Move visual config to theme
- [ ] Handle empty diffs
`)
).toMatchSnapshot();
});
test('commit with deletion', async function () {
expect(`commit eccfb5a2b3d76ba53df315f977da74b18d50113e
Author: Shrey Banga <shrey@quip.com>
Date: Thu Aug 22 10:07:25 2019 -0700
Remove deprecated option
diff --git a/Code/User/settings.json b/Code/User/settings.json
index a33d267..ae58a01 100644
--- a/Code/User/settings.json
+++ b/Code/User/settings.json
@@ -26,5 +26,4 @@
// search
"search.location": "panel",
- "search.usePCRE2": true,
// telemetry
`).toMatchSnapshot();
});
test('commit with a small diff', async function () {
expect(
await transform(`
commit 26ca49fb83758bace20a473e231d576aa1bbe115
Author: Shrey Banga <shrey@quip.com>
Date: Tue May 23 16:47:17 2017 -0700
sonos to brew
diff --git a/Brewfile b/Brewfile
index 5a38bdb..ef4ff52 100644
--- a/Brewfile
+++ b/Brewfile
@@ -19,2 +19,3 @@ brew 'python3'
brew 'socat'
+brew 'sonos'
brew 'terminal-notifier'
@@ -42,3 +43,2 @@ cask 'rescuetime'
cask 'slate'
-cask 'sonos'
cask 'spotify'`)
).toMatchSnapshot();
});
test('commit with tabs', async function () {
expect(
await transform(`
commit f735de7025c6d626c5ae1a291fe24f143dea0313
Author: Shrey Banga <banga.shrey@gmail.com>
Date: Sun Apr 11 15:25:34 2021 -0700
Add theme support
diff --git a/todo.md b/todo.md
index 9f14e96..eaf3730 100644
--- a/todo.md
+++ b/todo.md
@@ -9,2 +9,3 @@
- [x] Organize code
+- [x] Move visual config to theme
- [ ] Handle empty diffs
`)
).toMatchSnapshot();
});
test('multiple inserts and deletes in the same hunk', async function () {
expect(
await transform(`
commit e5f896655402f8cf2d947c528d45e1d56bbf5717
Author: Shrey Banga <banga.shrey@gmail.com>
Date: Sun Apr 11 16:23:54 2021 -0700
Small refactor to allow testing end-to-end
diff --git a/src/index.ts b/src/index.ts
index 149981d..fb507a4 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -1,5 +1,6 @@
import chalk from 'chalk';
import * as process from 'process';
+import stream from 'stream';
import terminalSize from 'term-size';
import { iterlinesFromReadableAsync } from './iterLinesFromReadable';
import { iterLinesWithoutAnsiColors } from './iterLinesWithoutAnsiColors';
@@ -12,15 +13,16 @@ function main() {
const screenWidth = terminalSize().columns;
const theme = defaultTheme(chalk, screenWidth);
- transformStreamWithIterables(
- process.stdin,
- [
+ stream.pipeline(
+ transformStreamWithIterables(
+ process.stdin,
iterlinesFromReadableAsync,
iterLinesWithoutAnsiColors,
iterSideBySideDiff(theme),
- iterWithNewlines,
- ],
- process.stdout
+ iterWithNewlines
+ ),
+ process.stdout,
+ console.error
);
}
`)
).toMatchSnapshot();
});
test('commit with file addition', async function () {
expect(
await transform(`
commit e4951eee3b9a8fa471d01dd64075c5fd44879a26
Author: Shrey Banga <banga.shrey@gmail.com>
Date: Sat Apr 10 14:35:42 2021 -0700
wip
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..6499edf
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,2 @@
+node_modules/**
+build/**
\ No newline at end of file`)
).toMatchSnapshot();
});
test('commit with binary file addition', async function () {
expect(
await transform(`
commit c0ca4394fd55f1709430414f03db3d04cb9cc72c (HEAD -> main)
Author: Shrey Banga <banga.shrey@gmail.com>
Date: Wed Apr 14 18:24:29 2021 -0700
test binary file addition
diff --git a/screenshots/default.png b/screenshots/default.png
new file mode 100644
index 0000000..40e16dc
Binary files /dev/null and b/screenshots/default.png differ
diff --git a/test dir a/default.png b/test dir a/default.png
index 44f1c8a..915e850 100644
Binary files a/test dir a/default.png and b/test dir a/default.png differ`)
).toMatchSnapshot();
});
test('commit with file move', async function () {
expect(
await transform(`
commit 1c76ed4bb05429741fd4a48896bb84b11bc661f5
Author: Shrey Banga <banga.shrey@gmail.com>
Date: Sat Apr 10 22:26:15 2021 -0700
Move sample diff files
diff --git a/colors.diff b/test-data/colors.diff
similarity index 100%
rename from colors.diff
rename to test-data/colors.diff
`)
).toMatchSnapshot();
});
test('commit with file deletion', async function () {
expect(
await transform(`
commit 1e6ebaccc6fadf3390a749e7aa2cc6372b24325e
Author: Shrey Banga <banga.shrey@gmail.com>
Date: Sun Apr 18 03:17:05 2021 -0700
Update main.yml
diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml
index dff1332..af022ac 100644
diff --git a/scripts/screenshotTheme b/scripts/screenshotTheme
deleted file mode 100755
index ca15c64..0000000
--- a/scripts/screenshotTheme
+++ /dev/null
@@ -1,7 +0,0 @@
-on run argv
- with timeout of 5 seconds
- tell app "Terminal"
- open "screenshots.sh"
- end tell
- end timeout
-end run
\ No newline at end of file`)
).toMatchSnapshot();
});
test('commit with inline line changes', async function () {
expect(
await transform(
`
commit 9e424d329800e945e3003c9e275f80bdef69e591
Author: Shrey Banga <banga.shrey@gmail.com>
Date: Sun Apr 4 19:04:26 2021 -0700
update lockfile
diff --git a/Brewfile.lock.json b/Brewfile.lock.json
index ecb417f..f412f84 100644
--- a/Brewfile.lock.json
+++ b/Brewfile.lock.json
@@ -5 +5 @@
- "revision": null
+ "revision": "ee2f8d3ba2976e50ef577d517bf175c94fbbb0dd"
@@ -8 +8 @@
- "revision": null
+ "revision": "c4cf96857c050dfa4f65f52109862dc68e55f60a"
@@ -11 +11 @@
- "revision": null
+ "revision": "504d4b93aa6eaf4fce1bf17c19f55828ad7229a4"
@@ -16 +16 @@
- "version": "1.14.2_1",
+ "version": "1.16.3",
@@ -17,0 +18 @@
+ "rebuild": 0,
@@ -19,0 +21 @@
+ "root_url": "https://homebrew.bintray.com/bottles",
@@ -20,0 +23,8 @@
+ "arm64_big_sur": {
+ "url": "https://homebrew.bintray.com/bottles/go-1.16.3.arm64_big_sur.bottle.tar.gz",
+ "sha256": "e7c1efdd09e951eb46d01a3200b01e7fa55ce285b75470051be7fef34f4233ce"
+ },
+ "big_sur": {
+ "url": "https://homebrew.bintray.com/bottles/go-1.16.3.big_sur.bottle.tar.gz",
+ "sha256": "ea37f33fd27369612a3e4e6db6adc46db0e8bdf6fac1332bf51bafaa66d43969"
+ },
@@ -22,2 +32,2 @@
- "url": "https://homebrew.bintray.com/bottles/go-1.14.2_1.catalina.bottle.tar.gz",
- "sha256": "15b5623471330edcc681d7f9d57b449660e6d4b98c7f67af67f4991fc75d61fc"
+ "url": "https://homebrew.bintray.com/bottles/go-1.16.3.catalina.bottle.tar.gz",
+ "sha256": "69c28f5e60612801c66e51e93d32068f822b245ab83246cb6cb374572eb59e15"
@@ -26,6 +36,2 @@
- "url": "https://homebrew.bintray.com/bottles/go-1.14.2_1.mojave.bottle.tar.gz",
- "sha256": "fa65e7dabe514e65ae625ed3c84a6bf58df01aceffc6e9aa99752ca8c320ce69"
- },
- "high_sierra": {
- "url": "https://homebrew.bintray.com/bottles/go-1.14.2_1.high_sierra.bottle.tar.gz",
- "sha256": "0997f6f5cda0e3bdb7789a80b53621cb588202ab37fd89bcd269f8dfafd23351"
+ "url": "https://homebrew.bintray.com/bottles/go-1.16.3.mojave.bottle.tar.gz",
+ "sha256": "bf1e90ed1680b8ee1acb49f2f99426c8a8ac3e49efd63c7f3b41e57e7214dd19"
`
)
).toMatchSnapshot();
});
});
} | the_stack |
import { AudioPlayr, AudioPlayrSettings } from "audioplayr";
import { factory, member } from "babyioc";
import { BattleMovr } from "battlemovr";
import { ClassCyclr, ClassCyclrSettings } from "classcyclr";
import {
EightBittr,
ComponentSettings,
EightBittrConstructorSettings,
EightBittrSettings,
} from "eightbittr";
import { FlagSwappr, FlagSwapprSettings } from "flagswappr";
import { GroupHoldr } from "groupholdr";
import { ItemsHoldr } from "itemsholdr";
import { MenuGraphr } from "menugraphr";
import { ModAttachrSettings, ModAttachr, ModsItemsHoldr } from "modattachr";
import { NumberMakrSettings, NumberMakr } from "numbermakr";
import { ScenePlayr } from "sceneplayr";
import { StateHoldr, StateItemsHoldr } from "stateholdr";
import { createAudioPlayer } from "./creators/createAudioPlayer";
import { createBattleMover } from "./creators/createBattleMover";
import { createClassCycler } from "./creators/createClassCycler";
import { createFlagSwapper, Flags } from "./creators/createFlagSwapper";
import { createMenuGrapher } from "./creators/createMenuGrapher";
import { createModAttacher } from "./creators/createModAttacher";
import { createNumberMaker } from "./creators/createNumberMaker";
import { createScenePlayer } from "./creators/createScenePlayer";
import { createStateHolder } from "./creators/createStateHolder";
import { Actions } from "./sections/Actions";
import { Animations } from "./sections/Animations";
import { Audio } from "./sections/Audio";
import { Battles } from "./sections/Battles";
import { Collisions } from "./sections/Collisions";
import { Constants } from "./sections/Constants";
import { Cutscenes } from "./sections/Cutscenes";
import { Cycling } from "./sections/Cycling";
import { Equations } from "./sections/Equations";
import { Evolution } from "./sections/Evolution";
import { Experience } from "./sections/Experience";
import { Fishing } from "./sections/Fishing";
import { Frames } from "./sections/Frames";
import { Gameplay } from "./sections/Gameplay";
import { Graphics } from "./sections/Graphics";
import { ActorGroups, Groups } from "./sections/Groups";
import { Inputs } from "./sections/Inputs";
import { Items } from "./sections/Items";
import { Maintenance } from "./sections/Maintenance";
import { MapScreenr, Maps } from "./sections/Maps";
import { Menus } from "./sections/Menus";
import { Mods } from "./sections/Mods";
import { MoveAdder } from "./sections/MoveAdder";
import { Objects } from "./sections/Objects";
import { Physics } from "./sections/Physics";
import { Quadrants } from "./sections/Quadrants";
import { Saves } from "./sections/Saves";
import { Scrolling } from "./sections/Scrolling";
import { StorageItems, Storage } from "./sections/Storage";
import { Player, Actors } from "./sections/Actors";
import { Timing } from "./sections/Timing";
import { Utilities } from "./sections/Utilities";
/**
* Settings to initialize a new FullScreenPokemon.
*/
export interface FullScreenPokemonComponentSettings extends ComponentSettings {
/**
* Setings overrides for the game's AudioPlayr.
*/
audioPlayer?: Partial<AudioPlayrSettings>;
/**
* Setings overrides for the game's ClassCyclr.
*/
classCycler?: Partial<ClassCyclrSettings>;
/**
* Setings overrides for the game's FlagSwappr.
*/
flagSwapper?: Partial<FlagSwapprSettings<Flags>>;
/**
* Setings overrides for the game's ModAttachr.
*/
modAttacher?: Partial<ModAttachrSettings>;
/**
* Setings overrides for the game's NumberMakr.
*/
numberMaker?: Partial<NumberMakrSettings>;
}
/**
* Filled-out settings to initialize a new FullScreenPokemon.
*/
export interface FullScreenPokemonConstructorSettings extends EightBittrConstructorSettings {
/**
* Component settings overrides.
*/
components?: Partial<FullScreenPokemonComponentSettings>;
}
/**
* Settings to initialize a new FullScreenPokemon.
*/
export interface FullScreenPokemonSettings extends EightBittrSettings {
/**
* Component settings overrides.
*/
components: Partial<FullScreenPokemonComponentSettings>;
}
/**
* HTML5 remake of the original Pokemon, expanded for modern browsers.
*/
export class FullScreenPokemon extends EightBittr {
/**
* Screen and component reset settings.
*/
public readonly settings: FullScreenPokemonSettings;
@factory(createAudioPlayer)
public readonly audioPlayer: AudioPlayr;
/**
* An in-game battle management system for RPG-like battles between actors.
*/
@factory(createBattleMover)
public readonly battleMover: BattleMovr;
/**
* Cycles through class names using TimeHandlr events.
*/
@factory(createClassCycler)
public readonly classCycler: ClassCyclr;
/**
* Gates flags behind generational gaps.
*/
@factory(createFlagSwapper)
public readonly flagSwapper: FlagSwappr<Flags>;
/**
* Stores arrays of Actors by their group name.
*/
public readonly groupHolder: GroupHoldr<ActorGroups>;
/**
* Cache-based wrapper around localStorage.
*/
public readonly itemsHolder: ItemsHoldr<StorageItems> & ModsItemsHoldr & StateItemsHoldr;
/**
* A flexible container for map attributes and viewport.
*/
public readonly mapScreener: MapScreenr;
/**
* In-game menu and dialog management system.
*/
@factory(createMenuGrapher)
public readonly menuGrapher: MenuGraphr;
/**
* Hookups for extensible triggered mod events.
*/
@factory(createModAttacher)
public readonly modAttacher: ModAttachr;
/**
* Configurable Mersenne Twister implementation.
*/
@factory(createNumberMaker)
public readonly numberMaker: NumberMakr;
/**
* A stateful cutscene runner for jumping between scenes and their routines.
*/
@factory(createScenePlayer)
public readonly scenePlayer: ScenePlayr;
/**
* General localStorage saving for collections of state.
*/
@factory(createStateHolder)
public readonly stateHolder: StateHoldr;
/**
* Actions characters may perform walking around.
*/
@member(Actions)
public readonly actions: Actions;
/**
* Generic animations for Actors.
*/
@member(Animations)
public readonly animations: Animations;
/**
* Friendly sound aliases and names for audio.
*/
@member(Audio)
public readonly audio: Audio;
/**
* BattleMovr hooks to run trainer battles.
*/
@member(Battles)
public readonly battles: Battles;
/**
* ActorHittr collision function generators.
*/
@member(Collisions)
public readonly collisions: Collisions<this>;
/**
* Universal game constants.
*/
@member(Constants)
public readonly constants: Constants;
/**
* ScenePlayr cutscenes, keyed by name.
*/
@member(Cutscenes)
public readonly cutscenes: Cutscenes;
/**
* Starts and stop characters cycling.
*/
@member(Cycling)
public readonly cycling: Cycling;
/**
* Common equations.
*/
@member(Equations)
public readonly equations: Equations;
/**
* Logic for what Pokemon are able to evolve into.
*/
@member(Evolution)
public readonly evolution: Evolution;
/**
* Calculates experience gains and level ups for Pokemon.
*/
@member(Experience)
public readonly experience: Experience;
/**
* Runs the player trying to fish for Pokemon.
*/
@member(Fishing)
public readonly fishing: Fishing;
/**
* How to advance each frame of the game.
*/
@member(Frames)
public readonly frames: Frames<this>;
/**
* Event hooks for major gameplay state changes.
*/
@member(Gameplay)
public readonly gameplay: Gameplay;
/**
* Changes the visual appearance of Actors.
*/
@member(Graphics)
public readonly graphics: Graphics<this>;
/**
* Collection settings for Actor group names.
*/
@member(Groups)
public readonly groups: Groups<this>;
/**
* User input filtering and handling.
*/
@member(Inputs)
public readonly inputs: Inputs<this>;
/**
* Storage keys and value settings.
*/
@member(Items)
public readonly items: Items<this>;
/**
* Maintains Actors during FrameTickr ticks.
*/
@member(Maintenance)
public readonly maintenance: Maintenance<this>;
/**
* Enters and spawns map areas.
*/
@member(Maps)
public readonly maps: Maps<this>;
/**
* Manipulates MenuGraphr menus.
*/
@member(Menus)
public readonly menus: Menus;
/**
* Creates ModAttachr from mod classes.
*/
@member(Mods)
public readonly mods: Mods;
/**
* Creates MoveAdder to teach Pokemon new moves.
*/
@member(MoveAdder)
public readonly moveAdder: MoveAdder;
/**
* Raw ObjectMakr factory settings.
*/
@member(Objects)
public readonly objects: Objects<this>;
/**
* Arranges game physics quadrants.
*/
@member(Quadrants)
public readonly quadrants: Quadrants<this>;
/**
* Physics functions to move Actors around.
*/
@member(Physics)
public readonly physics: Physics<this>;
/**
* Saves and load game data.
*/
@member(Saves)
public readonly saves: Saves;
/**
* Moves the screen and Actors in it.
*/
@member(Scrolling)
public readonly scrolling: Scrolling<this>;
/**
* Settings for storing items in ItemsHoldrs.
*/
@member(Storage)
public readonly storage: Storage;
/**
* Adds and processes new Actors into the game.
*/
@member(Actors)
public readonly actors: Actors<this>;
/**
* Timing constants for delayed events.
*/
@member(Timing)
public readonly timing: Timing<this>;
/**
* Miscellaneous utility functions.
*/
@member(Utilities)
public readonly utilities: Utilities<this>;
/**
* The game's single player.
*
* @remarks We assume nobody will try to access this before a map entrance.
*/
public readonly players: [Player] = [undefined as any];
/**
* Total FpsAnalyzr ticks that have elapsed since the constructor or saving.
*/
public ticksElapsed: number;
/**
* Initializes a new instance of the FullScreenPokemon class.
*
* @param settings Settings to be used for initialization.
*/
public constructor(settings: FullScreenPokemonConstructorSettings) {
super(settings);
this.itemsHolder.setAutoSave(this.itemsHolder.getItem(this.storage.names.autoSave));
}
} | the_stack |
import { Scheme } from 'ayu'
export default (scheme: Scheme) => ({
name: "ayu",
globals: {
background: scheme.editor.bg.hex(),
foreground: scheme.editor.fg.hex(),
invisibles: scheme.editor.fg.alpha(.3).hex(),
caret: scheme.common.accent.hex(),
block_caret: scheme.common.accent.alpha(.3).hex(),
line_highlight: scheme.editor.line.hex(),
// misspelling: ,
// fold_marker: ,
// minimap_border: ,
accent: scheme.common.accent.hex(),
popup_css: `
html, body {
background-color: ${scheme.ui.popup.bg.hex()};
color: ${scheme.editor.fg.hex()};
--mdpopups-font-mono: "PragmataPro Mono Liga", "sf mono", Consolas, "Liberation Mono", Menlo, Courier, monospace;
--mdpopups-bg: ${scheme.ui.popup.bg.hex()};
--mdpopups-link: ${scheme.syntax.entity.hex()};
}
body {
padding: 1px 3px;
}
a {
color: rgba(${scheme.syntax.entity.rgb()}, .7);
}
`,
gutter: scheme.editor.bg.hex(),
gutter_foreground: scheme.editor.gutter.normal.hex(),
line_diff_width: "2",
line_diff_added: scheme.vcs.added.alpha(.7).hex(),
line_diff_modified: scheme.vcs.modified.alpha(.7).hex(),
line_diff_deleted: scheme.vcs.removed.alpha(.7).hex(),
selection: scheme.editor.selection.active.hex(),
selection_border: scheme.editor.selection.active.hex(),
selection_border_width: "1",
inactive_selection: scheme.editor.selection.inactive.hex(),
inactive_selection_border: scheme.editor.selection.inactive.hex(),
selection_corner_style: "round",
selection_corner_radius: "4",
highlight: scheme.common.accent.alpha(.4).hex(),
find_highlight: scheme.common.accent.hex(),
find_highlight_foreground: scheme.editor.bg.hex(),
guide: scheme.editor.indentGuide.normal.hex(),
active_guide: scheme.editor.indentGuide.active.hex(),
stack_guide: scheme.editor.indentGuide.normal.alpha(.4).hex(),
shadow: scheme.editor.bg.alpha(0.3).hex(),
shadow_width: "3",
},
rules: [
{
name: 'Comment',
scope: 'comment',
font_style: 'italic',
foreground: scheme.syntax.comment.hex()
},
{
name: 'String',
scope: 'string - meta.template, constant.other.symbol, string.quoted',
foreground: scheme.syntax.string.hex()
},
{
name: 'Regular Expressions and Escape Characters',
scope: 'string.regexp, constant.character, constant.other',
foreground: scheme.syntax.regexp.hex()
},
{
name: 'Number',
scope: 'constant.numeric',
foreground: scheme.common.accent.hex()
},
{
name: 'Built-in constants',
scope: 'constant.language',
foreground: scheme.common.accent.hex()
},
{
name: 'Constants',
scope: 'meta.constant, entity.name.constant',
foreground: scheme.syntax.constant.hex()
},
{
name: 'Variable',
scope: 'variable',
foreground: scheme.editor.fg.hex()
},
{
name: 'Member Variable',
scope: 'variable.member',
foreground: scheme.syntax.markup.hex()
},
{
name: 'Language variable',
scope: 'variable.language',
font_style: 'italic',
foreground: scheme.syntax.tag.hex()
},
// ------
// Keywords
{
name: 'Storage',
scope: 'storage, storage.type.keyword',
foreground: scheme.syntax.keyword.hex()
},
{
name: 'Keyword',
scope: 'keyword',
foreground: scheme.syntax.keyword.hex()
},
{
name: 'Java keyword fixes',
scope: 'source.java meta.class.java meta.class.identifier.java storage.type.java',
foreground: scheme.syntax.keyword.hex()
},
// ------
// Operators
{
name: 'Operators',
scope: 'keyword.operator',
foreground: scheme.syntax.operator.hex()
},
// ------
// Punctuation
{
name: 'Separators like ; or ,',
scope: 'punctuation.separator, punctuation.terminator',
foreground: scheme.editor.fg.alpha(.7).hex()
},
{
name: 'Punctuation',
scope: 'punctuation.section',
foreground: scheme.editor.fg.hex()
},
{
name: 'Accessor',
scope: 'punctuation.accessor',
foreground: scheme.syntax.operator.hex()
},
{
name: 'JavaScript/TypeScript interpolation punctuation',
scope: 'punctuation.definition.template-expression',
foreground: scheme.syntax.keyword.hex()
},
{
name: 'Ruby interpolation punctuation',
scope: 'punctuation.section.interpolation',
foreground: scheme.syntax.keyword.hex()
},
// ------
// Types
{
name: 'Types fixes',
scope: 'source.java storage.type, source.haskell storage.type, source.c storage.type',
foreground: scheme.syntax.entity.hex()
},
{
name: 'Inherited class type',
scope: 'entity.other.inherited-class',
foreground: scheme.syntax.tag.hex()
},
// Fixes
{
name: 'Lambda arrow',
scope: 'storage.type.function',
foreground: scheme.syntax.keyword.hex()
},
{
name: 'Java primitive variable types',
scope: 'source.java storage.type.primitive',
foreground: scheme.syntax.tag.hex()
},
// ------
// Function/method names in definitions
// and calls
{
name: 'Function name',
scope: 'entity.name.function',
foreground: scheme.syntax.func.hex()
},
{
name: 'Function arguments',
scope: 'variable.parameter, meta.parameter',
foreground: scheme.syntax.constant.hex()
},
{
name: 'Function call',
scope: 'variable.function, variable.annotation, meta.function-call.generic, support.function.go',
foreground: scheme.syntax.func.hex()
},
{
name: 'Library function',
scope: 'support.function, support.macro',
foreground: scheme.syntax.markup.hex()
},
{
name: 'Imports and packages',
scope: 'entity.name.import, entity.name.package',
foreground: scheme.syntax.string.hex()
},
{
name: 'Entity name',
scope: 'entity.name, source.js meta.function-call.constructor variable.type',
foreground: scheme.syntax.entity.hex()
},
// Tag and their attributes
{
name: 'Tag',
scope: 'entity.name.tag, meta.tag.sgml',
foreground: scheme.syntax.tag.hex()
},
{
name: 'Tag start/end',
scope: 'punctuation.definition.tag.end, punctuation.definition.tag.begin, punctuation.definition.tag',
foreground: scheme.syntax.tag.alpha(.5).hex()
},
{
name: 'Tag attribute',
scope: 'entity.other.attribute-name',
foreground: scheme.syntax.func.hex()
},
{
name: 'Library constant',
scope: 'support.constant',
font_style: 'italic',
foreground: scheme.syntax.operator.hex()
},
{
name: 'Library class/type',
scope: 'support.type, support.class, source.go storage.type',
foreground: scheme.syntax.tag.hex()
},
{
name: 'Decorators/annotation',
scope: 'meta.decorator variable.other, meta.decorator punctuation.decorator, storage.type.annotation, variable.annotation, punctuation.definition.annotation',
foreground: scheme.syntax.special.hex()
},
{
name: 'Invalid',
scope: 'invalid',
foreground: scheme.common.error.hex()
},
{
name: 'diff.header',
scope: 'meta.diff, meta.diff.header',
foreground: '#c594c5'
},
{
name: 'Ruby class methods',
scope: 'source.ruby variable.other.readwrite',
foreground: scheme.syntax.func.hex()
},
{
name: 'CSS tag names',
scope: 'source.css entity.name.tag, source.sass entity.name.tag, source.scss entity.name.tag, source.less entity.name.tag, source.stylus entity.name.tag',
foreground: scheme.syntax.entity.hex()
},
{
name: 'CSS browser prefix',
scope: 'source.css support.type, source.sass support.type, source.scss support.type, source.less support.type, source.stylus support.type',
foreground: scheme.syntax.comment.hex()
},
{
name: 'CSS Properties',
scope: 'support.type.property-name',
font_style: 'normal',
foreground: scheme.syntax.tag.hex()
},
{
name: 'Search Results Nums',
scope: 'constant.numeric.line-number.find-in-files - match',
foreground: scheme.syntax.comment.hex()
},
{
name: 'Search Results Match Nums',
scope: 'constant.numeric.line-number.match',
foreground: scheme.syntax.keyword.hex()
},
{
name: 'Search Results Lines',
scope: 'entity.name.filename.find-in-files',
foreground: scheme.syntax.string.hex()
},
{
scope: 'message.error',
foreground: scheme.common.error.hex()
},
{
name: 'Markup heading',
scope: 'markup.heading, markup.heading entity.name',
font_style: 'bold',
foreground: scheme.syntax.string.hex()
},
{
name: 'Markup links',
scope: 'markup.underline.link, string.other.link',
foreground: scheme.syntax.entity.hex()
},
{
name: 'Markup Italic',
scope: 'markup.italic',
font_style: 'italic',
foreground: scheme.syntax.markup.hex()
},
{
name: 'Markup Bold',
scope: 'markup.bold',
font_style: 'bold',
foreground: scheme.syntax.markup.hex()
},
{
name: 'Markup Bold/italic',
scope: 'markup.italic markup.bold, markup.bold markup.italic',
font_style: 'bold italic'
},
{
name: 'Markup Code',
scope: 'markup.raw',
background: scheme.editor.fg.alpha(.02).hex()
},
{
name: 'Markup Code Inline',
scope: 'markup.raw.inline',
background: scheme.editor.fg.alpha(.06).hex()
},
{
name: 'Markdown Separator',
scope: 'meta.separator',
font_style: 'bold',
background: scheme.editor.fg.alpha(.06).hex(),
foreground: scheme.syntax.comment.hex()
},
{
name: 'Markup Blockquote',
scope: 'markup.quote',
foreground: scheme.syntax.regexp.hex(),
font_style: 'italic'
},
{
name: 'Markup List Bullet',
scope: 'markup.list punctuation.definition.list.begin',
foreground: scheme.syntax.func.hex()
},
{
name: 'Markup added',
scope: 'markup.inserted',
foreground: scheme.vcs.added.hex()
},
{
name: 'Markup modified',
scope: 'markup.changed',
foreground: scheme.vcs.modified.hex()
},
{
name: 'Markup removed',
scope: 'markup.deleted',
foreground: scheme.vcs.removed.hex()
},
{
name: 'Markup Strike',
scope: 'markup.strike',
foreground: scheme.syntax.special.hex()
},
{
name: 'Markup Table',
scope: 'markup.table',
background: scheme.editor.fg.alpha(.06).hex(),
foreground: scheme.syntax.tag.hex()
},
{
name: 'Markup Raw Inline',
scope: 'text.html.markdown markup.inline.raw',
foreground: scheme.syntax.operator.hex()
},
{
name: 'Markdown - Line Break',
scope: 'text.html.markdown meta.dummy.line-break',
background: scheme.syntax.comment.hex(),
foreground: scheme.syntax.comment.hex()
},
{
name: 'Markdown - Raw Block Fenced',
scope: 'punctuation.definition.markdown',
background: scheme.editor.fg.hex(),
foreground: scheme.syntax.comment.hex()
}
]
}) | the_stack |
import { IDataSet } from '../../src/base/engine';
import { pivot_dataset } from '../base/datasource.spec';
import { PivotView } from '../../src/pivotview/base/pivotview';
import { createElement, remove } from '@syncfusion/ej2-base';
import { ExcelExport, PDFExport } from '../../src/pivotview/actions';
import { ConditionalFormatting } from '../../src/common/conditionalformatting/conditional-formatting';
import * as util from '../utils.spec';
import { profile, inMB, getMemoryProfile } from '../common.spec';
describe('Miscellaneous Features', () => {
beforeAll(() => {
const isDef = (o: any) => o !== undefined && o !== null;
if (!isDef(window.performance)) {
console.log("Unsupported environment, window.performance.memory is unavailable");
this.skip(); //Skips test (in Chai)
return;
}
});
describe('Exporting and scrolling', () => {
let pivotGridObj: PivotView;
let elem: HTMLElement = createElement('div', { id: 'PivotGrid' });
if (document.getElementById(elem.id)) {
remove(document.getElementById(elem.id));
}
document.body.appendChild(elem);
afterAll(() => {
if (pivotGridObj) {
pivotGridObj.destroy();
}
remove(elem);
});
beforeAll(() => {
if (document.getElementById(elem.id)) {
remove(document.getElementById(elem.id));
}
document.body.appendChild(elem);
PivotView.Inject(ExcelExport, PDFExport);
pivotGridObj = new PivotView({
dataSourceSettings: {
dataSource: pivot_dataset as IDataSet[],
expandAll: true,
enableSorting: true,
sortSettings: [{ name: 'company', order: 'Descending' }],
formatSettings: [{ name: 'balance', format: 'C' }],
filterSettings: [
{ name: 'eyeColor', type: 'Include', items: ['blue', 'green'] },
{ name: 'isActive', type: 'Include', items: ['true'] },
{
name: 'date', type: 'Include', items: [
'Fri Dec 18 1987 05:37:53 GMT+0530 (India Standard Time)',
'Fri Jan 10 2003 20:13:56 GMT+0530 (India Standard Time)',
'Fri Jan 15 2010 12:24:35 GMT+0530 (India Standard Time)',
'Fri Mar 30 1990 00:54:08 GMT+0530 (India Standard Time)',
'Fri May 24 1996 23:27:58 GMT+0530 (India Standard Time)',
'Fri May 27 1983 06:48:41 GMT+0530 (India Standard Time)',
'Fri Nov 06 1987 19:11:22 GMT+0530 (India Standard Time)'
]
}],
columns: [{ name: 'eyeColor' }, { name: 'date' }],
rows: [{ name: 'isActive' }, { name: 'state' }],
values: [{ name: 'balance' }, { name: 'quantity' }]
},
beforeExport: util.beforeExport,
onPdfCellRender: util.pdfCellRender,
allowExcelExport: true,
allowPdfExport: true,
enableRtl: true,
width: 1000,
height: 100,
gridSettings: {
allowReordering: true,
pdfHeaderQueryCellInfo: (args: any): void => {
},
pdfQueryCellInfo: (args: any): void => {
},
excelHeaderQueryCellInfo: (args: any): void => {
},
excelQueryCellInfo: (args: any): void => {
}
}
});
pivotGridObj.appendTo('#PivotGrid');
});
it('pivotgrid excel export', () => {
pivotGridObj.excelExport();
});
it('pivotgrid csv dataSource', () => {
pivotGridObj.csvExport();
});
it('pivotgrid pdf dataSource', () => {
pivotGridObj.pdfExport();
});
it('pivotgrid excel-engine export', () => {
pivotGridObj.excelExportModule.exportToExcel('Excel');
});
it('pivotgrid csv-engine dataSource', () => {
pivotGridObj.excelExportModule.exportToExcel('CSV');
pivotGridObj.excelExportModule.destroy();
});
it('value axis row', () => {
pivotGridObj.dataSourceSettings.valueAxis = 'row';
pivotGridObj.pdfExportModule.exportToPDF();
pivotGridObj.pdfExportModule.destroy();
});
it('pivotgrid excel export', () => {
pivotGridObj.excelExport();
});
it('pivotgrid pdf dataSource', () => {
pivotGridObj.pdfExport();
});
});
describe('Pivot Grid Conditional Formatting Export', () => {
let pivotGridObj: PivotView;
let elem: HTMLElement = createElement('div', { id: 'PivotGrid' });
if (document.getElementById(elem.id)) {
remove(document.getElementById(elem.id));
}
document.body.appendChild(elem);
afterAll(() => {
if (pivotGridObj) {
pivotGridObj.destroy();
}
remove(elem);
});
beforeAll(() => {
if (document.getElementById(elem.id)) {
remove(document.getElementById(elem.id));
}
document.body.appendChild(elem);
PivotView.Inject(ExcelExport, PDFExport, ConditionalFormatting);
pivotGridObj = new PivotView({
dataSourceSettings: {
dataSource: pivot_dataset as IDataSet[],
expandAll: true,
enableSorting: true,
sortSettings: [{ name: 'company', order: 'Descending' }],
formatSettings: [{ name: 'balance', format: 'C' }],
filterSettings: [
{ name: 'eyeColor', type: 'Include', items: ['blue'] },
{ name: 'isActive', type: 'Include', items: ['true'] }
],
rows: [{ name: 'eyeColor' }, { name: 'product' }],
columns: [{ name: 'isActive' }, { name: 'gender' }],
values: [{ name: 'balance' }, { name: 'quantity' }],
conditionalFormatSettings: [
{
value1: 50000,
value2: 600,
conditions: 'Between',
style: {
backgroundColor: 'violet',
color: 'yellow',
fontFamily: 'Verdana',
fontSize: '13px'
},
}
]
},
allowConditionalFormatting: true,
allowExcelExport: true,
allowPdfExport: true,
width: 1000,
height: 200
});
pivotGridObj.appendTo('#PivotGrid');
});
it('pivotgrid excel-engine export', () => {
pivotGridObj.excelExportModule.exportToExcel('Excel');
});
it('pivotgrid pdf-engine dataSource', () => {
pivotGridObj.pdfExportModule.exportToPDF();
});
});
describe('Pivot Grid Conditional Formatting Export with Virtual Scrolling', () => {
let pivotGridObj: PivotView;
let elem: HTMLElement = createElement('div', { id: 'PivotGrid' });
if (document.getElementById(elem.id)) {
remove(document.getElementById(elem.id));
}
document.body.appendChild(elem);
afterAll(() => {
if (pivotGridObj) {
pivotGridObj.destroy();
}
remove(elem);
});
beforeAll(() => {
if (document.getElementById(elem.id)) {
remove(document.getElementById(elem.id));
}
document.body.appendChild(elem);
PivotView.Inject(ExcelExport, PDFExport, ConditionalFormatting);
pivotGridObj = new PivotView({
dataSourceSettings: {
dataSource: pivot_dataset as IDataSet[],
expandAll: true,
enableSorting: true,
sortSettings: [{ name: 'company', order: 'Descending' }],
formatSettings: [{ name: 'balance', format: 'C' }],
filterSettings: [
{ name: 'eyeColor', type: 'Include', items: ['blue'] },
{ name: 'isActive', type: 'Include', items: ['true'] }
],
rows: [{ name: 'eyeColor' }, { name: 'product' }],
columns: [{ name: 'isActive' }, { name: 'gender' }],
values: [{ name: 'balance' }, { name: 'quantity' }],
conditionalFormatSettings: [
{
value1: 50000,
value2: 600,
conditions: 'Between',
style: {
backgroundColor: 'violet',
color: 'yellow',
fontFamily: 'Verdana',
fontSize: '13px'
},
}
]
},
allowConditionalFormatting: true,
allowExcelExport: true,
allowPdfExport: true,
enableVirtualization: true,
width: 1000,
height: 200
});
pivotGridObj.appendTo('#PivotGrid');
});
it('pivotgrid excel-engine export', () => {
pivotGridObj.excelExportModule.exportToExcel('Excel');
});
it('pivotgrid pdf-engine dataSource', () => {
pivotGridObj.pdfExportModule.exportToPDF();
});
});
it('memory leak', () => {
profile.sample();
let average: any = inMB(profile.averageChange);
//Check average change in memory samples to not be over 10MB
//expect(average).toBeLessThan(10);
let memory: any = inMB(getMemoryProfile());
//Check the final memory usage against the first usage, there should be little change if everything was properly deallocated
expect(memory).toBeLessThan(profile.samples[0] + 0.25);
});
}); | the_stack |
import * as omit from "lodash.omit";
import * as singleLineString from "single-line-string";
import * as Web3 from "web3";
// Utils
import { BigNumber } from "../../utils/bignumber";
import { NULL_ADDRESS } from "../../utils/constants";
import * as TransactionUtils from "../../utils/transaction_utils";
// Types
import { DebtOrderData, DebtRegistryEntry, RepaymentSchedule } from "../types";
import { SimpleInterestLoanTerms } from "./simple_interest_loan_terms";
import { ContractsAPI } from "../apis";
import { Assertions } from "../invariants";
import { Adapter } from "./adapter";
export interface SimpleInterestLoanOrder extends DebtOrderData {
// Required Debt Order Parameters
principalAmount: BigNumber;
principalTokenSymbol: string;
// Parameters for Terms Contract
interestRate: BigNumber;
amortizationUnit: AmortizationUnit;
termLength: BigNumber;
}
export interface SimpleInterestTermsContractParameters {
principalAmount: BigNumber;
interestRate: BigNumber;
amortizationUnit: AmortizationUnit;
termLength: BigNumber;
principalTokenIndex: BigNumber;
}
export type AmortizationUnit = "hours" | "days" | "weeks" | "months" | "years";
const MAX_TERM_LENGTH_VALUE_HEX = "0xffff";
const MAX_INTEREST_RATE_PRECISION = 4;
export const SimpleInterestAdapterErrors = {
INVALID_TOKEN_INDEX: (tokenIndex: BigNumber) =>
singleLineString`Token Registry does not track a token at index
${tokenIndex.toString()}.`,
INVALID_PRINCIPAL_AMOUNT: () =>
singleLineString`Principal amount must be a whole number greater than 0
and less than 2^96 - 1.`,
INVALID_INTEREST_RATE: () =>
singleLineString`Interest amount cannot be negative,
greater than 1677.7216, or have more than
${MAX_INTEREST_RATE_PRECISION} decimal places.`,
INVALID_AMORTIZATION_UNIT_TYPE: () =>
singleLineString`Amortization unit must be of type HOURS, DAYS,
WEEKS, MONTHS, or YEARS.`,
INVALID_TERM_LENGTH: () =>
singleLineString`Term length value cannot be negative or greater
than ${parseInt(MAX_TERM_LENGTH_VALUE_HEX, 16)}`,
MISMATCHED_TOKEN_SYMBOL: (principalTokenIndex: BigNumber, symbol: string) =>
singleLineString`Terms contract parameters are invalid for the given debt order.
Principal token at index ${principalTokenIndex.toString()}, specified
in the terms contract, does not correspond to specified token
with symbol ${symbol}`,
MISMATCHED_TERMS_CONTRACT: (termsContract: string) =>
singleLineString`Terms contract at address ${termsContract} is not
a SimpleInterestTermsContract. As such, this adapter will not
interface with the terms contract as expected`,
};
export class SimpleInterestLoanAdapter implements Adapter {
public static Installments: { [type: string]: AmortizationUnit } = {
HOURLY: "hours",
DAILY: "days",
WEEKLY: "weeks",
MONTHLY: "months",
YEARLY: "years",
};
private assert: Assertions;
private readonly contracts: ContractsAPI;
private termsContractInterface: SimpleInterestLoanTerms;
public constructor(web3: Web3, contracts: ContractsAPI) {
this.assert = new Assertions(web3, contracts);
this.contracts = contracts;
this.termsContractInterface = new SimpleInterestLoanTerms(web3, contracts);
}
/**
* Asynchronously generates a Dharma debt order given an instance of a
* simple interest loan order.
*
* @param simpleInterestLoanOrder a simple interest loan order instance.
* @return the generated Dharma debt order.
*/
public async toDebtOrder(
simpleInterestLoanOrder: SimpleInterestLoanOrder,
): Promise<DebtOrderData> {
this.assert.schema.simpleInterestLoanOrder(
"simpleInterestLoanOrder",
simpleInterestLoanOrder,
);
const {
principalTokenSymbol,
principalAmount,
interestRate,
amortizationUnit,
termLength,
} = simpleInterestLoanOrder;
const principalToken = await this.contracts.loadTokenBySymbolAsync(principalTokenSymbol);
const principalTokenIndex = await this.contracts.getTokenIndexBySymbolAsync(
principalTokenSymbol,
);
const simpleInterestTermsContract = await this.contracts.loadSimpleInterestTermsContract();
let debtOrderData: DebtOrderData = omit(simpleInterestLoanOrder, [
"principalTokenSymbol",
"interestRate",
"amortizationUnit",
"termLength",
]);
debtOrderData = {
...debtOrderData,
principalToken: principalToken.address,
termsContract: simpleInterestTermsContract.address,
termsContractParameters: this.termsContractInterface.packParameters({
principalTokenIndex,
principalAmount,
interestRate,
amortizationUnit,
termLength,
}),
};
return TransactionUtils.applyNetworkDefaults(debtOrderData, this.contracts);
}
/**
* Asynchronously generates a simple interest loan order given a Dharma
* debt order instance.
*
* @param debtOrderData a Dharma debt order instance.
* @return the generated simple interest loan order.
*/
public async fromDebtOrder(debtOrderData: DebtOrderData): Promise<SimpleInterestLoanOrder> {
this.assert.schema.debtOrderWithTermsSpecified("debtOrder", debtOrderData);
const {
principalTokenIndex,
principalAmount,
interestRate,
termLength,
amortizationUnit,
} = this.unpackParameters(debtOrderData.termsContractParameters);
const principalTokenSymbol = await this.contracts.getTokenSymbolByIndexAsync(
principalTokenIndex,
);
return {
...debtOrderData,
principalAmount,
principalTokenSymbol,
interestRate,
termLength,
amortizationUnit,
};
}
/**
* Asynchronously translates a Dharma debt registry entry into a
* simple interest loan order.
*
* @param entry a Dharma debt registry entry
* @return the translated simple interest loan order
*/
public async fromDebtRegistryEntry(entry: DebtRegistryEntry): Promise<SimpleInterestLoanOrder> {
await this.assertIsSimpleInterestTermsContract(entry.termsContract);
const {
principalTokenIndex,
principalAmount,
interestRate,
termLength,
amortizationUnit,
} = this.unpackParameters(entry.termsContractParameters);
const principalTokenSymbol = await this.contracts.getTokenSymbolByIndexAsync(
principalTokenIndex,
);
return {
principalTokenSymbol,
principalAmount,
interestRate,
termLength,
amortizationUnit,
};
}
public getRepaymentSchedule(debtEntry: DebtRegistryEntry): number[] {
const { termsContractParameters, issuanceBlockTimestamp } = debtEntry;
const { termLength, amortizationUnit } = this.termsContractInterface.unpackParameters(
termsContractParameters,
);
return new RepaymentSchedule(
amortizationUnit,
termLength,
issuanceBlockTimestamp.toNumber(),
).toArray();
}
public unpackParameters(packedParams: string): SimpleInterestTermsContractParameters {
return this.termsContractInterface.unpackParameters(packedParams);
}
/**
* Validates that the basic invariants have been met for a given SimpleInterestLoanOrder.
*
* @param {SimpleInterestLoanOrder} simpleInterestLoanOrder
* @returns {Promise<void>}
*/
public async validateAsync(simpleInterestLoanOrder: SimpleInterestLoanOrder) {
this.termsContractInterface.validate(simpleInterestLoanOrder.termsContractParameters);
await this.assertIsSimpleInterestTermsContract(simpleInterestLoanOrder.termsContract);
await this.assertPrincipalTokenValidAsync(simpleInterestLoanOrder);
}
private async assertIsSimpleInterestTermsContract(termsContractAddress: string): Promise<void> {
const simpleInterestTermsContract = await this.contracts.loadSimpleInterestTermsContract();
if (termsContractAddress !== simpleInterestTermsContract.address) {
throw new Error(
SimpleInterestAdapterErrors.MISMATCHED_TERMS_CONTRACT(termsContractAddress),
);
}
}
/**
* Asserts that the address of the principal token specified in the loan order
* matches the address of the principal token specified in the terms contract parameters.
*
* @param {SimpleInterestLoanOrder} loanOrder
* @returns {Promise<void>}
*/
private async assertPrincipalTokenValidAsync(loanOrder: SimpleInterestLoanOrder) {
const principalTokenSymbol = loanOrder.principalTokenSymbol;
const unpackedTerms = this.unpackParameters(loanOrder.termsContractParameters);
const tokenIndex = unpackedTerms.principalTokenIndex;
// Find the token in the registry.
const tokenRegistry = await this.contracts.loadTokenRegistry();
const tokenAddress = await tokenRegistry.getTokenAddressBySymbol.callAsync(
principalTokenSymbol,
);
const expectedTokenAddress = await tokenRegistry.getTokenAddressByIndex.callAsync(
tokenIndex,
);
if (tokenAddress === NULL_ADDRESS || tokenAddress !== expectedTokenAddress) {
throw new Error(
SimpleInterestAdapterErrors.MISMATCHED_TOKEN_SYMBOL(
tokenIndex,
principalTokenSymbol,
),
);
}
}
} | the_stack |
import dayGridPlugin from '@fullcalendar/daygrid'
import rrulePlugin from '@fullcalendar/rrule'
import luxonPlugin from '@fullcalendar/luxon'
import { parseUtcDate, parseLocalDate } from '../lib/date-parsing'
describe('rrule plugin', () => {
pushOptions({
plugins: [rrulePlugin, dayGridPlugin],
initialView: 'dayGridMonth',
now: '2018-09-07',
timeZone: 'UTC',
})
it('expands events when given an rrule object', () => {
initCalendar({
events: [
{
rrule: {
dtstart: '2018-09-04T13:00:00',
freq: 'weekly',
},
},
],
})
let events = getSortedEvents()
expect(events.length).toBe(5)
expect(events[0].start).toEqualDate('2018-09-04T13:00:00Z')
expect(events[0].end).toBe(null)
expect(events[1].start).toEqualDate('2018-09-11T13:00:00Z')
expect(events[2].start).toEqualDate('2018-09-18T13:00:00Z')
expect(events[3].start).toEqualDate('2018-09-25T13:00:00Z')
expect(events[4].start).toEqualDate('2018-10-02T13:00:00Z')
})
it('can expand monthly recurrence when given an rrule object', () => {
initCalendar({
initialView: 'dayGridMonth',
now: '2018-12-25T12:00:00',
events: [{
rrule: {
dtstart: '2018-11-01',
freq: 'monthly',
count: 13,
bymonthday: [13],
},
}],
})
let events = currentCalendar.getEvents()
expect(events.length).toBe(1)
expect(events[0].start).toEqualDate('2018-12-13')
})
// https://github.com/fullcalendar/fullcalendar/issues/6059
it('can specify strings in byweekday', () => {
initCalendar({
initialView: 'dayGridMonth',
initialDate: '2021-01-01',
events: [{
allDay: true,
rrule: {
freq: 'weekly',
byweekday: ['mo', 'tu'],
dtstart: '2021-01-01',
},
}],
})
let events = currentCalendar.getEvents()
expect(events.length).toBe(10)
expect(events[0].start).toEqualDate('2021-01-04')
})
it('can exclude a recurrence with exdate', () => {
let calendar = initCalendar({
initialView: 'dayGridMonth',
now: '2020-12-01',
events: [{
rrule: {
dtstart: '2020-12-01',
freq: 'weekly',
},
exdate: '2020-12-08',
}],
})
let events = calendar.getEvents()
expect(events.length).toBe(5)
expect(events[0].start).toEqualDate('2020-12-01')
expect(events[1].start).toEqualDate('2020-12-15')
expect(events[2].start).toEqualDate('2020-12-22')
expect(events[3].start).toEqualDate('2020-12-29')
expect(events[4].start).toEqualDate('2021-01-05')
})
it('can exclude multiple recurrences with exdate', () => {
let calendar = initCalendar({
initialView: 'dayGridMonth',
now: '2020-12-01',
events: [{
rrule: {
dtstart: '2020-12-01',
freq: 'weekly',
},
exdate: ['2020-12-08', '2020-12-15'],
}],
})
let events = calendar.getEvents()
expect(events.length).toBe(4)
expect(events[0].start).toEqualDate('2020-12-01')
expect(events[1].start).toEqualDate('2020-12-22')
expect(events[2].start).toEqualDate('2020-12-29')
expect(events[3].start).toEqualDate('2021-01-05')
})
it('can exclude recurrences with an exrule', () => {
let calendar = initCalendar({
initialView: 'dayGridMonth',
now: '2020-12-01',
events: [{
rrule: {
dtstart: '2020-12-01',
freq: 'weekly',
},
exrule: {
dtstart: '2020-12-08',
until: '2020-12-15', // will include this date for exclusion
freq: 'weekly',
},
}],
})
let events = calendar.getEvents()
expect(events.length).toBe(4)
expect(events[0].start).toEqualDate('2020-12-01')
expect(events[1].start).toEqualDate('2020-12-22')
expect(events[2].start).toEqualDate('2020-12-29')
expect(events[3].start).toEqualDate('2021-01-05')
})
it('can exclude recurrences with multiple exrules', () => {
let calendar = initCalendar({
initialView: 'dayGridMonth',
now: '2020-12-01',
events: [{
rrule: {
dtstart: '2020-12-01',
freq: 'weekly',
},
exrule: [
{
dtstart: '2020-12-08',
until: '2020-12-15', // will include this date for exclusion
freq: 'weekly',
},
{
dtstart: '2020-12-22',
until: '2020-12-29', // will include this date for exclusion
freq: 'weekly',
},
],
}],
})
let events = calendar.getEvents()
expect(events.length).toBe(2)
expect(events[0].start).toEqualDate('2020-12-01')
expect(events[1].start).toEqualDate('2021-01-05')
})
it('expands events until a date', () => {
initCalendar({
events: [
{
rrule: {
dtstart: '2018-09-04T13:00:00',
until: '2018-10-01',
freq: 'weekly',
},
},
],
})
let events = getSortedEvents()
expect(events.length).toBe(4)
expect(events[0].start).toEqualDate('2018-09-04T13:00:00Z')
expect(events[0].end).toBe(null)
expect(events[1].start).toEqualDate('2018-09-11T13:00:00Z')
expect(events[2].start).toEqualDate('2018-09-18T13:00:00Z')
expect(events[3].start).toEqualDate('2018-09-25T13:00:00Z')
})
it('expands a range that starts exactly at the current view\'s start', () => {
initCalendar({
initialDate: '2019-04-02',
initialView: 'dayGridDay',
events: [
{
title: 'event with everyday with range',
allDay: true,
rrule: {
freq: 'daily',
dtstart: '2019-04-02',
until: '2019-04-09',
},
},
],
})
let events = getSortedEvents()
expect(events.length).toBeGreaterThanOrEqual(1)
expect(events[0].start).toEqualDate('2019-04-02')
})
it('expands events with a duration', () => {
initCalendar({
events: [
{
rrule: {
dtstart: '2018-09-04T13:00:00',
freq: 'weekly',
},
duration: '03:00',
},
],
})
let events = getSortedEvents()
expect(events.length).toBe(5)
expect(events[0].start).toEqualDate('2018-09-04T13:00:00Z')
expect(events[0].end).toEqualDate('2018-09-04T16:00:00Z')
})
it('expands events with guessed allDay', () => {
initCalendar({
events: [
{
rrule: {
dtstart: '2018-09-04',
freq: 'weekly',
},
},
],
})
let events = getSortedEvents()
expect(events.length).toBe(5)
expect(events[0].start).toEqualDate('2018-09-04')
expect(events[0].end).toBe(null)
expect(events[0].allDay).toBe(true)
})
it('inherits defaultAllDay from source', () => {
initCalendar({
defaultAllDay: false,
events: [
{
rrule: {
dtstart: parseUtcDate('2018-09-04'), // no allDay info
freq: 'weekly',
},
},
],
})
let events = getSortedEvents()
expect(events.length).toBe(5)
expect(events[0].start).toEqualDate('2018-09-04')
expect(events[0].end).toBe(null)
expect(events[0].allDay).toBe(false)
})
it('inherits defaultAllDay from source setting', () => {
initCalendar({
eventSources: [{
defaultAllDay: false,
events: [
{
rrule: {
dtstart: parseUtcDate('2018-09-04'), // no allDay info
freq: 'weekly',
},
},
],
}],
})
let events = getSortedEvents()
expect(events.length).toBe(5)
expect(events[0].start).toEqualDate('2018-09-04')
expect(events[0].end).toBe(null)
expect(events[0].allDay).toBe(false)
})
it('can generate local dates when given an rrule object', () => {
initCalendar({
timeZone: 'local',
events: [
{
rrule: {
dtstart: parseLocalDate('2018-09-04T05:00:00').toISOString(),
freq: 'weekly',
},
},
],
})
let events = getSortedEvents()
expect(events.length).toBe(5)
expect(events[0].start).toEqualLocalDate('2018-09-04T05:00:00')
expect(events[0].end).toBe(null)
expect(events[0].allDay).toBe(false)
})
describe('when given an rrule string', () => {
it('expands', () => {
initCalendar({
events: [
{
rrule:
'DTSTART:20180904T130000\n' +
'RRULE:FREQ=WEEKLY',
},
],
})
let events = getSortedEvents()
expect(events.length).toBe(5)
expect(events[0].start).toEqualDate('2018-09-04T13:00:00Z')
expect(events[0].end).toBe(null)
expect(events[1].start).toEqualDate('2018-09-11T13:00:00Z')
expect(events[2].start).toEqualDate('2018-09-18T13:00:00Z')
expect(events[3].start).toEqualDate('2018-09-25T13:00:00Z')
expect(events[4].start).toEqualDate('2018-10-02T13:00:00Z')
})
// https://github.com/fullcalendar/fullcalendar/issues/6126
it('expands correctly with UNTIL followed by newline', () => {
initCalendar({
events: [
{
rrule:
'DTSTART:20180904T130000\n' +
'RRULE:FREQ=WEEKLY;UNTIL=20180925T130000\n' +
'RDATE:20180904T130000',
},
],
})
let events = getSortedEvents()
expect(events.length).toBe(4)
})
it('respects allDay', () => {
initCalendar({
events: [
{
allDay: true,
rrule: 'DTSTART:20180904T130000\nRRULE:FREQ=WEEKLY',
},
],
})
let events = getSortedEvents()
expect(events[0].start).toEqualDate('2018-09-04') // should round down
expect(events[0].allDay).toBe(true)
expect(events[0].extendedProps).toEqual({}) // didnt accumulate allDay or rrule props
})
it('can expand monthly recurrence in UTC', () => {
initCalendar({
initialView: 'dayGridMonth',
now: '2018-12-25T12:00:00',
timeZone: 'UTC',
events: [{
rrule: 'DTSTART:20181101\nRRULE:FREQ=MONTHLY;COUNT=13;BYMONTHDAY=13',
}],
})
let events = currentCalendar.getEvents()
expect(events.length).toBe(1)
expect(events[0].start).toEqualDate('2018-12-13')
})
it('can expand monthly recurrence in local timeZone', () => {
initCalendar({
initialView: 'dayGridMonth',
now: '2018-12-25T12:00:00',
timeZone: 'local',
events: [{
rrule: 'DTSTART:20181101\nRRULE:FREQ=MONTHLY;COUNT=13;BYMONTHDAY=13',
}],
})
let events = currentCalendar.getEvents()
expect(events.length).toBe(1)
expect(events[0].start).toEqualLocalDate('2018-12-13')
})
it('can expand weekly timed recurrence in local timeZone', () => {
initCalendar({
initialView: 'dayGridMonth',
now: '2018-12-25T12:00:00',
timeZone: 'local',
events: [{
rrule: 'DTSTART:20181201T000000\nRRULE:FREQ=WEEKLY',
}],
})
let events = currentCalendar.getEvents()
expect(events.length).toBe(6)
expect(events[0].start).toEqualLocalDate('2018-12-01')
})
it('can expand weekly UTC-timed recurrence in local timeZone', () => {
initCalendar({
initialView: 'dayGridMonth',
now: '2018-12-25T12:00:00',
timeZone: 'local',
events: [{
rrule: 'DTSTART:20181201T000000Z\nRRULE:FREQ=WEEKLY',
}],
})
let events = currentCalendar.getEvents()
expect(events.length).toBe(6)
expect(events[0].start).toEqualDate('2018-12-01')
})
it('can expand weekly UTC-timed recurrence in local timeZone, with exclusion', () => {
initCalendar({
initialView: 'dayGridMonth',
now: '2018-12-25T12:00:00',
timeZone: 'local',
events: [{
rrule: 'DTSTART:20181201T000000Z\nRRULE:FREQ=WEEKLY\nEXDATE:20181208T000000Z',
}],
})
let events = currentCalendar.getEvents()
expect(events.length).toBe(5)
expect(events[0].start).toEqualDate('2018-12-01')
})
it('can generate local dates', () => {
let localStart = buildLocalRRuleDateStr('2018-09-04T05:00:00')
initCalendar({
timeZone: 'local',
events: [
{
rrule: `DTSTART:${localStart}\nRRULE:FREQ=WEEKLY`,
},
],
})
let events = getSortedEvents()
expect(events.length).toBe(5)
expect(events[0].start).toEqualLocalDate('2018-09-04T05:00:00')
expect(events[0].end).toBe(null)
expect(events[0].allDay).toBe(false)
})
it('can generate local dates, including EXDATE', () => {
let localStart = buildLocalRRuleDateStr('2018-09-04T05:00:00')
let localExdate = buildLocalRRuleDateStr('2018-09-05T05:00:00')
initCalendar({
timeZone: 'local',
events: [
{
rrule: `DTSTART:${localStart}\nRRULE:FREQ=WEEKLY\nEXDATE:${localExdate}`,
},
],
})
let events = getSortedEvents()
expect(events.length).toBe(5)
expect(events[0].start).toEqualLocalDate('2018-09-04T05:00:00')
expect(events[0].end).toBe(null)
expect(events[0].allDay).toBe(false)
})
// https://github.com/fullcalendar/fullcalendar/issues/5726
it('can generate local dates, including EXDATE, when BYDAY and TZ shifting', () => {
initCalendar({
timeZone: 'local',
initialDate: '2020-09-10',
events: [
{
rrule: 'DTSTART:20200915T030000Z\nRRULE:FREQ=WEEKLY;BYDAY=SA\nEXDATE:20201003T030000Z',
},
],
})
let events = getSortedEvents()
expect(events.length).toBe(3)
expect(events[0].start).toEqualDate('2020-09-19T03:00:00')
expect(events[1].start).toEqualDate('2020-09-26T03:00:00')
expect(events[2].start).toEqualDate('2020-10-10T03:00:00')
})
// https://github.com/fullcalendar/fullcalendar/issues/5993
it('won\'t accidentally clip dates when calendar has non-UTC timezone', () => {
let calendar = initCalendar({
plugins: [rrulePlugin, dayGridPlugin, luxonPlugin],
initialDate: '2020-11-01',
timeZone: 'Asia/Manila',
events: [
{
duration: '01:00',
rrule: {
freq: 'daily',
dtstart: '2020-10-24T16:00:00Z', // will be 00:00 in Manila
},
},
],
})
let events = calendar.getEvents()
expect(events[0].start).toEqualDate(calendar.view.activeStart)
})
})
// utils
function buildLocalRRuleDateStr(inputStr) { // produces strings like '20200101123030'
return parseLocalDate(inputStr).toISOString().replace('.000', '').replace(/[-:]/g, '')
}
function getSortedEvents() {
let events = currentCalendar.getEvents()
events.sort((eventA, eventB) => eventA.start.valueOf() - eventB.start.valueOf())
return events
}
}) | the_stack |
import { Action, action, Thunk, thunk } from "easy-peasy";
import * as Bech32 from "bech32";
import secp256k1 from "secp256k1";
import { CONSTANTS, JSHash } from "react-native-hash";
import { IStoreModel } from "./index";
import { IStoreInjections } from "./store";
import { timeout, bytesToString, getDomainFromURL, stringToUint8Array, hexToUint8Array, bytesToHexString, toast } from "../utils/index";
import { lnrpc } from "../../proto/lightning";
import { LndMobileEventEmitter } from "../utils/event-listener";
import { checkLndStreamErrorResponse } from "../utils/lndmobile";
import logger from "./../utils/log";
const log = logger("LNURL");
export type LNURLType = "channelRequest" | "login" | "withdrawRequest" | "payRequest" | "unknown" | "error" | "unsupported";
export type LightningAddress = string;
export interface ILNUrlError {
status: "ERROR";
reason: string;
}
export interface ILNUrlChannelRequest {
uri: string;
callback: string;
k1: string;
tag: "channelRequest";
}
export interface ILNUrlChannelRequestResponse {
status: "OK" | "ERROR";
reason: string;
}
export interface ILNUrlAuthRequest {
tag: "login",
k1: string;
}
export interface ILNUrlAuthResponse {
status: "OK" | "ERROR";
event?: "REGISTERED" | "LOGGEDIN" | "LINKED" | "AUTHED";
reason?: string;
}
export interface ILNUrlWithdrawRequest {
callback: string;
k1: string;
maxWithdrawable: number;
defaultDescription: string;
minWithdrawable?: number;
balanceCheck?: string;
currentBalance?: number;
payLink?: string;
tag: "withdrawRequest";
}
export interface ILNUrlWithdrawResponse {
status: "OK" | "ERROR";
reason?: string;
}
export type Metadata = [string, string];
export type ILNUrlPayRequestMetadata = Metadata[];
export interface ILNUrlPayRequestPayerData {
name?: {
mandatory: boolean;
};
pubkey?: {
mandatory: boolean;
};
identifier?: {
mandatory: boolean;
};
email?: {
mandatory: boolean;
};
auth?: {
mandatory?: boolean;
k1?: string; // hex
};
};
export interface ILNUrlPayResponsePayerData {
name?: string;
pubkey?: string; // hex
auth?: {
key: string;
k1: string;
sig: string; // hex
},
email?: string;
identifier?: string;
}
export interface ILNUrlPayRequest {
callback: string;
maxSendable: number;
minSendable: number;
metadata: string;
commentAllowed?: number;
disposable?: boolean | null;
tag: "payRequest";
payerData?: ILNUrlPayRequestPayerData;
}
export interface ILNUrlPayResponse {
pr: string;
successAction:
| ILNUrlPayResponseSuccessActionAes
| ILNUrlPayResponseSuccessActionMessage
| ILNUrlPayResponseSuccessActionUrl
| null;
routes: any[]; // NOT SUPPORTED
disposable?: boolean | null;
}
export interface ILNUrlPayResponseSuccessActionUrl {
tag: "url",
description: string;
url: string;
}
export interface ILNUrlPayResponseSuccessActionMessage {
tag: "message",
message: string;
}
export interface ILNUrlPayResponseSuccessActionAes {
tag: "aes",
description: string;
ciphertext: string; // base64-encoded
iv: string; // base64-encoded
}
export interface ILNUrlPayResponseError {
status: "ERROR";
reason: string;
}
export interface ILNUrlDummy {
tag: "X";
}
export interface IDoChannelRequestPayload {
private: true;
}
interface IDoPayRequestPayload {
msat: number;
comment?: string;
lightningAddress: string | null;
lud16IdentifierMimeType: string | null;
metadataTextPlain: string;
payerData?: ILNUrlPayResponsePayerData;
}
export type IDoPayRequestResponse = ILNUrlPayResponse;
type LNUrlRequest = ILNUrlChannelRequest | ILNUrlAuthRequest | ILNUrlWithdrawRequest | ILNUrlPayRequest | ILNUrlDummy;
const LNURLAUTH_CANONICAL_PHRASE = "DO NOT EVER SIGN THIS TEXT WITH YOUR PRIVATE KEYS! IT IS ONLY USED FOR DERIVATION OF LNURL-AUTH HASHING-KEY, DISCLOSING ITS SIGNATURE WILL COMPROMISE YOUR LNURL-AUTH IDENTITY AND MAY LEAD TO LOSS OF FUNDS!";
export interface ILNUrlModel {
setLNUrl: Thunk<ILNUrlModel, { bech32data?: string; url?: string }, any, IStoreModel, Promise<LNURLType>>;
doChannelRequest: Thunk<ILNUrlModel, IDoChannelRequestPayload, IStoreInjections, IStoreModel, Promise<boolean>>;
doAuthRequest: Thunk<ILNUrlModel, void, IStoreInjections, IStoreModel, Promise<boolean>>;
doWithdrawRequest: Thunk<ILNUrlModel, { satoshi: number; }, IStoreInjections, IStoreModel, Promise<boolean>>;
doPayRequest: Thunk<ILNUrlModel, IDoPayRequestPayload, IStoreInjections, IStoreModel, Promise<IDoPayRequestResponse>>;
setLNUrlStr: Action<ILNUrlModel, string>;
setType: Action<ILNUrlModel, LNURLType>;
setLNUrlObject: Action<ILNUrlModel, LNUrlRequest>;
setPayRequestResponse: Action<ILNUrlModel, ILNUrlPayResponse>;
lnUrlStr?: string;
type?: LNURLType;
lnUrlObject: LNUrlRequest | undefined;
payRequestResponse: ILNUrlPayResponse | undefined;
clear: Action<ILNUrlModel>;
resolveLightningAddress: Thunk<ILNUrlModel, LightningAddress>;
};
export const lnUrl: ILNUrlModel = {
setLNUrl: thunk(async (actions, { bech32data, url }) => {
log.i("setLNUrl");
actions.clear();
try {
let type: LNURLType;
if (bech32data) {
const decodedBech32 = Bech32.bech32.decode(bech32data, 1024);
url = bytesToString(Bech32.bech32.fromWords(decodedBech32.words));
} else if (!url) {
throw new Error("Neither bech32data or url is provided");
}
log.d("url", [url]);
actions.setLNUrlStr(url);
const queryParams = parseQueryParams(url);
log.d("queryParams", [queryParams]);
// If the data is in the URL
if ("tag" in queryParams) {
log.d(`Found tag ${queryParams.tag} in query params`);
const tag = queryParams.tag; // FIXME
if (!tryLNURLType(tag)) {
throw "unknown";
}
if (tag === "login") {
console.log("login");
type = "login";
}
else {
throw "unknown";
}
actions.setLNUrlObject(queryParams); // FIXME
}
// If we have to make a GET request to get the data
else {
log.d(`GET ${url}, looking for tag`);
const result = await fetch(url);
log.v(JSON.stringify(result));
let lnurlObject: LNUrlRequest | ILNUrlError;
try {
lnurlObject = await result.json();
} catch (e) {
log.d("", [e]);
throw new Error("Unable to parse message from the server");
}
log.d("response", [lnurlObject]);
if (isLNUrlPayResponseError(lnurlObject)) {
throw new Error(lnurlObject.reason);
}
log.v(JSON.stringify(lnurlObject));
if (lnurlObject.tag === "channelRequest") {
type = "channelRequest";
}
else if (lnurlObject.tag === "withdrawRequest") {
type = "withdrawRequest";
}
else if (lnurlObject.tag === "payRequest") {
type = "payRequest";
}
else {
throw "unknown";
}
log.d(`Found tag ${lnurlObject.tag}`);
actions.setLNUrlObject(lnurlObject);
}
actions.setType(type);
return type;
} catch (e) {
throw e;
}
}),
doChannelRequest: thunk(async (_, _2, { getStoreState, getState, injections }) => {
const type = getState().type;
const lnUrlObject = getState().lnUrlObject;
const connectPeer = injections.lndMobile.index.connectPeer;
if (type === "channelRequest" && lnUrlObject && lnUrlObject.tag === "channelRequest") {
log.i("Processing channelRequest");
while (!getStoreState().lightning.nodeInfo) {
log.i("nodeInfo is not available yet, sleeping for 1000ms");
await timeout(1000);
}
const localPubkey = getStoreState().lightning.nodeInfo!.identityPubkey;
const [pubkey, host] = lnUrlObject.uri.split("@");
try {
await connectPeer(pubkey, host);
} catch (e) { }
const request = `${lnUrlObject.callback}?k1=${lnUrlObject.k1}&remoteid=${localPubkey}&private=1`;
const result = await fetch(request);
log.v(JSON.stringify(result));
let response: ILNUrlChannelRequestResponse | ILNUrlError;
try {
response = await result.json();
} catch (e) {
log.d("", [e]);
throw new Error("Unable to parse message from the server");
}
log.d("response", [response]);
if (isLNUrlPayResponseError(response)) {
throw new Error(response.reason);
}
return true;
}
else {
throw new Error("Requirements not satisfied, type must be channelRequest and lnUrlObject must be set");
}
}),
doAuthRequest: thunk(async (_, _2, { getStoreState, getState, injections }) => {
const type = getState().type;
const lnUrlStr = getState().lnUrlStr;
const lnUrlObject = getState().lnUrlObject;
if (lnUrlStr && type === "login" && lnUrlObject && lnUrlObject.tag === "login") {
log.i("Processing login");
while (!getStoreState().lightning.nodeInfo) {
log.i("nodeInfo is not available yet, sleeping for 1000ms");
await timeout(1000);
}
// 1. The following canonical phrase is defined: [...].
// 2. LN WALLET obtains an RFC6979 deterministic signature of sha256(utf8ToBytes(canonical phrase)) using secp256k1 with node private key.
const signature = await injections.lndMobile.wallet.signMessageNodePubkey(stringToUint8Array(LNURLAUTH_CANONICAL_PHRASE));
// 3. LN WALLET defines hashingKey as PrivateKey(sha256(obtained signature)).
const hashingKey = new sha256Hash().update(stringToUint8Array(signature.signature)).digest();
// 4. SERVICE domain name is extracted from auth LNURL and then service-specific linkingPrivKey is defined as PrivateKey(hmacSha256(hashingKey, service domain name)).
const domain = getDomainFromURL(lnUrlStr);
const linkingKeyPriv = new sha256HMAC(hashingKey).update(stringToUint8Array(domain)).digest();
// Obtain the public key
const linkingKeyPub = secp256k1.publicKeyCreate(linkingKeyPriv, true);
// Sign the message
const signedMessage = secp256k1.ecdsaSign(hexToUint8Array(lnUrlObject.k1), linkingKeyPriv);
const signedMessageDER = secp256k1.signatureExport(signedMessage.signature)
// LN WALLET Then issues a GET to LN SERVICE using
// <LNURL_hostname_and_path>?<LNURL_existing_query_parameters>&sig=<hex(sign(k1.toByteArray, linkingPrivKey))>&key=<hex(linkingKey)>
const url = (
lnUrlStr +
`&sig=${bytesToHexString(signedMessageDER)}` +
`&key=${bytesToHexString(linkingKeyPub)}`
);
log.d("url", [url]);
// 4 omitted
const result = await fetch(url);
log.d("result", [JSON.stringify(result)]);
let response: ILNUrlAuthResponse | ILNUrlError;
try {
response = await result.json();
} catch (e) {
log.d("", [e]);
throw new Error("Unable to parse message from the server");
}
log.d("response", [response]);
if (isLNUrlPayResponseError(response)) {
throw new Error(response.reason);
}
return true;
}
else {
throw new Error("Requirements not satisfied, type must be login and lnUrlObject must be set");
}
}),
doWithdrawRequest: thunk(async (_, { satoshi }, { getStoreActions, getState, injections }) => {
const type = getState().type;
const lnUrlStr = getState().lnUrlStr;
const lnUrlObject = getState().lnUrlObject;
if (lnUrlStr && type === "withdrawRequest" && lnUrlObject && lnUrlObject.tag === "withdrawRequest") {
const promise = new Promise<boolean>((resolve, reject) => {
const r = getStoreActions().receive.addInvoice({
description: lnUrlObject.defaultDescription,
sat: satoshi,
tmpData: {
website: getDomainFromURL(lnUrlStr),
type: "LNURL",
payer: null,
}
});
// 5. Once accepted by the user, LN WALLET sends a GET to LN SERVICE in the form of <callback>?k1=<k1>&pr=<lightning invoice, ...>
const listener = LndMobileEventEmitter.addListener("SubscribeInvoices", async (e) => {
try {
log.d("SubscribeInvoices event", [e]);
listener.remove();
const error = checkLndStreamErrorResponse("SubscribeInvoices", e);
if (error === "EOF") {
return;
} else if (error) {
log.d("Got error from SubscribeInvoices", [error]);
return;
}
const invoice = injections.lndMobile.wallet.decodeInvoiceResult(e.data);
let firstSeparator = lnUrlObject.callback.includes("?") ? "&" : "?";
const url = `${lnUrlObject.callback}${firstSeparator}k1=${lnUrlObject.k1}&pr=${invoice.paymentRequest}`;
log.d("url", [url]);
const result = await fetch(url);
log.d("result", [JSON.stringify(result)]);
let response: ILNUrlWithdrawResponse | ILNUrlError;
try {
response = await result.json();
} catch (e) {
log.d("", [e]);
return reject(new Error("Unable to parse message from the server"));
}
log.d("response", [response]);
if (isLNUrlPayResponseError(response)) {
return reject(new Error(response.reason));
}
resolve(true);
} catch (error) {
toast(error.message, undefined, "danger");
}
});
})
return promise;
}
else {
throw new Error("Requirements not satisfied, type must be login and lnUrlObject must be set");
}
}),
doPayRequest: thunk(async (actions, payload, { getStoreActions, getState }) => {
const type = getState().type;
const lnUrlStr = getState().lnUrlStr;
const lnUrlObject = getState().lnUrlObject;
if (lnUrlStr && type === "payRequest" && lnUrlObject && lnUrlObject.tag === "payRequest") {
// 5. LN WALLET makes a GET request using
// <callback>?amount=<milliSatoshi>&fromnodes=<nodeId1,nodeId2,...>
// (we're skipping fromnodes)
const gotPayerData = !!payload.payerData;
let callback = lnUrlObject.callback;
let firstSeparator = lnUrlObject.callback.includes("?") ? "&" : "?"
callback = `${callback}${firstSeparator}amount=${payload.msat.toString()}`;
if (payload.comment) {
callback = `${callback}&comment=${encodeURIComponent(payload.comment)}`;
}
if (payload.payerData) {
callback = `${callback}&payerdata=${encodeURIComponent(JSON.stringify(payload.payerData))}`
}
log.d("callback" ,[callback]);
const result = await fetch(callback);
log.d("result", [JSON.stringify(result)]);
let response: ILNUrlPayResponse | ILNUrlPayResponseError;
try {
response = await result.json();
} catch (e) {
log.d("", [e]);
throw new Error("Unable to parse message from the server.");
}
log.d("response", [response]);
if (isLNUrlPayResponseError(response)) {
throw new Error(response.reason);
}
// 6. omitted
if (!response.pr || response.pr.length === 0) {
throw new Error("Response from the server did not contain an invoice.");
}
try {
log.d("pr", [response.pr]);
const paymentRequest: lnrpc.PayReq = await getStoreActions().send.setPayment({
paymentRequestStr: response.pr,
extraData: {
lnurlPayResponse: response,
payer: null,
type: "LNURL",
website: getDomainFromURL(lnUrlStr),
lightningAddress: payload.lightningAddress,
lud16IdentifierMimeType: payload.lud16IdentifierMimeType,
lnurlPayTextPlain: payload.metadataTextPlain,
},
});
// 7. LN WALLET Verifies that h tag in provided invoice is a
// hash of metadata string converted to byte array in UTF-8 encoding.
const descriptionHash = paymentRequest.descriptionHash;
if (!descriptionHash) {
log.d("", [descriptionHash]);
throw new Error("Invoice invalid. Description hash is missing.");
}
let dataToHash = lnUrlObject.metadata;
if (gotPayerData) {
dataToHash = `${dataToHash}${JSON.stringify(payload.payerData)}`;
}
const hashedMetadata = await JSHash(dataToHash, CONSTANTS.HashAlgorithms.sha256);
if (hashedMetadata !== descriptionHash) {
log.i("Description hash does not match metdata hash!", [hashedMetadata, descriptionHash]);
throw new Error("Invoice description hash is invalid.");
}
// 8. LN WALLET Verifies that amount in provided invoice equals an amount previously specified by user.
if (paymentRequest.numMsat.notEquals(payload.msat)) {
throw new Error("Received invoice does not match decided cost");
}
// 9. If routes array is not empty: verifies signature for every provided ChannelUpdate, may use these routes if fee levels are acceptable.
// TODO...
// 10. ommitted
// 11. LN WALLET pays the invoice, no additional user confirmation is required at this point.
// Jumping back to component:
actions.setPayRequestResponse(response);
return response;
} catch (e) {
log.i("Error setting invoice to send subsystem", [e]);
throw e;
}
}
else {
throw new Error("Requirements not satisfied, type must be login and lnUrlObject must be set");
}
}),
setLNUrlStr: action((state, payload) => { state.lnUrlStr = payload }),
setType: action((state, payload) => { state.type = payload }),
setLNUrlObject: action((state, payload) => { state.lnUrlObject = payload }),
setPayRequestResponse: action((state, payload) => { state.payRequestResponse = payload }),
clear: action((state) => {
state.lnUrlStr = undefined;
state.type = undefined;
state.lnUrlObject = undefined;
state.payRequestResponse = undefined;
}),
resolveLightningAddress: thunk(async (actions, lightningAddress) => {
actions.clear();
// https://github.com/fiatjaf/lnurl-rfc/blob/luds/16.md
// The idea here is that a SERVICE can offer human-readable addresses for users or specific internal endpoints
// that use the format <username>@<domainname>, e.g. satoshi@bitcoin.org. A user can then type these on a WALLET.
//
// Upon seeing such an address, WALLET makes a GET request to
// https://<domain>/.well-known/lnurlp/<username> endpoint if domain is clearnet or http://<domain>/.well-known/lnurlp/<name> if domain is onion.
// For example, if the address is satoshi@bitcoin.org, the request is to be made to https://bitcoin.org/.well-known/lnurlp/satoshi.
const [username, domain] = lightningAddress.toLowerCase().split("@");
if (domain == undefined) {
throw new Error("Invalid Lightning Address");
}
// Normal LNURL fetch request follows:
const lnurlPayUrl = `https://${domain}/.well-known/lnurlp/${username}`;
actions.setLNUrlStr(lnurlPayUrl);
const result = await fetch(lnurlPayUrl);
let lnurlObject: ILNUrlPayRequest | ILNUrlPayResponseError;
try {
const lnurlText = await result.text();
log.i("",[lnurlText]);
lnurlObject = JSON.parse(lnurlText);
} catch (e) {
throw new Error("Unable to parse message from the server: " + e.message);
}
log.d("response", [lnurlObject]);
if (isLNUrlPayResponseError(lnurlObject)) {
log.e("Got error");
throw new Error(lnurlObject.reason);
}
log.v(JSON.stringify(lnurlObject));
if (lnurlObject.tag === "payRequest") {
actions.setType("payRequest");
actions.setLNUrlObject(lnurlObject);
return true;
}
return false;
}),
lnUrlStr: undefined,
type: undefined,
lnUrlObject: undefined,
payRequestResponse: undefined,
};
const parseQueryParams = (url: string) => {
const params: { [key: string]: string } = {};
const firstQ = url.indexOf("?");
if (firstQ === -1) {
return params;
}
const queryParams = url.substring(firstQ + 1);
if (queryParams.length === 0) {
return params;
}
const ampSplit = queryParams.split("&");
for (const section of ampSplit) {
const [key, value] = section.split("=");
params[key] = value;
}
return params;
};
const tryLNURLType = (subject: string): subject is LNURLType => {
return (
subject === "channelRequest" ||
subject === "login"
);
}
const isLNUrlPayResponseError = (subject: any): subject is ILNUrlPayResponseError => {
return (
typeof subject === "object" &&
subject.status && subject.status === "ERROR"
);
} | the_stack |
import webpack from "webpack";
import HtmlWebpackPlugin from "html-webpack-plugin";
import TerserPlugin from "terser-webpack-plugin";
import MiniCssExtractPlugin from "mini-css-extract-plugin";
import ManifestPlugin from "webpack-manifest-plugin";
import getCSSModuleLocalIdent from "react-dev-utils/getCSSModuleLocalIdent";
import WatchMissingNodeModulesPlugin from "react-dev-utils/WatchMissingNodeModulesPlugin";
import InterpolateHtmlPlugin from "react-dev-utils/InterpolateHtmlPlugin";
import FriendlyErrorsWebpackPlugin from "friendly-errors-webpack-plugin";
import getClientEnvironment from "../config/env";
import { link } from "../utils/format";
type LoadWebpackOptions = {
paths: any;
dev: boolean;
useBabelrc: boolean;
url?: string;
};
type WebpackConfig = {};
const shouldUseSourceMap = true;
// style files regexes
const cssRegex = /\.css$/;
const cssModuleRegex = /\.module\.css$/;
const sassRegex = /\.(scss|sass)$/;
const sassModuleRegex = /\.module\.(scss|sass)$/;
// FIXME: detect when this should be true
const shouldUseRelativeAssetPaths = false;
// common function to get style loaders
const getStyleLoaders = ({
cssOptions,
preProcessor,
dev
}: {
cssOptions: any;
preProcessor?: string;
dev: boolean;
}) => {
const loaders = [
dev && require.resolve("style-loader"),
!dev && {
loader: MiniCssExtractPlugin.loader,
options: Object.assign(
{},
shouldUseRelativeAssetPaths ? { publicPath: "../../" } : undefined
)
},
{
loader: require.resolve("css-loader"),
options: cssOptions
},
{
// Options for PostCSS as we reference these options twice
// Adds vendor prefixing based on your specified browser support in
// package.json
loader: require.resolve("postcss-loader"),
options: {
// Necessary for external CSS imports to work
// https://github.com/facebook/create-react-app/issues/2677
ident: "postcss",
plugins: () => [
require("postcss-flexbugs-fixes"),
require("postcss-preset-env")({
autoprefixer: {
flexbox: "no-2009"
},
stage: 3
})
],
sourceMap: !dev && shouldUseSourceMap
}
}
].filter(Boolean);
if (preProcessor) {
loaders.push({
loader: require.resolve(preProcessor),
options: {
sourceMap: !dev && shouldUseSourceMap
}
});
}
return loaders;
};
export default async ({
paths,
dev,
url,
useBabelrc
}: LoadWebpackOptions): Promise<WebpackConfig> => {
const env = getClientEnvironment(paths.publicUrl.replace(/\/$/, ""));
const devPlugins = dev
? [
new webpack.HotModuleReplacementPlugin(),
// Watcher doesn't work well if you mistype casing in a path so we use
// a plugin that prints an error when you attempt to do this.
// See https://github.com/facebookincubator/create-react-app/issues/240
// new CaseSensitivePathsPlugin(),
// If you require a missing module and then `npm install` it, you still have
// to restart the development server for Webpack to discover it. This plugin
// makes the discovery automatic so you don't have to restart.
// See https://github.com/facebookincubator/create-react-app/issues/186
new WatchMissingNodeModulesPlugin(paths.appNodeModules),
new FriendlyErrorsWebpackPlugin({
compilationSuccessInfo: {
messages: url ? [`Catalog is running at ${link(url)}`] : []
}
})
]
: [];
return {
mode: dev ? "development" : "production",
devtool: dev ? "cheap-module-source-map" : "source-map",
bail: dev ? false : true,
entry: {
catalog: [require.resolve("react-app-polyfill/ie11")]
.concat(
dev ? [require.resolve("react-dev-utils/webpackHotDevClient")] : []
)
.concat(paths.catalogIndexJs)
},
output: {
path: paths.catalogBuildDir,
pathinfo: dev ? true : false,
filename: dev ? "static/[name].js" : "static/[name].[chunkhash:8].js",
chunkFilename: dev
? "static/[name].chunk.js"
: "static/[name].[chunkhash:8].chunk.js",
// This is the URL that app is served from. We use "/" in development.
publicPath: paths.publicUrl
},
resolve: {
modules: [paths.appSrc, "node_modules", paths.appNodeModules].concat(
paths.nodePaths
),
extensions: [".mjs", ".js", ".ts", ".tsx", ".json", ".jsx"],
alias: {
// Support React Native Web
// https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
"react-native": "react-native-web",
"babel-standalone": "babel-standalone/babel.min.js",
"js-yaml": "js-yaml/dist/js-yaml.min.js"
}
},
resolveLoader: {
modules: [paths.ownNodeModules, paths.appNodeModules]
},
module: {
rules: [
{
oneOf: [
// "url" loader works like "file" loader except that it embeds assets
// smaller than specified limit in bytes as data URLs to avoid requests.
// A missing `test` is equivalent to a match.
{
test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
loader: require.resolve("url-loader"),
options: {
limit: 10000,
name: "static/media/[name].[hash:8].[ext]"
}
},
// Process JS with Babel.
{
test: /\.(mjs|js|jsx|ts|tsx)$/,
include: [paths.appRoot, paths.catalogSrcDir],
exclude: /node_modules/,
loader: require.resolve("babel-loader"),
options: {
babelrc: useBabelrc,
presets: useBabelrc
? []
: [
require.resolve("babel-preset-react-app"),
require.resolve("@catalog/babel-preset")
],
cacheDirectory: true
}
},
// "postcss" loader applies autoprefixer to our CSS.
// "css" loader resolves paths in CSS and adds assets as dependencies.
// "style" loader turns CSS into JS modules that inject <style> tags.
// In production, we use MiniCSSExtractPlugin to extract that CSS
// to a file, but in development "style" loader enables hot editing
// of CSS.
// By default we support CSS Modules with the extension .module.css
{
test: cssRegex,
exclude: cssModuleRegex,
use: getStyleLoaders({
cssOptions: {
importLoaders: 1,
sourceMap: !dev && shouldUseSourceMap
},
dev
}),
// Don't consider CSS imports dead code even if the
// containing package claims to have no side effects.
// Remove this when webpack adds a warning or an error for this.
// See https://github.com/webpack/webpack/issues/6571
sideEffects: true
},
// Adds support for CSS Modules (https://github.com/css-modules/css-modules)
// using the extension .module.css
{
test: cssModuleRegex,
use: getStyleLoaders({
cssOptions: {
importLoaders: 1,
sourceMap: !dev && shouldUseSourceMap,
modules: true,
getLocalIdent: getCSSModuleLocalIdent
},
dev
})
},
// Opt-in support for SASS (using .scss or .sass extensions).
// By default we support SASS Modules with the
// extensions .module.scss or .module.sass
{
test: sassRegex,
exclude: sassModuleRegex,
use: getStyleLoaders({
cssOptions: {
importLoaders: 2,
sourceMap: !dev && shouldUseSourceMap
},
preProcessor: "sass-loader",
dev
}),
// Don't consider CSS imports dead code even if the
// containing package claims to have no side effects.
// Remove this when webpack adds a warning or an error for this.
// See https://github.com/webpack/webpack/issues/6571
sideEffects: true
},
// Adds support for CSS Modules, but using SASS
// using the extension .module.scss or .module.sass
{
test: sassModuleRegex,
use: getStyleLoaders({
cssOptions: {
importLoaders: 2,
sourceMap: !dev && shouldUseSourceMap,
modules: true,
getLocalIdent: getCSSModuleLocalIdent
},
preProcessor: "sass-loader",
dev
})
},
{
test: /\.md$/,
loaders: [require.resolve("@catalog/markdown-loader")]
},
{
exclude: [/\.mjs$/, /\.js$/, /\.html$/, /\.json$/, /\.md$/],
loader: require.resolve("file-loader"),
options: {
name: "static/media/[name].[hash:8].[ext]"
}
}
]
}
]
},
plugins: (dev
? []
: [
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: "static/css/[name].[contenthash:8].css",
chunkFilename: "static/css/[name].[contenthash:8].chunk.css"
}),
new ManifestPlugin({
fileName: "asset-manifest.json"
})
]
).concat([
new InterpolateHtmlPlugin(HtmlWebpackPlugin, env.raw),
new HtmlWebpackPlugin({
inject: true,
template: paths.catalogIndexHtml,
minify: dev
? false
: {
removeComments: true,
collapseWhitespace: true,
removeRedundantAttributes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeStyleLinkTypeAttributes: true,
keepClosingSlash: true,
minifyJS: true,
minifyCSS: true,
minifyURLs: true
}
}),
new webpack.DefinePlugin(env.stringified),
// This is necessary to emit hot updates (currently CSS only):
...devPlugins
]),
node: {
fs: "empty",
net: "empty",
tls: "empty"
},
performance: {
hints: false
},
optimization: {
minimize: !dev,
minimizer: [
// This is only used in production mode
new TerserPlugin({
terserOptions: {
parse: {
// we want terser to parse ecma 8 code. However, we don't want it
// to apply any minfication steps that turns valid ecma 5 code
// into invalid ecma 5 code. This is why the 'compress' and 'output'
// sections only apply transformations that are ecma 5 safe
// https://github.com/facebook/create-react-app/pull/4234
ecma: 8
},
compress: {
ecma: 5,
warnings: false,
// Disabled because of an issue with Uglify breaking seemingly valid code:
// https://github.com/facebook/create-react-app/issues/2376
// Pending further investigation:
// https://github.com/mishoo/UglifyJS2/issues/2011
comparisons: false,
// Disabled because of an issue with Terser breaking valid code:
// https://github.com/facebook/create-react-app/issues/5250
// Pending futher investigation:
// https://github.com/terser-js/terser/issues/120
inline: 2
},
mangle: {
safari10: true
},
output: {
ecma: 5,
comments: false,
// Turned on because emoji and regex is not minified properly using default
// https://github.com/facebook/create-react-app/issues/2488
ascii_only: true
}
},
// Use multi-process parallel running to improve the build speed
// Default number of concurrent runs: os.cpus().length - 1
parallel: true,
// Enable file caching
cache: true,
sourceMap: shouldUseSourceMap
})
],
// Automatically split vendor and commons
// https://twitter.com/wSokra/status/969633336732905474
// https://medium.com/webpack/webpack-4-code-splitting-chunk-graph-and-the-splitchunks-optimization-be739a861366
splitChunks: {
chunks: "all",
name: false
},
// Keep the runtime chunk separated to enable long term caching
// https://twitter.com/wSokra/status/969679223278505985
runtimeChunk: true
}
};
}; | the_stack |
import * as THREE from 'three'
import * as React from 'react'
import { ConcurrentRoot } from 'react-reconciler/constants'
import create, { UseBoundStore } from 'zustand'
import * as ReactThreeFiber from '../three-types'
import {
Renderer,
createStore,
isRenderer,
context,
RootState,
Size,
Dpr,
Performance,
PrivateKeys,
privateKeys,
} from './store'
import { createRenderer, extend, Instance, Root } from './renderer'
import { createLoop, addEffect, addAfterEffect, addTail } from './loop'
import { getEventPriority, EventManager, ComputeFunction } from './events'
import {
is,
dispose,
calculateDpr,
EquConfig,
getRootState,
useIsomorphicLayoutEffect,
Camera,
updateCamera,
} from './utils'
import { useStore } from './hooks'
const roots = new Map<Element, Root>()
const { invalidate, advance } = createLoop(roots)
const { reconciler, applyProps } = createRenderer(roots, getEventPriority)
const shallowLoose = { objects: 'shallow', strict: false } as EquConfig
type Properties<T> = Pick<T, { [K in keyof T]: T[K] extends (_: any) => any ? never : K }[keyof T]>
type GLProps =
| Renderer
| ((canvas: HTMLCanvasElement) => Renderer)
| Partial<Properties<THREE.WebGLRenderer> | THREE.WebGLRendererParameters>
| undefined
export type RenderProps<TCanvas extends Element> = {
/** A threejs renderer instance or props that go into the default renderer */
gl?: GLProps
/** Dimensions to fit the renderer to. Will measure canvas dimensions if omitted */
size?: Size
/**
* Enables PCFsoft shadows. Can accept `gl.shadowMap` options for fine-tuning.
* @see https://threejs.org/docs/#api/en/renderers/WebGLRenderer.shadowMap
*/
shadows?: boolean | Partial<THREE.WebGLShadowMap>
/**
* Disables three r139 color management.
* @see https://threejs.org/docs/#manual/en/introduction/Color-management
*/
legacy?: boolean
/** Switch off automatic sRGB encoding and gamma correction */
linear?: boolean
/** Use `THREE.NoToneMapping` instead of `THREE.ACESFilmicToneMapping` */
flat?: boolean
/** Creates an orthographic camera */
orthographic?: boolean
/**
* R3F's render mode. Set to `demand` to only render on state change or `never` to take control.
* @see https://docs.pmnd.rs/react-three-fiber/advanced/scaling-performance#on-demand-rendering
*/
frameloop?: 'always' | 'demand' | 'never'
/**
* R3F performance options for adaptive performance.
* @see https://docs.pmnd.rs/react-three-fiber/advanced/scaling-performance#movement-regression
*/
performance?: Partial<Omit<Performance, 'regress'>>
/** Target pixel ratio. Can clamp between a range: `[min, max]` */
dpr?: Dpr
/** Props that go into the default raycaster */
raycaster?: Partial<THREE.Raycaster>
/** A `THREE.Camera` instance or props that go into the default camera */
camera?: (
| Camera
| Partial<
ReactThreeFiber.Object3DNode<THREE.Camera, typeof THREE.Camera> &
ReactThreeFiber.Object3DNode<THREE.PerspectiveCamera, typeof THREE.PerspectiveCamera> &
ReactThreeFiber.Object3DNode<THREE.OrthographicCamera, typeof THREE.OrthographicCamera>
>
) & {
/** Flags the camera as manual, putting projection into your own hands */
manual?: boolean
}
/** An R3F event manager to manage elements' pointer events */
events?: (store: UseBoundStore<RootState>) => EventManager<HTMLElement>
/** Callback after the canvas has rendered (but not yet committed) */
onCreated?: (state: RootState) => void
/** Response for pointer clicks that have missed any target */
onPointerMissed?: (event: MouseEvent) => void
}
const createRendererInstance = <TElement extends Element>(gl: GLProps, canvas: TElement): THREE.WebGLRenderer => {
const customRenderer = (
typeof gl === 'function' ? gl(canvas as unknown as HTMLCanvasElement) : gl
) as THREE.WebGLRenderer
if (isRenderer(customRenderer)) return customRenderer
else
return new THREE.WebGLRenderer({
powerPreference: 'high-performance',
canvas: canvas as unknown as HTMLCanvasElement,
antialias: true,
alpha: true,
...gl,
})
}
export type ReconcilerRoot<TCanvas extends Element> = {
configure: (config?: RenderProps<TCanvas>) => ReconcilerRoot<TCanvas>
render: (element: React.ReactNode) => UseBoundStore<RootState>
unmount: () => void
}
function createRoot<TCanvas extends Element>(canvas: TCanvas): ReconcilerRoot<TCanvas> {
// Check against mistaken use of createRoot
let prevRoot = roots.get(canvas)
let prevFiber = prevRoot?.fiber
let prevStore = prevRoot?.store
if (prevRoot) console.warn('R3F.createRoot should only be called once!')
// Create store
const store = prevStore || createStore(invalidate, advance)
// Create renderer
const fiber = prevFiber || reconciler.createContainer(store, ConcurrentRoot, false, null)
// Map it
if (!prevRoot) roots.set(canvas, { fiber, store })
// Locals
let onCreated: ((state: RootState) => void) | undefined
let configured = false
return {
configure(props: RenderProps<TCanvas> = {}) {
let {
gl: glConfig,
size,
events,
onCreated: onCreatedCallback,
shadows = false,
linear = false,
flat = false,
legacy = false,
orthographic = false,
frameloop = 'always',
dpr = [1, 2],
performance,
raycaster: raycastOptions,
camera: cameraOptions,
onPointerMissed,
} = props
let state = store.getState()
// Set up renderer (one time only!)
let gl = state.gl
if (!state.gl) state.set({ gl: (gl = createRendererInstance(glConfig, canvas)) })
// Set up raycaster (one time only!)
let raycaster = state.raycaster
if (!raycaster) state.set({ raycaster: (raycaster = new THREE.Raycaster()) })
// Set raycaster options
const { params, ...options } = raycastOptions || {}
if (!is.equ(options, raycaster, shallowLoose)) applyProps(raycaster as any, { ...options })
if (!is.equ(params, raycaster.params, shallowLoose))
applyProps(raycaster as any, { params: { ...raycaster.params, ...params } })
// Create default camera (one time only!)
if (!state.camera) {
const isCamera = cameraOptions instanceof THREE.Camera
const camera = isCamera
? (cameraOptions as Camera)
: orthographic
? new THREE.OrthographicCamera(0, 0, 0, 0, 0.1, 1000)
: new THREE.PerspectiveCamera(75, 0, 0.1, 1000)
if (!isCamera) {
camera.position.z = 5
if (cameraOptions) applyProps(camera as any, cameraOptions as any)
// Always look at center by default
if (!cameraOptions?.rotation) camera.lookAt(0, 0, 0)
}
state.set({ camera })
}
// Set up XR (one time only!)
if (!state.xr) {
// Handle frame behavior in WebXR
const handleXRFrame: THREE.XRFrameRequestCallback = (timestamp: number, frame?: THREE.XRFrame) => {
const state = store.getState()
if (state.frameloop === 'never') return
advance(timestamp, true, state, frame)
}
// Toggle render switching on session
const handleSessionChange = () => {
const gl = store.getState().gl
gl.xr.enabled = gl.xr.isPresenting
// @ts-ignore
// WebXRManager's signature is incorrect.
// See: https://github.com/pmndrs/react-three-fiber/pull/2017#discussion_r790134505
gl.xr.setAnimationLoop(gl.xr.isPresenting ? handleXRFrame : null)
}
// WebXR session manager
const xr = {
connect() {
const gl = store.getState().gl
gl.xr.addEventListener('sessionstart', handleSessionChange)
gl.xr.addEventListener('sessionend', handleSessionChange)
},
disconnect() {
const gl = store.getState().gl
gl.xr.removeEventListener('sessionstart', handleSessionChange)
gl.xr.removeEventListener('sessionend', handleSessionChange)
},
}
// Subscribe to WebXR session events
if (gl.xr) xr.connect()
state.set({ xr })
}
// Set shadowmap
if (gl.shadowMap) {
const isBoolean = is.boo(shadows)
if ((isBoolean && gl.shadowMap.enabled !== shadows) || !is.equ(shadows, gl.shadowMap, shallowLoose)) {
const old = gl.shadowMap.enabled
gl.shadowMap.enabled = !!shadows
if (!isBoolean) Object.assign(gl.shadowMap, shadows)
else gl.shadowMap.type = THREE.PCFSoftShadowMap
if (old !== gl.shadowMap.enabled) gl.shadowMap.needsUpdate = true
}
}
// Set color management
if ((THREE as any).ColorManagement) {
;(THREE as any).ColorManagement.legacyMode = legacy
}
const outputEncoding = linear ? THREE.LinearEncoding : THREE.sRGBEncoding
const toneMapping = flat ? THREE.NoToneMapping : THREE.ACESFilmicToneMapping
if (gl.outputEncoding !== outputEncoding) gl.outputEncoding = outputEncoding
if (gl.toneMapping !== toneMapping) gl.toneMapping = toneMapping
// Update color management state
if (state.legacy !== legacy) state.set(() => ({ legacy }))
if (state.linear !== linear) state.set(() => ({ linear }))
if (state.flat !== flat) state.set(() => ({ flat }))
// Set gl props
if (glConfig && !is.fun(glConfig) && !isRenderer(glConfig) && !is.equ(glConfig, gl, shallowLoose))
applyProps(gl as any, glConfig as any)
// Store events internally
if (events && !state.events.handlers) state.set({ events: events(store) })
// Check pixelratio
if (dpr && state.viewport.dpr !== calculateDpr(dpr)) state.setDpr(dpr)
// Check size, allow it to take on container bounds initially
size = size || { width: canvas.parentElement?.clientWidth ?? 0, height: canvas.parentElement?.clientHeight ?? 0 }
if (!is.equ(size, state.size, shallowLoose)) state.setSize(size.width, size.height)
// Check frameloop
if (state.frameloop !== frameloop) state.setFrameloop(frameloop)
// Check pointer missed
if (!state.onPointerMissed) state.set({ onPointerMissed })
// Check performance
if (performance && !is.equ(performance, state.performance, shallowLoose))
state.set((state) => ({ performance: { ...state.performance, ...performance } }))
// Set locals
onCreated = onCreatedCallback
configured = true
return this
},
render(children: React.ReactNode) {
// The root has to be configured before it can be rendered
if (!configured) this.configure()
reconciler.updateContainer(
<Provider store={store} children={children} onCreated={onCreated} rootElement={canvas} />,
fiber,
null,
() => undefined,
)
return store
},
unmount() {
unmountComponentAtNode(canvas)
},
}
}
function render<TCanvas extends Element>(
children: React.ReactNode,
canvas: TCanvas,
config: RenderProps<TCanvas>,
): UseBoundStore<RootState> {
console.warn('R3F.render is no longer supported in React 18. Use createRoot instead!')
const root = createRoot(canvas)
root.configure(config)
return root.render(children)
}
function Provider<TElement extends Element>({
store,
children,
onCreated,
rootElement,
}: {
onCreated?: (state: RootState) => void
store: UseBoundStore<RootState>
children: React.ReactNode
rootElement: TElement
parent?: React.MutableRefObject<TElement | undefined>
}) {
useIsomorphicLayoutEffect(() => {
const state = store.getState()
// Flag the canvas active, rendering will now begin
state.set((state) => ({ internal: { ...state.internal, active: true } }))
// Notifiy that init is completed, the scene graph exists, but nothing has yet rendered
if (onCreated) onCreated(state)
// Connect events to the targets parent, this is done to ensure events are registered on
// a shared target, and not on the canvas itself
if (!store.getState().events.connected) state.events.connect?.(rootElement)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
return <context.Provider value={store}>{children}</context.Provider>
}
function unmountComponentAtNode<TElement extends Element>(canvas: TElement, callback?: (canvas: TElement) => void) {
const root = roots.get(canvas)
const fiber = root?.fiber
if (fiber) {
const state = root?.store.getState()
if (state) state.internal.active = false
reconciler.updateContainer(null, fiber, null, () => {
if (state) {
setTimeout(() => {
try {
state.events.disconnect?.()
state.gl?.renderLists?.dispose?.()
state.gl?.forceContextLoss?.()
if (state.gl?.xr) state.xr.disconnect()
dispose(state)
roots.delete(canvas)
if (callback) callback(canvas)
} catch (e) {
/* ... */
}
}, 500)
}
})
}
}
export type InjectState = Partial<
Omit<RootState, PrivateKeys> & {
events?: {
enabled?: boolean
priority?: number
compute?: ComputeFunction
connected?: any
}
size?: { width: number; height: number }
}
>
function createPortal(children: React.ReactNode, container: THREE.Object3D, state?: InjectState): React.ReactNode {
return <Portal key={container.uuid} children={children} container={container} state={state} />
}
function Portal({
state = {},
children,
container,
}: {
children: React.ReactNode
state?: InjectState
container: THREE.Object3D
}) {
/** This has to be a component because it would not be able to call useThree/useStore otherwise since
* if this is our environment, then we are not in r3f's renderer but in react-dom, it would trigger
* the "R3F hooks can only be used within the Canvas component!" warning:
* <Canvas>
* {createPortal(...)} */
const { events, size, ...rest } = state
const previousRoot = useStore()
const [raycaster] = React.useState(() => new THREE.Raycaster())
const [pointer] = React.useState(() => new THREE.Vector2())
const inject = React.useCallback(
(rootState: RootState, injectState: RootState) => {
const intersect: Partial<RootState> = { ...rootState } // all prev state props
// Only the fields of "rootState" that do not differ from injectState
// Some props should be off-limits
// Otherwise filter out the props that are different and let the inject layer take precedence
Object.keys(rootState).forEach((key) => {
if (
// Some props should be off-limits
privateKeys.includes(key as PrivateKeys) ||
// Otherwise filter out the props that are different and let the inject layer take precedence
rootState[key as keyof RootState] !== injectState[key as keyof RootState]
) {
delete intersect[key as keyof RootState]
}
})
let viewport = undefined
if (injectState && size) {
const camera = injectState.camera
// Calculate the override viewport, if present
viewport = rootState.viewport.getCurrentViewport(camera, new THREE.Vector3(), size)
// Update the portal camera, if it differs from the previous layer
if (camera !== rootState.camera) updateCamera(camera, size)
}
return {
// The intersect consists of the previous root state
...intersect,
// Portals have their own scene, which forms the root, a raycaster and a pointer
scene: container as THREE.Scene,
raycaster,
pointer,
mouse: pointer,
// Their previous root is the layer before it
previousRoot,
// Events, size and viewport can be overridden by the inject layer
events: { ...rootState.events, ...injectState?.events, ...events },
size: { ...rootState.size, ...size },
viewport: { ...rootState.viewport, ...viewport },
...rest,
} as RootState
},
[state],
)
const [usePortalStore] = React.useState(() => {
// Create a mirrored store, based on the previous root with a few overrides ...
const previousState = previousRoot.getState()
const store = create<RootState>((set, get) => ({
...previousState,
scene: container as THREE.Scene,
raycaster,
pointer,
mouse: pointer,
previousRoot,
events: { ...previousState.events, ...events },
size: { ...previousState.size, ...size },
...rest,
// Set and get refer to this root-state
set,
get,
// Layers are allowed to override events
setEvents: (events: Partial<EventManager<any>>) =>
set((state) => ({ ...state, events: { ...state.events, ...events } })),
}))
return store
})
React.useEffect(() => {
// Subscribe to previous root-state and copy changes over to the mirrored portal-state
const unsub = previousRoot.subscribe((prev) => usePortalStore.setState((state) => inject(prev, state)))
return () => {
unsub()
usePortalStore.destroy()
}
}, [])
React.useEffect(() => {
usePortalStore.setState((injectState) => inject(previousRoot.getState(), injectState))
}, [inject])
return (
<>
{reconciler.createPortal(
<context.Provider value={usePortalStore}>{children}</context.Provider>,
usePortalStore,
null,
)}
</>
)
}
reconciler.injectIntoDevTools({
bundleType: process.env.NODE_ENV === 'production' ? 0 : 1,
rendererPackageName: '@react-three/fiber',
version: '18.0.0',
})
const act = (React as any).unstable_act
export * from './hooks'
export {
context,
render,
createRoot,
unmountComponentAtNode,
createPortal,
reconciler,
applyProps,
dispose,
invalidate,
advance,
extend,
addEffect,
addAfterEffect,
addTail,
getRootState,
act,
roots as _roots,
} | the_stack |
import { api } from '#lib/discord/Api';
import { LanguageKeys } from '#lib/i18n/languageKeys';
import { Colors } from '#utils/constants';
import type { SerializedEmoji } from '#utils/functions';
import { fetchReactionUsers } from '#utils/util';
import { Embed, FooterOptions, roleMention, time, TimestampStyles, userMention } from '@discordjs/builders';
import { container } from '@sapphire/framework';
import { fetchT } from '@sapphire/plugin-i18next';
import { hasAtLeastOneKeyInMap, isNullish } from '@sapphire/utilities';
import {
APIAllowedMentions,
APIEmbed,
PermissionFlagsBits,
RESTJSONErrorCodes,
RESTPatchAPIChannelMessageJSONBody,
RESTPostAPIChannelMessageResult,
Snowflake
} from 'discord-api-types/v9';
import { DiscordAPIError, HTTPError } from 'discord.js';
import type { TFunction } from 'i18next';
import { FetchError } from 'node-fetch';
import { BaseEntity, Column, Entity, PrimaryColumn } from 'typeorm';
export const rawGiveawayEmoji = '🎉';
export const encodedGiveawayEmoji = encodeURIComponent(rawGiveawayEmoji) as SerializedEmoji;
export const giveawayBlockListEditErrors: RESTJSONErrorCodes[] = [
RESTJSONErrorCodes.UnknownMessage,
RESTJSONErrorCodes.UnknownChannel,
RESTJSONErrorCodes.UnknownGuild,
RESTJSONErrorCodes.MissingAccess,
RESTJSONErrorCodes.InvalidActionOnArchivedThread,
RESTJSONErrorCodes.InvalidFormBodyOrContentType,
RESTJSONErrorCodes.ThreadLocked
];
export const giveawayBlockListReactionErrors: RESTJSONErrorCodes[] = [
RESTJSONErrorCodes.UnknownMessage,
RESTJSONErrorCodes.UnknownChannel,
RESTJSONErrorCodes.UnknownGuild,
RESTJSONErrorCodes.MissingAccess,
RESTJSONErrorCodes.UnknownEmoji,
RESTJSONErrorCodes.InvalidActionOnArchivedThread,
RESTJSONErrorCodes.ThreadLocked
];
export type GiveawayEntityData = Pick<
GiveawayEntity,
'title' | 'endsAt' | 'guildId' | 'channelId' | 'messageId' | 'authorId' | 'minimum' | 'minimumWinners' | 'allowedRoles'
>;
@Entity('giveaway', { schema: 'public' })
export class GiveawayEntity extends BaseEntity {
#paused = true;
#endHandled = false;
#winners: string[] | null = null;
@Column('varchar', { length: 256 })
public title!: string;
@Column('timestamp without time zone')
public endsAt!: Date;
@PrimaryColumn('varchar', { length: 19 })
public guildId!: Snowflake;
@Column('varchar', { length: 19 })
public channelId!: Snowflake;
@PrimaryColumn('varchar', { length: 19 })
public messageId: Snowflake | null = null;
@Column('varchar', { length: 19 })
public authorId: Snowflake | null = null;
@Column('integer', { default: 1 })
public minimum = 1;
@Column('integer', { default: 1 })
public minimumWinners = 1;
@Column('varchar', { length: 19, array: true, default: () => 'ARRAY[]::VARCHAR[]' })
public allowedRoles: Snowflake[] = [];
public constructor(data: Partial<GiveawayEntityData> = {}) {
super();
Object.assign(this, data);
}
public get guild() {
return container.client.guilds.cache.get(this.guildId) ?? null;
}
public get endHandled() {
return this.#endHandled;
}
private get ended() {
return this.endsAt.getTime() <= Date.now();
}
public async fetchAuthor() {
if (!this.authorId) return null;
const { guild } = this;
if (!guild) return null;
return guild.members.fetch(this.authorId).catch(() => null);
}
public async insert() {
this.pause();
// Create the message
const message = (await api()
.channels(this.channelId)
.messages.post({ data: await this.getMessageBody() })) as RESTPostAPIChannelMessageResult;
this.messageId = message.id;
this.resume();
// Add a reaction to the message and save to database
await api().channels(this.channelId).messages(this.messageId).reactions(encodedGiveawayEmoji, '@me').put();
return this.save();
}
public resume() {
this.#paused = false;
return this;
}
public pause() {
this.#paused = true;
return this;
}
public async finish() {
this.#endHandled = true;
await this.remove();
return this;
}
public async destroy() {
await this.finish();
if (this.messageId) {
try {
await api().channels(this.channelId).messages(this.messageId).delete();
} catch (error) {
if (error instanceof DiscordAPIError && giveawayBlockListReactionErrors.includes(error.code)) {
return this;
}
container.logger.error(error);
}
}
return this;
}
public async render() {
// Skip early if it's already rendering
if (this.#paused) return this;
const data = await this.getMessageBody();
if (data === null) return this.finish();
try {
await api().channels(this.channelId).messages(this.messageId!).patch({ data });
} catch (error) {
if (error instanceof DiscordAPIError && giveawayBlockListEditErrors.includes(error.code)) {
await this.finish();
} else {
container.logger.error(error);
}
}
return this;
}
private async announceWinners(t: TFunction) {
const content = this.#winners
? t(LanguageKeys.Giveaway.EndedMessage, { title: this.title, winners: this.#winners.map(userMention) })
: t(LanguageKeys.Giveaway.EndedMessageNoWinner, { title: this.title });
try {
await api()
.channels(this.channelId)
.messages.post({ data: { content, allowed_mentions: { users: this.#winners ?? [], roles: [] } } });
} catch (error) {
container.logger.error(error);
}
}
private async pickWinners() {
const participants = await this.filterParticipants(await this.fetchParticipants());
if (participants.length < this.minimum) return null;
let m = participants.length;
while (m) {
const i = Math.floor(Math.random() * m--);
[participants[m], participants[i]] = [participants[i], participants[m]];
}
return participants.slice(0, this.minimumWinners);
}
private async fetchParticipants(): Promise<string[]> {
try {
const users = await fetchReactionUsers(this.channelId, this.messageId!, encodedGiveawayEmoji);
users.delete(process.env.CLIENT_ID);
return [...users];
} catch (error) {
if (error instanceof DiscordAPIError) {
if (error.code === RESTJSONErrorCodes.UnknownMessage || error.code === RESTJSONErrorCodes.UnknownEmoji) return [];
} else if (error instanceof HTTPError || error instanceof FetchError) {
if (error.code === 'ECONNRESET') return this.fetchParticipants();
container.logger.error(error);
}
return [];
}
}
private async filterParticipants(users: string[]): Promise<string[]> {
// If it's below minimum, there's no point of filtering, return empty array:
if (users.length < this.minimum) return [];
const { guild } = this;
// If the guild is uncached, return empty array:
if (guild === null) return [];
// If not all members are cached, fetch all members:
if (guild.members.cache.size !== guild.memberCount) await guild.members.fetch().catch(() => null);
const members = guild.members.cache;
const filtered: string[] = [];
for (const user of users) {
const member = members.get(user);
// If the user is not longer in the guild, skip:
if (member === undefined) continue;
// If there is at least one allowed role, and the user doesn't have any of them, skip:
if (this.allowedRoles.length > 0 && !hasAtLeastOneKeyInMap(member.roles.cache, this.allowedRoles)) continue;
// Add the user to the list of allowed members:
filtered.push(user);
}
return filtered;
}
private async getMessageBody(): Promise<RESTPatchAPIChannelMessageJSONBody | null> {
const { ended, guild } = this;
if (!guild) return null;
const t = await fetchT(guild);
if (ended) {
this.#winners = await this.pickWinners();
this.#endHandled = true;
await this.announceWinners(t);
}
const content = this.getMessageContent(ended, this.allowedRoles, t);
const allowedMentions = await this.fetchAllowedMentions();
const embed = this.getMessageEmbed(ended, t);
return { content, embed, allowed_mentions: allowedMentions };
}
private getMessageContent(ended: boolean, roles: string[], t: TFunction): string {
if (ended) return t(LanguageKeys.Giveaway.EndedTitle);
const key = roles.length ? LanguageKeys.Giveaway.TitleWithMentions : LanguageKeys.Giveaway.Title;
return t(key, { roles: roles.map(roleMention), count: roles.length });
}
private async fetchAllowedMentions(): Promise<APIAllowedMentions> {
const roles: Snowflake[] = [];
if (this.allowedRoles.length === 0) return { roles };
const member = await this.fetchAuthor();
if (member === null) return { roles };
const canMentionAnyway = member.permissions.has(PermissionFlagsBits.MentionEveryone);
for (const roleId of this.allowedRoles) {
const role = member.guild.roles.cache.get(roleId);
if (isNullish(role)) continue;
if (canMentionAnyway || role.mentionable) roles.push(roleId);
}
return { roles };
}
private getMessageEmbed(ended: boolean, t: TFunction): APIEmbed {
return new Embed()
.setColor(this.getMessageEmbedColor(ended))
.setTitle(this.title)
.setDescription(this.getMessageEmbedDescription(ended, t))
.setFooter(this.getMessageEmbedFooter(ended, t))
.setTimestamp(this.endsAt);
}
private getMessageEmbedColor(ended: boolean) {
return ended ? Colors.Red : Colors.Blue;
}
private getMessageEmbedDescription(ended: boolean, t: TFunction): string {
const lines = [ended ? this.getMessageEmbedDescriptionEnded(t) : this.getMessageEmbedDescriptionRunning(t)];
if (this.authorId) lines.push(t(LanguageKeys.Giveaway.EmbedHostedBy, { user: userMention(this.authorId) }));
return lines.join('\n');
}
private getMessageEmbedDescriptionEnded(t: TFunction) {
if (!this.#winners?.length) {
return t(LanguageKeys.Giveaway.EndedNoWinner);
}
const winners = this.#winners.map(userMention);
return t(LanguageKeys.Giveaway.Ended, { winners, count: winners.length });
}
private getMessageEmbedDescriptionRunning(t: TFunction) {
return t(LanguageKeys.Giveaway.Duration, { timestamp: time(this.endsAt, TimestampStyles.RelativeTime) });
}
private getMessageEmbedFooter(ended: boolean, t: TFunction): FooterOptions {
return { text: ended ? t(LanguageKeys.Giveaway.EndedAt) : t(LanguageKeys.Giveaway.EndsAt) };
}
} | the_stack |
import { Alternative1 } from 'fp-ts/lib/Alternative';
import { booleanAlgebraBoolean } from 'fp-ts/lib/BooleanAlgebra';
import { Eq, fromEquals, getTupleEq } from 'fp-ts/lib/Eq';
import { fieldNumber } from 'fp-ts/lib/Field';
import { constant, constFalse, constTrue, flip, flow, identity, Lazy, Predicate } from 'fp-ts/lib/function';
import * as M from 'fp-ts/lib/Map';
import { Monad1 } from 'fp-ts/lib/Monad';
import * as Mon from 'fp-ts/lib/Monoid';
import { Ord } from 'fp-ts/lib/Ord';
import { pipe, pipeable } from 'fp-ts/lib/pipeable';
import * as S from 'fp-ts/lib/Set';
type Fn1<A, B> = (a: A) => B;
type Fn2<A, B, C> = (a: A, b: B) => C;
const { meet: and, join: or } = booleanAlgebraBoolean;
const { add } = fieldNumber;
/**
* Empty graph
*/
export interface Empty {
readonly tag: 'Empty';
}
/**
* Single isolated vertex
*/
export interface Vertex<A> {
readonly tag: 'Vertex';
readonly value: A;
}
/**
* Overlay of two subgraphs
*/
export interface Overlay<A> {
readonly tag: 'Overlay';
readonly left: Graph<A>;
readonly right: Graph<A>;
}
/**
* Connection fotwo subgraphs
*/
export interface Connect<A> {
readonly tag: 'Connect';
readonly from: Graph<A>;
readonly to: Graph<A>;
}
/**
* Algrabraic graph
*/
export type Graph<A> =
| Empty
| Vertex<A>
| Overlay<A>
| Connect<A>;
export const URI = 'Graph';
export type URI = typeof URI;
declare module 'fp-ts/lib/HKT' {
interface URItoKind<A> {
Graph: Graph<A>;
}
}
export type AdjacencyMap<A> = Map<A, Set<A>>;
// Constructors
/**
* Construct an empty graph.
*/
const empty = <A>(): Graph<A> => ({ tag: 'Empty' });
/**
* Construct a graph consisting of a single isolated vertex.
* @param value Vertex value
*/
const vertex = <A>(value: A): Graph<A> => ({ tag: 'Vertex', value });
/**
* Construct a graph consisting of a set of isolated vertices.
* @param values List of vertex values
*/
const vertices = <A>(values: A[]): Graph<A> => overlays(values.map(vertex));
/**
* Construct a graph by overlaying two graphs.
* `overlay` is commutative, associative and idemponent operation with `empty` as identity.
* @param left First subgraph
* @param right Second subgraph
*/
const overlay = <A>(left: Graph<A>, right: Graph<A>): Graph<A> => ({ tag: 'Overlay', left, right });
/**
* Construct a graph by overlaying a list of subgraphs.
* @param gs List of graphs to overlay
*/
const overlays = <A>(gs: Array<Graph<A>>): Graph<A> => gs.reduce(overlay, empty());
/**
* Construct a graph by connecting each vertex of `from` subgraph to each vertex of `to` subgraph
* while keeping the original vertices and edges of `from` and `to` subgraphs.
* @param from A source graph of the connection
* @param to A target graph of the connection
*/
const connect = <A>(from: Graph<A>, to: Graph<A>): Graph<A> => ({ tag: 'Connect', from, to });
/**
* Construct a graph by connecting a list of subgraphs.
* @param gs A list of subgraphs
*/
const connects = <A>(gs: Array<Graph<A>>): Graph<A> => gs.reduce(connect, empty());
/**
* Construct a graph consisting of a single edge from `x` to `y`.
* @param x Value of a source vertex
* @param y Value of a target vertex
*/
const edge = <A>(x: A, y: A): Graph<A> => connect(vertex(x), vertex(y));
/**
* Construct a graph by connecting each pair of vertices build from the tuple data.
* @param es List of tuples with values for the source & target vertices
*/
const edges = <A>(es: Array<[A, A]>): Graph<A> => overlays(es.map(([x, y]) => edge(x, y)));
/**
* Constructo a clique from a given vertex values.
* @param values List of vertex values
*/
const clique = <A>(values: A[]): Graph<A> => connects(values.map(vertex));
/**
* Recursively collapse a graph by applying the provided functions to the leaves and internal nodes of the expression.
* @param onEmpty Lazy value of the resulting type
* @param onVertex Transformer function of a vertex data from `A` to `B`
* @param onOverlay Merging function of overlay which combines two `B` values
* @param onConnect Merging function of connection which combines two `B` values
*/
const fold = <A, B>(
onEmpty: Lazy<B>,
onVertex: Fn1<A, B>,
onOverlay: Fn2<B, B, B>,
onConnect: Fn2<B, B, B>,
): (g: Graph<A>) => B => {
const go = (g: Graph<A>): B => {
switch (g.tag) {
case 'Empty': return onEmpty();
case 'Vertex': return onVertex(g.value);
case 'Overlay': return onOverlay(go(g.left), go(g.right));
case 'Connect': return onConnect(go(g.from), go(g.to));
}
};
return go;
};
/**
* Instantiates `alga-ts` API from given constraints.
* @param eqA Equality typeclass instance for the `A` type
*/
export const getInstanceFor = <A>(eqA: Eq<A>) => {
const eqAA = getTupleEq(eqA, eqA);
const eqSetA = S.getEq(eqA);
const eqSetAA = S.getEq(eqAA);
const eqGraphA = fromEquals<Graph<A>>((x, y) => {
if (x.tag === 'Empty') {
return y.tag === 'Empty';
} else {
return eqSetA.equals(vertexSet(x), vertexSet(y)) && eqSetAA.equals(edgeSet(x), edgeSet(y));
}
});
const setUnion = S.union(eqAA);
const setUnionA = S.union(eqA);
const setChain = S.chain(eqAA);
const setMap = S.map(eqAA);
const const1 = constant(1);
const constId = constant(identity);
const constSet = constant(S.empty);
const monoidSet = S.getUnionMonoid(eqA);
const monoidMap = M.getMonoid(eqA, monoidSet);
/**
* Get a set of vertices of a given graph.
* @param g Graph
*/
const vertexSet: (g: Graph<A>) => Set<A> = fold(constSet, S.singleton, setUnionA, setUnionA);
/**
* Get a set of edges of a given graph. Each edge is represented by a tuple `[from, to]`.
* @param g Graph
*/
const edgeSet = (g: Graph<A>): Set<[A, A]> => {
switch (g.tag) {
case 'Empty':
case 'Vertex': return S.empty;
case 'Overlay': return setUnion(edgeSet(g.left), edgeSet(g.right));
case 'Connect': return setUnion(
setUnion(edgeSet(g.from), edgeSet(g.to)),
pipe(
vertexSet(g.from),
setChain(x => pipe(
vertexSet(g.to),
setMap(y => [x, y])),
),
),
);
}
};
/**
* Check whether a given graph contains a vertex with the specified value.
* @param v Value of the vertex to search for
*/
const hasVertex = (v: A): (g: Graph<A>) => boolean => fold<A, boolean>(constFalse, (a) => eqA.equals(v, a), or, or);
const _onOverlay = (left: Fn1<number, number>, right: Fn1<number, number>) => (n: number): number => {
switch (left(n)) {
case 0: return right(n);
case 1: return right(n) === 2 ? 2 : 1;
default: return 2;
}
};
const _onConnect = (from: Fn1<number, number>, to: Fn1<number, number>) => (n: number): number => {
const res = from(n);
switch (res) {
case 2: return 2;
default: return to(res);
}
};
/**
* Check whether given graph contains an edge with specified starting and finishing points.
* @param edgeFrom Value of the start of an edge
* @param edgeTo Value of the end of an edge
* @param g Graph
*/
const hasEdge = (edgeFrom: A, edgeTo: A, g: Graph<A>): boolean => {
const onVertex = (x: A) => (n: number): number => {
switch (n) {
case 0: return eqA.equals(edgeFrom, x) ? 1 : 0;
default: return eqA.equals(edgeTo, x) ? 2 : 1;
}
};
const f = fold<A, Fn1<number, number>>(constId, onVertex, _onOverlay, _onConnect)(g);
return f(0) === 2;
};
/**
* Induce a subgraph from a given graph by applying a predicate for each vertex.
* @param p Filtering predicate for vertices
*/
const induce = (p: Predicate<A>) => (g: Graph<A>): Graph<A> => graph.chain(g, a => p(a) ? vertex(a) : empty());
/**
* Remove all vertices with a given value.
* @param v Vertex value to remove
*/
const removeVertex = (v: A): (g: Graph<A>) => Graph<A> => induce(a => !eqA.equals(v, a));
/**
* Replace all occurrences of a vertices with the given value by a list of vertices while maintaining connectivity.
* @param v Vertex value to search for
* @param vs New values for the split vertices
*/
const splitVertex = (v: A, vs: A[]) => (g: Graph<A>): Graph<A> =>
graph.chain(g, a => eqA.equals(v, a) ? vertices(vs) : vertex(a));
/**
* Check whether given graph is empty
* @param g Graph
*/
const isEmpty = (g: Graph<A>): boolean => fold<A, boolean>(constTrue, constFalse, and, and)(g);
/**
* Compute a number of leaves in a graph expression, includeing `Empty` ones.
* @param g Graph
*/
const size = (g: Graph<A>): number => fold<A, number>(const1, const1, add, add)(g);
/**
* Transpose a given graph by flipping the direction of connections.
* @param g Graph
*/
const transpose = (g: Graph<A>): Graph<A> => fold<A, Graph<A>>(empty, vertex, overlay, flip(connect))(g);
const _simple = (op: Fn2<Graph<A>, Graph<A>, Graph<A>>) => (x: Graph<A>, y: Graph<A>): Graph<A> => {
const z = op(x, y);
switch (true) {
case eqGraphA.equals(x, z): return x;
case eqGraphA.equals(y, z): return y;
default: return z;
}
};
/**
* Simplify a graph expression. Semantically, this is the identity function,
* but it simplifies a given expression according to the laws of the algebra.
* The function does not compute the simplest possible expression,
* but uses heuristics to obtain useful simplifications in reasonable time.
* @param g Graph
*/
const simplify = (g: Graph<A>): Graph<A> =>
fold<A, Graph<A>>(empty, vertex, _simple(overlay), _simple(connect))(g);
/**
* Convert a graph to an adjacency map.
* @param g Graph
*/
const toAdjacencyMap: (g: Graph<A>) => AdjacencyMap<A> = fold<A, AdjacencyMap<A>>(
constant(M.empty),
x => M.singleton(x, S.empty),
monoidMap.concat,
(x, y) => {
const productEdges = new Map<A, Set<A>>();
for (const key of x.keys()) {
productEdges.set(key, new Set(y.keys()));
}
return Mon.fold(monoidMap)([x, y, productEdges]);
},
);
const toAdjacencyList = (ordA: Ord<A>) => (g: Graph<A>): Array<[A, A[]]> =>
M.toArray(ordA)(M.map(S.toArray(ordA))(toAdjacencyMap(g)));
const isSubgraph = (parent: Graph<A>) => (subgraph: Graph<A>): boolean => {
const eqSubsetA: Eq<Set<A>> = { equals: S.subset(eqA) };
return M.isSubmap(eqA, eqSubsetA)(toAdjacencyMap(subgraph), toAdjacencyMap(parent));
};
return {
...pipeable(graph),
eqGraph: eqGraphA,
empty,
vertex,
vertices,
overlay,
overlays,
connect,
connects,
edge,
edges,
clique,
fold,
vertexSet,
edgeSet,
hasVertex,
hasEdge,
removeVertex,
splitVertex,
isEmpty,
size,
induce,
transpose,
simplify,
toAdjacencyMap,
toAdjacencyList,
isSubgraph,
} as const;
};
export const graph: Monad1<URI> & Alternative1<URI> = {
URI,
map: <A, B>(g: Graph<A>, ab: Fn1<A, B>): Graph<B> => fold<A, Graph<B>>(
empty,
flow(ab, vertex),
overlay,
connect,
)(g),
of: vertex,
ap: <A, B>(gab: Graph<Fn1<A, B>>, ga: Graph<A>): Graph<B> => fold<Fn1<A, B>, Graph<B>>(
empty,
(ab) => fold<A, Graph<B>>(empty, flow(ab, vertex), overlay, connect)(ga),
overlay,
connect,
)(gab),
chain: <A, B>(ga: Graph<A>, f: Fn1<A, Graph<B>>): Graph<B> => fold<A, Graph<B>>(
empty,
(a) => fold<B, Graph<B>>(empty, vertex, overlay, connect)(f(a)),
overlay,
connect,
)(ga),
zero: empty,
alt: (fx, fy) => overlay(fx, fy()),
}; | the_stack |
export interface Resource {
content: string
type: string
tag: string
link: string
shortenedLink: string
title: string
}
export const resources: Array<Resource> = [
{
content: 'The API Explorer lets you learn and interact with Looker API.',
type: 'Resource',
tag: 'api',
link: 'https://hack.looker.com/extensions/marketplace_git_github_com_looker_open_source_extension_api_explorer_git::api-explorer',
shortenedLink: 'https://bit.ly/3j1sdWD',
title: 'API Explorer',
},
{
content: 'Gzr is a Looker Content Utility developer tool',
type: 'Example',
tag: 'devtool',
link: 'https://github.com/looker-open-source/gzr',
shortenedLink: 'https://bit.ly/3mSyZiu',
title: 'Gzr',
},
{
content:
'The SDK Codegen is the source of truth for all SDKs and lets you create them for any language',
type: 'Resource',
tag: 'api',
link: 'https://github.com/looker-open-source/sdk-codegen',
shortenedLink: 'https://bit.ly/3lIk23g',
title: 'SDK Codegen',
},
{
content:
'Our collection of SDK examples currently in: C#, Java, Kotlin, Python, R, Ruby, Swift, and TypeScript.',
type: 'Resource',
tag: 'api',
link: 'https://github.com/looker-open-source/sdk-codegen/tree/main/examples',
shortenedLink: 'https://bit.ly/3AL4VdI',
title: 'SDK Examples',
},
{
content:
'Look At Me Sideways (LAMS) is the official LookML style guide and linter to help you create maintainable LookML projects.',
type: 'Example',
tag: 'devtool',
link: 'https://github.com/looker-open-source/look-at-me-sideways',
shortenedLink: 'https://bit.ly/3DOrMGS',
title: 'LookML Style Guide & Linter',
},
{
content:
'Looker Components are a collection of tools for building Looker data experiences.',
type: 'Resource',
tag: 'other',
link: 'https://components.looker.com/',
shortenedLink: 'https://bit.ly/2Z2Q69C',
title: 'Looker Components',
},
{
content: 'Looker Components Storybook contains component examples',
type: 'Resource',
tag: 'other',
link: 'https://components.looker.com/storybook',
shortenedLink: 'https://bit.ly/3pbpygP',
title: 'Components Examples Storybook',
},
{
content:
'The Looker JavaScript Embed SDK makes embedding Looker content in your web application easy!',
type: 'Resource',
tag: 'embed',
link: 'https://github.com/looker-open-source/embed-sdk',
shortenedLink: 'https://bit.ly/3n2mDEJ',
title: 'Embed SDK',
},
{
content:
'Henry is a command line tool that finds model bloat in your Looker instance and identifies unused content in models and explores.',
type: 'example',
tag: 'devtool',
link: 'https://github.com/looker-open-source/henry',
shortenedLink: 'https://bit.ly/3j1NShp',
title: 'Henry',
},
{
content:
'A repository with multiple Extension Framework examples using Typescript, Javascript, React, and Redux',
type: 'example',
tag: 'extension',
link: 'https://github.com/looker-open-source/extension-examples',
shortenedLink: 'https://bit.ly/2YYdlkM',
title: 'Extension Framework Examples',
},
{
content: `This example demonstrates most of Extension SDK's functionality and is a great starting point.`,
type: 'example',
tag: 'extension',
link: 'https://github.com/looker-open-source/extension-examples/tree/main/react/typescript/kitchensink',
shortenedLink: 'https://bit.ly/3n1zbMk',
title: 'Extension Example: Kitchensink',
},
{
content:
'The React Extension SDK npm package. This lets you build a Looker extension — See the Extension Framework Examples for examples.',
type: 'resource',
tag: 'extension',
link: 'https://www.npmjs.com/package/@looker/extension-sdk-react',
shortenedLink: 'https://bit.ly/3pbzoPN',
title: 'Extension SDK: React',
},
{
content:
'Chatty is a simple web browser iframe host/client channel message manager. We use it for iframe communication.',
type: 'resources',
tag: 'embed',
link: 'https://github.com/looker-open-source/chatty',
shortenedLink: 'https://bit.ly/2Z2NrfP',
title: 'Chatty - Iframe Msg Manager',
},
{
content:
'A Snowflake based LookML that demonstrates Looker’s value in the digital marketing landscape.',
type: 'example',
tag: 'lookml',
link: 'https://github.com/looker-open-source/marketing_demo',
shortenedLink: 'https://bit.ly/2YR9rKN',
title: 'Digital Marketing Demo',
},
{
content:
'A BigQuery based LookML that demonstrates Looker’s value in the healthcare landscape.',
type: 'example',
tag: 'lookml',
link: 'https://github.com/looker-open-source/healthcare_demo',
shortenedLink: 'https://bit.ly/3FUokfN',
title: 'Healthcare Demo',
},
{
content:
'This is the official Looker Data Dictionary, fully open source and available as an example.',
type: 'example',
tag: 'extension',
link: 'https://github.com/looker-open-source/app-data-dictionary',
shortenedLink: 'https://bit.ly/3vhMlZh',
title: 'Data Dictionary Extension',
},
{
content:
'Thinking of doing a data analysis project for your hack? Browse and explore BigQuery public datasets through the hackathon instance',
type: 'resources',
tag: 'other',
link: 'https://hack.looker.com/dashboards/16',
shortenedLink: 'https://bit.ly/3FX72yF',
title: 'Public Datasets',
},
{
content:
'This COVID-19 Block consists of LookML models, pre-built dashboards, and explores. The underlying data is only available in BigQuery.',
type: 'example',
tag: 'lookml',
link: 'https://github.com/looker/covid19/blob/master/readme.md',
shortenedLink: 'https://bit.ly/3DPVWd5',
title: 'COVID-19 Data Block',
},
{
content: 'Prebuilt dashboards for immediate access to COVID-19 data.',
type: 'resource',
tag: 'lookml',
link: 'https://covid19response.cloud.looker.com/embed/dashboards-next/51',
shortenedLink: 'https://bit.ly/3n87txG',
title: 'COVID-19 Dashboards',
},
{
content:
'This example demonstrates how to write a Looker extension that needs an access key to run.',
type: 'example',
tag: 'extension',
link: 'https://github.com/looker-open-source/extension-examples/tree/main/react/typescript/access-key-demo',
shortenedLink: 'https://bit.ly/3C6UXo8',
title: 'Extension Example: Access Key',
},
{
content: 'An early-stage mockup of a Twitter-style Looker Extension.',
type: 'example',
tag: 'extension',
link: 'https://github.com/bryan-at-looker/looker-feed',
shortenedLink: 'https://bit.ly/3jhbyyu',
title: 'Looker Feed Extension Mockup',
},
{
content:
'The official Looker Action Hub repository for all your action requirements and examples.',
type: 'example',
tag: 'action',
link: 'https://github.com/looker/actions',
shortenedLink: 'https://bit.ly/3pc2vTa',
title: 'Action Hub',
},
{
content:
'Direct link to the directory of all complete Actions in the official action hub.',
type: 'example',
tag: 'action',
link: 'https://github.com/looker/actions/tree/master/src/actions',
shortenedLink: 'https://bit.ly/3vrwzeM',
title: 'Actions Examples',
},
{
content:
'Mock ActionHub for local or serverless (Google Cloud Functions) use.',
type: 'example',
tag: 'action',
link: 'https://github.com/fabio-looker/sample-cloud-function-action',
shortenedLink: 'https://bit.ly/3lSdCOU',
title: 'Mock ActionHub',
},
{
content:
'Learn how to write an action that exports the results of a Looker Query to BigQuery.',
type: 'tutorial',
tag: 'action',
link: 'https://discourse.looker.com/t/export-the-results-of-a-looker-query-to-bigquery/9720',
shortenedLink: 'https://bit.ly/3jeJICU',
title: 'BigQuery Writeback Action',
},
{
content:
'The official repository of Looker Custom Visualizations API and examples',
type: 'example',
tag: 'viz',
link: 'https://github.com/looker/custom_visualizations_v2',
shortenedLink: 'https://bit.ly/3FYL2ni',
title: 'Custom Visualizations v2',
},
{
content: 'Direct link to Looker Custom Visualization examples',
type: 'example',
tag: 'viz',
link: 'https://github.com/looker/custom_visualizations_v2/tree/master/src/examples',
shortenedLink: 'https://bit.ly/3n3LRCE',
title: 'Custom Viz Examples',
},
{
content: 'A Web IDE to help develop Looker Custom Visualizations.',
type: 'resource',
tag: 'viz',
link: 'https://lookervisbuilder.com/',
shortenedLink: 'https://bit.ly/3G2iHfw',
title: 'Custom Viz Builder',
},
{
content: 'A tutorial to build a custom viz development environment',
type: 'tutorial',
tag: 'viz',
link: 'https://discourse.looker.com/t/creating-a-development-environment-for-custom-visualizations/8470',
shortenedLink: 'https://bit.ly/3DRnZc2',
title: 'Custom Viz Dev Environment Setup',
},
{
content:
'An old example custom viz development environment developed by Headset. (may be out of date)',
type: 'example',
tag: 'viz',
link: 'https://github.com/Headset/looker-environment',
shortenedLink: 'https://bit.ly/30EsLLL',
title: 'Custom Vis Dev Envronment Example',
},
{
content: 'An older demo of Lookers custom viz capabilities',
type: 'resource',
tag: 'viz',
link: 'https://youtu.be/ixwWGKyG3wA',
shortenedLink: 'https://bit.ly/2Z0MtjU',
title: 'Custom Viz Demo Video',
},
{
content:
'This Google Apps Script uses Looker API to load Looks, get data dictionaries, etc.',
type: 'example',
tag: 'api',
link: 'https://github.com/brechtv/looker_google_sheets',
shortenedLink: 'https://bit.ly/3BUdkg1',
title: 'Looker API for Google Sheets',
},
{
content:
'This tool helps you troubleshoot SSO embed URLs generated by your scripts.',
type: 'resource',
tag: 'embed',
link: 'https://fabio-looker.github.io/looker_sso_tool/',
shortenedLink: 'https://bit.ly/30IY8F7',
title: 'SSO Embed Tool',
},
{
content:
'The source code for the SSO embed tool for you to extend or run locally.',
type: 'example',
tag: 'embed',
link: 'https://github.com/fabio-looker/looker_sso_tool',
shortenedLink: 'https://bit.ly/3n3MDzj',
title: 'SSO Embed Tool Source',
},
{
content: 'Vim syntax for LookML. (may be out of date)',
type: 'example',
tag: 'devtool',
link: 'https://github.com/thalesmello/lkml.vim',
shortenedLink: 'https://bit.ly/3G2qJFe',
title: 'LookML Vim Syntax',
},
{
content: 'VSCode syntax for LookML. (may be out of date)',
type: 'example',
tag: 'devtool',
link: 'https://github.com/Ladvien/vscode-looker',
shortenedLink: 'https://bit.ly/3lShYFK',
title: 'LookML VSCode Syntax',
},
{
content: 'An automated EAV builder for EAV schemas.',
type: 'example',
tag: 'devtool',
link: 'https://github.com/fabio-looker/eav-builder',
shortenedLink: 'https://bit.ly/2Xobcy8',
title: 'EAV Builder',
},
{
content:
'Learn how to set up your Looker instance to poll and make changes to your LookML model with an AWS Lambda function.',
type: 'tutorial',
tag: 'devtool',
link: 'https://discourse.looker.com/t/automating-frequently-changing-schemas-with-aws-lambda/10196',
shortenedLink: 'https://bit.ly/3lTyoOo',
title: 'Automate Schema Changes',
},
{
content:
'Developed by WW, this repository contains tools to handle best practices with developing LookML files.',
type: 'example',
tag: 'devtool',
link: 'https://github.com/ww-tech/lookml-tools',
shortenedLink: 'https://bit.ly/3vo5r01',
title: 'LookML Tools',
},
{
content:
'This script was designed for data tables with JSON objects. It creates a LookML view file with a dimension for each JSON object field. (may be out of date)',
type: 'example',
tag: 'devtool',
link: 'https://github.com/leighajarett/JSON_to_LookML',
shortenedLink: 'https://bit.ly/3lR2xhe',
title: 'JSON To LookML',
},
{
content:
'A tool to persist descriptions from your dbt project to your lookml project.',
type: 'example',
tag: 'devtool',
link: 'https://github.com/fishtown-analytics/dbtdocs-to-lookml',
shortenedLink: 'https://bit.ly/2Z81Szd',
title: 'DBTdocs To LookML',
},
{
content: 'A LookML parser and serializer implemented in Python.',
type: 'resource',
tag: 'devtool',
link: 'https://github.com/joshtemple/lkml',
shortenedLink: 'https://bit.ly/3lTzc5S',
title: 'LookML parser',
},
{
content: "A comprehensive demo of Looker's embedding capabilities",
type: 'example',
tag: 'embed',
link: 'https://atomfashion.io/',
shortenedLink: 'https://bit.ly/3BUogKR',
title: 'Embed Demo',
},
{
content: 'An awesome list of awesome Looker projects.',
type: 'resource',
tag: 'other',
link: 'https://gitlab.com/alison985/awesome-looker/-/tree/main',
shortenedLink: 'https://bit.ly/3DSZzPw',
title: 'Awesome Looker Projects',
},
{
content: 'Looker 3.0 SDK for R',
type: 'Example',
tag: 'api',
link: 'https://github.com/looker-open-source/lookr',
shortenedLink: 'https://bit.ly/3vfJwIr',
title: 'Looker R SDK 3.0',
},
] | the_stack |
import type { ComponentController } from '@leanadmin/alpine-typescript';
import Route from './route';
import {
buildContext,
handle,
sameOrigin,
samePath,
middleware,
saferEval,
match,
} from './utils';
const PineconeRouter = {
name: 'pinecone-router',
version: '1.0.4',
/**
* @type Route[]
* @summary array of routes instantiated from the Route class.
*/
routes: <Route[]>[],
settings: <Settings>{
hash: false,
basePath: '/',
allowNoHandler: false,
middlewares: {},
},
/**
* @type {Context}
* @summary The context object for current path.
*/
currentContext: <Context>{},
/**
* @description The handler for 404 pages, can be overwritten by a notfound route
*/
notfound: new Route('notfound'),
/**
* Entry point of the plugin
*/
start() {
if (!window.Alpine) {
throw new Error(`Alpine is required for ${this.name} to work.`);
}
// Routers that are already initialized
let routerCount = 0;
// Whenever a component is initialized, check if it is a router
// and check if the children are valid routes
window.Alpine.onComponentInitialized(
(component: ComponentController) => {
// @ts-ignore
if (component.$el.hasAttribute('x-router')) {
if (routerCount > 1) {
throw new Error(
`${this.name}: Only one router can be in a page.`
);
}
// Detect router settings
// javascript config
// this will check if there is a "settings" parameter
// inside the router component's data.
this.settings = {
...this.settings,
...(component.getUnobservedData()['settings'] ?? {}),
};
middleware('init', component, this.settings);
// Loop through child elements of this router
// filtering out everything that isn't a template tag
// and doesn't have x-route attribute.
// @ts-ignore
Array.from(component.$el.children)
.filter(
(el: any) => el.tagName.toLowerCase() == 'template'
)
.forEach((el: any) => this.processRoute(el, component));
routerCount++;
if (!this.settings.hash) {
// navigate to the current page to handle it
// ONLY if we not using hash routing for the default router
return this.navigate(
window.location.pathname,
false,
true
);
}
this.navigate(
window.location.hash.substring(1),
true,
true
);
}
}
);
// Intercept click event in links
this.interceptLinks(this);
// handle navigation events not emitted by links, for example, back button.
window.addEventListener('popstate', () => {
if (this.settings.hash) {
if (window.location.hash != '') {
this.navigate(window.location.hash.substring(1), true);
}
} else {
this.navigate(window.location.pathname, true);
}
});
// The $router magic helper
window.Alpine.addMagicProperty(
'router',
() => window.PineconeRouter.currentContext
);
},
/**
* Take the template element of a route and the router component
* @param {HTMLTemplateElement} el the routes HTML element, must be a template tag.
* @param {any} component the router Alpine component
*/
processRoute(el: HTMLTemplateElement, component: ComponentController) {
// The path must be a string
let path = el.getAttribute('x-route') ?? '/';
if (path.indexOf('#') > -1) {
throw new Error(
`${this.name}: A route's path may not have a hash character.`
);
}
middleware('onBeforeRouteProcessed', el, component, path);
// will hold handlers as functions
let handlers = [];
if (!el.hasAttribute('x-handler') && !this.settings.allowNoHandler) {
throw new Error(`${this.name}: Routes must have a handler.`);
} else if (el.hasAttribute('x-handler')) {
let result = saferEval(
el.getAttribute('x-handler'),
component.$data
);
if (typeof result == 'function') handlers = [result];
else if (typeof result == 'object') handlers = result;
else
throw new Error(
`${this.name}: Invalid handler type: ${typeof result}.`
);
if (path == 'notfound') this.notfound.handlers = handlers;
}
if (path != 'notfound') {
// if specified add the basePath
if (this.settings.basePath != '/') {
path = this.settings.basePath + path;
}
// register the new route if possible
this.add(path, handlers);
}
},
/**
* Check if the anchor element point to a navigation route.
* @param {any} el The anchor element or Event target
* @param {boolean} hash Set to true when using hash routing
* @returns {object} {valid: boolean, link: string}
*/
validLink(el: any, hash: boolean): { valid: boolean; link: string } {
// the object we'll return
let ret = { valid: false, link: '' };
// The checks in this block are taken from
// https://github.com/visionmedia/page.js/blob/master/index.js#L370
// continue ensure link
// el.nodeName for svg links are 'a' instead of 'A'
// traverse up till we find an anchor tag, since clicks
// on image links for example set the target as img instead of a.
while (el && 'A' !== el.nodeName.toUpperCase()) el = el.parentNode;
if (!el || 'A' !== el.nodeName.toUpperCase()) return ret;
// check if link is inside an svg
// in this case, both href and target are always inside an object
var svg =
typeof el.href === 'object' &&
el.href.constructor.name === 'SVGAnimatedString';
// Ignore if tag has
// 1. "download" attribute
// 2. rel="external" attribute
if (
el.hasAttribute('download') ||
el.getAttribute('rel') === 'external'
) {
return ret;
}
// ensure non-hash for the same path
ret.link = el.getAttribute('href') ?? '';
if (!hash && samePath(el) && (el.hash || '#' === ret.link)) {
return ret;
}
// Check for mailto: in the href
if (ret.link && ret.link.indexOf('mailto:') > -1) return ret;
// check target
// svg target is an object and its desired value is in .baseVal property
if (svg ? el.target.baseVal : el.target) return ret;
// x-origin
// note: svg links that are not relative don't call click events (and skip page.js)
// consequently, all svg links tested inside page.js are relative and in the same origin
if (!svg && !sameOrigin(el.href)) return ret;
ret.valid = true;
return ret;
},
/**
* @description Add a handler to click events on all valid links
*/
interceptLinks(t: any) {
window.document.body.addEventListener(
document.ontouchstart ? 'touchstart' : 'click',
function (e: any) {
if (
e.metaKey ||
e.ctrlKey ||
e.shiftKey ||
e.detail != 1 ||
e.defaultPrevented
) {
return;
}
// ensure link
// use shadow dom when available if not, fall back to composedPath()
// for browsers that only have shady
let el = e.target;
let eventPath =
e.path || (e.composedPath ? e.composedPath() : null);
if (eventPath) {
for (let i = 0; i < eventPath.length; i++) {
if (!eventPath[i].nodeName) continue;
if (eventPath[i].nodeName.toUpperCase() !== 'A')
continue;
if (!eventPath[i].href) continue;
el = eventPath[i];
break;
}
}
// allow skipping handler
if (el.hasAttribute('native')) return;
let ret = t.validLink(el, t.settings.hash);
if (!ret.valid) return;
t.navigate(ret.link);
// prevent default behavior.
e.preventDefault();
}
);
},
/**
* Go to the specified path without reloading
* @param {string} path the path with no hash even if using hash routing
* @param {boolean} fromPopState this will be set to true if called from window.onpopstate event
* @param {boolean} firstLoad this will be set to true if this is the first page loaded, also from page reload
*/
navigate(
path: string,
fromPopState: boolean = false,
firstLoad: boolean = false
) {
path ??= '/';
// only add basePath if it was set
// if not using hash routing
// and if it wasn't added already
if (
this.settings.basePath != '/' &&
!path.startsWith(this.settings.basePath)
) {
path = this.settings.basePath + path;
}
if (path == this.settings.basePath && !path.endsWith('/')) {
path += '/';
}
const route: Route | undefined = this.routes.find((route: Route) => {
let m = match(path, route.path);
route.params = m != false ? m : {};
return m;
});
let context =
typeof route == 'undefined'
? buildContext('notfound', path, [])
: buildContext(route.path, path, route.params);
this.currentContext = context;
// the middleware may return 'stop' to stop execution of this function
if (
middleware('onBeforeHandlersExecuted', route, path, firstLoad) ==
'stop'
)
return;
// do not call pushstate from popstate event https://stackoverflow.com/a/50830905
if (!fromPopState) {
let fullPath = '';
if (this.settings.hash) {
fullPath = '#';
if (window.location.pathname != '/') {
fullPath += window.location.pathname;
}
fullPath += window.location.search + path;
} else {
fullPath = path + window.location.search + window.location.hash;
}
history.pushState({ path: fullPath }, '', fullPath);
}
if (!handle(route?.handlers ?? this.notfound.handlers, context)) return;
middleware('onHandlersExecuted', route, path, firstLoad);
},
/**
* Add a new route
*/
add(path: string, handlers: Handler[]) {
// check if the route was registered on the same router.
if (this.routes.find((r: Route) => r.path == path) != null) {
throw new Error('Pinecone Router: route already exist');
}
this.routes.push(new Route(path, handlers));
},
/**
* Remove a route
*/
remove(path: string) {
this.routes = this.routes.filter((r: Route) => r.path != path);
},
};
const alpine =
window.deferLoadingAlpine || ((callback: Function) => callback());
window.PineconeRouter = PineconeRouter;
window.deferLoadingAlpine = function (callback: Function) {
window.PineconeRouter.start();
alpine(callback);
};
export default PineconeRouter;
declare global {
interface Window {
PineconeRouter: typeof PineconeRouter;
PineconeRouterMiddlewares: Array<Middleware>;
}
}
export declare type Context = {
route: string;
path: string;
params: { [key: string]: any };
/**
* query without leading '?'
*/
query: string;
/**
* hash without leading '#'
*/
hash: string;
redirect: (path: string) => string;
};
export declare interface Settings {
/**
* @default false
* @summary enable hash routing
*/
hash: boolean;
/**
* @default `/`
* @summary The base path of the site, for example /blog
* Note: do not use with using hash routing!
*/
basePath: string;
/**
* @default false
* @summary when true it wont throw an error when the handler of a route is not specified.
*/
allowNoHandler: boolean;
/**
* @default []
* @summmary array of middlewares
*/
middlewares: {[key: string]: Middleware};
}
export type Handler = (context: Context) => 'stop' | void;
export declare interface Middleware {
name: string;
version?: string;
settings?: { [key: string]: any };
/**
* This will be called at router initialization.
* used for detecting router settings.
*/
init?: (component: ComponentController, settings: Settings) => void;
/**
* Called for each route during initialization,
* before the route is processed & added.
* @param {HTMLTemplateElement} el the route's <template> element
* @param {ComponentController} component the router's alpine component
* @param {string} path the route's path
*/
onBeforeRouteProcessed?: (
el: HTMLTemplateElement,
component: ComponentController,
path: string
) => void;
/**
* Will be called before the handlers are executed.
* during navigation (PineconeRouter.navigate()).
* @param {Route} route the matched route, undefined if not found.
* @param {string} path the path visited by the client
* @param {boolean} firstload first page load and not link navigation request
* @returns {'stop'|null} 'stop' to make the navigate function exit (make sure to send the loadend event); none to continute execution.
*/
onBeforeHandlersExecuted?: (
route: Route,
path: string,
firstload: boolean
) => 'stop' | void;
/**
* Will be called after the handlers are executed and done.
* during navigation (PineconeRouter.navigate()).
* @param {Route} route the matched route, undefined if not found.
* @param {string} path the path visited by the client
* @param {boolean} firstload first page load and not link navigation request
* @returns {'stop'|null} 'stop' to make the navigate function exit (make sure to send the loadend event); none to continute execution.
*/
onHandlersExecuted?: (
route: Route,
path: string,
firstload: boolean
) => 'stop' | void;
[key: string]: any;
} | the_stack |
import {assert} from '@esm-bundle/chai';
import '../playground-code-editor.js';
import {PlaygroundCodeEditor} from '../playground-code-editor.js';
import {sendKeys} from '@web/test-runner-commands';
const raf = async () => new Promise((r) => requestAnimationFrame(r));
suite('playground-code-editor', () => {
let container: HTMLDivElement;
setup(() => {
container = document.createElement('div');
document.body.appendChild(container);
});
teardown(() => {
container.remove();
});
test('is registered', () => {
assert.instanceOf(
document.createElement('playground-code-editor'),
PlaygroundCodeEditor
);
});
test('renders initial value', async () => {
const editor = document.createElement('playground-code-editor');
editor.value = 'foo';
container.appendChild(editor);
await editor.updateComplete;
assert.include(editor.shadowRoot!.innerHTML, 'foo');
});
test('renders updated value', async () => {
const editor = document.createElement('playground-code-editor');
editor.value = 'foo';
container.appendChild(editor);
await editor.updateComplete;
editor.value = 'bar';
await editor.updateComplete;
assert.include(editor.shadowRoot!.innerHTML, 'bar');
});
test('dispatches change event', async () => {
const editor = document.createElement('playground-code-editor');
editor.value = 'foo';
container.appendChild(editor);
await editor.updateComplete;
await new Promise<void>((resolve) => {
editor.addEventListener('change', () => resolve());
const editorInternals = editor as unknown as {
_codemirror: PlaygroundCodeEditor['_codemirror'];
};
editorInternals._codemirror!.setValue('bar');
});
});
suite('history', () => {
let editor: PlaygroundCodeEditor;
let editorInternals: {
_codemirror: PlaygroundCodeEditor['_codemirror'];
};
setup(async () => {
editor = document.createElement('playground-code-editor');
// For correct history, CodeMirror needs to be initialized and attached to
// the DOM.
container.appendChild(editor);
await raf();
editorInternals = editor as unknown as typeof editorInternals;
});
teardown(() => {
editor.remove();
});
test(`and doc instance cache won't drive editor value`, async () => {
const DOCUMENT_KEY1 = {dockey: 1};
const DOCUMENT_KEY2 = {dockey: 2};
editor.value = 'document key 1';
editor.documentKey = DOCUMENT_KEY1;
await raf();
assert.equal(editorInternals._codemirror!.getValue(), 'document key 1');
editor.value = 'document key 2';
editor.documentKey = DOCUMENT_KEY2;
await raf();
assert.equal(editorInternals._codemirror!.getValue(), 'document key 2');
// If only the documentKey is changed, the current value is set on the
// document cache. The `value` property drives the CodeMirror contents.
editor.documentKey = DOCUMENT_KEY1;
await raf();
assert.equal(editorInternals._codemirror!.getValue(), 'document key 2');
// Changing documentKey and unsetting the value should clear the editor.
editor.value = undefined;
editor.documentKey = DOCUMENT_KEY2;
await raf();
assert.equal(editorInternals._codemirror!.getValue(), '');
// Unset the cache should result in a
editor.documentKey = undefined;
editor.value = 'value with no cache';
await raf();
assert.equal(
editorInternals._codemirror!.getValue(),
'value with no cache'
);
});
test(`is cleared on unsetting documentKey`, async () => {
const DOCUMENT_KEY1 = {dockey: 1};
editor.value = 'no cache';
await raf();
editor.documentKey = DOCUMENT_KEY1;
await raf();
editor.value = 'update on cache';
await raf();
editor.documentKey = undefined;
await raf();
assert.equal(editorInternals._codemirror!.getValue(), 'update on cache');
// No-op, because unsetting documentKey clears history.
editorInternals._codemirror!.undo();
await raf();
assert.equal(editorInternals._codemirror!.getValue(), 'update on cache');
await raf();
editor.value = 'changed';
await raf();
assert.equal(editorInternals._codemirror!.getValue(), 'changed');
editorInternals._codemirror!.undo();
await raf();
assert.equal(editorInternals._codemirror!.getValue(), 'update on cache');
});
test('is updated if value gets changed with doc cache', async () => {
const DOCUMENT_KEY1 = {dockey: 1};
const DOCUMENT_KEY2 = {dockey: 2};
editor.value = 'document key 1';
editor.documentKey = DOCUMENT_KEY1;
await raf();
assert.equal(editorInternals._codemirror!.getValue(), 'document key 1');
editor.value = 'document key 2';
editor.documentKey = DOCUMENT_KEY2;
await raf();
assert.equal(editorInternals._codemirror!.getValue(), 'document key 2');
editor.documentKey = DOCUMENT_KEY1;
editor.value = 'override document key 1';
await raf();
assert.equal(
editorInternals._codemirror!.getValue(),
'override document key 1'
);
editorInternals._codemirror?.undo();
await raf();
assert.equal(editorInternals._codemirror!.getValue(), 'document key 1');
});
test('is maintained without using documentKey', async () => {
editor.value = 'foo';
await raf();
assert.equal(editorInternals._codemirror!.getValue(), 'foo');
editor.value = 'bar';
await raf();
assert.equal(editorInternals._codemirror!.getValue(), 'bar');
editorInternals._codemirror!.undo();
await raf();
assert.equal(editorInternals._codemirror!.getValue(), 'foo');
});
test('is maintained with a document key', async () => {
const DOCUMENT_KEY1 = {};
editor.documentKey = DOCUMENT_KEY1;
editor.value = 'foo';
await editor.updateComplete;
assert.equal(editorInternals._codemirror!.getValue(), 'foo');
editor.value = 'bar';
await editor.updateComplete;
assert.equal(editorInternals._codemirror!.getValue(), 'bar');
editorInternals._codemirror!.undo();
await raf();
assert.equal(editorInternals._codemirror!.getValue(), 'foo');
});
test('is associated to the documentKey property', async () => {
const DOCUMENT_KEY1 = {};
const DOCUMENT_KEY2 = {};
editor.documentKey = DOCUMENT_KEY1;
editor.value = 'foo';
await editor.updateComplete;
editor.value = 'potato';
editor.documentKey = DOCUMENT_KEY2;
await editor.updateComplete;
assert.equal(editorInternals._codemirror!.getValue(), 'potato');
editorInternals._codemirror!.undo();
await raf();
assert.equal(editorInternals._codemirror!.getValue(), 'potato');
});
test('can be rehydrated from a saved document instance', async () => {
const DOCUMENT_KEY1 = {};
const DOCUMENT_KEY2 = {};
editor.documentKey = DOCUMENT_KEY1;
editor.value = 'foo';
await raf();
editor.value = 'bar';
await raf();
editor.documentKey = DOCUMENT_KEY2;
await raf();
editor.value = 'potato';
await raf();
editor.documentKey = DOCUMENT_KEY1;
editor.value = 'bar';
await raf();
assert.equal(editorInternals._codemirror!.getValue(), 'bar');
editorInternals._codemirror!.undo();
await raf();
assert.equal(editorInternals._codemirror!.getValue(), 'foo');
});
});
suite('syntax highlight', () => {
/**
* Traverse the given root node depth first, and return the first node whose
* trimmed text content is exactly equal to the given text.
*/
const findNodeWithText = (node: Node, text: string): Node | undefined => {
if (node.textContent?.trim() === text) {
return node;
}
for (const child of Array.from(node.childNodes)) {
const r = findNodeWithText(child, text);
if (r) {
return r;
}
}
return undefined;
};
const assertHighlight = async (
type: PlaygroundCodeEditor['type'],
value: string,
text: string,
color: string
) => {
const editor = document.createElement('playground-code-editor');
editor.type = type;
editor.value = value;
container.appendChild(editor);
await editor.updateComplete;
const element = findNodeWithText(editor.shadowRoot!, text);
assert.isDefined(element);
const style = window.getComputedStyle(element as HTMLElement);
assert.equal(style.color, color);
};
const tagColor = 'rgb(17, 119, 0)';
const typeColor = 'rgb(0, 136, 85)';
const atomColor = 'rgb(34, 17, 153)';
const keywordColor = 'rgb(119, 0, 136)';
const stringColor = 'rgb(170, 17, 17)';
test('html', async () =>
assertHighlight('html', '<p>foo</p>', '<p>', tagColor));
test('css', async () =>
assertHighlight('css', 'p { color: blue; }', 'blue', keywordColor));
test('js', async () =>
assertHighlight('js', 'if (true) {}', 'true', atomColor));
test('ts', async () =>
assertHighlight('ts', 'const x: string;', 'string', typeColor));
test('html-in-js', async () =>
assertHighlight('js', 'html`<p>foo</p>`', '<p>', tagColor));
test('html-in-ts', async () =>
assertHighlight('ts', 'html`<p>foo</p>`', '<p>', tagColor));
test('css-in-js', async () =>
assertHighlight('js', 'css`p { color: blue; }`', 'blue', keywordColor));
test('css-in-ts', async () =>
assertHighlight('ts', 'css`p { color: blue; }`', 'blue', keywordColor));
test('json', async () =>
assertHighlight('json', '{"foo": 123}', '"foo"', stringColor));
});
suite('comment toggle', () => {
async function assertToggle(
type: PlaygroundCodeEditor['type'],
value: string,
expect: string
) {
const editor = document.createElement('playground-code-editor');
editor.type = type;
editor.value = value;
container.appendChild(editor);
await editor.updateComplete;
const focusContainer =
editor.shadowRoot!.querySelector<HTMLDivElement>('#focusContainer')!;
editor.focus();
await sendKeys({
down: 'Control',
});
await sendKeys({
press: 'Slash',
});
await sendKeys({
up: 'Control',
});
assert.include(focusContainer.innerText, expect);
await sendKeys({
down: 'Control',
});
await sendKeys({
press: 'Slash',
});
await sendKeys({
up: 'Control',
});
assert.include(focusContainer.innerText, value);
}
test('ts', async () =>
assertToggle('ts', 'const g = 3;', '// const g = 3;'));
test('js', async () =>
assertToggle('js', 'const g = 3;', '// const g = 3;'));
test('html', async () =>
assertToggle('html', '<p>foo</p>', '<!-- <p>foo</p> -->'));
test('css', async () =>
assertToggle('css', 'p { color: blue; }', '/* p { color: blue; } */'));
test('ignored when readonly', async () => {
const editor = document.createElement('playground-code-editor');
editor.type = 'ts';
editor.readonly = true;
editor.value = 'const g = 3;';
container.appendChild(editor);
await editor.updateComplete;
editor.focus();
await sendKeys({
down: 'Control',
});
await sendKeys({
press: 'Slash',
});
await sendKeys({
up: 'Control',
});
await raf();
assert.include(
// There isn't a focusContainer when the editor is in readonly mode.
editor.shadowRoot!.querySelector<HTMLDivElement>('div')!.innerText,
'const g = 3;'
);
});
});
}); | the_stack |
import { AggregationFn, SortDirection } from "@tonclient/core";
import { ABIVersions, runner } from "../runner";
import { expect, jest, test } from "../jest";
import { contracts } from "../contracts";
test("net", async () => {
const net = runner.getClient().net;
expect(net).not.toBeNull();
});
enum Collection {
accounts = "accounts",
messages = "messages",
transactions = "transactions",
blocks_signatures = "blocks_signatures",
blocks = "blocks",
}
test("net: query_collection - Block signatures", async () => {
const net = runner.getClient().net;
const signaturesQuery = await net.query_collection({
collection: Collection.blocks_signatures,
filter: {},
result: "id",
limit: 1,
});
expect(signaturesQuery.result.length).toBeGreaterThanOrEqual(0);
});
test("net: query_collection - Accounts", async () => {
const net = runner.getClient().net;
const accountsQuery = await net.query_collection({
collection: Collection.accounts,
filter: {},
result: "id balance",
limit: 1,
});
expect(accountsQuery.result.length).toBeGreaterThan(0);
});
test("net: query_collection - Messages", async () => {
const net = runner.getClient().net;
const messagesQuery = await net.query_collection({
collection: Collection.messages,
filter: {},
result: "id",
limit: 1,
});
expect(messagesQuery.result.length).toBeGreaterThan(0);
});
test("net: query_collection - Transactions", async () => {
const net = runner.getClient().net;
const transactionsQuery = await net.query_collection({
collection: Collection.transactions,
filter: {},
result: "id",
limit: 1,
});
expect(transactionsQuery.result.length).toBeGreaterThan(0);
});
test("net: query_collection - Blocks", async () => {
const net = runner.getClient().net;
const blocksQuery = await net.query_collection({
collection: Collection.blocks,
filter: {},
result: "id",
limit: 1,
});
expect(blocksQuery.result.length).toBeGreaterThan(0);
});
test("net: query_collection - Ranges", async () => {
const net = runner.getClient().net;
const messages = await net.query_collection({
collection: Collection.messages,
filter: {created_at: {gt: 1562342740}},
result: "body created_at",
});
expect(messages.result[0].created_at).toBeGreaterThan(1562342740);
});
const testCountAggregation = async (collection: string, count: number) => {
const net = runner.getClient().net;
const result = await net.aggregate_collection({
collection,
filter: {},
fields: [{
field: "id",
fn: AggregationFn.COUNT,
}],
});
expect(Number(result.values[0])).toBeGreaterThanOrEqual(count);
};
test("net: aggregate_collection - count", async () => {
await testCountAggregation(Collection.blocks_signatures, 0);
await testCountAggregation(Collection.accounts, 1);
await testCountAggregation(Collection.blocks, 1);
await testCountAggregation(Collection.messages, 1);
await testCountAggregation(Collection.transactions, 1);
});
const testAggregateFunctions = async (collection: string, field: string) => {
const net = runner.getClient().net;
const result = await net.aggregate_collection({
collection,
filter: {},
fields: [
{
field,
fn: AggregationFn.MIN,
},
{
field,
fn: AggregationFn.MAX,
},
{
field,
fn: AggregationFn.SUM,
},
{
field,
fn: AggregationFn.AVERAGE,
},
],
});
expect(result.values[0]).toBeDefined();
expect(result.values[1]).toBeDefined();
expect(result.values[2]).toBeDefined();
expect(result.values[3]).toBeDefined();
};
test("net: aggregate_collection - Account balance", async () => {
await testAggregateFunctions(Collection.accounts, "balance");
});
test("net: wait_for_collection", async () => {
const net = runner.getClient().net;
const data = await net.wait_for_collection({
collection: Collection.transactions,
filter: {
now: {gt: 1563449},
},
result: "id status",
});
expect(data.result.status).toEqual(3);
});
const transactionWithAddresses = `
id
account_addr
in_message { dst src value }
`;
test.each(ABIVersions)("net: Subscribe (subscribe_collection) for transactions with addresses (ABIv%i)", async (abiVersion) => {
const net = runner.getClient().net;
const wallet = await runner.getAccount(contracts.WalletContract, abiVersion);
await runner.sendGramsTo(await wallet.getAddress());
const transactions = [];
const subscription = (await net.subscribe_collection({
collection: Collection.transactions,
filter: {
account_addr: {eq: await wallet.getAddress()},
},
result: "id",
},
(d) => {
transactions.push(d.result);
})).handle;
// hack for Windows-assembled TON NODE SE
// issue: https://github.com/tonlabs/tonos-se/issues/13
await new Promise((resolve=>setTimeout(resolve, 5_000)));
await wallet.deploy();
await new Promise(resolve => setTimeout(resolve, 1_000));
await net.unsubscribe({handle: subscription});
expect(transactions.length).toBeGreaterThan(0);
});
// This is a filter test
test.each(ABIVersions)("net: Subscribe (subscribe_collection) for messages (ABI v%i)", async (abiVersion) => {
const {net} = runner.getClient();
const docs = [];
const subscription = (await net.subscribe_collection({
collection: Collection.messages,
filter: {
src: {eq: "1"},
},
result: "id",
},
(evt) => {
docs.push(evt.result);
},
)).handle;
const wallet = await runner.getAccount(contracts.WalletContract, abiVersion);
await runner.deploy(wallet);
await net.unsubscribe({handle: subscription});
expect(docs.length).toEqual(0);
});
test("net: Query (query_collection) transactions with addresses", async () => {
const net = runner.getClient().net;
const queryResult = await net.query_collection({
collection: Collection.transactions,
filter: {},
result: transactionWithAddresses,
});
expect(queryResult.result[0]).toBeTruthy();
});
// Skipped explicitly as disabled
test.skip("Subscribe for failed server", async () => {
// const net = runner.getClient().net;
// console.log(">>>", "Subscribed");
// tests.client.queries.accounts.subscribe(
// {
// id: { eq: "-1:3333333333333333333333333333333333333333333333333333333333333333" }
// },
// "id balance",
// (e, d) => {
// console.log("">>>", e, d);
// });
// await new Promise((resolve) => {
// setTimeout(resolve, 100_000);
// })
});
const shardHashesQuery = `
workchain_id
master {
shard_hashes {
workchain_id
shard
descr {seq_no}
}
}
`;
test("net: Check (query_collection) shard_hashes greater then 0", async () => {
const net = runner.getClient().net;
const queryResult = await net.query_collection({
collection: Collection.blocks,
filter: {},
result: shardHashesQuery,
});
expect(queryResult.result.length).toBeGreaterThan(0);
});
// Skipped explicitly as disabled
test.skip("Subscribe for accounts", async () => {
// const net = runner.getClient().net;
// const { queries } = tests.client;
// const subscriptions = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
// .map(i => queries.accounts.subscribe({}, "id code data", (e, doc) => {
// console.log(i, doc.id);
// }));
// await new Promise(resolve => setTimeout(resolve, 1000_000));
// subscriptions.forEach(x => x.unsubscribe());
});
// Skipped explicitly as disabled
test.skip("Long time subscription", async () => {
const net = runner.getClient().net;
jest.setTimeout(1000000);
const subscription = await net.subscribe_collection({
collection: Collection.accounts,
filter: {},
result: "id code_hash data_hash",
}, (doc) => {
console.log(doc.id);
});
await new Promise(resolve => setTimeout(resolve, 1_000_000));
await net.unsubscribe({handle: subscription.handle});
});
test("net: Validator set", async () => {
if (runner.config.network?.endpoints?.[0].startsWith("http://localhost")) {
console.log("Skipping validator set test on localhost");
return;
}
const net = runner.getClient().net;
// test https://docs.ton.dev/86757ecb2/p/978847-get-config
const result = await net.query_collection({
collection: Collection.blocks,
filter: {},
order: [{
path: "seq_no",
direction: SortDirection.DESC,
}],
limit: 1,
result: "prev_key_block_seqno",
});
expect(result.result.length)
.toEqual(1);
const seq_no = result.result[0].prev_key_block_seqno;
expect(seq_no)
.toBeGreaterThanOrEqual(0);
// no masterblock before first election and seq_no = 0
if (seq_no > 0) {
const config = await net.query_collection({
collection: Collection.blocks,
filter: {
seq_no: { eq: seq_no },
workchain_id: { eq: -1 },
},
result: "master { config { p15 { validators_elected_for elections_start_before elections_end_before stake_held_for } p16 { max_validators max_main_validators min_validators } p17 { min_stake max_stake min_total_stake max_stake_factor } p34 { utime_since utime_until total total_weight list { public_key adnl_addr weight } } } }",
});
expect(config.result.length)
.toEqual(1);
const p15ConfigParams = config.result[0].master.config.p15;
expect(p15ConfigParams.validators_elected_for)
.toBeGreaterThan(0);
expect(p15ConfigParams.elections_start_before)
.toBeGreaterThan(0);
expect(p15ConfigParams.elections_end_before)
.toBeGreaterThan(0);
expect(p15ConfigParams.stake_held_for)
.toBeGreaterThan(0);
const p16ConfigParams = config.result[0].master.config.p16;
expect(BigInt(p16ConfigParams.max_validators))
.toBeGreaterThan(BigInt(p16ConfigParams.min_validators));
expect(BigInt(p16ConfigParams.max_validators))
.toBeGreaterThanOrEqual(p16ConfigParams.max_main_validators);
const p17ConfigParams = config.result[0].master.config.p17;
expect(p17ConfigParams.min_stake)
.toBeDefined();
expect(p17ConfigParams.max_stake)
.toBeDefined();
expect(BigInt(p17ConfigParams.min_stake))
.toBeLessThanOrEqual(BigInt(p17ConfigParams.max_stake));
expect(BigInt(p17ConfigParams.min_total_stake))
.toBeLessThanOrEqual(BigInt(p17ConfigParams.max_stake));
expect(p17ConfigParams.min_total_stake)
.toBeDefined();
expect(p17ConfigParams.max_stake_factor)
.toBeDefined();
const validatorSetList = config.result[0].master.config.p34.list;
const p34ConfigParams = config.result[0].master.config.p34;
expect(p34ConfigParams.total)
.toEqual(validatorSetList.length);
let weight = BigInt(0);
for (let i = 0; i < validatorSetList.length; i++) {
expect(validatorSetList[i].adnl_addr)
.toBeDefined();
expect(validatorSetList[i].public_key)
.toBeDefined();
expect(validatorSetList[i].public_key.length)
.toEqual(64);
weight += BigInt(validatorSetList[i].weight);
}
expect(BigInt(p34ConfigParams.total_weight))
.toEqual(weight);
}
}); | the_stack |
import window from 'global/window';
import {BrushingExtension} from '@deck.gl/extensions';
import SvgIconLayer from 'deckgl-layers/svg-icon-layer/svg-icon-layer';
import IconLayerIcon from './icon-layer-icon';
import {ICON_FIELDS, CLOUDFRONT} from 'constants/default-settings';
import IconInfoModalFactory from './icon-info-modal';
import Layer, {LayerBaseConfig, LayerColumn} from '../base-layer';
import {getTextOffsetByRadius, formatTextLabelData} from '../layer-text-label';
import {DataContainerInterface} from '../../utils/table-utils/data-container-interface';
import {
VisConfigBoolean,
VisConfigColorRange,
VisConfigNumber,
VisConfigRange
} from '../layer-factory';
import {ColorRange} from '../../constants/color-ranges';
import {Merge} from '../../reducers';
import {KeplerTable} from '../../utils';
export type IconLayerColumnsConfig = {
lat: LayerColumn;
lng: LayerColumn;
altitude: LayerColumn;
icon: LayerColumn;
};
type IconGeometry = {} | null;
export type IconLayerVisConfigSettings = {
radius: VisConfigNumber;
fixedRadius: VisConfigBoolean;
opacity: VisConfigNumber;
colorRange: VisConfigColorRange;
radiusRange: VisConfigRange;
};
export type IconLayerVisConfig = {
radius: number;
fixedRadius: boolean;
opacity: number;
colorRange: ColorRange;
radiusRange: [number, number];
};
export type IconLayerConfig = Merge<
LayerBaseConfig,
{columns: IconLayerColumnsConfig; visConfig: IconLayerVisConfig}
>;
export type IconLayerData = {index: number; icon: string};
const brushingExtension = new BrushingExtension();
export const SVG_ICON_URL = `${CLOUDFRONT}/icons/svg-icons.json`;
export const iconPosAccessor = ({lat, lng, altitude}: IconLayerColumnsConfig) => (
dc: DataContainerInterface
) => d => [
dc.valueAt(d.index, lng.fieldIdx),
dc.valueAt(d.index, lat.fieldIdx),
altitude?.fieldIdx > -1 ? dc.valueAt(d.index, altitude.fieldIdx) : 0
];
export const iconAccessor = ({icon}: IconLayerColumnsConfig) => (dc: DataContainerInterface) => d =>
dc.valueAt(d.index, icon.fieldIdx);
export const iconRequiredColumns: ['lat', 'lng', 'icon'] = ['lat', 'lng', 'icon'];
export const iconOptionalColumns: ['altitude'] = ['altitude'];
export const pointVisConfigs: {
radius: 'radius';
fixedRadius: 'fixedRadius';
opacity: 'opacity';
colorRange: 'colorRange';
radiusRange: 'radiusRange';
} = {
radius: 'radius',
fixedRadius: 'fixedRadius',
opacity: 'opacity',
colorRange: 'colorRange',
radiusRange: 'radiusRange'
};
function flatterIconPositions(icon) {
// had to flip y, since @luma modal has changed
return icon.mesh.cells.reduce((prev, cell) => {
cell.forEach(p => {
prev.push(
...[icon.mesh.positions[p][0], -icon.mesh.positions[p][1], icon.mesh.positions[p][2]]
);
});
return prev;
}, []);
}
export default class IconLayer extends Layer {
getIconAccessor: (dataContainer: DataContainerInterface) => (d: any) => any;
_layerInfoModal: () => JSX.Element;
iconGeometry: IconGeometry;
declare visConfigSettings: IconLayerVisConfigSettings;
declare config: IconLayerConfig;
constructor(
props: {
id?: string;
iconGeometry?: IconGeometry;
} & Partial<LayerBaseConfig> = {}
) {
super(props);
this.registerVisConfig(pointVisConfigs);
this.getPositionAccessor = (dataContainer: DataContainerInterface) =>
iconPosAccessor(this.config.columns)(dataContainer);
this.getIconAccessor = dataContainer => iconAccessor(this.config.columns)(dataContainer);
// prepare layer info modal
this._layerInfoModal = IconInfoModalFactory();
this.iconGeometry = props.iconGeometry || null;
this.getSvgIcons();
}
get type(): 'icon' {
return 'icon';
}
get requiredLayerColumns() {
return iconRequiredColumns;
}
get optionalColumns() {
return iconOptionalColumns;
}
get columnPairs() {
return this.defaultPointColumnPairs;
}
get layerIcon() {
return IconLayerIcon;
}
get visualChannels() {
return {
color: {
...super.visualChannels.color,
accessor: 'getFillColor',
defaultValue: config => config.color
},
size: {
...super.visualChannels.size,
property: 'radius',
range: 'radiusRange',
channelScaleType: 'radius',
accessor: 'getRadius',
defaultValue: 1
}
};
}
get layerInfoModal() {
return {
id: 'iconInfo',
template: this._layerInfoModal,
modalProps: {
title: 'modal.iconInfo.title'
}
};
}
getSvgIcons() {
const fetchConfig = {
method: 'GET',
mode: 'cors',
cache: 'no-cache'
};
if (window.fetch) {
window
.fetch(SVG_ICON_URL, fetchConfig)
.then(response => response.json())
.then((parsed: {svgIcons?: any[]} = {}) => {
const {svgIcons = []} = parsed;
this.iconGeometry = svgIcons.reduce(
(accu, curr) => ({
...accu,
[curr.id]: flatterIconPositions(curr)
}),
{}
);
this._layerInfoModal = IconInfoModalFactory(svgIcons);
});
}
}
static findDefaultLayerProps({fieldPairs = [], fields = []}: KeplerTable) {
const notFound = {props: []};
if (!fieldPairs.length || !fields.length) {
return notFound;
}
const iconFields = fields.filter(({name}) =>
name
.replace(/[_,.]+/g, ' ')
.trim()
.split(' ')
.some(seg => ICON_FIELDS.icon.some(t => t.includes(seg)))
);
if (!iconFields.length) {
return notFound;
}
// create icon layers for first point pair
const ptPair = fieldPairs[0];
const props = iconFields.map(iconField => ({
label: iconField.name.replace(/[_,.]+/g, ' ').trim(),
columns: {
lat: ptPair.pair.lat,
lng: ptPair.pair.lng,
icon: {
value: iconField.name,
fieldIdx: iconField.fieldIdx
}
},
isVisible: true
}));
return {props};
}
calculateDataAttribute({dataContainer, filteredIndex}: KeplerTable, getPosition) {
const getIcon = this.getIconAccessor(dataContainer);
const data: IconLayerData[] = [];
for (let i = 0; i < filteredIndex.length; i++) {
const index = filteredIndex[i];
const rowIndex = {index};
const pos = getPosition(rowIndex);
const icon = getIcon(rowIndex);
// if doesn't have point lat or lng, do not add the point
// deck.gl can't handle position = null
if (pos.every(Number.isFinite) && typeof icon === 'string') {
data.push({
index,
icon
});
}
}
return data;
}
formatLayerData(datasets, oldLayerData) {
if (this.config.dataId === null) {
return {};
}
const {textLabel} = this.config;
const {gpuFilter, dataContainer} = datasets[this.config.dataId];
const getPosition = this.getPositionAccessor(dataContainer);
const {data, triggerChanged} = this.updateData(datasets, oldLayerData);
// get all distinct characters in the text labels
const textLabels = formatTextLabelData({
textLabel,
triggerChanged,
oldLayerData,
data,
dataContainer
});
const accessors = this.getAttributeAccessors({dataContainer});
return {
data,
getPosition,
getFilterValue: gpuFilter.filterValueAccessor(dataContainer)(),
textLabels,
...accessors
};
}
updateLayerMeta(dataContainer, getPosition) {
const bounds = this.getPointsBounds(dataContainer, getPosition);
this.updateMeta({bounds});
}
renderLayer(opts) {
const {data, gpuFilter, objectHovered, mapState, interactionConfig} = opts;
const radiusScale = this.getRadiusScaleByZoom(mapState);
const layerProps = {
radiusScale,
...(this.config.visConfig.fixedRadius ? {} : {radiusMaxPixels: 500})
};
const updateTriggers = {
getPosition: this.config.columns,
getFilterValue: gpuFilter.filterValueUpdateTriggers,
...this.getVisualChannelUpdateTriggers()
};
const defaultLayerProps = this.getDefaultDeckLayerProps(opts);
const brushingProps = this.getBrushingExtensionProps(interactionConfig);
const getPixelOffset = getTextOffsetByRadius(radiusScale, data.getRadius, mapState);
const extensions = [...defaultLayerProps.extensions, brushingExtension];
// shared Props between layer and label layer
const sharedProps = {
getFilterValue: data.getFilterValue,
extensions,
filterRange: defaultLayerProps.filterRange,
...brushingProps
};
const labelLayers = [
...this.renderTextLabelLayer(
{
getPosition: data.getPosition,
sharedProps,
getPixelOffset,
updateTriggers
},
opts
)
];
const hoveredObject = this.hasHoveredObject(objectHovered);
const parameters = {
// icons will be flat on the map when the altitude column is not used
depthTest: this.config.columns.altitude?.fieldIdx > -1
};
return !this.iconGeometry
? []
: [
new SvgIconLayer({
...defaultLayerProps,
...brushingProps,
...layerProps,
...data,
parameters,
getIconGeometry: id => this.iconGeometry?.[id],
// update triggers
updateTriggers,
extensions
}),
...(hoveredObject
? [
// @ts-expect-error SvgIconLayerProps needs getIcon Field
new SvgIconLayer({
...this.getDefaultHoverLayerProps(),
...layerProps,
data: [hoveredObject],
parameters,
getPosition: data.getPosition,
getRadius: data.getRadius,
getFillColor: this.config.highlightColor,
getIconGeometry: id => this.iconGeometry?.[id]
})
]
: []),
// text label layer
...labelLayers
];
}
} | the_stack |
import {
createContext,
useCallback,
useContext,
useEffect,
useState,
} from 'react'
import { useFirebase } from '../adapters/firebase'
import inpaint, { RefinerType } from '../adapters/inpainting'
import { useUser } from '../adapters/user'
import { useAlert } from '../components/Alert'
import { downloadImage, loadImage, shareImage, useImage } from '../utils'
const BRUSH_COLOR = 'rgba(189, 255, 1, 0.75)'
interface BatchEdit {
lines: Line[]
render?: HTMLImageElement
}
export type Editor = {
useHD: boolean
setUseHD: (useHD: boolean) => void
refiner: RefinerType
setRefiner: (refiner: RefinerType) => void
file?: File
setFile: (file?: File) => void
originalFile?: File
setOriginalFile: (file?: File) => void
image?: HTMLImageElement
originalImage?: HTMLImageElement
maskCanvas: HTMLCanvasElement
edits: BatchEdit[]
addLine: (forceBatch?: boolean) => void
context?: CanvasRenderingContext2D
setContext: (ctx: CanvasRenderingContext2D) => void
render: () => Promise<void>
draw: () => void
undo: (forceBatch?: boolean) => void
download: () => void
}
export interface Line {
size?: number
pts: { x: number; y: number }[]
}
function drawLines(
ctx: CanvasRenderingContext2D,
lines: Line[],
color = BRUSH_COLOR
) {
ctx.strokeStyle = color
ctx.lineCap = 'round'
ctx.lineJoin = 'round'
lines.forEach(line => {
if (!line?.pts.length || !line.size) {
return
}
ctx.lineWidth = line.size
ctx.beginPath()
ctx.moveTo(line.pts[0].x, line.pts[0].y)
line.pts.forEach(pt => ctx.lineTo(pt.x, pt.y))
ctx.stroke()
})
}
const EditorContext = createContext<Editor | undefined>(undefined)
export function EditorProvider(props: any) {
const { children } = props
const [context, setContext] = useState<CanvasRenderingContext2D>()
const [edits, setEdits] = useState<BatchEdit[]>([{ lines: [{ pts: [] }] }])
const [file, setFile] = useState<File>()
const [originalFile, setOriginalFile] = useState<File>()
const image = useImage(file)
const originalImage = useImage(originalFile)
const user = useUser()
const [useHD, setUseHD] = useState(user?.isPro() || false)
const [refiner, setRefiner] = useState<RefinerType>('medium')
const [output] = useState(() => {
return document.createElement('canvas')
})
const [patch] = useState(() => {
return document.createElement('canvas')
})
const [maskCanvas] = useState<HTMLCanvasElement>(() => {
return document.createElement('canvas')
})
const alert = useAlert()
const firebase = useFirebase()
// Refresh HD & pro layoutclass when the user changes
useEffect(() => {
if (user?.isPro()) {
setUseHD(true)
document.body.classList.add('pro')
} else {
setUseHD(false)
document.body.classList.remove('pro')
}
}, [user])
// Reset edits when HD changes
useEffect(() => {
setEdits([{ lines: [{ pts: [] }] }])
}, [useHD])
// Reset when the file changes
useEffect(() => {
if (!file) {
setOriginalFile(undefined)
setEdits([{ lines: [{ pts: [] }] }])
setContext(undefined)
}
}, [file])
const undo = useCallback(
(forceBatch = false) => {
const currentEdit = edits[edits.length - 1]
if (!currentEdit) {
throw new Error('no edit to undo')
}
if (!useHD && !forceBatch) {
edits.pop()
edits[edits.length - 1].lines = [{ pts: [] }]
setEdits([...edits])
}
// If the current batch has more than one line, we just remove the last line
else if (currentEdit.lines.length > 1 || !useHD) {
currentEdit.lines.pop()
currentEdit.lines[currentEdit.lines.length - 1] = { pts: [] }
setEdits([...edits])
}
// Otherwise if the current batch has only one line and there are more than
// 1 batch, we remove the entire batch
else if (edits.length > 1) {
edits.pop()
setEdits([...edits])
} else {
// eslint-disable-next-line no-console
console.log('nothing to undo')
}
},
[edits, useHD]
)
const draw = useCallback(() => {
if (!context || !image) {
return
}
context.clearRect(0, 0, context.canvas.width, context.canvas.height)
const currentEdit = edits[edits.length - 1]
if (currentEdit.render?.src) {
context.drawImage(currentEdit.render, 0, 0)
} else {
context.drawImage(image, 0, 0)
}
drawLines(context, edits[edits.length - 1].lines)
}, [context, image, edits])
// Draw when edits change
useEffect(() => {
draw()
}, [edits, draw])
const getLastRender = useCallback(() => {
for (let i = edits.length - 1; i >= 0; i -= 1) {
if (edits[i].render) {
return edits[i].render
}
}
}, [edits])
const refreshCanvasMask = useCallback(() => {
if (!context?.canvas.width || !context?.canvas.height) {
throw new Error('canvas has invalid size')
}
maskCanvas.width = context?.canvas.width
maskCanvas.height = context?.canvas.height
const ctx = maskCanvas.getContext('2d')
if (!ctx) {
throw new Error('could not retrieve mask canvas')
}
// Combine the lines of all the edits into one array using reduce
const lines = edits.reduce(
(acc, edit) => [...acc, ...edit.lines],
[] as Line[]
)
drawLines(ctx, lines, 'white')
}, [context?.canvas.height, context?.canvas.width, edits, maskCanvas])
const renderOutput = useCallback(() => {
if (!file || !originalImage || !context?.canvas) {
// eslint-disable-next-line
console.error(file, originalImage, context?.canvas)
return
}
// Make sure that the canvas doesn't have lines drawn on it.
const lastRender = getLastRender()
if (!lastRender) {
throw new Error('no last render')
}
context.drawImage(lastRender, 0, 0)
patch.width = originalImage.width
patch.height = originalImage.height
const patchCtx = patch.getContext('2d')
if (!patchCtx) {
throw new Error('Could not get patch context')
}
// Clear the canvas
patchCtx.globalCompositeOperation = 'source-over'
patchCtx.clearRect(0, 0, patch.width, patch.height)
// Draw the inpainted image masked by the mask
patchCtx?.drawImage(
maskCanvas,
0,
0,
originalImage.width,
originalImage.height
)
patchCtx.globalCompositeOperation = 'source-in'
patchCtx?.drawImage(
context?.canvas,
0,
0,
originalImage.width,
originalImage.height
)
// Draw the final output
output.width = originalImage.width
output.height = originalImage.height
const outputCtx = output.getContext('2d')
if (!patchCtx) {
throw new Error('Could not get output context')
}
outputCtx?.drawImage(originalImage, 0, 0)
outputCtx?.drawImage(patch, 0, 0)
return outputCtx?.canvas.toDataURL(file.type)
}, [context, file, maskCanvas, originalImage, output, patch, getLastRender])
const download = useCallback(() => {
if (!file || !context) {
// eslint-disable-next-line
console.error('no file or context')
return
}
const base64 = useHD ? renderOutput() : context.canvas.toDataURL(file.type)
if (!base64) {
throw new Error('could not get canvas data')
}
const name = file.name.replace(/(\.[\w\d_-]+)$/i, '_cleanup$1')
if (shareImage(base64, name)) {
firebase?.logEvent('download', { mode: 'share' })
} else {
downloadImage(base64, name)
firebase?.logEvent('download', { mode: 'download' })
}
}, [context, file, firebase, renderOutput, useHD])
const render = useCallback(async () => {
refreshCanvasMask()
try {
if (!firebase) {
throw new Error('Firebase is not initialized')
}
if (!file) {
throw new Error('No file')
}
if (!image) {
throw new Error('No image')
}
const start = Date.now()
firebase?.logEvent('inpaint_start')
const appCheckToken = await firebase.getAppCheckToken()
const authToken = await firebase.getAuthToken()
const res = await inpaint(
file,
maskCanvas.toDataURL(),
useHD,
refiner,
appCheckToken,
authToken
)
if (!res) {
throw new Error('empty response')
}
// TODO: fix the render if it failed loading
const newRender = new Image()
await loadImage(newRender, res)
// Add the new render & new line.
setEdits([...edits, { lines: [{ pts: [] }], render: newRender }])
firebase?.logEvent('inpaint_processed', {
duration: Date.now() - start,
width: image.naturalWidth,
height: image.naturalHeight,
})
} catch (error: any) {
firebase?.logEvent('inpaint_failed', {
error,
})
// Add a new line. It prevents from adding a long straight line when
// the user draws again.
const currentEdit = edits[edits.length - 1]
currentEdit.lines.push({ pts: [] })
setEdits([...edits])
alert(error.message ? error.message : error.toString())
}
}, [
file,
firebase,
image,
maskCanvas,
edits,
refreshCanvasMask,
alert,
useHD,
refiner,
])
const addLine = useCallback(
(forceBatch = false) => {
// In SD we create a new batch for each line
if (!useHD && !forceBatch) {
const newEdit = { lines: [{ pts: [] }] }
setEdits([...edits, newEdit])
}
// In HD we add the line to the current batch
else {
const currentEdit = edits[edits.length - 1]
currentEdit.lines.push({ pts: [] } as Line)
setEdits([...edits])
}
},
[edits, useHD]
)
const editor: Editor = {
useHD,
setUseHD,
refiner,
setRefiner,
file,
setFile,
originalFile,
setOriginalFile,
image,
edits,
addLine,
maskCanvas,
context,
setContext,
render,
draw,
undo,
download,
}
return (
<EditorContext.Provider value={editor}>{children}</EditorContext.Provider>
)
}
export function useEditor() {
const ctx = useContext(EditorContext)
if (!ctx) {
throw new Error('No EditorUI context (missing EditorUIProvider?)')
}
return ctx
} | the_stack |
import { timeout } from '@celo/base'
import { Block } from '@celo/connect'
import { ContractKit, newKit } from '@celo/contractkit'
import { ClaimTypes, IdentityMetadataWrapper } from '@celo/contractkit/lib/identity'
import { FileKeystore, KeystoreWalletWrapper } from '@celo/keystores'
import { eqAddress } from '@celo/utils/lib/address'
import Logger from 'bunyan'
import moment from 'moment'
import { FindOptions, Op, Sequelize, Transaction } from 'sequelize'
import {
fetchEnv,
fetchEnvOrDefault,
getAccountAddress,
getAttestationSignerAddress,
getCeloProviders,
isYes,
} from './env'
import { rootLogger } from './logger'
import { Gauges } from './metrics'
import Attestation, {
AttestationKey,
AttestationModel,
AttestationStatic,
} from './models/attestation'
import { ErrorMessages } from './request'
export let sequelize: Sequelize | undefined
let dbRecordExpiryMins: number | null
const maxAgeLatestBlock: number = parseInt(fetchEnvOrDefault('MAX_AGE_LATEST_BLOCK_SECS', '20'), 10)
const getBlockTimeout = parseInt(fetchEnvOrDefault('GET_BLOCK_TIMEOUT_MS', '500'), 10)
// Process these once instead of at each reinitialization of the kits
const celoProviders = getCeloProviders()
const smartFallback = !isYes(fetchEnvOrDefault('DISABLE_SMART_FALLBACK', 'false'))
const keystoreDirpath = fetchEnvOrDefault('ATTESTATION_SIGNER_KEYSTORE_DIRPATH', '')
const keystorePassphrase = fetchEnvOrDefault('ATTESTATION_SIGNER_KEYSTORE_PASSPHRASE', '')
const signerAddress = fetchEnv('ATTESTATION_SIGNER_ADDRESS')
export type SequelizeLogger = boolean | ((sql: string, timing?: number) => void)
export function makeSequelizeLogger(logger: Logger): SequelizeLogger {
return (msg: string, sequelizeLogArgs: any) =>
logger.debug({ sequelizeLogArgs, component: 'sequelize' }, msg)
}
export async function initializeDB() {
if (sequelize === undefined) {
sequelize = new Sequelize(fetchEnv('DATABASE_URL'), {
logging: makeSequelizeLogger(rootLogger),
})
rootLogger.info('Initializing Database')
await sequelize.authenticate()
// Check four times every `dbRecordExpiryMins` period to delete records older than dbRecordExpiryMins
dbRecordExpiryMins = parseInt(fetchEnvOrDefault('DB_RECORD_EXPIRY_MINS', '60'), 10)
const dbRecordExpiryCheckEveryMs = dbRecordExpiryMins * 15 * 1000
setInterval(purgeExpiredRecords, dbRecordExpiryCheckEveryMs)
}
}
export function isDBOnline() {
if (sequelize === undefined) {
return initializeDB()
} else {
return sequelize.authenticate() as Promise<void>
}
}
const kits = new Array<ContractKit | undefined>(celoProviders.length).fill(undefined)
/**
* Decorator to wrap execution of f
* with an optional prioritization of kit1 and kit2
* and retry logic if execution with the first kit fails
* @param f function to execute
* @param kit1 primary kit instance
* @param kit2 optional secondary kit instance
* @returns f(kit)
*/
async function execWithFallback<T>(
f: (kit: ContractKit) => T,
kit1: ContractKit,
kit2?: ContractKit | undefined
): Promise<T> {
let primaryKit = kit1
let secondaryKit = kit2
// Check if backup kit is ahead of primary kit; change prioritization as such
if (
smartFallback &&
kit2 &&
// Prioritize block age over syncing/not; avoids complex checks for stalls
// and assumes that if one is stalled, the next block number check will correct this.
(!kit1 ||
(await getAgeOfLatestBlockFromKit(kit2)).number >
(await getAgeOfLatestBlockFromKit(kit1)).number)
) {
rootLogger.info('Prioritizing a backup provider')
primaryKit = kit2
secondaryKit = kit1
}
try {
return await f(primaryKit)
} catch (error) {
rootLogger.warn(`Using ContractKit failed: ${error}`)
if (secondaryKit) {
rootLogger.info(`Attempting to use secondary ContractKit`)
return f(secondaryKit!)
} else {
throw error
}
}
}
export async function useKit<T>(f: (kit: ContractKit) => T): Promise<T> {
let usableKits = kits.filter((k) => k !== undefined)
const reinitAndRetry = async () => {
await initializeKits(true)
usableKits = kits.filter((k) => k !== undefined)
return execWithFallback(f, usableKits[0]!, usableKits[1])
}
if (!usableKits.length) {
// This throws an error if no kits are initialized
return reinitAndRetry()
} else {
try {
return await execWithFallback(f, usableKits[0]!, usableKits[1])
} catch (error) {
return reinitAndRetry()
}
}
}
async function isNodeSyncingFromKit(k: ContractKit) {
const syncProgress = await k.isSyncing()
return typeof syncProgress === 'boolean' && syncProgress
}
export async function isNodeSyncing() {
return useKit(isNodeSyncingFromKit)
}
export async function getAgeOfLatestBlockFromKit(k: ContractKit) {
try {
return await timeout(
async () => {
let latestBlock: Block
try {
// Differentiate between errors with getBlock and timeouts
latestBlock = await k!.connection.getBlock('latest')
} catch (error: any) {
throw new Error(`Error fetching latest block: ${error.message}`)
}
const ageOfLatestBlock = Date.now() / 1000 - Number(latestBlock.timestamp)
return {
ageOfLatestBlock,
number: latestBlock.number,
}
},
[],
getBlockTimeout,
new Error(`Timeout fetching block after ${getBlockTimeout} ms`)
)
} catch (error: any) {
rootLogger.warn(error.message)
// On failure return values that should always be comparatively out-of-date
return {
ageOfLatestBlock: maxAgeLatestBlock + 1,
number: -1,
}
}
}
export async function getAgeOfLatestBlock() {
return useKit(getAgeOfLatestBlockFromKit)
}
export async function isAttestationSignerUnlocked() {
// The only way to see if a key is unlocked is to try to sign something
try {
await useKit((k) => k.connection.sign('DO_NOT_USE', getAttestationSignerAddress()))
return true
} catch {
return false
}
}
// Verify a signer and validator address are provided, are valid, match the on-chain signer,
// that signer account is unlocked, that metadata is accessible and valid and that the
// attestationServiceURL claim is present in the metadata (external name/port may be
// different to instance, so we cannot validate its details)
export async function verifyConfigurationAndGetURL() {
const signer = getAttestationSignerAddress()
const validator = getAccountAddress()
const accounts = await useKit((k) => k.contracts.getAccounts())
if (!(await accounts.isAccount(validator))) {
throw Error(`${validator} is not registered as an account!`)
}
if (!(await accounts.hasAuthorizedAttestationSigner(validator))) {
throw Error(`No attestation signer authorized for ${validator}!`)
}
const signerOnChain = await accounts.getAttestationSigner(validator)
if (!eqAddress(signerOnChain, signer)) {
throw Error(
`Different attestation signer in config ${signer} than on-chain ${signerOnChain} for ${validator}!`
)
}
if (!(await isAttestationSignerUnlocked())) {
throw Error(`Need to unlock attestation signer account ${signer}`)
}
const metadataURL = await accounts.getMetadataURL(validator)
try {
const metadata = await useKit((k) => IdentityMetadataWrapper.fetchFromURL(k, metadataURL))
const claim = metadata.findClaim(ClaimTypes.ATTESTATION_SERVICE_URL)
if (!claim) {
throw Error('Missing ATTESTATION_SERVICE_URL claim')
}
return claim.url
} catch (error) {
throw Error(`Could not verify metadata at ${metadataURL}: ${error}`)
}
}
/**
* Function to initialize each kit in the global array of Contract Kit(s)
* @param force if true, reinitialize kit(s) whether or not they already exist
*/
export async function initializeKits(force: boolean = false) {
rootLogger.info('Initializing Contract Kit(s)')
let keystoreWalletWrapper: KeystoreWalletWrapper | undefined
// Prefer to use keystore if these variables are set
if (keystoreDirpath && keystorePassphrase) {
keystoreWalletWrapper = new KeystoreWalletWrapper(new FileKeystore(keystoreDirpath))
try {
await keystoreWalletWrapper.unlockAccount(signerAddress, keystorePassphrase)
} catch (error: any) {
throw new Error(
`Unlocking keystore file for account ${signerAddress} failed: ` + error.message
)
}
}
const failedConnections = await Promise.all(
kits.map(async (kit, i) => {
// Return whether kit_i fails to connect to the given provider
if (kit === undefined || force) {
try {
kits[i] = keystoreWalletWrapper
? newKit(celoProviders[i], keystoreWalletWrapper.getLocalWallet())
: newKit(celoProviders[i])
// Copied from @celo/cli/src/utils/helpers
await kits[i]!.connection.getBlock('latest')
rootLogger.info(`Connected to Celo node at ${celoProviders[i]}`)
return false
} catch (error) {
kits[i] = undefined
rootLogger.warn(`Failed to connect to Celo node at ${celoProviders[i]}`)
return true
}
}
})
)
// No kits successfully reinitialized nor existing kits that work
if (failedConnections && failedConnections.filter(Boolean).length === kits.length) {
throw new Error(`Initializing ContractKit failed for all providers: ${celoProviders}.`)
}
}
export async function startPeriodicHealthCheck() {
await tryHealthCheck()
setInterval(tryHealthCheck, 60 * 1000)
}
export async function startPeriodicKitsCheck() {
// Cover the edge case where one kit is set to undefined,
// causing prioritization logic to always default to the other kits
// without reinitializing this kit.
const checkUndefinedKits = async () => {
if (kits.filter((k) => k !== undefined).length < kits.length) {
// Only attempt to reinitialize undefined kits
try {
await initializeKits(false)
} catch (error: any) {
rootLogger.error(`Periodic kits check failed: ${error.message}`)
}
}
}
setInterval(checkUndefinedKits, 60 * 1000)
}
let AttestationTable: AttestationStatic
async function getAttestationTable() {
if (AttestationTable) {
return AttestationTable
}
AttestationTable = await Attestation(sequelize!)
return AttestationTable
}
export async function findAttestationByKey(
key: AttestationKey,
options: FindOptions = {}
): Promise<AttestationModel | null> {
return (await getAttestationTable()).findOne({
where: { ...key },
...options,
})
}
export async function findAttestationByDeliveryId(
ongoingDeliveryId: string,
options: FindOptions = {}
): Promise<AttestationModel | null> {
return (await getAttestationTable()).findOne({
where: { ongoingDeliveryId },
// Ensure deterministic result, since deliveryId uniqueness is not enforced
order: [['createdAt', 'DESC']],
...options,
})
}
export async function findOrCreateAttestation(
key: AttestationKey,
defaults: object | undefined,
transaction: Transaction
): Promise<AttestationModel> {
const attestationTable = await getAttestationTable()
await attestationTable.findOrCreate({
where: {
...key,
},
defaults,
transaction,
})
// Query to lock the record
const attestationRecord = await findAttestationByKey(
{
...key,
},
{ transaction, lock: Transaction.LOCK.UPDATE }
)
if (!attestationRecord) {
// This should never happen
throw new Error(`Somehow we did not get an attestation record`)
}
return attestationRecord
}
async function purgeExpiredRecords() {
try {
const sequelizeLogger = makeSequelizeLogger(rootLogger)
const transaction = await sequelize!.transaction({ logging: sequelizeLogger })
try {
const table = await getAttestationTable()
const rowsDeleted = await table.destroy({
where: {
createdAt: {
[Op.lte]: moment().subtract(dbRecordExpiryMins!, 'minutes').toDate(),
},
},
transaction,
})
await transaction.commit()
if (rowsDeleted) {
rootLogger.info({ rowsDeleted }, 'Purged expired records')
}
} catch (err) {
rootLogger.error({ err }, 'Cannot purge expired records')
await transaction.rollback()
}
} catch (err) {
rootLogger.error({ err }, 'Cannot purge expired records')
}
}
// Do the health check to update the gauge
async function tryHealthCheck() {
try {
const failureReason = await doHealthCheck()
if (failureReason) {
rootLogger.warn(`Health check failed: ${failureReason}`)
}
} catch {
rootLogger.warn(`Health check failed`)
}
}
// Check health and return failure reason, null on success.
export async function doHealthCheck(): Promise<string | null> {
try {
if (!(await isAttestationSignerUnlocked())) {
Gauges.healthy.set(0)
return ErrorMessages.ATTESTATION_SIGNER_CANNOT_SIGN
}
if (await isNodeSyncing()) {
Gauges.healthy.set(0)
return ErrorMessages.NODE_IS_SYNCING
}
const { ageOfLatestBlock } = await getAgeOfLatestBlock()
if (ageOfLatestBlock > maxAgeLatestBlock) {
Gauges.healthy.set(0)
return ErrorMessages.NODE_IS_STUCK
}
try {
await isDBOnline()
} catch (error) {
Gauges.healthy.set(0)
return ErrorMessages.DATABASE_IS_OFFLINE
}
Gauges.healthy.set(1)
return null
} catch (error) {
Gauges.healthy.set(0)
return ErrorMessages.UNKNOWN_ERROR
}
} | the_stack |
import * as Bytes from './bytes';
import {EciesHkdfKemRecipient, fromJsonWebKey as recipientFromJsonWebKey} from './ecies_hkdf_kem_recipient';
import {fromJsonWebKey as senderFromJsonWebKey} from './ecies_hkdf_kem_sender';
import * as EllipticCurves from './elliptic_curves';
import * as Random from './random';
describe('ecies hkdf kem recipient test', function() {
beforeEach(function() {
// Use a generous promise timeout for running continuously.
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 1000; // 1000s
});
afterEach(function() {
// Reset the promise timeout to default value.
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000; // 1s
});
it('encap decap', async function() {
const keyPair = await EllipticCurves.generateKeyPair('ECDH', 'P-256');
const publicKey = await EllipticCurves.exportCryptoKey(keyPair.publicKey);
const privateKey = await EllipticCurves.exportCryptoKey(keyPair.privateKey);
const sender = await senderFromJsonWebKey(publicKey);
const recipient = await recipientFromJsonWebKey(privateKey);
for (let i = 1; i < 20; i++) {
const keySizeInBytes = i;
const pointFormat = EllipticCurves.PointFormatType.UNCOMPRESSED;
const hkdfHash = 'SHA-256';
const hkdfInfo = Random.randBytes(i);
const hkdfSalt = Random.randBytes(i);
const kemKeyToken = await sender.encapsulate(
keySizeInBytes, pointFormat, hkdfHash, hkdfInfo, hkdfSalt);
const key = await recipient.decapsulate(
kemKeyToken['token'], keySizeInBytes, pointFormat, hkdfHash, hkdfInfo,
hkdfSalt);
expect(kemKeyToken['key'].length).toBe(keySizeInBytes);
expect(Bytes.toHex(kemKeyToken['key'])).toBe(Bytes.toHex(key));
}
});
it('decap, non integer key size', async function() {
const keyPair = await EllipticCurves.generateKeyPair('ECDH', 'P-256');
const publicKey = await EllipticCurves.exportCryptoKey(keyPair.publicKey);
const privateKey = await EllipticCurves.exportCryptoKey(keyPair.privateKey);
const sender = await senderFromJsonWebKey(publicKey);
const recipient = await recipientFromJsonWebKey(privateKey);
const keySizeInBytes = 16;
const pointFormat = EllipticCurves.PointFormatType.UNCOMPRESSED;
const hkdfHash = 'SHA-256';
const hkdfInfo = Random.randBytes(16);
const hkdfSalt = Random.randBytes(16);
const kemKeyToken = await sender.encapsulate(
keySizeInBytes, pointFormat, hkdfHash, hkdfInfo, hkdfSalt);
try {
await recipient.decapsulate(
kemKeyToken['token'], NaN, pointFormat, hkdfHash, hkdfInfo, hkdfSalt);
fail('An exception should be thrown.');
} catch (e) {
expect(e.toString())
.toBe('InvalidArgumentsException: size must be an integer');
}
try {
await recipient.decapsulate(
kemKeyToken['token'], 1.8, pointFormat, hkdfHash, hkdfInfo, hkdfSalt);
fail('An exception should be thrown.');
} catch (e) {
expect(e.toString())
.toBe('InvalidArgumentsException: size must be an integer');
}
});
it('new instance, invalid parameters', async function() {
// Test newInstance with public key instead private key.
const keyPair = await EllipticCurves.generateKeyPair('ECDH', 'P-256');
const publicKey = await EllipticCurves.exportCryptoKey(keyPair.publicKey);
try {
await recipientFromJsonWebKey(publicKey);
fail('An exception should be thrown.');
} catch (e) {
}
});
it('new instance, invalid private key', async function() {
for (const testVector of TEST_VECTORS) {
const ellipticCurveString = EllipticCurves.curveToString(testVector.crv);
const privateJwk = EllipticCurves.pointDecode(
ellipticCurveString, testVector.pointFormat,
Bytes.fromHex(testVector.privateKeyPoint));
privateJwk['d'] = Bytes.toBase64(
Bytes.fromHex(testVector.privateKeyValue), /* opt_webSafe = */ true);
// Change the x value such that the key si no more valid. Recipient should
// either throw an exception or ignore the x value and compute the same
// output value.
const xLength = EllipticCurves.fieldSizeInBytes(testVector.crv);
privateJwk['x'] =
Bytes.toBase64(new Uint8Array(xLength), /* opt_webSafe = */ true);
let output;
try {
const recipient = await recipientFromJsonWebKey(privateJwk);
const hkdfInfo = Bytes.fromHex(testVector.hkdfInfo);
const salt = Bytes.fromHex(testVector.salt);
output = await recipient.decapsulate(
Bytes.fromHex(testVector.token), testVector.outputLength,
testVector.pointFormat, testVector.hashType, hkdfInfo, salt);
} catch (e) {
// Everything works properly if exception was thrown.
return;
}
// If there was no exception, the output should be still correct (x value
// should be ignored during the computation).
expect(Bytes.toHex(output)).toBe(testVector.expectedOutput);
}
});
it('constructor, invalid parameters', async function() {
// Test public key instead of private key.
const keyPair = await EllipticCurves.generateKeyPair('ECDH', 'P-256');
try {
new EciesHkdfKemRecipient(keyPair.publicKey);
fail('An exception should be thrown.');
} catch (e) {
expect(e.toString())
.toBe('SecurityException: Expected crypto key of type: private.');
}
});
it('encap decap, different params', async function() {
const curveTypes = [
EllipticCurves.CurveType.P256, EllipticCurves.CurveType.P384,
EllipticCurves.CurveType.P521
];
const hashTypes = ['SHA-1', 'SHA-256', 'SHA-512'];
for (const curve of curveTypes) {
const curveString = EllipticCurves.curveToString(curve);
for (const hashType of hashTypes) {
const keyPair =
await EllipticCurves.generateKeyPair('ECDH', curveString);
const keySizeInBytes = 32;
const pointFormat = EllipticCurves.PointFormatType.UNCOMPRESSED;
const hkdfInfo = Random.randBytes(8);
const hkdfSalt = Random.randBytes(16);
const publicKey =
await EllipticCurves.exportCryptoKey(keyPair.publicKey);
const sender = await senderFromJsonWebKey(publicKey);
const kemKeyToken = await sender.encapsulate(
keySizeInBytes, pointFormat, hashType, hkdfInfo, hkdfSalt);
const privateKey =
await EllipticCurves.exportCryptoKey(keyPair.privateKey);
const recipient = await recipientFromJsonWebKey(privateKey);
const key = await recipient.decapsulate(
kemKeyToken['token'], keySizeInBytes, pointFormat, hashType,
hkdfInfo, hkdfSalt);
expect(kemKeyToken['key'].length).toBe(keySizeInBytes);
expect(Bytes.toHex(kemKeyToken['key'])).toBe(Bytes.toHex(key));
}
}
});
it('encap decap, modified token', async function() {
const curveTypes = [
EllipticCurves.CurveType.P256, EllipticCurves.CurveType.P384,
EllipticCurves.CurveType.P521
];
const hashTypes = ['SHA-1', 'SHA-256', 'SHA-512'];
for (let curve of curveTypes) {
const curveString = EllipticCurves.curveToString(curve);
for (let hashType of hashTypes) {
const keyPair =
await EllipticCurves.generateKeyPair('ECDH', curveString);
const privateKey =
await EllipticCurves.exportCryptoKey(keyPair.privateKey);
const recipient = await recipientFromJsonWebKey(privateKey);
const keySizeInBytes = 32;
const pointFormat = EllipticCurves.PointFormatType.UNCOMPRESSED;
const hkdfInfo = Random.randBytes(8);
const hkdfSalt = Random.randBytes(16);
// Create invalid token (EC point), while preserving the 0x04 prefix
// byte.
const token = Random.randBytes(
EllipticCurves.encodingSizeInBytes(curve, pointFormat));
token[0] = 0x04;
try {
await recipient.decapsulate(
token, keySizeInBytes, pointFormat, hashType, hkdfInfo, hkdfSalt);
fail('Should throw an exception');
} catch (e) {
}
}
}
});
it('decapsulate, test vectors generated by java', async function() {
for (const testVector of TEST_VECTORS) {
const ellipticCurveString = EllipticCurves.curveToString(testVector.crv);
const privateJwk = EllipticCurves.pointDecode(
ellipticCurveString, testVector.pointFormat,
Bytes.fromHex(testVector.privateKeyPoint));
privateJwk['d'] = Bytes.toBase64(
Bytes.fromHex(testVector.privateKeyValue), /* opt_webSafe = */ true);
const recipient = await recipientFromJsonWebKey(privateJwk);
const hkdfInfo = Bytes.fromHex(testVector.hkdfInfo);
const salt = Bytes.fromHex(testVector.salt);
const output = await recipient.decapsulate(
Bytes.fromHex(testVector.token), testVector.outputLength,
testVector.pointFormat, testVector.hashType, hkdfInfo, salt);
expect(Bytes.toHex(output)).toBe(testVector.expectedOutput);
}
});
});
class TestVector {
constructor(
readonly crv: EllipticCurves.CurveType, readonly hashType: string,
readonly pointFormat: EllipticCurves.PointFormatType,
readonly token: string, readonly privateKeyPoint: string,
readonly privateKeyValue: string, readonly salt: string,
readonly hkdfInfo: string, readonly outputLength: number,
readonly expectedOutput: string) {}
}
// Test vectors generated by Java version of Tink.
//
// Token (i.e. sender public key) and privateKeyPoint values are in UNCOMPRESSED
// EcPoint encoding (i.e. it has prefix '04' followed by x and y values).
const TEST_VECTORS: TestVector[] = [
new TestVector(
EllipticCurves.CurveType.P256, 'SHA-256',
EllipticCurves.PointFormatType.UNCOMPRESSED,
/* token = */ '04' +
'5cdd8e426d11970a610f0e5f9b27f247a421c477b379f2ff3fd3bac50dfff9ff' +
'7cada79ab1de9ce4aeaff45fcd2628d1b6d7ecac99d4c26409d4ab8a362c8e7a',
/* privateKeyPoint = */ '04' +
'4adf0fff84b995bb97af250128a3d779c86ba3cd7e5c0fa2c10895d0b995aaee' +
'cdced57616ebb04c808f191c2bf3848c495dcfddcdd1bb73d8ea7a15c642af05',
/* privateKeyValue = */
'da73e10f7d81483daa63438b982c879706bcf8fef8c7c4d3071c3ef2367714f3',
/* salt = */ 'abcdef',
/* hkdfInfo = */ 'aaaaaaaaaaaaaaaa',
/* outputLength = */ 32,
/* expectedOutput = */
'aeeee35a14967310798f037e2f126e2e326369115eb9e2d1a34d9c6761f60511'),
new TestVector(
EllipticCurves.CurveType.P384, 'SHA-1',
EllipticCurves.PointFormatType.UNCOMPRESSED,
/* token = */ '04' +
'75bc8a2e6cf80ce2e0a1cd60ab3d68e4d357b58ff69f0de14b7ec13c58a79750496e07db3f933167148d80730b96f000' +
'9389967de410535ca3e103e7ce73dae9525f934589a6cd1fca37e61411985788dcedc71b35ef63b7365e391f6e2a945f',
/* privateKeyPoint = */ '04' +
'5f81886c4202897355b1da79348d53abd9e9119a7de6f5f10dfe751f7ca9c807035c029bac59499337c4af185fe61728' +
'f132bfb234365a9c61e1e56c11acca3bee6621961c7c38eb9dcbd39b332fd35006876dccdb206a7b2d43cf70589c3356',
/* privateKeyValue = */
'544b5f32731d6277fa71e756f0b2d6840f62e6b744a8b8cdf91f8cf29e6d8562f6237369721f756ab044711e0d42c53c',
/* salt = */ 'ababcdcd',
/* hkdfInfo = */ '100000000000000001',
/* outputLength = */ 32,
/* expectedOutput = */
'7a25c525eabaa0d994c27f7661a208b5ea25c2a778198237de6e4f235cd64a33'),
new TestVector(
EllipticCurves.CurveType.P521, 'SHA-512',
EllipticCurves.PointFormatType.UNCOMPRESSED,
/* token = */ '04' +
'0075192f8decddf7a0371b2c859aad738cc5424fa70e74b560070ed8309ae8a6064b06f9aaad8020ac8620e62a6c1196efa44180d325a36a54945743b9382bd49bc1' +
'000dfa1e30b228e975998b7afeaaf30235ec505960e58bf3269b69fffcbce9f15fc1441fab2ed97f554ae4bde8b956efb2372c5b330cb1aa0ab81b99e792acd7f5a8',
/* privateKeyPoint = */ '04' +
'00e57037a96bcbca532ef2f75646d825304ea716bbc9c4bf953455074347158f4818122c76e26a4cf94b39f451b7f5960b9cda43d49999ddc401c1be7f082052b387' +
'0147197ba83ec55c8b02e6cbe7b49ce6d6c238edb89561bde6b4574a585c684379d8040888117866823258216344a7268dc696c3a2d192824a1e693609b44661fc2c',
/* privateKeyValue = */
'001e5410117d22e95c5768b82a786dd66fa8c326b938a3a81fdd6113499437ae9f74e9f876adf085c187c6a147abc13460b8ed3050a6b228005426b61f2b616a79c6',
/* salt = */ '00001111',
/* hkdfInfo = */ '1234123412341234',
/* outputLength = */ 32,
/* expectedOutput = */
'3f7f64c7aba2cb012c9b5a952385290604b3b5843ec6e6714647a9c9d6ac87be')
]; | the_stack |
import { dirname, basename } from 'path'
import {
ComputerLanguage,
Person,
SoftwarePackage,
SoftwareSourceCode,
} from '@stencila/schema'
import OperatingSystem from '@stencila/schema/dist/OperatingSystem'
import Parser from './Parser'
import pythonSystemModules from './PythonBuiltins'
const REQUIREMENTS_COMMENT_REGEX = /^\s*#/
const REQUIREMENTS_EDITABLE_SOURCE_REGEX = /^\s*-e\s*([^\s]+)\s*/
const REQUIREMENTS_INCLUDE_PATH_REGEX = /^\s*-r\s+([^\s]+)\s*/
const REQUIREMENTS_STANDARD_REGEX = /^\s*([^\s]+)/
const REQUIREMENTS_FILE_NAME = 'requirements.txt'
/**
* Return true if the passed in line is a requirements.txt comment (starts with "#" which might be preceded by spaces).
*/
function lineIsComment(line: string): boolean {
return REQUIREMENTS_COMMENT_REGEX.exec(line) !== null
}
/**
* Execute the given `regex` against the line and return the first match. If there is no match, return `null`.
*/
function applyRegex(line: string, regex: RegExp): string | null {
const result = regex.exec(line)
if (result === null) {
return null
}
return result[1]
}
/**
* Execute the `REQUIREMENTS_EDITABLE_SOURCE_REGEX` against a line and return the first result (or null if no match).
* This is used to find a requirements.txt line of a URL source (e.g. including a package from github).
*/
function extractEditableSource(line: string): string | null {
return applyRegex(line, REQUIREMENTS_EDITABLE_SOURCE_REGEX)
}
/**
* Execute the `REQUIREMENTS_INCLUDE_PATH_REGEX` against a line and return the first result (or null if no match).
* This is used to find a requirements.txt line that includes another requirements file.
*/
function extractIncludedRequirementsPath(line: string): string | null {
return applyRegex(line, REQUIREMENTS_INCLUDE_PATH_REGEX)
}
/**
* Execute the `REQUIREMENTS_STANDARD_REGEX` against a line and return the first result (or null if no match).
* This is used to find "standard" requirements.txt lines.
*/
function extractStandardRequirements(line: string): string | null {
return applyRegex(line, REQUIREMENTS_STANDARD_REGEX)
}
/**
* Split a requirement line into name and then version. For example "package==1.0.1" => ["package", "==1.0.1"]
* The version specifier can be `==`, `<=`, `>=`, `~=`, `<` or `>`.
*/
function splitStandardRequirementVersion(
requirement: string
): [string, string | null] {
let firstSplitterIndex = -1
for (const splitter of ['==', '<=', '>=', '~=', '<', '>']) {
const splitterIndex = requirement.indexOf(splitter)
if (
splitterIndex > -1 &&
(firstSplitterIndex === -1 || splitterIndex < firstSplitterIndex)
) {
firstSplitterIndex = splitterIndex
}
}
if (firstSplitterIndex !== -1) {
return [
requirement.substring(0, firstSplitterIndex),
requirement.substring(firstSplitterIndex),
]
}
return [requirement, null]
}
/**
* Convert a list of classifiers to a Map between main classification and sub classification(s).
* e.g: ['A :: B', 'A :: C', 'D :: E'] => {'A': ['B', 'C'], 'D': ['E']}
*/
function buildClassifierMap(
classifiers: Array<string>
): Map<string, Array<string>> {
const classifierMap = new Map<string, Array<string>>()
for (const classifier of classifiers) {
const doubleColonPosition = classifier.indexOf('::')
const classifierKey = classifier.substring(0, doubleColonPosition).trim()
const classifierValue = classifier.substring(doubleColonPosition + 2).trim()
if (!classifierMap.has(classifierKey)) {
classifierMap.set(classifierKey, [])
}
classifierMap.get(classifierKey)!.push(classifierValue)
}
return classifierMap
}
/**
* Each PyPI "Topic" might contain multiple levels of categorisation separated by "::". E.g.
* "Topic :: Category :: Secondary Category :: Tertiary Category". This will split into an array of strings of the same
* length as the number of categories, i.e. ["Category", "Secondary Category", "Tertiary Category"]
*/
function splitTopic(topics: string): Array<string> {
return topics.split('::').map((topic) => topic.trim())
}
/**
* Parse an array of PyPI formatted topics into unique lists, returns a tuple of top level and optionally second level
* topics. This is because PyPI will repeat top level Topics in sub topics, e.g. the list might contain:
* ["Topic :: Game", "Topic :: Game :: Arcade"] hence "Game" is defined twice.
*/
function parseTopics(
topicsList: Array<string>
): [Array<string>, Array<string>] {
const primaryTopics: Array<string> = []
const secondaryTopics: Array<string> = []
for (const topics of topicsList) {
const splitTopics = splitTopic(topics)
if (splitTopics.length) {
if (!primaryTopics.includes(splitTopics[0]))
primaryTopics.push(splitTopics[0])
if (splitTopics.length > 1) {
if (!secondaryTopics.includes(splitTopics[1]))
secondaryTopics.push(splitTopics[1])
}
}
}
return [primaryTopics, secondaryTopics]
}
/**
* Convert a string containing an operating system name into an array of `OperatingSystem`s. In some instances the
* description may map to multiple `OperatingSystems`, e.g. "Unix" => Linux and macOS.
*/
function parseOperatingSystem(operatingSystem: string): Array<OperatingSystem> {
if (/windows/i.exec(operatingSystem)) {
return [OperatingSystem.windows]
}
if (/unix/i.exec(operatingSystem)) {
return [OperatingSystem.linux, OperatingSystem.macos, OperatingSystem.unix]
}
if (/linux/i.exec(operatingSystem)) {
return [OperatingSystem.linux]
}
if (/macos/i.exec(operatingSystem) || /mac os/i.exec(operatingSystem)) {
return [OperatingSystem.macos]
}
return []
}
export enum RequirementType {
Named,
URL,
}
interface PythonRequirement {
/**
* Type of requirement specified (name or URL)
*/
type: RequirementType
/**
* Name or URL value of the requirement
*/
value: string
/**
* Version of the requirement
*/
version?: string | null
}
/**
* Parser to be used on a directory with Python source code and (optionally) a `requirements.txt` file.
* If no `requirements.txt` file exists then the Parser will attempt to read requirements from the Python source code.
*/
export default class PythonParser extends Parser {
async parse(): Promise<SoftwarePackage | null> {
const files = this.glob(['**/*.py'])
const pkg = new SoftwarePackage()
pkg.runtimePlatform = 'Python'
if (this.folder) {
pkg.name = basename(this.folder)
}
let requirements
if (this.exists(REQUIREMENTS_FILE_NAME)) {
requirements = await this.parseRequirementsFile(REQUIREMENTS_FILE_NAME)
} else {
if (!files.length) {
// no .py files so don't parse this directory
return null
}
requirements = this.generateRequirementsFromSource()
}
for (const rawRequirement of requirements) {
if (rawRequirement.type === RequirementType.Named) {
pkg.softwareRequirements.push(await this.createPackage(rawRequirement))
} else if (rawRequirement.type === RequirementType.URL) {
const sourceRequirement = new SoftwareSourceCode()
sourceRequirement.runtimePlatform = 'Python'
sourceRequirement.codeRepository = rawRequirement.value
}
}
return pkg
}
/**
* Convert a `PythonRequirement` into a `SoftwarePackage` by augmenting with metadata from PyPI
*/
private async createPackage(
requirement: PythonRequirement
): Promise<SoftwarePackage> {
const softwarePackage = new SoftwarePackage()
softwarePackage.name = requirement.value
softwarePackage.runtimePlatform = 'Python'
softwarePackage.programmingLanguages = [ComputerLanguage.py]
if (requirement.version) {
softwarePackage.version = requirement.version
}
const pyPiMetadata = await this.fetch(
`https://pypi.org/pypi/${softwarePackage.name}/json`
)
if (pyPiMetadata?.info) {
if (pyPiMetadata.info.author) {
softwarePackage.authors.push(
Person.fromText(
`${pyPiMetadata.info.author} <${pyPiMetadata.info.author_email}>`
)
)
}
if (pyPiMetadata.info.project_url) {
softwarePackage.codeRepository = pyPiMetadata.info.project_url
}
if (pyPiMetadata.info.classifiers) {
const classifiers = buildClassifierMap(pyPiMetadata.info.classifiers)
if (classifiers.has('Topic')) {
const [topics, subTopics] = parseTopics(classifiers.get('Topic')!)
if (topics.length) softwarePackage.applicationCategories = topics
if (subTopics.length)
softwarePackage.applicationSubCategories = subTopics
}
if (classifiers.has('Operating System')) {
const operatingSystems: Array<OperatingSystem> = []
for (const operatingSystemDescription of classifiers.get(
'Operating System'
)!) {
for (const operatingSystem of parseOperatingSystem(
operatingSystemDescription
)) {
if (!operatingSystems.includes(operatingSystem))
operatingSystems.push(operatingSystem)
}
}
softwarePackage.operatingSystems = operatingSystems
}
}
if (pyPiMetadata.info.keywords)
softwarePackage.keywords = pyPiMetadata.info.keywords
if (pyPiMetadata.info.license)
softwarePackage.license = pyPiMetadata.info.license
if (pyPiMetadata.info.long_description) {
softwarePackage.description = pyPiMetadata.info.long_description
} else if (pyPiMetadata.info.description) {
softwarePackage.description = pyPiMetadata.info.description
}
}
return softwarePackage
}
/**
* Parse a `requirements.txt` file at `path` and return a list of `PythonRequirement`s
*/
async parseRequirementsFile(path: string): Promise<Array<PythonRequirement>> {
const requirementsContent = this.read(path)
const allRequirementLines = requirementsContent.split('\n')
let requirements: Array<PythonRequirement> = []
for (const line of allRequirementLines) {
if (lineIsComment(line)) {
continue
}
const editableSource = extractEditableSource(line)
if (editableSource !== null) {
requirements.push({ value: editableSource, type: RequirementType.URL })
continue
}
const includePath = extractIncludedRequirementsPath(line)
if (includePath !== null) {
const includedRequirements = await this.parseRequirementsFile(
includePath
)
requirements = requirements.concat(includedRequirements)
continue
}
const standardRequirement = extractStandardRequirements(line)
if (standardRequirement !== null) {
const [requirementName, version] =
splitStandardRequirementVersion(standardRequirement)
requirements.push({
value: requirementName,
type: RequirementType.Named,
version: version,
})
}
}
return requirements
}
/**
* Parse Python source files are find any non-system imports, return this as an array of `PythonRequirement`s.
*/
generateRequirementsFromSource(): Array<PythonRequirement> {
const nonSystemImports = this.findImports().filter(
(pythonImport) => !pythonSystemModules.includes(pythonImport)
)
return nonSystemImports.map((nonSystemImport) => {
return {
value: nonSystemImport,
type: RequirementType.Named,
version: '',
}
})
}
/**
* Parse Python source files are find all imports (including system imports).
*/
findImports(): Array<string> {
const files = this.glob(['**/*.py'])
const imports: Array<string> = []
if (files.length) {
for (const file of files) {
for (const importName of this.readImportsInFile(file)) {
if (!imports.includes(importName)) imports.push(importName)
}
}
}
return imports
}
/**
* Parse Python a single Python source file for imports.
*/
readImportsInFile(path: string): Array<string> {
const fileContent = this.read(path)
const importRegex = /^\s*from ([\w_]+)|^\s*import ([\w_]+)/gm
const imports: Array<string> = []
const fileDirectory = dirname(path)
while (true) {
const match = importRegex.exec(fileContent)
if (!match) break
const pkg = match[1] || match[2]
if (
this.glob([
fileDirectory + '/' + pkg + '.py',
fileDirectory + '/' + pkg + '/__init__.py',
]).length
) {
continue
}
if (!imports.includes(pkg)) imports.push(pkg)
}
return imports
}
} | the_stack |
import { ColorList } from './color';
import { capitalize } from '../string';
export const ColorLists = {
/**
* Brewer Color Lists
*
* Copyright (c) 2002 Cynthia Brewer, Mark Harrower, and The Pennsylvania State University.
* Licensed under the Apache License, Version 2.0 (the "License");
*/
'orange-red': ColorList('Orange-Red', 'sequential',
'Orange-Red, sequential color scheme from ColorBrewer 2.0',
[0xfff7ec, 0xfee8c8, 0xfdd49e, 0xfdbb84, 0xfc8d59, 0xef6548, 0xd7301f, 0xb30000, 0x7f0000]
),
'purple-blue': ColorList('Purple-Blue', 'sequential',
'Purple-Blue, sequential color scheme from ColorBrewer 2.0',
[0xfff7fb, 0xece7f2, 0xd0d1e6, 0xa6bddb, 0x74a9cf, 0x3690c0, 0x0570b0, 0x045a8d, 0x023858]
),
'blue-purple': ColorList('Blue-Purple', 'sequential',
'Blue-Purple, sequential color scheme from ColorBrewer 2.0',
[0xf7fcfd, 0xe0ecf4, 0xbfd3e6, 0x9ebcda, 0x8c96c6, 0x8c6bb1, 0x88419d, 0x810f7c, 0x4d004b]
),
'oranges': ColorList('Oranges', 'sequential',
'',
[0xfff5eb, 0xfee6ce, 0xfdd0a2, 0xfdae6b, 0xfd8d3c, 0xf16913, 0xd94801, 0xa63603, 0x7f2704]
),
'blue-green': ColorList('Blue-Green', 'sequential',
'',
[0xf7fcfd, 0xe5f5f9, 0xccece6, 0x99d8c9, 0x66c2a4, 0x41ae76, 0x238b45, 0x006d2c, 0x00441b]
),
'yellow-orange-brown': ColorList('Yellow-Orange-Brown', 'sequential',
'',
[0xffffe5, 0xfff7bc, 0xfee391, 0xfec44f, 0xfe9929, 0xec7014, 0xcc4c02, 0x993404, 0x662506]
),
'yellow-green': ColorList('Yellow-Green', 'sequential',
'',
[0xffffe5, 0xf7fcb9, 0xd9f0a3, 0xaddd8e, 0x78c679, 0x41ab5d, 0x238443, 0x006837, 0x004529]
),
'reds': ColorList('Reds', 'sequential',
'',
[0xfff5f0, 0xfee0d2, 0xfcbba1, 0xfc9272, 0xfb6a4a, 0xef3b2c, 0xcb181d, 0xa50f15, 0x67000d]
),
'red-purple': ColorList('Red-Purple', 'sequential',
'',
[0xfff7f3, 0xfde0dd, 0xfcc5c0, 0xfa9fb5, 0xf768a1, 0xdd3497, 0xae017e, 0x7a0177, 0x49006a]
),
'greens': ColorList('Greens', 'sequential',
'',
[0xf7fcf5, 0xe5f5e0, 0xc7e9c0, 0xa1d99b, 0x74c476, 0x41ab5d, 0x238b45, 0x006d2c, 0x00441b]
),
'yellow-green-blue': ColorList('Yellow-Green-Blue', 'sequential',
'',
[0xffffd9, 0xedf8b1, 0xc7e9b4, 0x7fcdbb, 0x41b6c4, 0x1d91c0, 0x225ea8, 0x253494, 0x081d58]
),
'purples': ColorList('Purples', 'sequential',
'',
[0xfcfbfd, 0xefedf5, 0xdadaeb, 0xbcbddc, 0x9e9ac8, 0x807dba, 0x6a51a3, 0x54278f, 0x3f007d]
),
'green-blue': ColorList('Green-Blue', 'sequential',
'',
[0xf7fcf0, 0xe0f3db, 0xccebc5, 0xa8ddb5, 0x7bccc4, 0x4eb3d3, 0x2b8cbe, 0x0868ac, 0x084081]
),
'greys': ColorList('Greys', 'sequential',
'',
[0xffffff, 0xf0f0f0, 0xd9d9d9, 0xbdbdbd, 0x969696, 0x737373, 0x525252, 0x252525, 0x000000]
),
'yellow-orange-red': ColorList('Yellow-Orange-Red', 'sequential',
'',
[0xffffcc, 0xffeda0, 0xfed976, 0xfeb24c, 0xfd8d3c, 0xfc4e2a, 0xe31a1c, 0xbd0026, 0x800026]
),
'purple-red': ColorList('Purple-Red', 'sequential',
'',
[0xf7f4f9, 0xe7e1ef, 0xd4b9da, 0xc994c7, 0xdf65b0, 0xe7298a, 0xce1256, 0x980043, 0x67001f]
),
'blues': ColorList('Blues', 'sequential',
'',
[0xf7fbff, 0xdeebf7, 0xc6dbef, 0x9ecae1, 0x6baed6, 0x4292c6, 0x2171b5, 0x08519c, 0x08306b]
),
'purple-blue-green': ColorList('Purple-Blue-Green', 'sequential',
'',
[0xfff7fb, 0xece2f0, 0xd0d1e6, 0xa6bddb, 0x67a9cf, 0x3690c0, 0x02818a, 0x016c59, 0x014636]
),
'spectral': ColorList('Spectral', 'diverging',
'',
[0x9e0142, 0xd53e4f, 0xf46d43, 0xfdae61, 0xfee08b, 0xffffbf, 0xe6f598, 0xabdda4, 0x66c2a5, 0x3288bd, 0x5e4fa2]
),
'red-yellow-green': ColorList('Red-Yellow-Green', 'diverging',
'',
[0xa50026, 0xd73027, 0xf46d43, 0xfdae61, 0xfee08b, 0xffffbf, 0xd9ef8b, 0xa6d96a, 0x66bd63, 0x1a9850, 0x006837]
),
'red-blue': ColorList('Red-Blue', 'diverging',
'',
[0x67001f, 0xb2182b, 0xd6604d, 0xf4a582, 0xfddbc7, 0xf7f7f7, 0xd1e5f0, 0x92c5de, 0x4393c3, 0x2166ac, 0x053061]
),
'pink-yellow-green': ColorList('Pink-Yellow-Green', 'diverging',
'',
[0x8e0152, 0xc51b7d, 0xde77ae, 0xf1b6da, 0xfde0ef, 0xf7f7f7, 0xe6f5d0, 0xb8e186, 0x7fbc41, 0x4d9221, 0x276419]
),
'purple-green': ColorList('Purple-Green', 'diverging',
'',
[0x40004b, 0x762a83, 0x9970ab, 0xc2a5cf, 0xe7d4e8, 0xf7f7f7, 0xd9f0d3, 0xa6dba0, 0x5aae61, 0x1b7837, 0x00441b]
),
'red-yellow-blue': ColorList('Red-Yellow-Blue', 'diverging',
'Red-Yellow-Blue, diverging color scheme from ColorBrewer 2.0',
[0xa50026, 0xd73027, 0xf46d43, 0xfdae61, 0xfee090, 0xffffbf, 0xe0f3f8, 0xabd9e9, 0x74add1, 0x4575b4, 0x313695]
),
'brown-white-green': ColorList('Brown-White-Green', 'diverging',
'',
[0x543005, 0x8c510a, 0xbf812d, 0xdfc27d, 0xf6e8c3, 0xf5f5f5, 0xc7eae5, 0x80cdc1, 0x35978f, 0x01665e, 0x003c30]
),
'red-grey': ColorList('Red-Grey', 'diverging',
'',
[0x67001f, 0xb2182b, 0xd6604d, 0xf4a582, 0xfddbc7, 0xffffff, 0xe0e0e0, 0xbababa, 0x878787, 0x4d4d4d, 0x1a1a1a]
),
'orange-purple': ColorList('Orange-Purple', 'diverging',
'',
[0x7f3b08, 0xb35806, 0xe08214, 0xfdb863, 0xfee0b6, 0xf7f7f7, 0xd8daeb, 0xb2abd2, 0x8073ac, 0x542788, 0x2d004b]
),
'set-2': ColorList('Set-2', 'qualitative',
'',
[0x66c2a5, 0xfc8d62, 0x8da0cb, 0xe78ac3, 0xa6d854, 0xffd92f, 0xe5c494, 0xb3b3b3]
),
'accent': ColorList('Accent', 'qualitative',
'',
[0x7fc97f, 0xbeaed4, 0xfdc086, 0xffff99, 0x386cb0, 0xf0027f, 0xbf5b17, 0x666666]
),
'set-1': ColorList('Set-1', 'qualitative',
'',
[0xe41a1c, 0x377eb8, 0x4daf4a, 0x984ea3, 0xff7f00, 0xffff33, 0xa65628, 0xf781bf, 0x999999]
),
'set-3': ColorList('Set-3', 'qualitative',
'',
[0x8dd3c7, 0xffffb3, 0xbebada, 0xfb8072, 0x80b1d3, 0xfdb462, 0xb3de69, 0xfccde5, 0xd9d9d9, 0xbc80bd, 0xccebc5, 0xffed6f]
),
'dark-2': ColorList('Dark-2', 'qualitative',
'',
[0x1b9e77, 0xd95f02, 0x7570b3, 0xe7298a, 0x66a61e, 0xe6ab02, 0xa6761d, 0x666666]
),
'paired': ColorList('Paired', 'qualitative',
'',
[0xa6cee3, 0x1f78b4, 0xb2df8a, 0x33a02c, 0xfb9a99, 0xe31a1c, 0xfdbf6f, 0xff7f00, 0xcab2d6, 0x6a3d9a, 0xffff99, 0xb15928]
),
'pastel-2': ColorList('Pastel-2', 'qualitative',
'',
[0xb3e2cd, 0xfdcdac, 0xcbd5e8, 0xf4cae4, 0xe6f5c9, 0xfff2ae, 0xf1e2cc, 0xcccccc]
),
'pastel-1': ColorList('Pastel-1', 'qualitative',
'',
[0xfbb4ae, 0xb3cde3, 0xccebc5, 0xdecbe4, 0xfed9a6, 0xffffcc, 0xe5d8bd, 0xfddaec, 0xf2f2f2]
),
'many-distinct': ColorList('Many-Distinct', 'qualitative',
'',
[
// dark-2
0x1b9e77, 0xd95f02, 0x7570b3, 0xe7298a, 0x66a61e, 0xe6ab02, 0xa6761d, 0x666666,
// set-1
0xe41a1c, 0x377eb8, 0x4daf4a, 0x984ea3, 0xff7f00, 0xffff33, 0xa65628, 0xf781bf, 0x999999,
// set-2
0x66c2a5, 0xfc8d62, 0x8da0cb, 0xe78ac3, 0xa6d854, 0xffd92f, 0xe5c494, 0xb3b3b3
]
),
/**
* Matplotlib colormaps, including various perceptually uniform shades, see https://bids.github.io/colormap/
*/
'magma': ColorList('Magma', 'sequential',
'Perceptually uniform shades of black-red-white',
[0x420f74, 0x4a1079, 0x52127c, 0x5a157e, 0x61187f, 0x691c80, 0x711f81, 0x792281, 0x812581, 0x892881, 0x912a80, 0x992d7f, 0xa12f7e, 0xa9327c, 0xb1357a, 0xb93778, 0xc23a75, 0xca3e72, 0xd1426e, 0xd9466a, 0xe04b66, 0xe65162, 0xec585f, 0xf0605d, 0xf4685b, 0xf7715b, 0xf97b5d, 0xfb8460, 0xfc8e63, 0xfd9768, 0xfda16e, 0xfeaa74, 0xfeb37b, 0xfebc82, 0xfec689, 0xfdcf92, 0xfdd89a, 0xfde1a3, 0xfceaac, 0xfcf3b5, 0xfbfcbf]
),
'inferno': ColorList('Inferno', 'sequential',
'Perceptually uniform shades of black-red-yellow',
[0x480b6a, 0x500d6c, 0x58106d, 0x60136e, 0x68166e, 0x70196e, 0x781c6d, 0x801f6b, 0x88216a, 0x902468, 0x982765, 0xa02a62, 0xa72d5f, 0xaf315b, 0xb73456, 0xbe3852, 0xc53d4d, 0xcc4148, 0xd24742, 0xd94d3d, 0xde5337, 0xe45a31, 0xe8612b, 0xed6825, 0xf0701e, 0xf37918, 0xf68111, 0xf88a0b, 0xfa9306, 0xfb9d06, 0xfba60b, 0xfbb014, 0xfbb91e, 0xf9c32a, 0xf8cd37, 0xf5d745, 0xf3e056, 0xf1e968, 0xf1f27d, 0xf5f891, 0xfcfea4],
),
'plasma': ColorList('Plasma', 'sequential',
'Perceptually uniform shades of blue-red-yellow',
[0x1b068c, 0x250591, 0x2f0495, 0x380499, 0x40039c, 0x49029f, 0x5101a2, 0x5901a4, 0x6100a6, 0x6800a7, 0x7000a8, 0x7801a8, 0x7f03a7, 0x8607a6, 0x8e0ca4, 0x9511a1, 0x9b179e, 0xa21c9a, 0xa82296, 0xae2791, 0xb42d8d, 0xb93388, 0xbe3883, 0xc33e7f, 0xc8447a, 0xcd4975, 0xd14f71, 0xd6556d, 0xda5a68, 0xde6064, 0xe26660, 0xe56c5b, 0xe97257, 0xec7853, 0xef7e4e, 0xf2854a, 0xf58b46, 0xf79241, 0xf9993d, 0xfaa039, 0xfca735, 0xfdaf31, 0xfdb62d, 0xfdbe29, 0xfdc626, 0xfcce25, 0xfad624, 0xf8df24, 0xf5e726, 0xf2f026, 0xeff821]
),
'viridis': ColorList('Viridis', 'sequential',
'Perceptually uniform shades of blue-green-yellow',
[0x45085b, 0x470f62, 0x471669, 0x481d6f, 0x482374, 0x472a79, 0x46307d, 0x453681, 0x433c84, 0x414286, 0x3e4888, 0x3c4d8a, 0x3a538b, 0x37588c, 0x355d8c, 0x32628d, 0x30678d, 0x2e6c8e, 0x2c718e, 0x2a768e, 0x287a8e, 0x267f8e, 0x24848d, 0x23898d, 0x218d8c, 0x1f928c, 0x1e978a, 0x1e9b89, 0x1ea087, 0x20a585, 0x23a982, 0x28ae7f, 0x2eb27c, 0x35b778, 0x3dbb74, 0x45bf6f, 0x4fc369, 0x59c764, 0x64cb5d, 0x70ce56, 0x7cd24f, 0x88d547, 0x95d73f, 0xa2da37, 0xafdc2e, 0xbdde26, 0xcae01e, 0xd7e219, 0xe4e318, 0xf1e51c, 0xfde724]
),
'cividis': ColorList('Cividis', 'sequential',
'Perceptually uniform shades of blue-green-yellow, should look effectively identical to colorblind and non-colorblind users',
[0x002c67, 0x003070, 0x083370, 0x16366f, 0x1f3a6e, 0x273d6d, 0x2e416c, 0x34446c, 0x39486c, 0x3f4b6b, 0x444f6b, 0x49526b, 0x4e566c, 0x52596c, 0x575d6d, 0x5b606e, 0x60646e, 0x64676f, 0x686b71, 0x6d6e72, 0x717273, 0x757575, 0x797977, 0x7e7d78, 0x838078, 0x878478, 0x8c8878, 0x918c77, 0x968f77, 0x9b9376, 0xa09775, 0xa59b73, 0xaa9f72, 0xafa370, 0xb4a76f, 0xb9ab6d, 0xbeb06a, 0xc4b468, 0xc9b865, 0xcebc62, 0xd4c15e, 0xd9c55a, 0xdfca56, 0xe4ce51, 0xead34c, 0xefd846, 0xf5dc3f, 0xfbe136, 0xfde737]
),
'twilight': ColorList('Twilight', 'sequential',
'Perceptually uniform shades of white-blue-black-red-white, cyclic',
[0xdfd9e1, 0xd8d7dd, 0xced3d8, 0xc2cdd3, 0xb4c7ce, 0xa7c0ca, 0x9ab8c7, 0x8eb0c5, 0x83a8c3, 0x7a9fc2, 0x7297c0, 0x6b8ebf, 0x6684bd, 0x637bbb, 0x6171b9, 0x5f67b6, 0x5e5cb2, 0x5e51ad, 0x5d46a7, 0x5c3c9f, 0x5b3196, 0x58278b, 0x531e7d, 0x4d176e, 0x46135f, 0x3e1151, 0x381045, 0x32113b, 0x301336, 0x361138, 0x3e113c, 0x471240, 0x521445, 0x5e1749, 0x6a1a4d, 0x761e4f, 0x812350, 0x8b2a50, 0x95324f, 0x9d3a4f, 0xa5434f, 0xac4d50, 0xb25752, 0xb86155, 0xbc6c59, 0xc0775f, 0xc48267, 0xc78d70, 0xc9987b, 0xcca389, 0xceae97, 0xd2b8a6, 0xd6c1b5, 0xdacac4, 0xddd1d1, 0xe0d6db, 0xe1d8e1]
),
/**
* https://ai.googleblog.com/2019/08/turbo-improved-rainbow-colormap-for.html
*/
'turbo': ColorList('Turbo', 'sequential',
'Improved (smooth) rainbow colormap for visualization',
[0x4a41b5, 0x4a58dd, 0x426ff2, 0x3987f9, 0x2f9df5, 0x28b2e9, 0x25c6d8, 0x27d7c4, 0x2ee5ae, 0x3bf098, 0x4df884, 0x62fd70, 0x7bfe5f, 0x95fb51, 0xaff444, 0xc8ea3a, 0xdedd32, 0xf0cc2c, 0xfeb927, 0xffa423, 0xff8e1f, 0xff761c, 0xf65f18, 0xe54813, 0xd0330e, 0xba2208, 0xa51403, 0x960d00]
),
/**
* Other
*/
'rainbow': ColorList('Rainbow', 'sequential',
'',
[0x3361E1, 0x35A845, 0xF9FF00, 0xEC8711, 0xBF2222]
),
'red-white-blue': ColorList('Red-White-Blue', 'diverging',
'',
[0xBF2222, 0xFFFFFF, 0x3361E1]
),
};
export type ColorListName = keyof typeof ColorLists
export const ColorListNames = Object.keys(ColorLists);
export const ColorListOptions = ColorListNames.map(n => [n, ColorLists[n as ColorListName].label, capitalize(ColorLists[n as ColorListName].type)] as [ColorListName, string, string]);
export const ColorListOptionsScale = ColorListOptions.filter(v => ColorLists[v[0]].type === 'diverging' || ColorLists[v[0]].type === 'sequential');
export const ColorListOptionsSet = ColorListOptions.filter(v => ColorLists[v[0]].type === 'qualitative');
export function getColorListFromName(name: ColorListName) {
if (name in ColorLists) return ColorLists[name as ColorListName];
console.warn(`unknown color list named '${name}'`);
return ColorLists['red-yellow-blue'];
} | the_stack |
import * as React from 'react';
import { RunsModel } from '../models/RunsModel';
import { NotebookPanel } from '@jupyterlab/notebook';
import { ServerConnection } from '@jupyterlab/services';
import { IStateDB, URLExt } from '@jupyterlab/coreutils';
import { JSONValue, ReadonlyJSONObject, JSONArray } from '@phosphor/coreutils';
import { Signal } from '@phosphor/signaling';
import { Widget } from '@phosphor/widgets';
import {
UploadNotebookResponse,
InvokeRequest,
InvokeResponse,
CreateRuleRequest,
CreateRuleResponse,
ErrorResponse,
} from '../server';
import { InputColumn, LabeledTextInput } from './InputColumn';
import { ParameterEditor, ParameterKV } from './ParameterEditor';
import { Alert, AlertProps } from './Alert';
import {
runSidebarSectionClass,
runSidebarNotebookNameClass,
runSidebarNoHeaderClass,
sidebarButtonClass,
alertAreaClass,
runSidebarNoNotebookClass,
flexButtonsClass,
} from '../style/SchedulePanel';
import { JupyterFrontEnd, ILabShell } from '@jupyterlab/application';
import { RulesModel } from '../models/RulesModel';
const KEY = 'sagemaker-run-notebook:schedule-sidebar:data';
/** Interface for SchedulePanel component props */
export interface ISchedulePanelProps {
app: JupyterFrontEnd;
shell: ILabShell;
runsModel: RunsModel;
rulesModel: RulesModel;
stateDB: IStateDB;
}
interface PersistentState {
image: string;
role: string;
instanceType: string;
ruleName: string;
schedule: string;
eventPattern: string;
}
interface ISchedulePanelState extends PersistentState {
notebook: string;
notebookPanel: NotebookPanel;
parameters: ParameterKV[];
alerts: (AlertProps & { key: string })[];
}
// convertParameters turns the parameters we use here into a map that the server and containter expect.
// TODO: fix the container to take lists and delete this function so that parameters are always in the order specified
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function convertParameters(params: ParameterKV[]): Record<string, any> {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const result: Record<string, any> = {};
params.forEach((param) => {
result[param.name] = param.value;
});
return result;
}
/** A React component for the schedule extension's main display */
export class SchedulePanel extends React.Component<ISchedulePanelProps, ISchedulePanelState> {
constructor(props: ISchedulePanelProps) {
super(props);
this.app = props.app;
this.shell = props.shell;
this.currentNotebookChanged = new Signal<SchedulePanel, NotebookPanel>(this);
this.setCurrentWidget(this.shell.currentWidget);
this.state = {
notebook: this.notebook,
notebookPanel: this.currentNotebookPanel,
image: '',
parameters: null,
role: '',
instanceType: '',
ruleName: '',
schedule: '',
eventPattern: '',
alerts: [],
};
this.loadState();
this.shell.currentChanged.connect(this.onCurrentWidgetChanged, this);
}
//TODO: track notebook renames
private onCurrentWidgetChanged(sender: ILabShell, args: ILabShell.IChangedArgs) {
const newWidget = args.newValue;
const label = newWidget && newWidget.title.label;
console.log(`current widget changed to ${label}`);
this.setCurrentWidget(newWidget);
this.setState({ notebook: this.notebook, notebookPanel: this.currentNotebookPanel });
}
private setCurrentWidget(newWidget: Widget): void {
const context = newWidget && (newWidget as NotebookPanel).context;
const session = context && context.session;
const isNotebook = session && session.type === 'notebook';
if (isNotebook) {
this.currentNotebookPanel = newWidget as NotebookPanel;
this.notebook = session.name;
} else {
this.currentNotebookPanel = null;
this.notebook = null;
}
this.currentNotebookChanged.emit(this.currentNotebookPanel);
}
/**
* Renders the component.
*
* @returns React element
*/
render = (): React.ReactElement => {
const notebookIndependent = (
<div>
{this.renderViewButtons()}
{this.renderCurrentNotebook()}
</div>
);
const notebookDependent = this.currentNotebookPanel ? (
<div>
{this.renderRunParameters()}
{this.renderScheduleParameters()}
{this.renderExecuteButtons()}
{this.renderAlerts()}
</div>
) : (
<p className={runSidebarNoNotebookClass}>Select or create a notebook to enable execution and scheduling.</p>
);
return (
<div>
{notebookIndependent}
{notebookDependent}
</div>
);
};
private renderViewButtons() {
return (
<div className={runSidebarSectionClass}>
<header>View</header>
<div>
<div className={flexButtonsClass}>
<input
className={sidebarButtonClass}
type="button"
title="View notebook runs"
value="Runs"
onClick={this.onRunListClick}
/>
<input
className={sidebarButtonClass}
type="button"
title="View notebook schedules"
value="Schedules"
onClick={this.onScheduleListClick}
/>
</div>
</div>
</div>
);
}
private renderCurrentNotebook() {
const notebook = this.state.notebook;
let notebookDisplay: React.ReactElement;
if (notebook != null) {
notebookDisplay = <span>{notebook}</span>;
} else {
notebookDisplay = <span>No notebook selected</span>;
}
return (
<div className={runSidebarSectionClass}>
<header>Current Notebook</header>
<p className={runSidebarNotebookNameClass}>{notebookDisplay}</p>
</div>
);
}
private renderRunParameters() {
return (
<div className={runSidebarSectionClass}>
<header>Notebook Execution</header>
<ParameterEditor
onChange={this.onParametersChange}
notebookPanel={this.currentNotebookPanel}
notebookPanelChanged={this.currentNotebookChanged}
/>
<InputColumn>
<LabeledTextInput
label="Image:"
value={this.state.image}
title="ECR image to use"
onChange={this.onImageChange}
/>
<LabeledTextInput
label="Role:"
value={this.state.role}
title="IAM role to use"
onChange={this.onRoleChange}
/>
<LabeledTextInput
label="Instance:"
value={this.state.instanceType}
title="Instance type to run on"
onChange={this.onInstanceTypeChange}
/>
</InputColumn>
</div>
);
}
private renderScheduleParameters() {
return (
<div className={runSidebarSectionClass}>
<header>Schedule Rule</header>
<InputColumn>
<LabeledTextInput
label="Rule Name:"
value={this.state.ruleName}
title="A name for this schedule"
onChange={this.onRuleNameChange}
/>
<LabeledTextInput
label="Schedule:"
value={this.state.schedule}
title="Schedule for the notebook run"
onChange={this.onScheduleChange}
/>
<LabeledTextInput
label="Event Pattern:"
value={this.state.eventPattern}
title="Events to trigger the notebook run"
onChange={this.onEventPatternChange}
/>
</InputColumn>
</div>
);
}
private renderExecuteButtons() {
return (
<div className={`${runSidebarSectionClass} ${runSidebarNoHeaderClass}`}>
<div>
<div className={flexButtonsClass}>
<input
className={sidebarButtonClass}
type="button"
title="Run the notebook"
value="Run Now"
onClick={this.onRunClick}
/>
<input
className={sidebarButtonClass}
type="button"
title="Create schedule"
value="Create Schedule"
onClick={this.onScheduleClick}
/>
</div>
</div>
</div>
);
}
private renderAlerts() {
return (
<div className={alertAreaClass}>
{this.state.alerts.map((alert) => (
<Alert key={`alert-${alert.key}`} type={alert.type} message={alert.message} />
))}
</div>
);
}
private onParametersChange = (editor: ParameterEditor): void => {
this.setState({ parameters: editor.value });
};
private onImageChange = (event: React.ChangeEvent<HTMLInputElement>): void => {
this.setState({ image: event.target.value }, () => this.saveState());
};
private onRoleChange = (event: React.ChangeEvent<HTMLInputElement>): void => {
this.setState({ role: event.target.value }, () => this.saveState());
};
private onInstanceTypeChange = (event: React.ChangeEvent<HTMLInputElement>): void => {
this.setState({ instanceType: event.target.value }, () => this.saveState());
};
private onRuleNameChange = (event: React.ChangeEvent<HTMLInputElement>): void => {
this.setState({ ruleName: event.target.value }, () => this.saveState());
};
private onScheduleChange = (event: React.ChangeEvent<HTMLInputElement>): void => {
this.setState({ schedule: event.target.value }, () => this.saveState());
};
private onEventPatternChange = (event: React.ChangeEvent<HTMLInputElement>): void => {
this.setState({ eventPattern: event.target.value }, () => this.saveState());
};
private onRunListClick = async (): Promise<void> => {
this.app.commands.execute('sagemaker_run_notebook:open_list_runs');
};
private onScheduleListClick = async (): Promise<void> => {
this.app.commands.execute('sagemaker_run_notebook:open_list_schedules');
};
private onRunClick = async (): Promise<void> => {
console.log('Run!!!');
this.clearAlerts();
try {
this.addAlert({
type: 'notice',
message: `Starting notebook run for "${this.state.notebook}"`,
});
const content = this.currentNotebookPanel.model.toJSON();
const s3Object = await this.uploadNotebook(content);
console.log(`notebook uploaded to ${s3Object}`);
// TODO: clean up non-camel-case entries in the server requests
/* eslint-disable @typescript-eslint/camelcase */
const request: InvokeRequest = {
image: this.state.image,
input_path: s3Object,
notebook: this.state.notebook,
parameters: convertParameters(this.state.parameters),
role: this.state.role,
instance_type: this.state.instanceType,
};
/* eslint-enable @typescript-eslint/camelcase */
const jobName = await this.invokeNotebook(request);
this.addAlert({ message: `Started notebook run "${jobName}"` });
console.log(`started job ${jobName}`);
this.props.runsModel.refresh();
} catch (e) {
this.addAlert({
type: 'error',
message: `Error starting run for "${this.state.notebook}": ${e.message}`,
});
}
};
private onScheduleClick = async (): Promise<void> => {
console.log('Create schedule!!!');
this.clearAlerts();
try {
this.addAlert({
type: 'notice',
message: `Creating rule "${this.state.ruleName}"`,
});
const content = this.currentNotebookPanel.model.toJSON();
const s3Object = await this.uploadNotebook(content);
console.log(`notebook uploaded to ${s3Object}`);
/* eslint-disable @typescript-eslint/camelcase */
const request: CreateRuleRequest = {
image: this.state.image,
input_path: s3Object,
notebook: this.state.notebook,
parameters: convertParameters(this.state.parameters),
role: this.state.role,
instance_type: this.state.instanceType,
};
const schedule = this.state.schedule;
if (schedule !== '') {
request.schedule = schedule;
}
const eventPattern = this.state.eventPattern;
if (eventPattern !== '') {
request.event_pattern = eventPattern;
}
/* eslint-enable @typescript-eslint/camelcase */
const ruleName = await this.createRule(this.state.ruleName, request);
this.addAlert({ message: `Created rule "${ruleName}"` });
console.log(`created rule ${ruleName}`);
this.props.rulesModel.refresh();
} catch (e) {
this.addAlert({
type: 'error',
message: `Error creating rule "${this.state.ruleName}": ${e.message}`,
});
}
};
private async uploadNotebook(notebook: JSONValue): Promise<string> {
const settings = ServerConnection.makeSettings();
const response = await ServerConnection.makeRequest(
URLExt.join(settings.baseUrl, 'sagemaker-scheduler', 'upload'),
{ method: 'PUT', body: JSON.stringify(notebook) },
settings,
);
if (!response.ok) {
const error = (await response.json()) as ErrorResponse;
let errorMessage: string;
if (error.error) {
errorMessage = error.error.message;
} else {
errorMessage = JSON.stringify(error);
}
throw Error('Uploading notebook to S3 failed: ' + errorMessage);
}
const data = (await response.json()) as UploadNotebookResponse;
return data.s3Object;
}
// Figure out if the current notebook has a parameter cell marked
private hasParameterCell(): boolean {
if (!this.currentNotebookPanel) {
return false;
}
const cells = this.currentNotebookPanel.model.cells;
for (let i = 0; i < cells.length; i++) {
const tags = cells.get(i).metadata.get('tags') as JSONArray;
if (tags && tags.includes('parameters')) {
return true;
}
}
return false;
}
private runReady(): string[] {
const result: string[] = [];
if (!this.state.image) {
result.push('missing container image');
}
if (!this.state.instanceType) {
result.push('missing instance type');
}
if (this.state.parameters.length > 0 && !this.hasParameterCell()) {
result.push(`no parameter cell defined in ${this.notebook}`);
}
return result;
}
private async invokeNotebook(request: InvokeRequest): Promise<string> {
const errors = this.runReady();
if (errors.length > 0) {
throw new Error(errors.join(', '));
}
const settings = ServerConnection.makeSettings();
const response = await ServerConnection.makeRequest(
URLExt.join(settings.baseUrl, 'sagemaker-scheduler', 'run'),
{ method: 'POST', body: JSON.stringify(request) },
settings,
);
if (!response.ok) {
const error = (await response.json()) as ErrorResponse;
let errorMessage: string;
if (error.error) {
errorMessage = error.error.message;
} else {
errorMessage = JSON.stringify(error);
}
throw Error(errorMessage);
}
const data = (await response.json()) as InvokeResponse;
return data.job_name;
}
// Return an array of reasons that we can't create a schedule.
private scheduleReady(): string[] {
const result = this.runReady();
if (!this.state.ruleName) {
result.push('missing schedule name');
}
if (!(this.state.schedule || this.state.eventPattern)) {
result.push('must have either a schedule or an event pattern');
}
return result;
}
private async createRule(ruleName: string, request: CreateRuleRequest): Promise<string> {
const errors = this.scheduleReady();
if (errors.length > 0) {
throw new Error(errors.join(', '));
}
const settings = ServerConnection.makeSettings();
const response = await ServerConnection.makeRequest(
URLExt.join(settings.baseUrl, 'sagemaker-scheduler', 'schedule', ruleName),
{ method: 'POST', body: JSON.stringify(request) },
settings,
);
if (!response.ok) {
const error = (await response.json()) as ErrorResponse;
let errorMessage: string;
if (error.error) {
errorMessage = error.error.message;
} else {
errorMessage = JSON.stringify(error);
}
throw Error(errorMessage);
}
const data = (await response.json()) as CreateRuleResponse;
return data.rule_name;
}
private alertKey = 0;
private addAlert(alert: AlertProps) {
const key = this.alertKey++;
const keyedAlert: AlertProps & { key: string } = { ...alert, key: `alert-${key}` };
this.setState({ alerts: [keyedAlert] });
}
private clearAlerts() {
this.setState({ alerts: [] });
}
private saveState() {
const state = {
image: this.state.image,
role: this.state.role,
instanceType: this.state.instanceType,
ruleName: this.state.ruleName,
schedule: this.state.schedule,
eventPattern: this.state.eventPattern,
};
this.props.stateDB.save(KEY, state);
}
private loadState() {
this.props.stateDB.fetch(KEY).then((s) => {
const state = s as ReadonlyJSONObject;
if (state) {
this.setState({
image: state['image'] as string,
role: state['role'] as string,
instanceType: state['instanceType'] as string,
ruleName: state['ruleName'] as string,
schedule: state['schedule'] as string,
eventPattern: state['eventPattern'] as string,
});
}
});
}
private app: JupyterFrontEnd;
private shell: ILabShell;
private currentNotebookPanel: NotebookPanel;
private notebook: string;
private currentNotebookChanged: Signal<SchedulePanel, NotebookPanel>;
} | the_stack |
import { Chip } from './chip';
import { GlobalMembers } from './global-members';
import { Operator } from './operator';
import { Shifts, SynthMode } from './db-opl3';
/*
* 2019 - Typescript Version: Thomas Zeugner
*/
export class Channel {
private channels: Channel[];
public ChannelIndex: number;
private Channel(index: number): Channel {
return this.channels[this.ChannelIndex + index];
}
private operators: Operator[];
private thisOpIndex: number;
public Op(index: number): Operator {
return this.operators[this.thisOpIndex + index];
}
public synthMode: SynthMode;
public chanData: number; /** int */
public old: Int32Array = new Int32Array(2);
public feedback: number; /** byte */
public regB0: number; /** byte */
public regC0: number; /** byte */
public fourMask: number; /** byte */
public maskLeft: number; /** char */
public maskRight: number; /** char */
public SetChanData(chip: Chip, data: number /** Bit32u */): void {
const change = this.chanData ^ data;
this.chanData = data;
this.Op(0).chanData = data;
this.Op(1).chanData = data;
//Since a frequency update triggered this, always update frequency
this.Op(0).UpdateFrequency();
this.Op(1).UpdateFrequency();
if ((change & (0xff << Shifts.SHIFT_KSLBASE)) != 0) {
this.Op(0).UpdateAttenuation();
this.Op(1).UpdateAttenuation();
}
if ((change & (0xff << Shifts.SHIFT_KEYCODE)) != 0) {
this.Op(0).UpdateRates(chip);
this.Op(1).UpdateRates(chip);
}
}
public UpdateFrequency(chip: Chip, fourOp: number /** UInt8 */): void {
//Extrace the frequency signed long
let data = this.chanData & 0xffff;
const kslBase = GlobalMembers.KslTable[data >>> 6];
let keyCode = (data & 0x1c00) >>> 9;
if ((chip.reg08 & 0x40) != 0) {
keyCode |= (data & 0x100) >>> 8; /* notesel == 1 */
}
else {
keyCode |= (data & 0x200) >>> 9;/* notesel == 0 */
}
//Add the keycode and ksl into the highest signed long of chanData
data |= (keyCode << Shifts.SHIFT_KEYCODE) | (kslBase << Shifts.SHIFT_KSLBASE);
this.Channel(0).SetChanData(chip, data);
if ((fourOp & 0x3f) != 0) {
this.Channel(1).SetChanData(chip, data);
}
}
public WriteA0(chip: Chip, val: number /* UInt8 */): void {
const fourOp = (chip.reg104 & chip.opl3Active & this.fourMask);
//Don't handle writes to silent fourop channels
if (fourOp > 0x80) {
return;
}
const change = (this.chanData ^ val) & 0xff;
if (change != 0) {
this.chanData ^= change;
this.UpdateFrequency(chip, fourOp);
}
}
public WriteB0(chip: Chip, val: number /* UInt8 */): void {
const fourOp = (chip.reg104 & chip.opl3Active & this.fourMask);
//Don't handle writes to silent fourop channels
if (fourOp > 0x80) {
return;
}
const change = ((this.chanData ^ (val << 8)) & 0x1f00);
if (change != 0) {
this.chanData ^= change;
this.UpdateFrequency(chip, fourOp);
}
//Check for a change in the keyon/off state
if (((val ^ this.regB0) & 0x20) == 0) {
return;
}
this.regB0 = val;
if ((val & 0x20) != 0) {
this.Op(0).KeyOn(0x1);
this.Op(1).KeyOn(0x1);
if ((fourOp & 0x3f) != 0) {
this.Channel(1).Op(0).KeyOn(1);
this.Channel(1).Op(1).KeyOn(1);
}
}
else {
this.Op(0).KeyOff(0x1);
this.Op(1).KeyOff(0x1);
if ((fourOp & 0x3f) != 0) {
this.Channel(1).Op(0).KeyOff(1);
this.Channel(1).Op(1).KeyOff(1);
}
}
}
public WriteC0(chip: Chip, val: number /* UInt8 */): void {
const change = (val ^ this.regC0);
if (change == 0) {
return;
}
this.regC0 = val;
this.feedback = ((val >>> 1) & 7);
if (this.feedback != 0) {
//We shift the input to the right 10 bit wave index value
this.feedback = (9 - this.feedback) & 0xFF;
}
else {
this.feedback = 31;
}
//Select the new synth mode
if (chip.opl3Active) {
//4-op mode enabled for this channel
if (((chip.reg104 & this.fourMask) & 0x3f) != 0) {
let chan0: Channel;
let chan1: Channel;
//Check if it's the 2nd channel in a 4-op
if ((this.fourMask & 0x80) == 0) {
chan0 = this.Channel(0);
chan1 = this.Channel(1);
}
else {
chan0 = this.Channel(- 1);
chan1 = this.Channel(0);
}
const synth = (((chan0.regC0 & 1) << 0) | ((chan1.regC0 & 1) << 1));
switch (synth) {
case 0:
//chan0.synthHandler = this.BlockTemplate<SynthMode.sm3FMFM>;
chan0.synthMode = SynthMode.sm3FMFM;
break;
case 1:
//chan0.synthHandler = this.BlockTemplate<SynthMode.sm3AMFM>;
chan0.synthMode = SynthMode.sm3AMFM;
break;
case 2:
//chan0.synthHandler = this.BlockTemplate<SynthMode.sm3FMAM>;
chan0.synthMode = SynthMode.sm3FMAM;
break;
case 3:
//chan0.synthHandler = this.BlockTemplate<SynthMode.sm3AMAM>;
chan0.synthMode = SynthMode.sm3AMAM;
break;
}
//Disable updating percussion channels
}
else if ((this.fourMask & 0x40) && (chip.regBD & 0x20)) {
//Regular dual op, am or fm
}
else if (val & 1) {
//this.synthHandler = this.BlockTemplate<SynthMode.sm3AM>;
this.synthMode = SynthMode.sm3AM;
}
else {
//this.synthHandler = this.BlockTemplate<SynthMode.sm3FM>;
this.synthMode = SynthMode.sm3FM;
}
this.maskLeft = (val & 0x10) != 0 ? -1 : 0;
this.maskRight = (val & 0x20) != 0 ? -1 : 0;
//opl2 active
}
else {
//Disable updating percussion channels
if ((this.fourMask & 0x40) != 0 && (chip.regBD & 0x20) != 0) {
//Regular dual op, am or fm
}
else if (val & 1) {
//this.synthHandler = this.BlockTemplate<SynthMode.sm2AM>;
this.synthMode = SynthMode.sm2AM;
}
else {
//this.synthHandler = this.BlockTemplate<SynthMode.sm2FM>;
this.synthMode = SynthMode.sm2FM;
}
}
}
public ResetC0(chip: Chip): void {
const val = this.regC0;
this.regC0 ^= 0xff;
this.WriteC0(chip, val);
}
// template< bool opl3Mode> void Channel::GeneratePercussion( Chip* chip, Bit32s* output ) {
public GeneratePercussion(opl3Mode: boolean, chip: Chip, output: Int32Array /* Bit32s */, outputOffset: number): void {
//BassDrum
let mod = ((this.old[0] + this.old[1])) >>> this.feedback;
this.old[0] = this.old[1];
this.old[1] = this.Op(0).GetSample(mod);
//When bassdrum is in AM mode first operator is ignoed
if ((this.regC0 & 1) != 0) {
mod = 0;
}
else {
mod = this.old[0];
}
let sample = this.Op(1).GetSample(mod);
//Precalculate stuff used by other outputs
const noiseBit = chip.ForwardNoise() & 0x1;
const c2 = this.Op(2).ForwardWave();
const c5 = this.Op(5).ForwardWave();
const phaseBit = (((c2 & 0x88) ^ ((c2 << 5) & 0x80)) | ((c5 ^ (c5 << 2)) & 0x20)) != 0 ? 0x02 : 0x00;
//Hi-Hat
const hhVol = this.Op(2).ForwardVolume();
if (!((hhVol) >= ((12 * 256) >> (3 - ((9) - 9))))) {
const hhIndex = (phaseBit << 8) | (0x34 << (phaseBit ^ (noiseBit << 1)));
sample += this.Op(2).GetWave(hhIndex, hhVol);
}
//Snare Drum
const sdVol = this.Op(3).ForwardVolume();
if (!((sdVol) >= ((12 * 256) >> (3 - ((9) - 9))))) {
const sdIndex = (0x100 + (c2 & 0x100)) ^ (noiseBit << 8);
sample += this.Op(3).GetWave(sdIndex, sdVol);
}
//Tom-tom
sample += this.Op(4).GetSample(0);
//Top-Cymbal
const tcVol = this.Op(5).ForwardVolume();
if (!((tcVol) >= ((12 * 256) >> (3 - ((9) - 9))))) {
const tcIndex = (1 + phaseBit) << 8;
sample += this.Op(5).GetWave(tcIndex, tcVol);
}
sample <<= 1;
if (opl3Mode) {
output[outputOffset + 0] += sample;
output[outputOffset + 1] += sample;
}
else {
output[outputOffset + 0] += sample;
}
}
/// template<SynthMode mode> Channel* Channel::BlockTemplate( Chip* chip, Bit32u samples, Bit32s* output )
//public BlockTemplate(mode: SynthMode, chip: Chip, samples: number, output: Int32Array /** Bit32s* */): Channel {
public synthHandler(chip: Chip, samples: number, output: Int32Array, outputIndex: number /** Bit32s* */): Channel | null {
const mode = this.synthMode;
switch (mode) {
case SynthMode.sm2AM:
case SynthMode.sm3AM:
if (this.Op(0).Silent() && this.Op(1).Silent()) {
this.old[0] = this.old[1] = 0;
return this.Channel(1);
}
break;
case SynthMode.sm2FM:
case SynthMode.sm3FM:
if (this.Op(1).Silent()) {
this.old[0] = this.old[1] = 0;
return this.Channel(1);
}
break;
case SynthMode.sm3FMFM:
if (this.Op(3).Silent()) {
this.old[0] = this.old[1] = 0;
return this.Channel(2);
}
break;
case SynthMode.sm3AMFM:
if (this.Op(0).Silent() && this.Op(3).Silent()) {
this.old[0] = this.old[1] = 0;
return this.Channel(2);
}
break;
case SynthMode.sm3FMAM:
if (this.Op(1).Silent() && this.Op(3).Silent()) {
this.old[0] = this.old[1] = 0;
return this.Channel(2);
}
break;
case SynthMode.sm3AMAM:
if (this.Op(0).Silent() && this.Op(2).Silent() && this.Op(3).Silent()) {
this.old[0] = this.old[1] = 0;
return this.Channel(2);
}
break;
}
//Init the operators with the the current vibrato and tremolo values
this.Op(0).Prepare(chip);
this.Op(1).Prepare(chip);
if (mode > SynthMode.sm4Start) {
this.Op(2).Prepare(chip);
this.Op(3).Prepare(chip);
}
if (mode > SynthMode.sm6Start) {
this.Op(4).Prepare(chip);
this.Op(5).Prepare(chip);
}
for (let i = 0; i < samples; i++) {
//Early out for percussion handlers
if (mode == SynthMode.sm2Percussion) {
this.GeneratePercussion(false, chip, output, outputIndex + i);
continue;//Prevent some unitialized value bitching
}
else if (mode == SynthMode.sm3Percussion) {
this.GeneratePercussion(true, chip, output, outputIndex + i * 2);
continue;//Prevent some unitialized value bitching
}
//Do unsigned shift so we can shift out all signed long but still stay in 10 bit range otherwise
const mod = ((this.old[0] + this.old[1])) >>> this.feedback;
this.old[0] = this.old[1];
this.old[1] = this.Op(0).GetSample(mod);
let sample = 0;
const out0 = this.old[0];
if (mode == SynthMode.sm2AM || mode == SynthMode.sm3AM) {
sample = out0 + this.Op(1).GetSample(0);
}
else if (mode == SynthMode.sm2FM || mode == SynthMode.sm3FM) {
sample = this.Op(1).GetSample(out0);
}
else if (mode == SynthMode.sm3FMFM) {
let next = this.Op(1).GetSample(out0);
next = this.Op(2).GetSample(next);
sample = this.Op(3).GetSample(next);
}
else if (mode == SynthMode.sm3AMFM) {
sample = out0;
let next = this.Op(1).GetSample(0);
next = this.Op(2).GetSample(next);
sample += this.Op(3).GetSample(next);
}
else if (mode == SynthMode.sm3FMAM) {
sample = this.Op(1).GetSample(out0);
const next = this.Op(2).GetSample(0);
sample += this.Op(3).GetSample(next);
}
else if (mode == SynthMode.sm3AMAM) {
sample = out0;
const next = this.Op(1).GetSample(0);
sample += this.Op(2).GetSample(next);
sample += this.Op(3).GetSample(0);
}
switch (mode) {
case SynthMode.sm2AM:
case SynthMode.sm2FM:
output[outputIndex + i] += sample;
break;
case SynthMode.sm3AM:
case SynthMode.sm3FM:
case SynthMode.sm3FMFM:
case SynthMode.sm3AMFM:
case SynthMode.sm3FMAM:
case SynthMode.sm3AMAM:
output[outputIndex + i * 2 + 0] += sample & this.maskLeft;
output[outputIndex + i * 2 + 1] += sample & this.maskRight;
break;
}
}
switch (mode) {
case SynthMode.sm2AM:
case SynthMode.sm2FM:
case SynthMode.sm3AM:
case SynthMode.sm3FM:
return this.Channel(1);
case SynthMode.sm3FMFM:
case SynthMode.sm3AMFM:
case SynthMode.sm3FMAM:
case SynthMode.sm3AMAM:
return this.Channel(2);
case SynthMode.sm2Percussion:
case SynthMode.sm3Percussion:
return this.Channel(3);
}
return null;
}
public constructor(channels: Channel[], thisChannel: number, operators: Operator[], thisOpIndex: number) {
this.channels = channels;
this.ChannelIndex = thisChannel;
this.operators = operators;
this.thisOpIndex = thisOpIndex;
this.old[0] = this.old[1] = 0 | 0;
this.chanData = 0 | 0;
this.regB0 = 0 | 0;
this.regC0 = 0 | 0;
this.maskLeft = -1 | 0;
this.maskRight = -1 | 0;
this.feedback = 31 | 0;
this.fourMask = 0 | 0;
this.synthMode = SynthMode.sm2FM;
}
} | the_stack |
export =Cesium;
export as namespace Cesium;
declare namespace Cesium {
/**
* @private
*/
export enum BufferUsage {
STREAM_DRAW = WebGLConstants.STREAM_DRAW,
STATIC_DRAW = WebGLConstants.STATIC_DRAW,
DYNAMIC_DRAW = WebGLConstants.DYNAMIC_DRAW
}
/**
* @private
*/
export class Buffer {
constructor(options: {
context: Context
bufferTarget: number
typedArray: ArrayBufferView
sizeInBytes: number
usage: BufferUsage
})
_gl: WebGL2RenderingContext | WebGLRenderingContext
_webgl2: boolean
_bufferTarget: number
_sizeInBytes: number
_usage: BufferUsage
_buffer: WebGLBuffer
vertexArrayDestroyable: boolean
/**
* @readonly
*/
sizeInBytes: number
/**
* @readonly
*/
usage: BufferUsage
_getBuffer: () => WebGLBuffer
copyFromArrayView: (arrayView: ArrayBufferView, offsetInBytes: number) => void
copyFromBuffer: (
readBuffer: Buffer,
readOffset: number,
writeOffset: number,
sizeInBytes: number
) => void
getBufferData: (
arrayView: ArrayBufferView,
sourceOffset: number,
destinationOffset: number,
length: number
) => void
isDestroyed: () => boolean
destroy: () => any
/**
* Creates a vertex buffer, which contains untyped vertex data in GPU-controlled memory.
* <br /><br />
* A vertex array defines the actual makeup of a vertex, e.g., positions, normals, texture coordinates,
* etc., by interpreting the raw data in one or more vertex buffers.
*
* @param {Object} options An object containing the following properties:
* @param {Context} options.context The context in which to create the buffer
* @param {ArrayBufferView} [options.typedArray] A typed array containing the data to copy to the buffer.
* @param {Number} [options.sizeInBytes] A <code>Number</code> defining the size of the buffer in bytes. Required if options.typedArray is not given.
* @param {BufferUsage} options.usage Specifies the expected usage pattern of the buffer. On some GL implementations, this can significantly affect performance. See {@link BufferUsage}.
* @returns {VertexBuffer} The vertex buffer, ready to be attached to a vertex array.
*
* @exception {DeveloperError} Must specify either <options.typedArray> or <options.sizeInBytes>, but not both.
* @exception {DeveloperError} The buffer size must be greater than zero.
* @exception {DeveloperError} Invalid <code>usage</code>.
*
*
* @example
* // Example 1. Create a dynamic vertex buffer 16 bytes in size.
* var buffer = Buffer.createVertexBuffer({
* context : context,
* sizeInBytes : 16,
* usage : BufferUsage.DYNAMIC_DRAW
* });
*
* @example
* // Example 2. Create a dynamic vertex buffer from three floating-point values.
* // The data copied to the vertex buffer is considered raw bytes until it is
* // interpreted as vertices using a vertex array.
* var positionBuffer = buffer.createVertexBuffer({
* context : context,
* typedArray : new Float32Array([0, 0, 0]),
* usage : BufferUsage.STATIC_DRAW
* });
*
* @see {@link https://www.khronos.org/opengles/sdk/docs/man/xhtml/glGenBuffer.xml|glGenBuffer}
* @see {@link https://www.khronos.org/opengles/sdk/docs/man/xhtml/glBindBuffer.xml|glBindBuffer} with <code>ARRAY_BUFFER</code>
* @see {@link https://www.khronos.org/opengles/sdk/docs/man/xhtml/glBufferData.xml|glBufferData} with <code>ARRAY_BUFFER</code>
*/
static createVertexBuffer: (options: {
context: Context
typedArray?: ArrayBufferView
usage: BufferUsage
sizeInBytes?: number
}) => Buffer
/**
* Creates an index buffer, which contains typed indices in GPU-controlled memory.
* <br /><br />
* An index buffer can be attached to a vertex array to select vertices for rendering.
* <code>Context.draw</code> can render using the entire index buffer or a subset
* of the index buffer defined by an offset and count.
*
* @param {Object} options An object containing the following properties:
* @param {Context} options.context The context in which to create the buffer
* @param {ArrayBufferView} [options.typedArray] A typed array containing the data to copy to the buffer.
* @param {Number} [options.sizeInBytes] A <code>Number</code> defining the size of the buffer in bytes. Required if options.typedArray is not given.
* @param {BufferUsage} options.usage Specifies the expected usage pattern of the buffer. On some GL implementations, this can significantly affect performance. See {@link BufferUsage}.
* @param {IndexDatatype} options.indexDatatype The datatype of indices in the buffer.
* @returns {IndexBuffer} The index buffer, ready to be attached to a vertex array.
*
* @exception {DeveloperError} Must specify either <options.typedArray> or <options.sizeInBytes>, but not both.
* @exception {DeveloperError} IndexDatatype.UNSIGNED_INT requires OES_element_index_uint, which is not supported on this system. Check context.elementIndexUint.
* @exception {DeveloperError} The size in bytes must be greater than zero.
* @exception {DeveloperError} Invalid <code>usage</code>.
* @exception {DeveloperError} Invalid <code>indexDatatype</code>.
*
*
* @example
* // Example 1. Create a stream index buffer of unsigned shorts that is
* // 16 bytes in size.
* var buffer = Buffer.createIndexBuffer({
* context : context,
* sizeInBytes : 16,
* usage : BufferUsage.STREAM_DRAW,
* indexDatatype : IndexDatatype.UNSIGNED_SHORT
* });
*
* @example
* // Example 2. Create a static index buffer containing three unsigned shorts.
* var buffer = Buffer.createIndexBuffer({
* context : context,
* typedArray : new Uint16Array([0, 1, 2]),
* usage : BufferUsage.STATIC_DRAW,
* indexDatatype : IndexDatatype.UNSIGNED_SHORT
* });
*
* @see {@link https://www.khronos.org/opengles/sdk/docs/man/xhtml/glGenBuffer.xml|glGenBuffer}
* @see {@link https://www.khronos.org/opengles/sdk/docs/man/xhtml/glBindBuffer.xml|glBindBuffer} with <code>ELEMENT_ARRAY_BUFFER</code>
* @see {@link https://www.khronos.org/opengles/sdk/docs/man/xhtml/glBufferData.xml|glBufferData} with <code>ELEMENT_ARRAY_BUFFER</code>
*/
static createIndexBuffer: (options: {
context: Context
sizeInBytes?: number
usage: BufferUsage
indexDatatype: IndexDatatype
typedArray?: ArrayBufferView
}) => Buffer
}
/**
* The render pass for a command.
*
* @private
*/
export enum Pass {
// If you add/modify/remove Pass constants, also change the automatic GLSL constants
// that start with 'czm_pass'
//
// Commands are executed in order by pass up to the translucent pass.
// Translucent geometry needs special handling (sorting/OIT). The compute pass
// is executed first and the overlay pass is executed last. Both are not sorted
// by frustum.
ENVIRONMENT = 0,
COMPUTE = 1,
GLOBE = 2,
TERRAIN_CLASSIFICATION = 3,
CESIUM_3D_TILE = 4,
CESIUM_3D_TILE_CLASSIFICATION = 5,
CESIUM_3D_TILE_CLASSIFICATION_IGNORE_SHOW = 6,
OPAQUE = 7,
TRANSLUCENT = 8,
OVERLAY = 9,
NUMBER_OF_PASSES = 10
}
/**
* Represents a command to the renderer for clearing a framebuffer.
*
* @private
*/
export class ClearCommand {
constructor(options: {
/**
* The value to clear the color buffer to. When <code>undefined</code>, the color buffer is not cleared.
*
* @type {Color}
*
* @default undefined
*/
color: Color
/**
* The value to clear the depth buffer to. When <code>undefined</code>, the depth buffer is not cleared.
*
* @type {Number}
*
* @default undefined
*/
depth: number
/**
* The value to clear the stencil buffer to. When <code>undefined</code>, the stencil buffer is not cleared.
*
* @type {Number}
*
* @default undefined
*/
stencil: number
/**
* The render state to apply when executing the clear command. The following states affect clearing:
* scissor test, color mask, depth mask, and stencil mask. When the render state is
* <code>undefined</code>, the default render state is used.
*
* @type {RenderState}
*
* @default undefined
*/
renderState: RenderState
/**
* The framebuffer to clear.
*
* @type {Framebuffer}
*
* @default undefined
*/
framebuffer: Framebuffer
/**
* The object who created this command. This is useful for debugging command
* execution; it allows you to see who created a command when you only have a
* reference to the command, and can be used to selectively execute commands
* with {@link Scene#debugCommandFilter}.
*
* @type {Object}
*
* @default undefined
*
* @see Scene#debugCommandFilter
*/
owner: object
/**
* The pass in which to run this command.
*
* @type {Pass}
*
* @default undefined
*/
pass: Pass
})
/**
* The value to clear the color buffer to. When <code>undefined</code>, the color buffer is not cleared.
*
* @type {Color}
*
* @default undefined
*/
color: Color
/**
* The value to clear the depth buffer to. When <code>undefined</code>, the depth buffer is not cleared.
*
* @type {Number}
*
* @default undefined
*/
depth: number
/**
* The value to clear the stencil buffer to. When <code>undefined</code>, the stencil buffer is not cleared.
*
* @type {Number}
*
* @default undefined
*/
stencil: number
/**
* The render state to apply when executing the clear command. The following states affect clearing:
* scissor test, color mask, depth mask, and stencil mask. When the render state is
* <code>undefined</code>, the default render state is used.
*
* @type {RenderState}
*
* @default undefined
*/
renderState: RenderState
/**
* The framebuffer to clear.
*
* @type {Framebuffer}
*
* @default undefined
*/
framebuffer: Framebuffer
/**
* The object who created this command. This is useful for debugging command
* execution; it allows you to see who created a command when you only have a
* reference to the command, and can be used to selectively execute commands
* with {@link Scene#debugCommandFilter}.
*
* @type {Object}
*
* @default undefined
*
* @see Scene#debugCommandFilter
*/
owner: object
/**
* The pass in which to run this command.
*
* @type {Pass}
*
* @default undefined
*/
pass: Pass
/**
* Clears color to (0.0, 0.0, 0.0, 0.0); depth to 1.0; and stencil to 0.
*
* @type {ClearCommand}
*
* @constant
*/
static ALL = ClearCommand
execute(context: Context, passState: PassState): void
}
/**
* @private
*/
export class CubeMap {
constructor(options: {
context: Context
source: {
positiveX: ImageData | HTMLImageElement | HTMLCanvasElement | HTMLVideoElement
negativeX: ImageData | HTMLImageElement | HTMLCanvasElement | HTMLVideoElement
positiveY: ImageData | HTMLImageElement | HTMLCanvasElement | HTMLVideoElement
negativeY: ImageData | HTMLImageElement | HTMLCanvasElement | HTMLVideoElement
positiveZ: ImageData | HTMLImageElement | HTMLCanvasElement | HTMLVideoElement
negativeZ: ImageData | HTMLImageElement | HTMLCanvasElement | HTMLVideoElement
}
pixelFormat?: PixelFormat
pixelDatatype?: PixelDatatype
preMultiplyAlpha?: boolean
width?: number
height?: number
flipY?: boolean
})
_context: Context
positiveX: CubeMapFace
negativeX: CubeMapFace
positiveY: CubeMapFace
negativeY: CubeMapFace
positiveZ: CubeMapFace
negativeZ: CubeMapFace
sampler: Sampler
pixelFormat: PixelFormat
pixelDatatype: number
width: number
height: number
sizeInBytes: number
preMultiplyAlpha: boolean
flipY: boolean
_target: number
/**
* Generates a complete mipmap chain for each cubemap face.
*
* @param {MipmapHint} [hint=MipmapHint.DONT_CARE] A performance vs. quality hint.
*
* @exception {DeveloperError} hint is invalid.
* @exception {DeveloperError} This CubeMap's width must be a power of two to call generateMipmap().
* @exception {DeveloperError} This CubeMap's height must be a power of two to call generateMipmap().
* @exception {DeveloperError} This CubeMap was destroyed, i.e., destroy() was called.
*
* @example
* // Generate mipmaps, and then set the sampler so mipmaps are used for
* // minification when the cube map is sampled.
* cubeMap.generateMipmap();
* cubeMap.sampler = new Sampler({
* minificationFilter : Cesium.TextureMinificationFilter.NEAREST_MIPMAP_LINEAR
* });
*/
generateMipmap(hint): void
isDestroyed(): boolean
destroy(): any
}
/**
* Asynchronously loads six images and creates a cube map. Returns a promise that
* will resolve to a {@link CubeMap} once loaded, or reject if any image fails to load.
*
* @function loadCubeMap
*
* @param {Context} context The context to use to create the cube map.
* @param {Object} urls The source URL of each image. See the example below.
* @returns {Promise.<CubeMap>} a promise that will resolve to the requested {@link CubeMap} when loaded.
*
* @exception {DeveloperError} context is required.
* @exception {DeveloperError} urls is required and must have positiveX, negativeX, positiveY, negativeY, positiveZ, and negativeZ properties.
*
*
* @example
* Cesium.loadCubeMap(context, {
* positiveX : 'skybox_px.png',
* negativeX : 'skybox_nx.png',
* positiveY : 'skybox_py.png',
* negativeY : 'skybox_ny.png',
* positiveZ : 'skybox_pz.png',
* negativeZ : 'skybox_nz.png'
* }).then(function(cubeMap) {
* // use the cubemap
* }).otherwise(function(error) {
* // an error occurred
* });
*
* @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
* @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
*
* @private
*/
export function loadCubeMap(context: Context, urls: string): Promise<CubeMap>
/**
* The state for a particular rendering pass. This is used to supplement the state
* in a command being executed.
*
* @private
* @constructor
*/
export class PassState {
constructor(context)
/**
* The context used to execute commands for this pass.
*
* @type {Context}
*/
context: Context
/**
* The framebuffer to render to. This framebuffer is used unless a {@link DrawCommand}
* or {@link ClearCommand} explicitly define a framebuffer, which is used for off-screen
* rendering.
*
* @type {Framebuffer}
* @default undefined
*/
framebuffer: Framebuffer
/**
* When defined, this overrides the blending property of a {@link DrawCommand}'s render state.
* This is used to, for example, to allow the renderer to turn off blending during the picking pass.
* <p>
* When this is <code>undefined</code>, the {@link DrawCommand}'s property is used.
* </p>
*
* @type {Boolean}
* @default undefined
*/
blendingEnabled: Boolean
/**
* When defined, this overrides the scissor test property of a {@link DrawCommand}'s render state.
* This is used to, for example, to allow the renderer to scissor out the pick region during the picking pass.
* <p>
* When this is <code>undefined</code>, the {@link DrawCommand}'s property is used.
* </p>
*
* @type {Object}
* @default undefined
*/
scissorTest: Object
/**
* The viewport used when one is not defined by a {@link DrawCommand}'s render state.
* @type {BoundingRectangle}
* @default undefined
*/
viewport: BoundingRectangle
}
/**
* @private
*/
interface PickId {
_pickObjects: object
key: string
color: Color
destroy: () => void
}
/**
* @private
*/
interface IRenderState {
frontFace: WindingOrder //= defaultValue(rs.frontFace, WindingOrder.COUNTER_CLOCKWISE);
cull: {
enabled: boolean// defaultValue(cull.enabled, false),
face: CullFace// WebGLConstants.BACK|WebGLConstants.FRONT|WebGLConstants.FRONT_AND_BACK //defaultValue(cull.face, WebGLConstants.BACK),
};
lineWidth: number//= defaultValue(rs.lineWidth, 1.0);
polygonOffset: {
enabled: boolean //defaultValue(polygonOffset.enabled, false),
factor: number // defaultValue(polygonOffset.factor, 0),
units: number// defaultValue(polygonOffset.units, 0),
};
scissorTest: {
enabled: boolean// defaultValue(scissorTest.enabled, false),
rectangle: BoundingRectangle// BoundingRectangle.clone(scissorTestRectangle),
};
depthRange: {
near: number// defaultValue(depthRange.near, 0),
far: number//defaultValue(depthRange.far, 1),
};
depthTest: {
enabled: boolean// defaultValue(depthTest.enabled, false),
func: DepthFunction// WebGLConstants.LESS|WebGLConstants.LEQUAL|WebGLConstants.GREATER|WebGLConstants.GEQUAL //defaultValue(depthTest.func, WebGLConstants.LESS), // func, because function is a JavaScript keyword
};
colorMask: {
red: boolean// defaultValue(colorMask.red, true),
green: boolean//defaultValue(colorMask.green, true),
blue: boolean//defaultValue(colorMask.blue, true),
alpha: boolean//defaultValue(colorMask.alpha, true),
};
depthMask: boolean// defaultValue(rs.depthMask, true);
stencilMask: number// defaultValue(rs.stencilMask, ~0);
blending: {
enabled: boolean// defaultValue(blending.enabled, false),
color: Color
equationRgb: BlendEquation// WebGLConstants.FUNC_ADD|WebGLConstants.FUNC_SUBTRACT|WebGLConstants.FUNC_REVERSE_SUBTRACT //defaultValue(blending.equationRgb, WebGLConstants.FUNC_ADD),
equationAlpha: BlendEquation //WebGLConstants.FUNC_ADD|WebGLConstants.FUNC_SUBTRACT|WebGLConstants.FUNC_REVERSE_SUBTRACT
// defaultValue(
// blending.equationAlpha,
// WebGLConstants.FUNC_ADD
// ),
functionSourceRgb: BlendFunction// WebGLConstants.ONE| WebGLConstants.ZERO| WebGLConstants.ON
// defaultValue(
// blending.functionSourceRgb,
// WebGLConstants.ONE
// ),
functionSourceAlpha: BlendFunction
// defaultValue(
// blending.functionSourceAlpha,
// WebGLConstants.ONE
// ),
functionDestinationRgb: BlendFunction
functionDestinationAlpha: BlendFunction
};
stencilTest: {
enabled: boolean //defaultValue(stencilTest.enabled, false),
frontFunction: StencilFunction
backFunction: StencilFunction //defaultValue(stencilTest.backFunction, WebGLConstants.ALWAYS),
reference: number// defaultValue(stencilTest.reference, 0),
mask: number// defaultValue(stencilTest.mask, ~0),
frontOperation: {
fail: StencilOperation //defaultValue(stencilTestFrontOperation.fail, WebGLConstants.KEEP),
zFail: StencilOperation//defaultValue(stencilTestFrontOperation.zFail, WebGLConstants.KEEP),
zPass: StencilOperation// defaultValue(stencilTestFrontOperation.zPass, WebGLConstants.KEEP),
},
backOperation: {
fail: StencilOperation//defaultValue(stencilTestBackOperation.fail, WebGLConstants.KEEP),
zFail: StencilOperation//defaultValue(stencilTestBackOperation.zFail, WebGLConstants.KEEP),
zPass: StencilOperation//defaultValue(stencilTestBackOperation.zPass, WebGLConstants.KEEP),
},
};
sampleCoverage: {
enabled: boolean// defaultValue(sampleCoverage.enabled, false),
value: number// defaultValue(sampleCoverage.value, 1.0),
invert: boolean// defaultValue(sampleCoverage.invert, false),
};
viewport: {
x: number
y: number
width: number
height: number
}
}
/**
* @private
*/
export class RenderState extends IRenderState {
constructor(renderState: IRenderState)
/**
* Validates and then finds or creates an immutable render state, which defines the pipeline
* state for a {@link DrawCommand} or {@link ClearCommand}. All inputs states are optional. Omitted states
* use the defaults shown in the example below.
*
* @param {Object} [renderState] The states defining the render state as shown in the example below.
*
* @exception {RuntimeError} renderState.lineWidth is out of range.
* @exception {DeveloperError} Invalid renderState.frontFace.
* @exception {DeveloperError} Invalid renderState.cull.face.
* @exception {DeveloperError} scissorTest.rectangle.width and scissorTest.rectangle.height must be greater than or equal to zero.
* @exception {DeveloperError} renderState.depthRange.near can't be greater than renderState.depthRange.far.
* @exception {DeveloperError} renderState.depthRange.near must be greater than or equal to zero.
* @exception {DeveloperError} renderState.depthRange.far must be less than or equal to zero.
* @exception {DeveloperError} Invalid renderState.depthTest.func.
* @exception {DeveloperError} renderState.blending.color components must be greater than or equal to zero and less than or equal to one
* @exception {DeveloperError} Invalid renderState.blending.equationRgb.
* @exception {DeveloperError} Invalid renderState.blending.equationAlpha.
* @exception {DeveloperError} Invalid renderState.blending.functionSourceRgb.
* @exception {DeveloperError} Invalid renderState.blending.functionSourceAlpha.
* @exception {DeveloperError} Invalid renderState.blending.functionDestinationRgb.
* @exception {DeveloperError} Invalid renderState.blending.functionDestinationAlpha.
* @exception {DeveloperError} Invalid renderState.stencilTest.frontFunction.
* @exception {DeveloperError} Invalid renderState.stencilTest.backFunction.
* @exception {DeveloperError} Invalid renderState.stencilTest.frontOperation.fail.
* @exception {DeveloperError} Invalid renderState.stencilTest.frontOperation.zFail.
* @exception {DeveloperError} Invalid renderState.stencilTest.frontOperation.zPass.
* @exception {DeveloperError} Invalid renderState.stencilTest.backOperation.fail.
* @exception {DeveloperError} Invalid renderState.stencilTest.backOperation.zFail.
* @exception {DeveloperError} Invalid renderState.stencilTest.backOperation.zPass.
* @exception {DeveloperError} renderState.viewport.width must be greater than or equal to zero.
* @exception {DeveloperError} renderState.viewport.width must be less than or equal to the maximum viewport width.
* @exception {DeveloperError} renderState.viewport.height must be greater than or equal to zero.
* @exception {DeveloperError} renderState.viewport.height must be less than or equal to the maximum viewport height.
*
*
* @example
* var defaults = {
* frontFace : WindingOrder.COUNTER_CLOCKWISE,
* cull : {
* enabled : false,
* face : CullFace.BACK
* },
* lineWidth : 1,
* polygonOffset : {
* enabled : false,
* factor : 0,
* units : 0
* },
* scissorTest : {
* enabled : false,
* rectangle : {
* x : 0,
* y : 0,
* width : 0,
* height : 0
* }
* },
* depthRange : {
* near : 0,
* far : 1
* },
* depthTest : {
* enabled : false,
* func : DepthFunction.LESS
* },
* colorMask : {
* red : true,
* green : true,
* blue : true,
* alpha : true
* },
* depthMask : true,
* stencilMask : ~0,
* blending : {
* enabled : false,
* color : {
* red : 0.0,
* green : 0.0,
* blue : 0.0,
* alpha : 0.0
* },
* equationRgb : BlendEquation.ADD,
* equationAlpha : BlendEquation.ADD,
* functionSourceRgb : BlendFunction.ONE,
* functionSourceAlpha : BlendFunction.ONE,
* functionDestinationRgb : BlendFunction.ZERO,
* functionDestinationAlpha : BlendFunction.ZERO
* },
* stencilTest : {
* enabled : false,
* frontFunction : StencilFunction.ALWAYS,
* backFunction : StencilFunction.ALWAYS,
* reference : 0,
* mask : ~0,
* frontOperation : {
* fail : StencilOperation.KEEP,
* zFail : StencilOperation.KEEP,
* zPass : StencilOperation.KEEP
* },
* backOperation : {
* fail : StencilOperation.KEEP,
* zFail : StencilOperation.KEEP,
* zPass : StencilOperation.KEEP
* }
* },
* sampleCoverage : {
* enabled : false,
* value : 1.0,
* invert : false
* }
* };
*
* var rs = RenderState.fromCache(defaults);
*
* @see DrawCommand
* @see ClearCommand
*
* @private
*/
static fromCache: (renderState: IRenderState) => RenderState
}
/**
* @private
* @constructor
*/
export class Context {
constructor(canvas: HTMLCanvasElement, options: Object)
isDestroyed: () => void
destroy: () => any
/**
* Creates a unique ID associated with the input object for use with color-buffer picking.
* The ID has an RGBA color value unique to this context. You must call destroy()
* on the pick ID when destroying the input object.
*
* @param {Object} object The object to associate with the pick ID.
* @returns {Object} A PickId object with a <code>color</code> property.
*
* @exception {RuntimeError} Out of unique Pick IDs.
*
*
* @example
* this._pickId = context.createPickId({
* primitive : this,
* id : this.id
* });
*
* @see Context#getObjectByPickColor
*/
createPickId: (object: Object) => Object
/**
* Gets the object associated with a pick color.
*
* @param {Color} pickColor The pick color.
* @returns {Object} The object associated with the pick color, or undefined if no object is associated with that color.
*
* @example
* var object = context.getObjectByPickColor(pickColor);
*
* @see Context#createPickId
*/
getObjectByPickColor: (pickColor: Color) => Object
getViewportQuadVertexArray: () => VertexArray
createViewportQuadCommand: (
fragmentShaderSource: string,
overrides?: {
renderState?: RenderState
uniformMap?: {[key: string]: () => (number | boolean | number[] | Cartesian2 | Cartesian3 | Cartesian4 | Color | Matrix2 | Matrix3 | Matrix4 | Texture | CubeMap)}
owner?: object
framebuffer?: Framebuffer
pass?: Pass
}
) => DrawCommand
readPixels: (readState?: {
x?: number
y?: number
width?: number
height?: number
framebuffer?: Framebuffer;
}) => ArrayBufferView
endFrame: () => void
draw: (drawCommand: DrawCommand, passState: PassState, shaderProgram: ShaderProgram, uniformMap: {[key: string]: () => (number | boolean | number[] | Cartesian2 | Cartesian3 | Cartesian4 | Color | Matrix2 | Matrix3 | Matrix4 | Texture | CubeMap)}) => void
clear: (clearCommand: ClearCommand, passState: PassState) => void
/**
* The number of stencil bits per pixel in the default bound framebuffer. The minimum is eight bits.
* @memberof Context.prototype
* @type {Number}
* @readonly
* @see {@link https://www.khronos.org/opengles/sdk/docs/man/xhtml/glGet.xml|glGet} with <code>STENCIL_BITS</code>.
*/
stencilBits: number
/**
* <code>true</code> if the WebGL context supports stencil buffers.
* Stencil buffers are not supported by all systems.
* @memberof Context.prototype
* @type {Boolean}
* @readonly
*/
stencilBuffer: boolean
/**
* <code>true</code> if the WebGL context supports antialiasing. By default
* antialiasing is requested, but it is not supported by all systems.
* @memberof Context.prototype
* @type {Boolean}
* @readonly
*/
antialias: boolean
/**
* <code>true</code> if the OES_standard_derivatives extension is supported. This
* extension provides access to <code>dFdx</code>, <code>dFdy</code>, and <code>fwidth</code>
* functions from GLSL. A shader using these functions still needs to explicitly enable the
* extension with <code>#extension GL_OES_standard_derivatives : enable</code>.
* @memberof Context.prototype
* @type {Boolean}
* @readonly
* @see {@link http://www.khronos.org/registry/gles/extensions/OES/OES_standard_derivatives.txt|OES_standard_derivatives}
*/
standardDerivatives: boolean
/**
* <code>true</code> if the EXT_float_blend extension is supported. This
* extension enables blending with 32-bit float values.
* @memberof Context.prototype
* @type {Boolean}
* @readonly
* @see {@link https://www.khronos.org/registry/webgl/extensions/EXT_float_blend/}
*/
floatBlend: boolean
/**
* <code>true</code> if the EXT_blend_minmax extension is supported. This
* extension extends blending capabilities by adding two new blend equations:
* the minimum or maximum color components of the source and destination colors.
* @memberof Context.prototype
* @type {Boolean}
* @readonly
* @see {@link https://www.khronos.org/registry/webgl/extensions/EXT_blend_minmax/}
*/
blendMinmax: boolean
/**
* <code>true</code> if the OES_element_index_uint extension is supported. This
* extension allows the use of unsigned int indices, which can improve performance by
* eliminating batch breaking caused by unsigned short indices.
* @memberof Context.prototype
* @type {Boolean}
* @readonly
* @see {@link http://www.khronos.org/registry/webgl/extensions/OES_element_index_uint/|OES_element_index_uint}
*/
elementIndexUint: boolean
/**
* <code>true</code> if WEBGL_depth_texture is supported. This extension provides
* access to depth textures that, for example, can be attached to framebuffers for shadow mapping.
* @memberof Context.prototype
* @type {Boolean}
* @readonly
* @see {@link http://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/|WEBGL_depth_texture}
*/
depthTexture: boolean
/**
* <code>true</code> if OES_texture_float is supported. This extension provides
* access to floating point textures that, for example, can be attached to framebuffers for high dynamic range.
* @memberof Context.prototype
* @type {Boolean}
* @readonly
* @see {@link https://www.khronos.org/registry/webgl/extensions/OES_texture_float/}
*/
floatingPointTexture: boolean
/**
* <code>true</code> if OES_texture_half_float is supported. This extension provides
* access to floating point textures that, for example, can be attached to framebuffers for high dynamic range.
* @memberof Context.prototype
* @type {Boolean}
* @readonly
* @see {@link https://www.khronos.org/registry/webgl/extensions/OES_texture_float/}
*/
halfFloatingPointTexture: boolean
/**
* <code>true</code> if OES_texture_float_linear is supported. This extension provides
* access to linear sampling methods for minification and magnification filters of floating-point textures.
* @memberof Context.prototype
* @type {Boolean}
* @readonly
* @see {@link https://www.khronos.org/registry/webgl/extensions/OES_texture_float_linear/}
*/
textureFloatLinear: boolean
/**
* <code>true</code> if OES_texture_half_float_linear is supported. This extension provides
* access to linear sampling methods for minification and magnification filters of half floating-point textures.
* @memberof Context.prototype
* @type {Boolean}
* @readonly
* @see {@link https://www.khronos.org/registry/webgl/extensions/OES_texture_half_float_linear/}
*/
textureHalfFloatLinear: boolean
/**
* <code>true</code> if EXT_texture_filter_anisotropic is supported. This extension provides
* access to anisotropic filtering for textured surfaces at an oblique angle from the viewer.
* @memberof Context.prototype
* @type {Boolean}
* @readonly
* @see {@link https://www.khronos.org/registry/webgl/extensions/EXT_texture_filter_anisotropic/}
*/
textureFilterAnisotropic: boolean
/**
* <code>true</code> if WEBGL_texture_compression_s3tc is supported. This extension provides
* access to DXT compressed textures.
* @memberof Context.prototype
* @type {Boolean}
* @readonly
* @see {@link https://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_s3tc/}
*/
s3tc: boolean
/**
* <code>true</code> if WEBGL_texture_compression_pvrtc is supported. This extension provides
* access to PVR compressed textures.
* @memberof Context.prototype
* @type {Boolean}
* @readonly
* @see {@link https://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_pvrtc/}
*/
pvrtc: boolean
/**
* <code>true</code> if WEBGL_texture_compression_etc1 is supported. This extension provides
* access to ETC1 compressed textures.
* @memberof Context.prototype
* @type {Boolean}
* @readonly
* @see {@link https://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_etc1/}
*/
etc1: boolean
/**
* <code>true</code> if the OES_vertex_array_object extension is supported. This
* extension can improve performance by reducing the overhead of switching vertex arrays.
* When enabled, this extension is automatically used by {@link VertexArray}.
* @memberof Context.prototype
* @type {Boolean}
* @readonly
* @see {@link http://www.khronos.org/registry/webgl/extensions/OES_vertex_array_object/|OES_vertex_array_object}
*/
vertexArrayObject: boolean
/**
* <code>true</code> if the EXT_frag_depth extension is supported. This
* extension provides access to the <code>gl_FragDepthEXT</code> built-in output variable
* from GLSL fragment shaders. A shader using these functions still needs to explicitly enable the
* extension with <code>#extension GL_EXT_frag_depth : enable</code>.
* @memberof Context.prototype
* @type {Boolean}
* @readonly
* @see {@link http://www.khronos.org/registry/webgl/extensions/EXT_frag_depth/|EXT_frag_depth}
*/
fragmentDepth: boolean
/**
* <code>true</code> if the ANGLE_instanced_arrays extension is supported. This
* extension provides access to instanced rendering.
* @memberof Context.prototype
* @type {Boolean}
* @readonly
* @see {@link https://www.khronos.org/registry/webgl/extensions/ANGLE_instanced_arrays}
*/
instancedArrays: boolean
/**
* <code>true</code> if the EXT_color_buffer_float extension is supported. This
* extension makes the gl.RGBA32F format color renderable.
* @memberof Context.prototype
* @type {Boolean}
* @readonly
* @see {@link https://www.khronos.org/registry/webgl/extensions/WEBGL_color_buffer_float/}
* @see {@link https://www.khronos.org/registry/webgl/extensions/EXT_color_buffer_float/}
*/
colorBufferFloat: boolean
/**
* <code>true</code> if the EXT_color_buffer_half_float extension is supported. This
* extension makes the format gl.RGBA16F format color renderable.
* @memberof Context.prototype
* @type {Boolean}
* @readonly
* @see {@link https://www.khronos.org/registry/webgl/extensions/EXT_color_buffer_half_float/}
* @see {@link https://www.khronos.org/registry/webgl/extensions/EXT_color_buffer_float/}
*/
colorBufferHalfFloat: boolean
/**
* <code>true</code> if the WEBGL_draw_buffers extension is supported. This
* extensions provides support for multiple render targets. The framebuffer object can have mutiple
* color attachments and the GLSL fragment shader can write to the built-in output array <code>gl_FragData</code>.
* A shader using this feature needs to explicitly enable the extension with
* <code>#extension GL_EXT_draw_buffers : enable</code>.
* @memberof Context.prototype
* @type {Boolean}
* @readonly
* @see {@link http://www.khronos.org/registry/webgl/extensions/WEBGL_draw_buffers/|WEBGL_draw_buffers}
*/
drawBuffers: boolean
/**
* A 1x1 RGBA texture initialized to [255, 255, 255, 255]. This can
* be used as a placeholder texture while other textures are downloaded.
* @memberof Context.prototype
* @type {Texture}
* @readonly
*/
defaultTexture: Texture
/**
* A cube map, where each face is a 1x1 RGBA texture initialized to
* [255, 255, 255, 255]. This can be used as a placeholder cube map while
* other cube maps are downloaded.
* @memberof Context.prototype
* @type {CubeMap}
* @readonly
*/
defaultCubeMap: CubeMap
/**
* The drawingBufferHeight of the underlying GL context.
* @memberof Context.prototype
* @type {Number}
* @readonly
* @see {@link https://www.khronos.org/registry/webgl/specs/1.0/#DOM-WebGLRenderingContext-drawingBufferHeight|drawingBufferHeight}
*/
drawingBufferHeight: number
/**
* The drawingBufferWidth of the underlying GL context.
* @memberof Context.prototype
* @type {Number}
* @readonly
* @see {@link https://www.khronos.org/registry/webgl/specs/1.0/#DOM-WebGLRenderingContext-drawingBufferWidth|drawingBufferWidth}
*/
drawingBufferWidth: number
/**
* Gets an object representing the currently bound framebuffer. While this instance is not an actual
* {@link Framebuffer}, it is used to represent the default framebuffer in calls to
* {@link Texture.fromFramebuffer}.
* @memberof Context.prototype
* @type {Object}
* @readonly
*/
defaultFramebuffer: Framebuffer
}
/**
* @private
*/
interface VertexArrayAttribute {
index: number
vertexBuffer: Buffer
componentsPerAttribute: number
componentDatatype: ComponentDatatype
/**
* @default false
*/
normalize?: boolean
/**
* @default 0
*/
offsetInBytes?: number
/**
* @default 0
*/
strideInBytes?: number
/**
* @default 0
*/
instanceDivisor?: number
}
/**
* Creates a vertex array, which defines the attributes making up a vertex, and contains an optional index buffer
* to select vertices for rendering. Attributes are defined using object literals as shown in Example 1 below.
*
* @param {Object} options Object with the following properties:
* @param {Context} options.context The context in which the VertexArray gets created.
* @param {Object[]} options.attributes An array of attributes.
* @param {IndexBuffer} [options.indexBuffer] An optional index buffer.
*
* @returns {VertexArray} The vertex array, ready for use with drawing.
*
* @exception {DeveloperError} Attribute must have a <code>vertexBuffer</code>.
* @exception {DeveloperError} Attribute must have a <code>componentsPerAttribute</code>.
* @exception {DeveloperError} Attribute must have a valid <code>componentDatatype</code> or not specify it.
* @exception {DeveloperError} Attribute must have a <code>strideInBytes</code> less than or equal to 255 or not specify it.
* @exception {DeveloperError} Index n is used by more than one attribute.
*
*
* @example
* // Example 1. Create a vertex array with vertices made up of three floating point
* // values, e.g., a position, from a single vertex buffer. No index buffer is used.
* var positionBuffer = Buffer.createVertexBuffer({
* context : context,
* sizeInBytes : 12,
* usage : BufferUsage.STATIC_DRAW
* });
* var attributes = [
* {
* index : 0,
* enabled : true,
* vertexBuffer : positionBuffer,
* componentsPerAttribute : 3,
* componentDatatype : ComponentDatatype.FLOAT,
* normalize : false,
* offsetInBytes : 0,
* strideInBytes : 0 // tightly packed
* instanceDivisor : 0 // not instanced
* }
* ];
* var va = new VertexArray({
* context : context,
* attributes : attributes
* });
*
* @example
* // Example 2. Create a vertex array with vertices from two different vertex buffers.
* // Each vertex has a three-component position and three-component normal.
* var positionBuffer = Buffer.createVertexBuffer({
* context : context,
* sizeInBytes : 12,
* usage : BufferUsage.STATIC_DRAW
* });
* var normalBuffer = Buffer.createVertexBuffer({
* context : context,
* sizeInBytes : 12,
* usage : BufferUsage.STATIC_DRAW
* });
* var attributes = [
* {
* index : 0,
* vertexBuffer : positionBuffer,
* componentsPerAttribute : 3,
* componentDatatype : ComponentDatatype.FLOAT
* },
* {
* index : 1,
* vertexBuffer : normalBuffer,
* componentsPerAttribute : 3,
* componentDatatype : ComponentDatatype.FLOAT
* }
* ];
* var va = new VertexArray({
* context : context,
* attributes : attributes
* });
*
* @example
* // Example 3. Creates the same vertex layout as Example 2 using a single
* // vertex buffer, instead of two.
* var buffer = Buffer.createVertexBuffer({
* context : context,
* sizeInBytes : 24,
* usage : BufferUsage.STATIC_DRAW
* });
* var attributes = [
* {
* vertexBuffer : buffer,
* componentsPerAttribute : 3,
* componentDatatype : ComponentDatatype.FLOAT,
* offsetInBytes : 0,
* strideInBytes : 24
* },
* {
* vertexBuffer : buffer,
* componentsPerAttribute : 3,
* componentDatatype : ComponentDatatype.FLOAT,
* normalize : true,
* offsetInBytes : 12,
* strideInBytes : 24
* }
* ];
* var va = new VertexArray({
* context : context,
* attributes : attributes
* });
*
* @see Buffer#createVertexBuffer
* @see Buffer#createIndexBuffer
* @see Context#draw
*
* @private
*/
export class VertexArray {
constructor(options: {
/**
* The context in which the VertexArray gets created.
*/
context: Context
/**
* An array of attributes.
*/
attributes: VertexArrayAttribute[]
/**
* An optional index buffer.
*/
indexBuffer: IndexBuffer
})
/**
* @readonly
*/
numberOfAttributes: number
/**
* @readonly
*/
numberOfVertices: number
/**
* @readonly
*/
indexBuffer: Buffer
_bind: () => void
_unBind: () => void
isDestroyed: () => boolean
destroy: () => void
/**
* Creates a vertex array from a geometry. A geometry contains vertex attributes and optional index data
* in system memory, whereas a vertex array contains vertex buffers and an optional index buffer in WebGL
* memory for use with rendering.
* <br /><br />
* The <code>geometry</code> argument should use the standard layout like the geometry returned by {@link BoxGeometry}.
* <br /><br />
* <code>options</code> can have four properties:
* <ul>
* <li><code>geometry</code>: The source geometry containing data used to create the vertex array.</li>
* <li><code>attributeLocations</code>: An object that maps geometry attribute names to vertex shader attribute locations.</li>
* <li><code>bufferUsage</code>: The expected usage pattern of the vertex array's buffers. On some WebGL implementations, this can significantly affect performance. See {@link BufferUsage}. Default: <code>BufferUsage.DYNAMIC_DRAW</code>.</li>
* <li><code>interleave</code>: Determines if all attributes are interleaved in a single vertex buffer or if each attribute is stored in a separate vertex buffer. Default: <code>false</code>.</li>
* </ul>
* <br />
* If <code>options</code> is not specified or the <code>geometry</code> contains no data, the returned vertex array is empty.
*
* @param {Object} options An object defining the geometry, attribute indices, buffer usage, and vertex layout used to create the vertex array.
*
* @exception {RuntimeError} Each attribute list must have the same number of vertices.
* @exception {DeveloperError} The geometry must have zero or one index lists.
* @exception {DeveloperError} Index n is used by more than one attribute.
*
*
* @example
* // Example 1. Creates a vertex array for rendering a box. The default dynamic draw
* // usage is used for the created vertex and index buffer. The attributes are not
* // interleaved by default.
* var geometry = new BoxGeometry();
* var va = VertexArray.fromGeometry({
* context : context,
* geometry : geometry,
* attributeLocations : GeometryPipeline.createAttributeLocations(geometry),
* });
*
* @example
* // Example 2. Creates a vertex array with interleaved attributes in a
* // single vertex buffer. The vertex and index buffer have static draw usage.
* var va = VertexArray.fromGeometry({
* context : context,
* geometry : geometry,
* attributeLocations : GeometryPipeline.createAttributeLocations(geometry),
* bufferUsage : BufferUsage.STATIC_DRAW,
* interleave : true
* });
*
* @example
* // Example 3. When the caller destroys the vertex array, it also destroys the
* // attached vertex buffer(s) and index buffer.
* va = va.destroy();
*
* @see Buffer#createVertexBuffer
* @see Buffer#createIndexBuffer
* @see GeometryPipeline.createAttributeLocations
* @see ShaderProgram
*/
static fromGeometry: (options: {
context: Context
geometry: Geometry
attributeLocations: { [key: string]: number }
bufferUsage?: BufferUsage
interleave?: boolean
vertexArrayAttributes?: VertexArrayAttribute[]
}) => VertexArray
}
/**
* An object containing various inputs that will be combined to form a final GLSL shader string.
*
* @param {Object} [options] Object with the following properties:
* @param {String[]} [options.sources] An array of strings to combine containing GLSL code for the shader.
* @param {String[]} [options.defines] An array of strings containing GLSL identifiers to <code>#define</code>.
* @param {String} [options.pickColorQualifier] The GLSL qualifier, <code>uniform</code> or <code>varying</code>, for the input <code>czm_pickColor</code>. When defined, a pick fragment shader is generated.
* @param {Boolean} [options.includeBuiltIns=true] If true, referenced built-in functions will be included with the combined shader. Set to false if this shader will become a source in another shader, to avoid duplicating functions.
*
* @exception {DeveloperError} options.pickColorQualifier must be 'uniform' or 'varying'.
*
* @example
* // 1. Prepend #defines to a shader
* var source = new Cesium.ShaderSource({
* defines : ['WHITE'],
* sources : ['void main() { \n#ifdef WHITE\n gl_FragColor = vec4(1.0); \n#else\n gl_FragColor = vec4(0.0); \n#endif\n }']
* });
*
* // 2. Modify a fragment shader for picking
* var source = new Cesium.ShaderSource({
* sources : ['void main() { gl_FragColor = vec4(1.0); }'],
* pickColorQualifier : 'uniform'
* });
*
* @private
*/
export class ShaderSource {
constructor(options?: {
defines?: string[]
sources?: string[]
pickColorQualifier?: string
includeBuiltIns?: boolean
})
clone(): ShaderSource
/**
* Create a single string containing the full, combined vertex shader with all dependencies and defines.
*
* @param {Context} context The current rendering context
*
* @returns {String} The combined shader string.
*/
createCombinedVertexShader(context: Context): String
/**
* Create a single string containing the full, combined fragment shader with all dependencies and defines.
*
* @param {Context} context The current rendering context
*
* @returns {String} The combined shader string.
*/
createCombinedFragmentShader(context: Context): string
static replaceMain(source, renamedMain): string
/**
* For ShaderProgram testing
* @private
*/
static _czmBuiltinsAndUniforms = {};
static createPickVertexShaderSource(vertexShaderSource: string): string
static createPickFragmentShaderSource(
fragmentShaderSource: string,
pickColorQualifier: string
): string
static findVarying: (shaderSource: ShaderSource, names: string[]) => string
static findNormalVarying: (shaderSource: ShaderSource) => string
static findPositionVarying: (shaderSource: ShaderSource) => string
}
/**
* @private
*/
export class ShaderProgram {
constructor(options: {
vertexShaderText: string
fragmentShaderText: string
attributeLocations: { [key: string]: number }
logShaderCompilation?: boolean
debugShaders?: boolean
vertexShaderSource?: ShaderSource
duplicateUniformNames?: { [key: string]: string }
fragmentShaderSource?: ShaderSource
})
/**
*
*/
static fromCache: (options: {
/**
* The GLSL source for the vertex shader.
*/
vertexShaderSource: String | ShaderSource
/**
* The GLSL source for the fragment shader.
*/
fragmentShaderSource: String | ShaderSource
/**
* Indices for the attribute inputs to the vertex shader.
*/
attributeLocations: { [key: string]: number }
}) => ShaderProgram
static replaceCache: (options: {
/**
* The shader program that is being reassigned.
*/
shaderProgram: ShaderProgram;
/**
* The GLSL source for the vertex shader.
*/
vertexShaderSource: String | ShaderSource
/**
* The GLSL source for the fragment shader.
*/
fragmentShaderSource: String | ShaderSource
/**
* Indices for the attribute inputs to the vertex shader.
*/
attributeLocations: { [key: string]: number }
}) => ShaderProgram
/**
* GLSL source for the shader program's vertex shader.
* @memberof ShaderProgram.prototype
*
* @type {ShaderSource}
* @readonly
*/
vertexShaderSource: ShaderSource
/**
* GLSL source for the shader program's fragment shader.
* @memberof ShaderProgram.prototype
*
* @type {ShaderSource}
* @readonly
*/
fragmentShaderSource: ShaderSource
/**
* @readonly
*/
vertexAttributes: {
[key: string]: {
name: string
type: number
index: number
}
}
/**
* @readonly
*/
numberOfVertexAttributes: number
/**
* @readonly
*/
allUniforms: string[]
}
/**
* @private
*/
export enum TextureWrap {
CLAMP_TO_EDGE = WebGLConstants.CLAMP_TO_EDGE,
REPEAT = WebGLConstants.REPEAT,
MIRRORED_REPEAT = WebGLConstants.MIRRORED_REPEAT
}
/**
* @private
*/
export class Sampler {
constructor(options: {
wrapS: TextureWrap
wrapT: TextureWrap
minificationFilter: TextureMinificationFilter
magnificationFilter: TextureMagnificationFilter
maximumAnisotropy?: number
})
/**
* @readonly
*/
wrapS: TextureWrap
/**
* @readonly
*/
wrapT: TextureWrap
/**
* @readonly
*/
minificationFilter: TextureMinificationFilter
/**
* @readonly
*/
magnificationFilter: TextureMagnificationFilter
/**
* @readonly
*/
maximumAnisotropy: number
static equals(left: Sampler, right: Sampler): boolean
static NEAREST: Sampler
}
/**
* @private
*/
export class Texture {
constructor(options: {
context: Context
width: number
height: number
source?: ImageData | HTMLImageElement | HTMLCanvasElement | HTMLVideoElement
pixelFormat?: PixelFormat
pixelDatatype?: PixelDatatype
preMultiplyAlpha?: boolean
sampler?: Sampler
})
/**
* This function is identical to using the Texture constructor except that it can be
* replaced with a mock/spy in tests.
* @private
*/
static create(options: {
context: Context
width: number
height: number
source?: ImageData | HTMLImageElement | HTMLCanvasElement | HTMLVideoElement
pixelFormat?: PixelFormat
pixelDatatype?: PixelDatatype
preMultiplyAlpha?: boolean
sampler?: Sampler
}): Texture
/**
* Creates a texture, and copies a subimage of the framebuffer to it. When called without arguments,
* the texture is the same width and height as the framebuffer and contains its contents.
*
* @param {Object} options Object with the following properties:
* @param {Context} options.context The context in which the Texture gets created.
* @param {PixelFormat} [options.pixelFormat=PixelFormat.RGB] The texture's internal pixel format.
* @param {Number} [options.framebufferXOffset=0] An offset in the x direction in the framebuffer where copying begins from.
* @param {Number} [options.framebufferYOffset=0] An offset in the y direction in the framebuffer where copying begins from.
* @param {Number} [options.width=canvas.clientWidth] The width of the texture in texels.
* @param {Number} [options.height=canvas.clientHeight] The height of the texture in texels.
* @param {Framebuffer} [options.framebuffer=defaultFramebuffer] The framebuffer from which to create the texture. If this
* parameter is not specified, the default framebuffer is used.
* @returns {Texture} A texture with contents from the framebuffer.
*
* @exception {DeveloperError} Invalid pixelFormat.
* @exception {DeveloperError} pixelFormat cannot be DEPTH_COMPONENT, DEPTH_STENCIL or a compressed format.
* @exception {DeveloperError} framebufferXOffset must be greater than or equal to zero.
* @exception {DeveloperError} framebufferYOffset must be greater than or equal to zero.
* @exception {DeveloperError} framebufferXOffset + width must be less than or equal to canvas.clientWidth.
* @exception {DeveloperError} framebufferYOffset + height must be less than or equal to canvas.clientHeight.
*
*
* @example
* // Create a texture with the contents of the framebuffer.
* var t = Texture.fromFramebuffer({
* context : context
* });
*
* @see Sampler
*
* @private
*/
fromFramebuffer(options: {
context: Context
pixelFormat?: PixelFormat.RGB
framebufferXOffset?: number
framebufferYOffset?: number
width?: number
height?: number
framebuffer?: Framebuffer
}): Texture
/**
* A unique id for the texture
* @memberof Texture.prototype
* @type {String}
* @readonly
* @private
*/
id: string
/**
* The sampler to use when sampling this texture.
* Create a sampler by calling {@link Sampler}. If this
* parameter is not specified, a default sampler is used. The default sampler clamps texture
* coordinates in both directions, uses linear filtering for both magnification and minification,
* and uses a maximum anisotropy of 1.0.
* @memberof Texture.prototype
* @type {Object}
*/
sampler: Object | Sampler
/**
* @readonly
*/
pixelFormat: PixelFormat
/**
* @readonly
*/
pixelDatatype: PixelDatatype
/**
* @readonly
*/
dimensions: Cartesian2
/**
* @readonly
*/
preMultiplyAlpha: boolean
/**
* @readonly
*/
flipY: boolean
/**
* @readonly
*/
width: number
/**
* @readonly
*/
height: number
/**
* @readonly
*/
sizeInBytes: number
/**
* @readonly
*/
_target: number
/**
* Copy new image data into this texture, from a source {@link ImageData}, {@link HTMLImageElement}, {@link HTMLCanvasElement}, or {@link HTMLVideoElement}.
* or an object with width, height, and arrayBufferView properties.
*
* @param {Object} source The source {@link ImageData}, {@link HTMLImageElement}, {@link HTMLCanvasElement}, or {@link HTMLVideoElement},
* or an object with width, height, and arrayBufferView properties.
* @param {Number} [xOffset=0] The offset in the x direction within the texture to copy into.
* @param {Number} [yOffset=0] The offset in the y direction within the texture to copy into.
*
* @exception {DeveloperError} Cannot call copyFrom when the texture pixel format is DEPTH_COMPONENT or DEPTH_STENCIL.
* @exception {DeveloperError} Cannot call copyFrom with a compressed texture pixel format.
* @exception {DeveloperError} xOffset must be greater than or equal to zero.
* @exception {DeveloperError} yOffset must be greater than or equal to zero.
* @exception {DeveloperError} xOffset + source.width must be less than or equal to width.
* @exception {DeveloperError} yOffset + source.height must be less than or equal to height.
* @exception {DeveloperError} This texture was destroyed, i.e., destroy() was called.
*
* @example
* texture.copyFrom({
* width : 1,
* height : 1,
* arrayBufferView : new Uint8Array([255, 0, 0, 255])
* });
*/
copyFrom(source: ImageData | HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, xOffset?: number, yOffset?: number): void
/**
* @param {Number} [xOffset=0] The offset in the x direction within the texture to copy into.
* @param {Number} [yOffset=0] The offset in the y direction within the texture to copy into.
* @param {Number} [framebufferXOffset=0] optional
* @param {Number} [framebufferYOffset=0] optional
* @param {Number} [width=width] optional
* @param {Number} [height=height] optional
*
* @exception {DeveloperError} Cannot call copyFromFramebuffer when the texture pixel format is DEPTH_COMPONENT or DEPTH_STENCIL.
* @exception {DeveloperError} Cannot call copyFromFramebuffer when the texture pixel data type is FLOAT.
* @exception {DeveloperError} Cannot call copyFromFramebuffer when the texture pixel data type is HALF_FLOAT.
* @exception {DeveloperError} Cannot call copyFrom with a compressed texture pixel format.
* @exception {DeveloperError} This texture was destroyed, i.e., destroy() was called.
* @exception {DeveloperError} xOffset must be greater than or equal to zero.
* @exception {DeveloperError} yOffset must be greater than or equal to zero.
* @exception {DeveloperError} framebufferXOffset must be greater than or equal to zero.
* @exception {DeveloperError} framebufferYOffset must be greater than or equal to zero.
* @exception {DeveloperError} xOffset + width must be less than or equal to width.
* @exception {DeveloperError} yOffset + height must be less than or equal to height.
*/
copyFromFramebuffer(
xOffset: number,
yOffset: number,
framebufferXOffset: number,
framebufferYOffset: number,
width: number,
height: number
): void
/**
* @param {MipmapHint} [hint=MipmapHint.DONT_CARE] optional.
*
* @exception {DeveloperError} Cannot call generateMipmap when the texture pixel format is DEPTH_COMPONENT or DEPTH_STENCIL.
* @exception {DeveloperError} Cannot call generateMipmap when the texture pixel format is a compressed format.
* @exception {DeveloperError} hint is invalid.
* @exception {DeveloperError} This texture's width must be a power of two to call generateMipmap().
* @exception {DeveloperError} This texture's height must be a power of two to call generateMipmap().
* @exception {DeveloperError} This texture was destroyed, i.e., destroy() was called.
*/
generateMipmap(hint: MipmapHint): void
isDestroyed(): boolean
destroy(): any
}
/**
* @private
*/
export enum RenderbufferFormat {
RGBA4 = WebGLConstants.RGBA4,
RGB5_A1 = WebGLConstants.RGB5_A1,
RGB565 = WebGLConstants.RGB565,
DEPTH_COMPONENT16 = WebGLConstants.DEPTH_COMPONENT16,
STENCIL_INDEX8 = WebGLConstants.STENCIL_INDEX8,
DEPTH_STENCIL = WebGLConstants.DEPTH_STENCIL,
}
/**
* @private
*/
export class Renderbuffer {
constructor(options: {
context: Context
format: RenderbufferFormat
width: number
height: number
})
_gl: WebGL2RenderingContext | WebGLRenderingContext
_format: RenderbufferFormat
_width: number
_height: number
_renderbuffer: WebGLRenderbuffer
/**
* @readonly
*/
format: RenderbufferFormat
/**
* @readonly
*/
width: number
/**
* @readonly
*/
height: number
_getRenderbuffer(): WebGLRenderbuffer
isDestroyed(): boolean
destroy(): void
}
/**
* Creates a framebuffer with optional initial color, depth, and stencil attachments.
* Framebuffers are used for render-to-texture effects; they allow us to render to
* textures in one pass, and read from it in a later pass.
*
* @param {Object} options The initial framebuffer attachments as shown in the example below. <code>context</code> is required. The possible properties are <code>colorTextures</code>, <code>colorRenderbuffers</code>, <code>depthTexture</code>, <code>depthRenderbuffer</code>, <code>stencilRenderbuffer</code>, <code>depthStencilTexture</code>, and <code>depthStencilRenderbuffer</code>.
*
* @exception {DeveloperError} Cannot have both color texture and color renderbuffer attachments.
* @exception {DeveloperError} Cannot have both a depth texture and depth renderbuffer attachment.
* @exception {DeveloperError} Cannot have both a depth-stencil texture and depth-stencil renderbuffer attachment.
* @exception {DeveloperError} Cannot have both a depth and depth-stencil renderbuffer.
* @exception {DeveloperError} Cannot have both a stencil and depth-stencil renderbuffer.
* @exception {DeveloperError} Cannot have both a depth and stencil renderbuffer.
* @exception {DeveloperError} The color-texture pixel-format must be a color format.
* @exception {DeveloperError} The depth-texture pixel-format must be DEPTH_COMPONENT.
* @exception {DeveloperError} The depth-stencil-texture pixel-format must be DEPTH_STENCIL.
* @exception {DeveloperError} The number of color attachments exceeds the number supported.
* @exception {DeveloperError} The color-texture pixel datatype is HALF_FLOAT and the WebGL implementation does not support the EXT_color_buffer_half_float extension.
* @exception {DeveloperError} The color-texture pixel datatype is FLOAT and the WebGL implementation does not support the EXT_color_buffer_float or WEBGL_color_buffer_float extensions.
*
* @example
* // Create a framebuffer with color and depth texture attachments.
* var width = context.canvas.clientWidth;
* var height = context.canvas.clientHeight;
* var framebuffer = new Framebuffer({
* context : context,
* colorTextures : [new Texture({
* context : context,
* width : width,
* height : height,
* pixelFormat : PixelFormat.RGBA
* })],
* depthTexture : new Texture({
* context : context,
* width : width,
* height : height,
* pixelFormat : PixelFormat.DEPTH_COMPONENT,
* pixelDatatype : PixelDatatype.UNSIGNED_SHORT
* })
* });
*
* @private
* @constructor
*/
export class Framebuffer {
constructor(options: {
context: Context
colorTextures: Texture[]
colorRenderbuffers?: Renderbuffer[]
depthTexture: Texture
depthRenderbuffer: Renderbuffer
/**
* @default true
*/
destroyAttachments?: boolean
depthStencilTexture?: Texture
depthStencilRenderbuffer?: Renderbuffer
})
/**
* The status of the framebuffer. If the status is not WebGLConstants.FRAMEBUFFER_COMPLETE,
* a {@link DeveloperError} will be thrown when attempting to render to the framebuffer.
* @memberof Framebuffer.prototype
* @type {Number}
* @readonly
*/
status: number
/**
* @readonly
*/
numberOfColorAttachments: number
/**
* @readonly
*/
depthTexture: Texture
/**
* @readonly
*/
depthRenderbuffer: Renderbuffer
/**
* @readonly
*/
stencilRenderbuffer: Renderbuffer
/**
* @readonly
*/
depthStencilTexture: Texture
/**
* @readonly
*/
depthStencilRenderbuffer: Renderbuffer
/**
* True if the framebuffer has a depth attachment. Depth attachments include
* depth and depth-stencil textures, and depth and depth-stencil renderbuffers. When
* rendering to a framebuffer, a depth attachment is required for the depth test to have effect.
* @memberof Framebuffer.prototype
* @type {Boolean}
* @readonly
*/
hasDepthAttachment: boolean
_bind(): void
_unBind(): void
_getActiveColorAttachments(): void
getColorTexture(index): Texture
getColorRenderbuffer(index): Renderbuffer
isDestroyed(): boolean
destroy(): any
}
/**
* Represents a command to the renderer for drawing.
*
* @private
*/
export class DrawCommand {
constructor(options: {
modelMatrix: Matrix4
vertexArray: VertexArray
shaderProgram: ShaderProgram
uniformMap: {[key: string]: () => (number | boolean | number[] | Cartesian2 | Cartesian3 | Cartesian4 | Color | Matrix2 | Matrix3 | Matrix4 | Texture | CubeMap)}
renderState: RenderState
/**
* @default PrimitiveType.TRIANGLES
*/
primitiveType?: PrimitiveType
owner?: object
instanceCount?: number
framebuffer?: Framebuffer
/**
* @default false
*/
castShadows?: boolean
/**
* @default false
*/
receiveShadows?: boolean
pickId: Object
/**
* @default false
*/
pickOnly?: boolean
boundingVolume?: BoundingSphere | AxisAlignedBoundingBox
orientedBoundingBox?: OrientedBoundingBox
/**
* @default true
*/
cull?: boolean
/**
* @default true
*/
occlude?: boolean
executeInClosestFrustum?: boolean
pass?: Pass
count?: number
debugShowBoundingVolume?: boolean
})
/**
* Executes the draw command.
*
* @param {Context} context The renderer context in which to draw.
* @param {PassState} [passState] The state for the current render pass.
*/
execute: (context: Context, passState: PassState) => void
/**
* @private
*/
static shallowClone: (command: DrawCommand, result?: DrawCommand) => DrawCommand
/**
* The bounding volume of the geometry in world space. This is used for culling and frustum selection.
* <p>
* For best rendering performance, use the tightest possible bounding volume. Although
* <code>undefined</code> is allowed, always try to provide a bounding volume to
* allow the tightest possible near and far planes to be computed for the scene, and
* minimize the number of frustums needed.
* </p>
*
* @memberof DrawCommand.prototype
* @type {Object}
* @default undefined
*
* @see DrawCommand#debugShowBoundingVolume
*/
boundingVolume: Object
/**
* The oriented bounding box of the geometry in world space. If this is defined, it is used instead of
* {@link DrawCommand#boundingVolume} for plane intersection testing.
*
* @memberof DrawCommand.prototype
* @type {OrientedBoundingBox}
* @default undefined
*
* @see DrawCommand#debugShowBoundingVolume
*/
orientedBoundingBox: OrientedBoundingBox
/**
* When <code>true</code>, the renderer frustum and horizon culls the command based on its {@link DrawCommand#boundingVolume}.
* If the command was already culled, set this to <code>false</code> for a performance improvement.
*
* @memberof DrawCommand.prototype
* @type {Boolean}
* @default true
*/
cull: boolean
/**
* When <code>true</code>, the horizon culls the command based on its {@link DrawCommand#boundingVolume}.
* {@link DrawCommand#cull} must also be <code>true</code> in order for the command to be culled.
*
* @memberof DrawCommand.prototype
* @type {Boolean}
* @default true
*/
occlude: boolean
/**
* The transformation from the geometry in model space to world space.
* <p>
* When <code>undefined</code>, the geometry is assumed to be defined in world space.
* </p>
*
* @memberof DrawCommand.prototype
* @type {Matrix4}
* @default undefined
*/
modelMatrix: Matrix4
/**
* The type of geometry in the vertex array.
*
* @memberof DrawCommand.prototype
* @type {PrimitiveType}
* @default PrimitiveType.TRIANGLES
*/
primitiveType: PrimitiveType
/**
* The vertex array.
*
* @memberof DrawCommand.prototype
* @type {VertexArray}
* @default undefined
*/
vertexArray: VertexArray
/**
* The number of vertices to draw in the vertex array.
*
* @memberof DrawCommand.prototype
* @type {Number}
* @default undefined
*/
count: number
/**
* The offset to start drawing in the vertex array.
*
* @memberof DrawCommand.prototype
* @type {Number}
* @default 0
*/
offset: number
/**
* The number of instances to draw.
*
* @memberof DrawCommand.prototype
* @type {Number}
* @default 0
*/
instanceCount: number
/**
* The shader program to apply.
*
* @memberof DrawCommand.prototype
* @type {ShaderProgram}
* @default undefined
*/
shaderProgram: ShaderProgram
/**
* Whether this command should cast shadows when shadowing is enabled.
*
* @memberof DrawCommand.prototype
* @type {Boolean}
* @default false
*/
castShadows: boolean
/**
* Whether this command should receive shadows when shadowing is enabled.
*
* @memberof DrawCommand.prototype
* @type {Boolean}
* @default false
*/
receiveShadows: boolean
/**
* An object with functions whose names match the uniforms in the shader program
* and return values to set those uniforms.
*
* @memberof DrawCommand.prototype
* @type {Object}
* @default undefined
*/
uniformMap: {[key: string]: () => (number | boolean | number[] | Cartesian2 | Cartesian3 | Cartesian4 | Color | Matrix2 | Matrix3 | Matrix4 | Texture | CubeMap)}
/**
* The render state.
*
* @memberof DrawCommand.prototype
* @type {RenderState}
* @default undefined
*/
renderState: RenderState
/**
* The framebuffer to draw to.
*
* @memberof DrawCommand.prototype
* @type {Framebuffer}
* @default undefined
*/
framebuffer: Framebuffer
/**
* The pass when to render.
*
* @memberof DrawCommand.prototype
* @type {Pass}
* @default undefined
*/
pass: Pass
/**
* Specifies if this command is only to be executed in the frustum closest
* to the eye containing the bounding volume. Defaults to <code>false</code>.
*
* @memberof DrawCommand.prototype
* @type {Boolean}
* @default false
*/
executeInClosestFrustum: boolean
/**
* The object who created this command. This is useful for debugging command
* execution; it allows us to see who created a command when we only have a
* reference to the command, and can be used to selectively execute commands
* with {@link Scene#debugCommandFilter}.
*
* @memberof DrawCommand.prototype
* @type {Object}
* @default undefined
*
* @see Scene#debugCommandFilter
*/
owner: Object
/**
* This property is for debugging only; it is not for production use nor is it optimized.
* <p>
* Draws the {@link DrawCommand#boundingVolume} for this command, assuming it is a sphere, when the command executes.
* </p>
*
* @memberof DrawCommand.prototype
* @type {Boolean}
* @default false
*
* @see DrawCommand#boundingVolume
*/
debugShowBoundingVolume: boolean
/**
* Used to implement Scene.debugShowFrustums.
* @private
*/
debugOverlappingFrustums: boolean
/**
* A GLSL string that will evaluate to a pick id. When <code>undefined</code>, the command will only draw depth
* during the pick pass.
*
* @memberof DrawCommand.prototype
* @type {String}
* @default undefined
*/
pickId: string
/**
* Whether this command should be executed in the pick pass only.
*
* @memberof DrawCommand.prototype
* @type {Boolean}
* @default false
*/
pickOnly: boolean
} | the_stack |
import {
BurnAndReleaseTransaction,
getRenNetworkDetails,
LockAndMintTransaction,
LockChain,
Logger,
MintChain,
NullLogger,
RenNetwork,
RenNetworkDetails,
RenNetworkString,
SyncOrPromise,
TxStatus,
} from "@renproject/interfaces";
import { HttpProvider, Provider } from "@renproject/provider";
import {
assertType,
fromBase64,
isDefined,
SECONDS,
sleep,
toURLBase64,
} from "@renproject/utils";
import BigNumber from "bignumber.js";
import { AbstractRenVMProvider } from "../abstract";
import {
ParamsQueryBlock,
ParamsQueryBlocks,
ParamsQueryTx,
ParamsQueryTxs,
ParamsSubmitBurn,
ParamsSubmitGateway,
ParamsSubmitMint,
RenVMParams,
RenVMResponses,
RPCMethod,
} from "./methods";
import { BlockState } from "./methods/ren_queryBlockState";
import { unmarshalTypedPackValue } from "./pack/pack";
import {
hashTransaction,
mintParamsType,
MintTransactionInput,
SubmitGatewayInput,
submitGatewayType,
} from "./transaction";
import { unmarshalBurnTx, unmarshalMintTx } from "./unmarshal";
export const resolveV2Contract = ({
asset,
from,
to,
}: {
asset: string;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
from: LockChain<any, any, any> | MintChain<any, any>;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
to: LockChain<any, any, any> | MintChain<any, any>;
}): string => {
if (
(from as LockChain).assetIsNative &&
(from as LockChain).assetIsNative(asset)
) {
return `${asset}/to${to.name}`;
}
if (
(to as LockChain).assetIsNative &&
(to as LockChain).assetIsNative(asset)
) {
return `${asset}/from${from.name}`;
}
return `${asset}/from${from.name}To${to.name}`;
};
export class RenVMProvider
implements AbstractRenVMProvider<RenVMParams, RenVMResponses>
{
public version = () => 2;
private readonly network: RenNetwork;
public readonly provider: Provider<RenVMParams, RenVMResponses>;
private readonly logger: Logger;
constructor(
network: RenNetwork | RenNetworkString | RenNetworkDetails,
provider?: Provider<RenVMParams, RenVMResponses> | string,
logger: Logger = NullLogger,
) {
if (!provider || typeof provider === "string") {
const rpcUrl =
provider || (getRenNetworkDetails(network) || {}).lightnode;
try {
provider = new HttpProvider<RenVMParams, RenVMResponses>(
rpcUrl,
logger,
);
} catch (error) {
if (/Invalid node URL/.exec(String(error && error.message))) {
throw new Error(
`Invalid network or provider URL: "${
(getRenNetworkDetails(network) || {}).name ||
String(network)
}"`,
);
}
throw error;
}
}
this.network = network as RenNetwork;
this.logger = logger;
this.provider = provider;
}
public sendMessage = <Method extends keyof RenVMParams & string>(
method: Method,
request: RenVMParams[Method],
retry?: number,
timeout?: number,
): SyncOrPromise<RenVMResponses[Method]> => {
return this.provider.sendMessage(method, request, retry, timeout);
};
public selector = (params: {
asset: string;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
from: LockChain<any, any, any> | MintChain<any, any>;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
to: LockChain<any, any, any> | MintChain<any, any>;
}): string => {
return resolveV2Contract(params);
};
public queryBlock = async (
blockHeight: ParamsQueryBlock["blockHeight"],
retry?: number,
) =>
this.sendMessage<RPCMethod.QueryBlock>(
RPCMethod.QueryBlock,
{ blockHeight },
retry,
);
public queryBlocks = async (
blockHeight: ParamsQueryBlocks["blockHeight"],
n: ParamsQueryBlocks["n"],
retry?: number,
) =>
this.sendMessage<RPCMethod.QueryBlocks>(
RPCMethod.QueryBlocks,
{ blockHeight, n },
retry,
);
public submitGateway = async (
gateway: ParamsSubmitGateway["gateway"],
tx: ParamsSubmitGateway["tx"],
retry?: number,
) =>
this.sendMessage<RPCMethod.SubmitGateway>(
RPCMethod.SubmitGateway,
{ gateway, tx },
retry,
);
public submitTx = async (
tx: ParamsSubmitBurn["tx"] | ParamsSubmitMint["tx"],
retry?: number,
) =>
this.sendMessage<RPCMethod.SubmitTx>(
RPCMethod.SubmitTx,
{ tx } as ParamsSubmitBurn | ParamsSubmitMint,
retry,
);
public queryTx = async (txHash: ParamsQueryTx["txHash"], retry?: number) =>
this.sendMessage<RPCMethod.QueryTx>(
RPCMethod.QueryTx,
{ txHash },
retry,
);
public queryTxs = async (
tags: ParamsQueryTxs["tags"],
page?: number,
pageSize?: number,
txStatus?: ParamsQueryTxs["txStatus"],
retry?: number,
) =>
this.sendMessage<RPCMethod.QueryTxs>(
RPCMethod.QueryTxs,
{
tags,
page: (page || 0).toString(),
pageSize: (pageSize || 0).toString(),
txStatus,
},
retry,
);
public queryConfig = async (retry?: number) =>
this.sendMessage<RPCMethod.QueryConfig>(
RPCMethod.QueryConfig,
{},
retry,
);
/**
* @deprecated - use `queryBlockState` instead.
*/
public queryState = async (retry?: number) =>
this.sendMessage<RPCMethod.QueryState>(RPCMethod.QueryState, {}, retry);
public queryBlockState = async (retry?: number) =>
this.sendMessage<RPCMethod.QueryBlockState>(
RPCMethod.QueryBlockState,
{},
retry,
);
public buildGateway = ({
selector,
gHash,
gPubKey,
nHash,
nonce,
payload,
pHash,
to,
transactionVersion,
}: {
selector: string;
gHash: Buffer;
gPubKey: Buffer;
nHash: Buffer;
nonce: Buffer;
payload: Buffer;
pHash: Buffer;
to: string;
transactionVersion?: number;
}): SubmitGatewayInput => {
assertType<Buffer>("Buffer", {
gHash,
gPubKey,
nHash,
nonce,
payload,
pHash,
});
assertType<string>("string", { to });
const version = isDefined(transactionVersion)
? String(transactionVersion)
: "1";
const txIn = {
t: submitGatewayType(),
v: {
ghash: toURLBase64(gHash),
gpubkey: toURLBase64(gPubKey),
nhash: toURLBase64(nHash),
nonce: toURLBase64(nonce),
payload: toURLBase64(payload),
phash: toURLBase64(pHash),
to,
},
};
return {
selector: selector,
version,
// TODO: Fix types
in: txIn as unknown as SubmitGatewayInput["in"],
};
};
public buildTransaction = ({
selector,
gHash,
gPubKey,
nHash,
nonce,
output,
amount,
payload,
pHash,
to,
transactionVersion,
}: {
selector: string;
gHash: Buffer;
gPubKey: Buffer;
nHash: Buffer;
nonce: Buffer;
output: { txid: Buffer; txindex: string };
amount: string;
payload: Buffer;
pHash: Buffer;
to: string;
transactionVersion?: number;
}): MintTransactionInput => {
assertType<Buffer>("Buffer", {
gHash,
gPubKey,
nHash,
nonce,
payload,
pHash,
txid: output.txid,
});
assertType<string>("string", { to, amount, txindex: output.txindex });
const version = isDefined(transactionVersion)
? String(transactionVersion)
: "1";
const txIn = {
t: mintParamsType(),
v: {
txid: toURLBase64(output.txid),
txindex: output.txindex,
ghash: toURLBase64(gHash),
gpubkey: toURLBase64(gPubKey),
nhash: toURLBase64(nHash),
nonce: toURLBase64(nonce),
payload: toURLBase64(payload),
phash: toURLBase64(pHash),
to,
amount,
},
};
return {
hash: toURLBase64(hashTransaction(version, selector, txIn)),
selector: selector,
version,
// TODO: Fix types
in: txIn as unknown as MintTransactionInput["in"],
};
};
public mintTxHash = (params: {
selector: string;
gHash: Buffer;
gPubKey: Buffer;
nHash: Buffer;
nonce: Buffer;
output: { txindex: string; txid: Buffer };
amount: string;
payload: Buffer;
pHash: Buffer;
to: string;
transactionVersion?: number;
}): Buffer => {
return fromBase64(this.buildTransaction(params).hash);
};
public submitMint = async (
params: {
selector: string;
gHash: Buffer;
gPubKey: Buffer;
nHash: Buffer;
nonce: Buffer;
output: { txindex: string; txid: Buffer };
amount: string;
payload: Buffer;
pHash: Buffer;
to: string;
transactionVersion?: number;
},
retries?: number,
): Promise<Buffer> => {
const tx = this.buildTransaction(params);
await this.submitTx(tx, retries);
return fromBase64(tx.hash);
};
public submitGatewayDetails = async (
gateway: string,
params: {
selector: string;
gHash: Buffer;
gPubKey: Buffer;
nHash: Buffer;
nonce: Buffer;
payload: Buffer;
pHash: Buffer;
to: string;
transactionVersion?: number;
},
retries?: number,
): Promise<string> => {
const tx = this.buildGateway(params);
await this.submitGateway(gateway, tx, retries);
return gateway;
};
public burnTxHash = this.mintTxHash;
public submitBurn = this.submitMint;
/**
* Queries the result of a RenVM transaction and unmarshals the result into
* a [[LockAndMintTransaction]] or [[BurnAndReleaseTransaction]].
*
* @param renVMTxHash The transaction hash as a Buffer.
*/
public readonly queryMintOrBurn = async <
T extends LockAndMintTransaction | BurnAndReleaseTransaction,
>(
_selector: string,
renVMTxHash: Buffer,
retries?: number,
): Promise<T> => {
try {
const response = await this.queryTx(
toURLBase64(renVMTxHash),
retries,
);
// Unmarshal transaction.
// TODO: Improve mint/burn detection. Currently checks if the format
// is `ASSET/toChain` or `ASSET/fromChainToChain`. It may return
// a false positive if the chain name contains `To`.
const isMint = /((\/to)|(To))/.exec(response.tx.selector);
if (isMint) {
return unmarshalMintTx(response) as T;
} else {
return unmarshalBurnTx(response) as T;
}
} catch (error) {
throw error;
}
};
/**
* Fetches the result of a RenVM transaction on a repeated basis until the
* transaction's status is `"done"`.
*
* @param utxoTxHash The transaction hash as a Buffer.
* @param onStatus A callback called each time the status of the transaction
* is refreshed - even if it hasn't changed.
* @param _cancelRequested A function that returns `true` to cancel the
* loop.
*/
public readonly waitForTX = async <
T extends LockAndMintTransaction | BurnAndReleaseTransaction,
>(
selector: string,
utxoTxHash: Buffer,
onStatus?: (status: TxStatus) => void,
_cancelRequested?: () => boolean,
timeout?: number,
): Promise<T> => {
assertType<Buffer>("Buffer", { utxoTxHash });
let rawResponse: T;
while (true) {
if (_cancelRequested && _cancelRequested()) {
throw new Error(`waitForTX cancelled.`);
}
try {
const result = await this.queryMintOrBurn<T>(
selector,
utxoTxHash,
);
if (result && result.txStatus === TxStatus.TxStatusDone) {
rawResponse = result;
break;
} else if (onStatus && result && result.txStatus) {
onStatus(result.txStatus);
}
} catch (error) {
if (
/(not found)|(not available)/.exec(
String((error || {}).message),
)
) {
// ignore
} else {
this.logger.error(String(error));
// TODO: throw unexpected errors
}
}
await sleep(isDefined(timeout) ? timeout : 15 * SECONDS);
}
return rawResponse;
};
/**
* selectPublicKey fetches the public key for the RenVM shard handling
* the provided contract.
*
* @param chain The chain for which the public key should be fetched.
* @returns The public key hash (20 bytes) as a string.
*/
public readonly selectPublicKey = async (
selector: string,
_chain: string,
): Promise<Buffer> => {
const asset = selector.split("/")[0];
// Call the ren_queryBlockState RPC.
const renVMState = await this.queryBlockState(5);
const blockState: BlockState = unmarshalTypedPackValue(
renVMState.state,
);
if (!blockState[asset]) {
throw new Error(`No RenVM block state found for ${asset}.`);
}
const pubKey = blockState[asset].shards[0].pubKey;
if (!pubKey || pubKey.length === 0) {
throw new Error(`Unable to fetch RenVM public key for ${asset}.`);
}
return fromBase64(pubKey);
};
// In the future, this will be asynchronous. It returns a promise for
// compatibility.
// eslint-disable-next-line @typescript-eslint/require-await
public getNetwork = async (_selector: string): Promise<RenNetwork> => {
return this.network;
};
public getConfirmationTarget = async (
_selector: string,
chain: { name: string },
) => {
const renVMConfig = await this.sendMessage(RPCMethod.QueryConfig, {});
return parseInt(renVMConfig.confirmations[chain.name], 10);
};
public estimateTransactionFee = async (
asset: string,
_lockChain: { name: string },
hostChain: { name: string },
): Promise<{
lock: BigNumber;
release: BigNumber;
mint: number;
burn: number;
}> => {
const renVMState = await this.queryBlockState();
const blockState: BlockState = unmarshalTypedPackValue(
renVMState.state,
);
if (!blockState[asset]) {
throw new Error(`No fee details found for ${asset}`);
}
const { gasLimit, gasCap } = blockState[asset];
const fee = new BigNumber(gasLimit).times(new BigNumber(gasCap));
const mintAndBurnFees = blockState[asset].fees.chains.filter(
(chainFees) => chainFees.chain === hostChain.name,
)[0];
return {
lock: fee,
release: fee,
mint:
mintAndBurnFees && mintAndBurnFees.mintFee
? mintAndBurnFees.mintFee.toNumber()
: 15,
burn:
mintAndBurnFees && mintAndBurnFees.burnFee
? mintAndBurnFees.burnFee.toNumber()
: 15,
};
};
} | the_stack |
import { arrayRemoveItem, ProcessLock, ProcessLocker } from '@deepkit/core';
import { createRpcMessage, RpcConnectionWriter, RpcKernel, RpcKernelBaseConnection, RpcKernelConnections, RpcMessage, RpcMessageBuilder, RpcMessageRouteType } from '@deepkit/rpc';
import {
brokerDelete,
brokerEntityFields,
brokerGet,
brokerIncrement,
brokerLock,
brokerLockId,
brokerPublish,
brokerResponseIncrement,
brokerResponseIsLock,
brokerResponseSubscribeMessage,
brokerSet,
brokerSubscribe,
BrokerType
} from './model';
export class BrokerConnection extends RpcKernelBaseConnection {
protected subscribedChannels: string[] = [];
protected locks = new Map<number, ProcessLock>();
protected replies = new Map<number, ((message: RpcMessage) => void)>();
constructor(
transportWriter: RpcConnectionWriter,
protected connections: RpcKernelConnections,
protected state: BrokerState,
) {
super(transportWriter, connections);
}
public close(): void {
super.close();
for (const c of this.subscribedChannels) {
this.state.unsubscribe(c, this);
}
for (const lock of this.locks.values()) {
lock.unlock();
}
}
protected async sendEntityFields(name: string) {
const fields = this.state.getEntityFields(name);
const promises: Promise<void>[] = [];
for (const connection of this.connections.connections) {
if (connection === this) continue;
promises.push(connection.sendMessage<brokerEntityFields>(BrokerType.EntityFields, { name, fields }).ackThenClose());
}
await Promise.all(promises);
}
async onMessage(message: RpcMessage, response: RpcMessageBuilder): Promise<void> {
switch (message.type) {
case BrokerType.PublishEntityFields: {
const body = message.parseBody<brokerEntityFields>();
const changed = this.state.publishEntityFields(body.name, body.fields);
if (changed) {
await this.sendEntityFields(body.name);
}
response.reply<brokerEntityFields>(
BrokerType.EntityFields,
{ name: body.name, fields: this.state.getEntityFields(body.name) }
);
break;
}
case BrokerType.UnsubscribeEntityFields: {
const body = message.parseBody<brokerEntityFields>();
const changed = this.state.unsubscribeEntityFields(body.name, body.fields);
if (changed) {
await this.sendEntityFields(body.name);
}
response.reply<brokerEntityFields>(
BrokerType.EntityFields,
{ name: body.name, fields: this.state.getEntityFields(body.name) }
);
break;
}
case BrokerType.AllEntityFields: {
const composite = response.composite(BrokerType.AllEntityFields);
for (const name of this.state.entityFields.keys()) {
composite.add<brokerEntityFields>(BrokerType.EntityFields, { name, fields: this.state.getEntityFields(name) });
}
composite.send();
break;
}
case BrokerType.Lock: {
const body = message.parseBody<brokerLock>();
this.state.lock(body.id, body.ttl, body.timeout).then(lock => {
this.locks.set(message.id, lock);
response.reply(BrokerType.ResponseLock);
}, (error) => {
response.error(error);
});
break;
}
case BrokerType.Unlock: {
const lock = this.locks.get(message.id);
if (lock) {
this.locks.delete(message.id);
lock.unlock();
response.ack();
} else {
response.error(new Error('Unknown lock for message id ' + message.id));
}
break;
}
case BrokerType.IsLocked: {
const body = message.parseBody<brokerLockId>();
response.reply<brokerResponseIsLock>(BrokerType.ResponseIsLock, { v: this.state.isLocked(body.id) });
break;
}
case BrokerType.TryLock: {
const body = message.parseBody<brokerLock>();
this.state.tryLock(body.id, body.ttl).then(lock => {
if (lock) {
this.locks.set(message.id, lock);
response.reply(BrokerType.ResponseLock);
} else {
response.reply(BrokerType.ResponseLockFailed);
}
});
break;
}
case BrokerType.Subscribe: {
const body = message.parseBody<brokerSubscribe>();
this.state.subscribe(body.c, this);
this.subscribedChannels.push(body.c);
response.ack();
break;
}
case BrokerType.Unsubscribe: {
const body = message.parseBody<brokerSubscribe>();
this.state.unsubscribe(body.c, this);
arrayRemoveItem(this.subscribedChannels, body.c);
response.ack();
break;
}
case BrokerType.Publish: {
const body = message.parseBody<brokerPublish>();
this.state.publish(body.c, body.v);
response.ack();
break;
}
case BrokerType.Set: {
const body = message.parseBody<brokerSet>();
this.state.set(body.n, body.v);
response.ack();
break;
}
case BrokerType.Increment: {
const body = message.parseBody<brokerIncrement>();
const newValue = this.state.increment(body.n, body.v);
response.reply<brokerResponseIncrement>(BrokerType.ResponseIncrement, { v: newValue });
break;
}
case BrokerType.Delete: {
const body = message.parseBody<brokerDelete>();
this.state.delete(body.n);
response.ack();
break;
}
case BrokerType.Get: {
const body = message.parseBody<brokerGet>();
response.replyBinary(BrokerType.ResponseGet, this.state.get(body.n));
break;
}
}
}
}
export class BrokerState {
public setStore = new Map<string, Uint8Array>();
public subscriptions = new Map<string, BrokerConnection[]>();
public entityFields = new Map<string, Map<string, number>>();
public locker = new ProcessLocker();
public getEntityFields(name: string): string[] {
return Array.from(this.entityFields.get(name)?.keys() || []);
}
public publishEntityFields(name: string, fields: string[]): boolean {
let store = this.entityFields.get(name);
if (!store) {
store = new Map();
this.entityFields.set(name, store);
}
let changed = false;
for (const field of fields) {
const v = store.get(field);
if (v === undefined) {
store.set(field, 1);
changed = true;
} else {
store.set(field, v + 1);
}
}
return changed;
}
public unsubscribeEntityFields(name: string, fields: string[]) {
let store = this.entityFields.get(name);
if (!store) return;
let changed = false;
for (const field of fields) {
let v = store.get(field);
if (v === undefined) continue;
v--;
if (v === 0) {
store.delete(field);
changed = true;
continue;
}
store.set(field, v);
}
return changed;
}
public lock(id: string, ttl: number, timeout: number = 0): Promise<ProcessLock> {
return this.locker.acquireLock(id, ttl, timeout);
}
public tryLock(id: string, ttl: number = 0): Promise<ProcessLock | undefined> {
return this.locker.tryLock(id, ttl);
}
public isLocked(id: string): boolean {
return this.locker.isLocked(id);
}
public unsubscribe(channel: string, connection: BrokerConnection) {
const subscriptions = this.subscriptions.get(channel);
if (!subscriptions) return;
arrayRemoveItem(subscriptions, connection);
}
public subscribe(channel: string, connection: BrokerConnection) {
let subscriptions = this.subscriptions.get(channel);
if (!subscriptions) {
subscriptions = [];
this.subscriptions.set(channel, subscriptions);
}
subscriptions.push(connection);
}
public publish(channel: string, v: Uint8Array) {
const subscriptions = this.subscriptions.get(channel);
if (!subscriptions) return;
const message = createRpcMessage<brokerResponseSubscribeMessage>(
0, BrokerType.ResponseSubscribeMessage,
{ c: channel, v: v }, RpcMessageRouteType.server
);
for (const connection of subscriptions) {
connection.writer.write(message);
}
}
public set(id: string, data: Uint8Array) {
this.setStore.set(id, data);
}
public increment(id: string, v?: number): number {
const buffer = this.setStore.get(id);
const float64 = buffer ? new Float64Array(buffer.buffer, buffer.byteOffset) : new Float64Array(1);
float64[0] += v || 1;
if (!buffer) this.setStore.set(id, new Uint8Array(float64.buffer));
return float64[0];
}
public get(id: string): Uint8Array | undefined {
return this.setStore.get(id);
}
public delete(id: string) {
this.setStore.delete(id);
}
}
export class BrokerKernel extends RpcKernel {
protected state: BrokerState = new BrokerState;
createConnection(writer: RpcConnectionWriter): BrokerConnection {
return new BrokerConnection(writer, this.connections, this.state);
}
} | the_stack |
import _ from 'lodash';
import { Router } from 'mediasoup/lib/Router';
import { Consumer, MediaKind, Producer, RtpCapabilities, WebRtcTransportOptions } from 'mediasoup/lib/types';
import { SuccessOrError } from '../../common-types';
import * as errors from '../../errors';
import Logger from '../../utils/logger';
import Connection from '../connection';
import { Participant } from '../participant';
import { RoomManager } from '../rooms/room-manager';
import { ConferenceRepository } from '../synchronization/conference-repository';
import { ProducerSource } from '../types';
import { ConferenceMessenger } from './conference-messenger';
import {
ChangeProducerSourceRequest,
ChangeStreamRequest,
ConnectTransportRequest,
CreateTransportRequest,
CreateTransportResponse,
InitializeConnectionRequest,
SetPreferredLayersRequest,
TransportProduceRequest,
TransportProduceResponse,
} from './request-types';
import { StreamInfoRepo } from './stream-info-repo';
const logger = new Logger('Conference');
export class Conference {
private connections: Map<string, Connection> = new Map();
private roomManager: RoomManager;
/** participantId -> Participant */
private participants: Map<string, Participant> = new Map();
public streamInfoRepo: StreamInfoRepo;
constructor(
private router: Router,
public conferenceId: string,
private messenger: ConferenceMessenger,
repo: ConferenceRepository,
private options: WebRtcTransportOptions,
private maxIncomingBitrate?: number,
) {
this.roomManager = new RoomManager(conferenceId, messenger, router, repo);
this.streamInfoRepo = new StreamInfoRepo(messenger, conferenceId);
}
get routerCapabilities(): RtpCapabilities {
return this.router.rtpCapabilities;
}
public close(): void {
logger.info('Close conference %s', this.conferenceId);
this.router.close();
}
public async addConnection(request: InitializeConnectionRequest): Promise<void> {
const connection = new Connection(
request.rtpCapabilities,
request.sctpCapabilities,
request.connectionId,
request.participantId,
);
// create locally
this.connections.set(connection.connectionId, connection);
// search participant, check if it already exists
let participant = this.participants.get(connection.participantId);
if (!participant) {
participant = new Participant(connection.participantId);
// does not exist, add
this.participants.set(connection.participantId, participant);
}
// add connection
participant.connections.push(connection);
// notify room manager
await this.roomManager.updateParticipant(participant);
// update streams
await this.streamInfoRepo.updateStreams(this.participants.values());
}
public async removeConnection(connectionId: string): Promise<SuccessOrError> {
const connection = this.connections.get(connectionId);
if (!connection) return { success: false, error: errors.connectionNotFound(connectionId) };
this.connections.delete(connection.connectionId);
// if that was the last connection of this participant, remove participant
const participant = this.participants.get(connection.participantId);
if (participant) {
// remove connection from participant
_.remove(participant.connections, (x) => x.connectionId === connection.connectionId);
for (const [, producer] of connection.producers) {
producer.close();
this.removeProducer(producer, participant);
}
await this.roomManager.updateParticipant(participant);
if (participant.connections.length === 0) {
// remove participant
this.participants.delete(participant.participantId);
await this.roomManager.removeParticipant(participant);
}
}
// update streams
await this.streamInfoRepo.updateStreams(this.participants.values());
return { success: true };
}
public async removeParticipant(participantId: string): Promise<SuccessOrError> {
logger.info('removeParticipant() | participantId: %s', participantId);
const participant = this.participants.get(participantId);
if (!participant) return { success: false, error: errors.participantNotFound(participantId) };
for (const connection of participant.connections) {
for (const [, producer] of connection.producers) {
producer.close();
}
for (const [, consumer] of connection.consumers) {
consumer.close();
}
for (const [, transport] of connection.transport) {
transport.close();
}
}
await this.roomManager.removeParticipant(participant);
this.participants.delete(participant.participantId);
// update streams
await this.streamInfoRepo.updateStreams(this.participants.values());
return { success: true };
}
public async updateParticipant(participantId: string): Promise<SuccessOrError> {
const participant = this.participants.get(participantId);
if (!participant) return { success: false, error: errors.participantNotFound(participantId) };
await this.roomManager.updateParticipant(participant);
// update streams
await this.streamInfoRepo.updateStreams(this.participants.values());
return { success: true };
}
/**
* Change a producer/consumer of the participant. The parameter provides information about the type (consumer|producer),
* id and action (pause|resume|close)
*/
public async changeStream({ id, type, action }: ChangeStreamRequest, connectionId: string): Promise<SuccessOrError> {
const connection = this.connections.get(connectionId);
if (!connection) {
return { success: false, error: errors.connectionNotFound(connectionId) };
}
let stream: Producer | Consumer | undefined;
if (type === 'consumer') {
stream = connection.consumers.get(id);
} else if (type === 'producer') {
stream = connection.producers.get(id);
}
if (!stream) {
return { success: false, error: errors.streamNotFound(type, id) };
}
if (action === 'pause') {
await stream.pause();
} else if (action === 'resume') {
await stream.resume();
} else if (action === 'close') {
stream.close();
if (type === 'consumer') {
connection.consumers.delete(id);
} else {
connection.producers.delete(id);
const producer = stream as Producer;
const participant = this.participants.get(connection.participantId);
if (participant) {
this.removeProducer(producer, participant);
await this.roomManager.updateParticipant(participant);
}
}
}
// update streams
await this.streamInfoRepo.updateStreams(this.participants.values());
return { success: true };
}
public async setConsumerLayers(
{ consumerId, layers }: SetPreferredLayersRequest,
connectionId: string,
): Promise<SuccessOrError> {
const connection = this.connections.get(connectionId);
if (!connection) {
return { success: false, error: errors.connectionNotFound(connectionId) };
}
const consumer = connection.consumers.get(consumerId);
if (!consumer) {
return { success: false, error: errors.streamNotFound('consumer', consumerId) };
}
logger.debug('Set prefferred layers to %O', layers);
await consumer.setPreferredLayers(layers);
return { success: true };
}
/**
* Change a specific selected producer source of the participant. This may specifically be used by moderators to disable
* the microphone on certain participants. They can not use changeStream directly as they don't know which connection a
* producer belongs to
*/
public async changeProducerSource(
payload: ChangeProducerSourceRequest,
participantId: string,
): Promise<SuccessOrError> {
const participant = this.participants.get(participantId);
if (!participant) {
return { success: false, error: errors.participantNotFound(participantId) };
}
const { source, action } = payload;
const producerLink = participant.producers[source];
if (!producerLink) {
return { success: false, error: errors.producerSourceNotFound(source) };
}
const result = await this.changeStream(
{ action, id: producerLink.producer.id, type: 'producer' },
producerLink.connectionId,
);
if (result.success) {
await this.messenger.notifyProducerChanged(producerLink.connectionId, {
...payload,
producerId: producerLink.producer.id,
});
}
return result;
}
/**
* Create a new producer in an existing transport
*/
public async transportProduce(
{ transportId, appData, kind, ...producerOptions }: TransportProduceRequest,
connectionId: string,
): Promise<SuccessOrError<TransportProduceResponse>> {
const connection = this.connections.get(connectionId);
if (!connection) return { success: false, error: errors.connectionNotFound(connectionId) };
const participant = this.participants.get(connection.participantId);
if (!participant) return { success: false, error: errors.participantNotFound(connection.participantId) };
const transport = connection.transport.get(transportId);
if (!transport) return { success: false, error: errors.transportNotFound(transportId) };
const source: ProducerSource = appData.source;
if (!this.verifyProducerSource(kind, source))
return { success: false, error: errors.invalidProducerKind(source, kind) };
appData = { ...appData, participantId: participant.participantId };
const producer = await transport.produce({
...producerOptions,
kind,
appData,
});
if (participant.producers[source]) {
participant.producers[source]?.producer.close();
participant.producers[source] = undefined;
}
producer.on('score', (score) => {
this.messenger.notifyProducerScore(connection.connectionId, { producerId: producer.id, score });
});
connection.producers.set(producer.id, producer);
participant.producers[source] = { producer, connectionId: connection.connectionId };
await this.roomManager.updateParticipant(participant);
// update streams
await this.streamInfoRepo.updateStreams(this.participants.values());
return { success: true, response: { id: producer.id } };
}
/**
* Connect the transport after initialization
*/
public async connectTransport(payload: ConnectTransportRequest, connectionId: string): Promise<SuccessOrError> {
const connection = this.connections.get(connectionId);
if (!connection) return { success: false, error: errors.connectionNotFound(connectionId) };
const transport = connection.transport.get(payload.transportId);
if (!transport) return { success: false, error: errors.transportNotFound(payload.transportId) };
logger.debug('connectTransport() | participantId: %s', connection.participantId);
await transport.connect(payload);
return { success: true };
}
/**
* Initialize a new transport
*/
public async createTransport(
{ sctpCapabilities, forceTcp, producing, consuming }: CreateTransportRequest,
connectionId: string,
): Promise<SuccessOrError<CreateTransportResponse>> {
const connection = this.connections.get(connectionId);
if (!connection) return { success: false, error: errors.connectionNotFound(connectionId) };
const participant = this.participants.get(connection.participantId);
if (!participant) return { success: false, error: errors.participantNotFound(connection.participantId) };
logger.debug('createTransport() | participantId: %s', connection.participantId);
const webRtcTransportOptions: WebRtcTransportOptions = {
...this.options,
enableSctp: Boolean(sctpCapabilities),
numSctpStreams: sctpCapabilities?.numStreams,
appData: { producing, consuming },
};
if (forceTcp) {
webRtcTransportOptions.enableUdp = false;
webRtcTransportOptions.enableTcp = true;
}
const transport = await this.router.createWebRtcTransport(webRtcTransportOptions);
connection.transport.set(transport.id, transport);
// If set, apply max incoming bitrate limit.
if (this.maxIncomingBitrate) {
try {
await transport.setMaxIncomingBitrate(this.maxIncomingBitrate);
} catch (error) {}
}
if (consuming) participant.receiveConnection = connection;
await this.roomManager.updateParticipant(participant);
return {
success: true,
response: {
id: transport.id,
iceParameters: transport.iceParameters,
iceCandidates: transport.iceCandidates,
dtlsParameters: transport.dtlsParameters,
sctpParameters: transport.sctpParameters,
},
};
}
private removeProducer(producer: Producer, participant: Participant): void {
for (const [k, activeProducer] of Object.entries(participant.producers)) {
if (activeProducer?.producer.id === producer.id) {
participant.producers[k as ProducerSource] = undefined;
}
}
}
private verifyProducerSource(kind: MediaKind, source: ProducerSource): boolean {
if (source === 'mic' && kind === 'audio') return true;
if (source === 'screen' && kind === 'video') return true;
if (source === 'webcam' && kind === 'video') return true;
if (source === 'loopback-mic' && kind === 'audio') return true;
if (source === 'loopback-webcam' && kind === 'video') return true;
if (source === 'loopback-screen' && kind === 'video') return true;
return false;
}
} | the_stack |
import { wrapped, wrappedSelf } from "../functions";
import { primitive, FunctionMap, PossibleRepresentation } from "../reified";
import { addVariable, lookup, mangleName, uniqueName, Scope } from "../scope";
import { concat } from "../utils";
import { binary, call, callable, conditional, expr, expressionLiteralValue, functionValue, ignore, literal, member, read, reuse, set, statements, typeTypeValue, typeValue, undefinedValue, Value } from "../values";
import { applyDefaultConformances, binaryBuiltin, cachedBuilder, reuseArgs, voidType } from "./common";
import { emptyOptional, wrapInOptional } from "./Optional";
import { blockStatement, forStatement, identifier, newExpression, returnStatement, updateExpression, Statement } from "@babel/types";
function stringBoundsFailed(scope: Scope) {
return call(functionValue("Swift.(swift-to-js).stringBoundsFailed()", undefined, { kind: "function", arguments: voidType, return: voidType, throws: true, rethrows: false, attributes: [] }), [], [], scope);
}
function stringBoundsCheck(stringValue: Value, index: Value, scope: Scope, mode: "read" | "write") {
return reuse(stringValue, scope, "string", (reusableString) => {
return reuse(index, scope, "index", (reusableIndex) => {
return member(
reusableString,
conditional(
binary(mode === "write" ? ">=" : ">",
member(reusableString, "length", scope),
reusableIndex,
scope,
),
reusableIndex,
stringBoundsFailed(scope),
scope,
),
scope,
);
});
});
}
export function String(simpleStrings: boolean) {
return cachedBuilder((globalScope) => {
const UnicodeScalarView = primitive(PossibleRepresentation.Array, literal([]), {
count: wrapped((scope, arg) => {
return member(arg(0, "view"), "length", scope);
}, "(Self) -> Int"),
startIndex: wrapped((scope, arg) => {
return literal(0);
}, "(Self) -> Int"),
endIndex: wrapped((scope, arg) => {
return member(arg(0, "view"), "length", scope);
}, "(Self) -> Int"),
});
const UTF16View = primitive(PossibleRepresentation.String, literal(""), {
count: wrapped((scope, arg) => {
return member(arg(0, "view"), "length", scope);
}, "(Self) -> Int"),
startIndex: wrapped((scope, arg) => {
return literal(0);
}, "(Self) -> Int"),
endIndex: wrapped((scope, arg) => {
return member(arg(0, "view"), "length", scope);
}, "(Self) -> Int"),
});
const UTF8View = primitive(PossibleRepresentation.Array, literal([]), {
count: wrapped((scope, arg) => {
return member(arg(0, "view"), "length", scope);
}, "(Self) -> Int"),
startIndex: wrapped((scope, arg) => {
return literal(0);
}, "(Self) -> Int"),
endIndex: wrapped((scope, arg) => {
return member(arg(0, "view"), "length", scope);
}, "(Self) -> Int"),
});
const hashValue = wrapped((scope, arg) => {
return reuseArgs(arg, 0, scope, ["string"], (str) => {
const hash = uniqueName(scope, "hash");
const i = uniqueName(scope, "i");
return statements([
addVariable(scope, hash, "Int", literal(0)),
forStatement(
addVariable(scope, i, "Int", literal(0)),
read(binary("<", lookup(i, scope), member(str, "length", scope), scope), scope),
updateExpression("++", mangleName(i)),
blockStatement(
ignore(set(
lookup(hash, scope),
binary("-",
binary("+",
binary("<<",
lookup(hash, scope),
literal(5),
scope,
),
call(member(str, "charCodeAt", scope), [lookup(i, scope)], ["Int"], scope),
scope,
),
lookup(hash, scope),
scope,
),
scope,
), scope),
),
),
returnStatement(read(binary("|", lookup(hash, scope), literal(0), scope), scope)),
]);
});
}, "(String) -> Int");
const collectionFunctions: FunctionMap = {
"startIndex": wrapped((scope, arg) => {
return literal(0);
}, "(Self) -> Self.Index"),
"endIndex": wrapped((scope, arg) => {
return member(arg(0, "string"), "length", scope);
}, "(Self) -> Self.Index"),
"prefix(upTo:)": wrappedSelf((scope, arg, type, self) => {
return call(
member(self, "substring", scope),
[literal(0), arg(0, "end")],
["Int", "Int"],
scope,
);
}, "(Self, Self.Index) -> Self.SubSequence"),
};
if (simpleStrings) {
collectionFunctions["subscript(_:)"] = wrapped((scope, arg) => {
return stringBoundsCheck(arg(0, "str"), arg(1, "i"), scope, "read");
}, "(Self, Self.Index) -> Self.Element");
collectionFunctions["index(after:)"] = (scope, arg, name) => {
const arg0 = arg(1, "string");
return callable((innerScope, innerArg, length) => {
return reuse(arg0, innerScope, "string", (str) => {
return reuseArgs(innerArg, 0, innerScope, ["index"], (index) => {
return conditional(
binary(">",
member(str, "length", innerScope),
index,
scope,
),
binary("+", index, literal(1), innerScope),
stringBoundsFailed(innerScope),
innerScope,
);
});
});
}, "(String, String.Index) -> String.Index");
};
collectionFunctions.count = wrapped((scope, arg) => {
return member(arg(0, "string"), "length", scope);
}, "(String) -> Int");
collectionFunctions["distance(from:to:)"] = wrappedSelf((scope, arg, type) => {
return reuseArgs(arg, 0, scope, ["start"], (start) => {
return binary("-", arg(1, "end"), start, scope);
});
}, "(Self, Self.Index, Self.Index) -> Int");
collectionFunctions["index(_:offsetBy:)"] = wrappedSelf((scope, arg, type, collection) => {
return reuseArgs(arg, 0, scope, ["index", "distance"], (index, distance) => {
return reuse(binary("+", index, distance, scope), scope, "result", (result) => {
return conditional(
binary(">", result, member(collection, "length", scope), scope),
stringBoundsFailed(scope),
result,
scope,
);
});
});
}, "(Self, Self.Index, Int) -> Self.Index");
collectionFunctions["index(_:offsetBy:limitedBy:)"] = wrappedSelf((scope, arg, type, collection) => {
return reuseArgs(arg, 0, scope, ["index", "distance", "limit"], (index, distance, limit) => {
return reuse(binary("+", index, distance, scope), scope, "result", (result) => {
return conditional(
binary(">", result, limit, scope),
limit,
conditional(
binary(">", result, member(collection, "length", scope), scope),
stringBoundsFailed(scope),
result,
scope,
),
scope,
);
});
});
}, "(Self, Self.Index, Int) -> Self.Index");
} else {
collectionFunctions["subscript(_:)"] = wrapped((scope, arg) => {
return stringBoundsCheck(arg(0, "str"), arg(1, "i"), scope, "read");
}, "(Self, Self.Index) -> Self.Element");
collectionFunctions["index(after:)"] = (scope, arg, name) => {
const arg0 = arg(1, "string");
return callable((innerScope, innerArg, length) => {
return reuse(arg0, innerScope, "string", (str) => {
return reuseArgs(innerArg, 0, innerScope, ["index"], (index) => {
return conditional(
binary(">",
member(str, "length", innerScope),
index,
scope,
),
binary("+", index, literal(1), innerScope),
stringBoundsFailed(innerScope),
innerScope,
);
});
});
}, "(String, String.Index) -> String.Index");
};
}
return primitive(PossibleRepresentation.String, literal(""), {
"init()": wrapped((scope, arg) => literal(""), "(String) -> String"),
"init(_:)": wrapped((scope, arg) => call(expr(identifier("String")), [arg(0, "value")], [typeValue("String")], scope), "(String) -> String"),
"init(repeating:count:)": wrapped((scope, arg) => {
return reuseArgs(arg, 0, scope, ["source", "count"], (source, count) => {
const result = uniqueName(scope, "result");
const i = uniqueName(scope, "i");
return statements([
addVariable(scope, result, "String", literal("")),
forStatement(
addVariable(scope, i, "Int", literal(0)),
read(binary("<",
lookup(i, scope),
count,
scope,
), scope),
updateExpression("++", read(lookup(i, scope), scope)),
blockStatement(
ignore(set(lookup(result, scope), source, scope, "+="), scope),
),
),
returnStatement(read(lookup(result, scope), scope)),
]);
});
}, "(String, Int) -> String"),
"+": wrapped(binaryBuiltin("+", 0), "(String, String) -> String"),
"+=": wrapped((scope, arg) => {
return set(arg(0, "lhs"), arg(1, "rhs"), scope, "+=");
}, "(inout String, String) -> Void"),
"write(_:)": wrapped((scope, arg) => {
return set(arg(0, "lhs"), arg(1, "rhs"), scope, "+=");
}, "(inout String, String) -> Void"),
"append(_:)": wrapped((scope, arg) => {
return set(arg(0, "lhs"), arg(1, "rhs"), scope, "+=");
}, "(inout String, String) -> Void"),
"insert(_:at:)": wrapped((scope, arg) => {
return reuseArgs(arg, 0, scope, ["string", "character", "index"], (self, character, index) => {
return set(
self,
binary(
"+",
binary(
"+",
call(member(self, "substring", scope), [literal(0), index], ["Int", "Int"], scope),
character,
scope,
),
call(member(self, "substring", scope), [index], ["Int"], scope),
scope,
),
scope,
);
});
}, "(inout String, Character, Int) -> Void"),
// "insert(contentsOf:at:)": wrapped((scope, arg) => {
// }, "(inout String, ?, String.Index) -> Void"),
// "replaceSubrange(_:with:)": wrapped((scope, arg) => {
// }, "(inout String, ?, ?) -> Void"),
"remove(at:)": wrapped((scope, arg) => {
// TODO: Support grapheme clusters
return reuseArgs(arg, 0, scope, ["string", "index"], (self, index) => {
const removed = uniqueName(scope, "removed");
return statements(concat(
[addVariable(scope, removed, "String", member(self, index, scope)) as Statement],
ignore(set(
self,
binary(
"+",
call(member(self, "substring", scope), [literal(0), index], ["Int", "Int"], scope),
call(member(self, "substring", scope), [binary("+", index, literal(1), scope)], ["Int"], scope),
scope,
),
scope,
), scope),
[returnStatement(read(lookup(removed, scope), scope))],
));
});
}, "(inout String, String.Index) -> Character"),
"removeAll(keepingCapacity:)": wrapped((scope, arg) => {
return set(arg(0, "string"), literal(""), scope);
}, "(inout String, Bool) -> Void"),
// "removeAll(where:)": wrapped((scope, arg) => {
// return reuseArgs(arg, 0, scope, ["string", "predicate"], (string, predicate) => {
// });
// }, "(inout String, (Character) throws -> Bool) rethrows -> Void"),
"removeFirst()": wrapped((scope, arg) => {
// TODO: Support grapheme clusters
return reuseArgs(arg, 0, scope, ["string"], (self) => {
const first = uniqueName(scope, "first");
return statements(concat(
[addVariable(scope, first, "Character", member(self, 0, scope)) as Statement],
ignore(set(
self,
call(member(self, "substring", scope), [literal(1)], ["Int"], scope),
scope,
), scope),
[returnStatement(read(lookup(first, scope), scope))],
));
return member(arg(0, "string"), 0, scope);
});
}, "(inout String) -> Character"),
"removeFirst(_:)": wrapped((scope, arg) => {
// TODO: Support grapheme clusters
return reuseArgs(arg, 0, scope, ["string"], (self) => {
return set(
self,
call(member(self, "substring", scope), [arg(1, "k")], ["Int"], scope),
scope,
);
});
}, "(inout String, Int) -> Void"),
"removeLast()": wrapped((scope, arg) => {
// TODO: Support grapheme clusters
return reuseArgs(arg, 0, scope, ["string"], (self) => {
const index = uniqueName(scope, "index");
const last = uniqueName(scope, "last");
return statements(concat(
[
addVariable(scope, index, "Int", binary("-", member(self, "length", scope), literal(1), scope)) as Statement,
addVariable(scope, last, "Character", member(self, lookup(index, scope), scope)) as Statement,
],
ignore(set(
self,
call(
member(self, "substring", scope),
[binary("-", member(self, "length", scope), lookup(index, scope), scope)],
["Int"],
scope,
),
scope,
), scope),
[returnStatement(read(lookup(last, scope), scope))],
));
return member(arg(0, "string"), 0, scope);
});
}, "(inout String) -> Character"),
"removeLast(_:)": wrapped((scope, arg) => {
// TODO: Support grapheme clusters
return reuseArgs(arg, 0, scope, ["string"], (self) => {
return set(
self,
call(
member(self, "substring", scope),
[binary("-", member(self, "length", scope), arg(1, "k"), scope)],
["Int"],
scope,
),
scope,
);
});
}, "(inout String, Int) -> Void"),
// "removeSubrange()": wrapped((scope, arg) => {
// }, "(inout String, Range<String.Index>) -> Void"),
// "filter(_:)": wrapped((scope, arg) => {
// }, "(String, (Character) -> Bool) -> String"),
// "drop(while:)": wrapped((scope, arg) => {
// }, "(String, (Character) -> Bool) -> Substring"),
"dropFirst()": wrapped((scope, arg) => {
// TODO: Support grapheme clusters
return call(
member(arg(0, "string"), "substring", scope),
[literal(1)],
["Int"],
scope,
);
}, "(String) -> Void"),
"dropFirst(_:)": wrapped((scope, arg) => {
// TODO: Support grapheme clusters
return call(
member(arg(0, "string"), "substring", scope),
[arg(1, "k")],
["Int"],
scope,
);
}, "(String, Int) -> Void"),
"dropLast()": wrapped((scope, arg) => {
// TODO: Support grapheme clusters
return reuseArgs(arg, 0, scope, ["string"], (self) => {
return call(
member(self, "substring", scope),
[binary("-", member(self, "length", scope), literal(1), scope)],
["Int"],
scope,
);
});
}, "(String) -> Void"),
"dropLast(_:)": wrapped((scope, arg) => {
// TODO: Support grapheme clusters
return reuseArgs(arg, 0, scope, ["string"], (self) => {
return call(
member(self, "substring", scope),
[binary("-", member(self, "length", scope), arg(1, "k"), scope)],
["Int"],
scope,
);
});
}, "(String, Int) -> Void"),
"popLast()": wrapped((scope, arg) => {
// TODO: Support grapheme clusters
return reuseArgs(arg, 0, scope, ["string"], (self) => {
const characterType = typeValue("Character");
return conditional(
binary("!==", member(self, "length", scope), literal(0), scope),
wrapInOptional(member(self, binary("-", member(self, "length", scope), literal(1), scope), scope), characterType, scope),
emptyOptional(characterType, scope),
scope,
);
});
}, "(inout String) -> Character?"),
"hasPrefix(_:)": wrapped((scope, arg) => {
return call(member(arg(0, "string"), "hasPrefix", scope), [arg(1, "prefix")], ["String"], scope);
}, "(String, String) -> Bool"),
"hasSuffix(_:)": wrapped((scope, arg) => {
return call(member(arg(0, "string"), "hasSuffix", scope), [arg(1, "suffix")], ["String"], scope);
}, "(String, String) -> Bool"),
"contains(_:)": wrapped((scope, arg) => {
return binary("!==",
call(member(arg(0, "string"), "indexOf", scope), [arg(1, "element")], ["Character"], scope),
literal(0),
scope,
);
}, "(String, Character) -> Bool"),
// "allSatisfy(_:)": wrapped((scope, arg) => {
// }, "(String, (Character) throws -> Bool) rethrows -> Bool"),
// "contains(where:)": wrapped((scope, arg) => {
// }, "(String, (Character) -> Bool) -> Bool"),
// "first(where:)": wrapped((scope, arg) => {
// }, "(String, (Character) -> Bool) -> Character?"),
"subscript(_:)": wrapped((scope, arg) => {
return stringBoundsCheck(arg(0, "str"), arg(1, "i"), scope, "read");
}, "(String, String.Index) -> Character"),
"firstIndex(of:)": wrapped((scope, arg) => {
const index = call(member(arg(0, "string"), "indexOf", scope), [arg(1, "element")], ["Character"], scope);
return reuse(index, scope, "index", (reusedIndex) => {
const indexType = typeValue("Int");
return conditional(
binary("!==", reusedIndex, literal(-1), scope),
wrapInOptional(reusedIndex, indexType, scope),
emptyOptional(indexType, scope),
scope,
);
});
}, "(String, Character) -> String.Index?"),
// "firstIndex(where:)": wrapped((scope, arg) => {
// }, "(String, (Character) throws -> Bool) rethrows -> String.Index?"),
"index(after:)": (scope, arg, name) => {
const arg1 = arg(0, "string");
return callable((innerScope, innerArg, length) => {
return reuse(arg1, innerScope, "string", (str) => {
return reuseArgs(innerArg, 0, innerScope, ["string"], (index) => {
return conditional(
binary(">",
member(str, "length", innerScope),
index,
scope,
),
binary("+", index, literal(1), innerScope),
stringBoundsFailed(innerScope),
innerScope,
);
});
});
}, "(String, String.Index) -> String.Index");
},
"formIndex(after:)": wrapped((scope, arg) => {
// TODO: Use grapheme clusters
return set(arg(1, "index"), literal(1), scope, "+=");
}, "(String, inout String.Index) -> Void"),
"index(before:)": wrapped((scope, arg) => {
// TODO: Use grapheme clusters
return reuseArgs(arg, 0, scope, ["index"], (index) => {
return conditional(
index,
binary("-", index, literal(1), scope),
stringBoundsFailed(scope),
scope,
);
});
}, "(String, String.Index) -> String.Index"),
"formIndex(before:)": wrapped((scope, arg) => {
// TODO: Use grapheme clusters
return set(arg(1, "index"), literal(1), scope, "-=");
}, "(String, inout String.Index) -> Void"),
"index(_:offsetBy:)": wrapped((scope, arg) => {
// TODO: Use grapheme clusters
return binary("+", arg(1, "index"), arg(2, "distance"), scope);
}, "(String, String.Index, String.IndexDistance) -> String.Index"),
"index(_:offsetBy:limitedBy:)": wrapped((scope, arg) => {
// TODO: Use grapheme clusters
return reuseArgs(arg, 1, scope, ["i", "distance"], (i, distance) => {
return reuse(binary("+", i, distance, scope), scope, "result", (result) => {
const indexType = typeValue("String.Index");
return conditional(
conditional(
binary(">",
distance,
literal(0),
scope,
),
binary(">",
result,
arg(3, "limit"),
scope,
),
binary("<",
result,
arg(3, "limit"),
scope,
),
scope,
),
emptyOptional(indexType, scope),
wrapInOptional(result, indexType, scope),
scope,
);
});
});
}, "(String, String.Index, String.IndexDistance, String.Index) -> String.Index?"),
"distance(from:to:)": wrapped((scope, arg) => {
// TODO: Support grapheme clusters
return reuseArgs(arg, 1, scope, ["from"], (from) => {
return binary("-", arg(2, "to"), from, scope);
});
}, "(String, String.Index, String.Index) -> String.IndexDistance"),
// "prefix(while:)": wrapped((scope, arg) => {
// }, "(String, (Character) -> Bool) -> Substring"),
"suffix(from:)": wrapped((scope, arg) => {
return call(
member(arg(0, "string"), "substring", scope),
[arg(1, "start")],
["Int"],
scope,
);
}, "(String, String.Index) -> Substring"),
"split(separator:maxSplits:omittingEmptySubsequences:)": wrapped((scope, arg) => {
return reuseArgs(arg, 0, scope, ["string", "separator", "maxSplits", "omittingEmptySubsequences"], (str, separator, maxSplits, omittingEmptySubsequences) => {
const omitting = expressionLiteralValue(read(omittingEmptySubsequences, scope));
if (omitting === false) {
return call(
member(str, "split", scope),
[separator, maxSplits],
["Character", "Int"],
scope,
);
}
throw new Error(`String.split(separator:maxSplits:omittingEmptySubsequences:) with omittingEmptySubsequences !== false not implemented yet`);
});
}, "(String, Character, Int, Bool) -> [Substring]"),
"lowercased()": (scope, arg, type) => callable(() => call(member(arg(0, "value"), "toLowerCase", scope), [], [], scope), "(String) -> String"),
"uppercased()": (scope, arg, type) => callable(() => call(member(arg(0, "value"), "toUpperCase", scope), [], [], scope), "(String) -> String"),
"reserveCapacity(_:)": wrapped((scope, arg) => {
return statements([]);
}, "(String, String) -> Void"),
"unicodeScalars": wrapped((scope, arg) => {
return call(member("Array", "from", scope), [arg(0, "value")], [typeValue("String")], scope);
}, "(String) -> String.UnicodeScalarView"),
"utf16": wrapped((scope, arg) => {
return arg(0, "value");
}, "(String) -> String.UTF16View"),
"utf8": wrapped((scope, arg) => {
return call(member(expr(newExpression(identifier("TextEncoder"), [read(literal("utf-8"), scope)])), "encode", scope), [arg(0, "value")], [typeValue("String")], scope);
}, "(String) -> String.UTF8View"),
"isEmpty": wrapped((scope, arg) => {
return binary("===", member(arg(0, "string"), "length", scope), literal(0), scope);
}, "(String) -> Bool"),
"count": wrapped((scope, arg) => {
// TODO: Count grapheme clusters
return member(arg(0, "string"), "length", scope);
}, "(String) -> Int"),
"startIndex": wrapped((scope, arg) => {
return literal(0);
}, "(String) -> Int"),
"endIndex": wrapped((scope, arg) => {
return member(arg(0, "string"), "length", scope);
}, "(String) -> Int"),
"first": wrapped((scope, arg) => {
// TODO: Support grapheme clusters
return reuseArgs(arg, 0, scope, ["string"], (str) => {
const characterType = typeValue("Character");
return conditional(
member(str, "length", scope),
wrapInOptional(member(str, literal(0), scope), characterType, scope),
emptyOptional(characterType, scope),
scope,
);
});
}, "(String) -> Character?"),
"last": wrapped((scope, arg) => {
// TODO: Support grapheme clusters
return reuseArgs(arg, 0, scope, ["string"], (str) => {
const characterType = typeValue("Character");
return conditional(
member(str, "length", scope),
wrapInOptional(member(str, binary("-", member(str, "length", scope), literal(1), scope), scope), characterType, scope),
emptyOptional(characterType, scope),
scope,
);
});
}, "(String) -> Character?"),
hashValue,
}, applyDefaultConformances({
Equatable: {
functions: {
"==": wrapped(binaryBuiltin("===", 0), "(String, String) -> Bool"),
"!=": wrapped(binaryBuiltin("!==", 0), "(String, String) -> Bool"),
},
requirements: [],
},
Hashable: {
functions: {
hashValue,
"hash(into:)": wrapped((scope, arg) => {
return reuseArgs(arg, 0, scope, ["string", "hasher"], (str, hasher) => {
const hasherType = typeValue("Hasher");
const combine = call(functionValue("combine()", hasherType, "(Type) -> (inout Hasher, Int) -> Void"), [hasherType], [typeTypeValue], scope);
const i = uniqueName(scope, "i");
return statements([
forStatement(
addVariable(scope, i, "Int", literal(0)),
read(binary("<", lookup(i, scope), member(str, "length", scope), scope), scope),
updateExpression("++", mangleName(i)),
blockStatement(
ignore(call(combine, [arg(1, "hasher"), call(member(str, "charCodeAt", scope), [lookup(i, scope)], ["Int"], scope)], ["Hasher", "Int"], scope), scope),
),
),
]);
});
}, "(Self, inout Hasher) -> Bool"),
},
requirements: [],
},
Collection: {
functions: collectionFunctions,
requirements: [],
},
}, globalScope), {
Type: cachedBuilder(() => primitive(PossibleRepresentation.Undefined, undefinedValue)),
UnicodeScalarView: () => UnicodeScalarView,
UTF16View: () => UTF16View,
UTF8View: () => UTF8View,
});
});
} | the_stack |
import waitForExpect from "wait-for-expect";
import { getState, dispatch, hostUrl } from "./test_helper";
import { getUserEncryptedKeys } from "@api_shared/blob";
import { query } from "@api_shared/db";
import * as R from "ramda";
import { loadAccount } from "./auth_helper";
import { Client, Api, Model } from "@core/types";
import { getEnvironments } from "./envs_helper";
import { getOrgUserDevicesByUserId, graphTypes } from "@core/lib/graph";
import { getOrgGraph } from "@api_shared/graph";
import { getRootPubkeyReplacements } from "./crypto_helper";
import { wait } from "@core/lib/utils/wait";
export const testRemoveUser = async (
params: {
actorId: string;
actorCliKey?: string;
targetId: string;
targetCliKey?: string;
} & (
| ({
canRemove: true;
isRemovingRoot?: true;
uninvolvedUserId?: string;
numAdditionalKeyables?: number;
} & (
| {
canImmediatelyRevoke: true;
canSubsequentlyRevoke?: undefined;
revocationRequestProcessorId?: undefined;
}
| ({
canImmediatelyRevoke: false;
} & (
| {
canSubsequentlyRevoke: true;
revocationRequestProcessorId?: undefined;
}
| {
canSubsequentlyRevoke: false;
revocationRequestProcessorId: string;
}
))
))
| {
canRemove: false;
canImmediatelyRevoke?: undefined;
canSubsequentlyRevoke?: undefined;
isRemovingRoot?: undefined;
revocationRequestProcessorId?: undefined;
uninvolvedUserId?: undefined;
numAdditionalKeyables?: undefined;
}
)
) => {
const {
actorId,
actorCliKey,
targetId,
targetCliKey,
canRemove,
canImmediatelyRevoke,
canSubsequentlyRevoke,
isRemovingRoot,
numAdditionalKeyables,
revocationRequestProcessorId,
uninvolvedUserId,
} = params;
const start = Date.now();
if (actorCliKey) {
await dispatch(
{
type: Client.ActionType.AUTHENTICATE_CLI_KEY,
payload: { cliKey: actorCliKey },
},
actorCliKey
);
} else {
await loadAccount(actorId);
}
let state = getState(actorCliKey ?? actorId),
byType = graphTypes(state.graph);
const actor = state.graph[actorId] as Model.OrgUser | Model.CliUser;
const target = state.graph[targetId] as Model.OrgUser | Model.CliUser;
const isRemovingSelf = actorId === targetId,
[basicRole, ownerRole] = R.props(
["Basic User", "Org Owner"] as string[],
R.indexBy(R.prop("name"), byType.orgRoles)
),
actorIsBasicUser = actor.orgRoleId == basicRole.id,
isRemovingOwner =
(state.graph[targetId] as Model.OrgUser | Model.CliUser).orgRoleId ==
ownerRole.id,
targetDeviceId =
target.type == "orgUser"
? getState(targetId).orgUserAccounts[targetId]!.deviceId
: undefined,
actorDeviceId =
actor.type == "orgUser"
? getState(actorId).orgUserAccounts[actorId]!.deviceId
: undefined,
orgId = byType.org.id,
targetDevices = getOrgUserDevicesByUserId(state.graph)[targetId] ?? [],
[{ id: appId }] = byType.apps,
[appDevelopment] = getEnvironments(targetCliKey ?? targetId, appId);
let localKeyId: string | undefined,
localGeneratedEnvkeyId: string | undefined,
recoveryEncryptionKey: string | undefined;
if (canRemove) {
if (targetCliKey) {
await dispatch(
{
type: Client.ActionType.AUTHENTICATE_CLI_KEY,
payload: { cliKey: targetCliKey },
},
targetCliKey
);
} else {
await loadAccount(targetId);
}
state = getState(targetCliKey ?? targetId);
byType = graphTypes(state.graph);
if (target.type == "orgUser") {
await dispatch(
{
type: Client.ActionType.CREATE_LOCAL_KEY,
payload: {
appId,
name: "Development Key",
environmentId: appDevelopment.id,
},
},
targetCliKey ?? targetId
);
state = getState(targetCliKey ?? targetId);
byType = graphTypes(state.graph);
({ id: localKeyId } = byType.localKeys[byType.localKeys.length - 1]);
[{ id: localGeneratedEnvkeyId }] = byType.generatedEnvkeys.filter(
R.propEq("keyableParentId", localKeyId)
);
}
if (isRemovingOwner) {
await dispatch(
{
type: Client.ActionType.CREATE_RECOVERY_KEY,
},
targetId
);
state = getState(targetCliKey ?? targetId);
recoveryEncryptionKey = state.generatedRecoveryKey!.encryptionKey;
}
}
let generatedDeviceGrant:
| Client.State["generatedDeviceGrants"][0]
| undefined;
if (canRemove && !actorIsBasicUser && target.type == "orgUser") {
await dispatch(
{
type: Client.ActionType.APPROVE_DEVICES,
payload: [{ granteeId: targetId }],
},
actorCliKey ?? actorId
);
state = getState(targetCliKey ?? targetId);
generatedDeviceGrant = state.generatedDeviceGrants[0];
}
let promise: Promise<Client.DispatchResult>;
if (target.type == "orgUser") {
promise = dispatch(
{
type: Api.ActionType.REMOVE_FROM_ORG,
payload: { id: targetId },
},
actorCliKey ?? actorId
);
} else {
promise = dispatch(
{
type: Api.ActionType.DELETE_CLI_USER,
payload: { id: targetId },
},
actorCliKey ?? actorId
);
}
await waitForExpect(() => {
state = getState(actorCliKey ?? actorId);
expect(state.isRemoving[targetId]).toBeTrue();
});
const res1 = await promise;
if (canRemove) {
expect(res1.success).toBeTrue();
}
state = getState(actorCliKey ?? actorId);
if (isRemovingSelf && canRemove) {
expect(state.orgUserAccounts[targetId]).toBeUndefined();
} else {
expect(state.isRemoving[targetId]).toBeUndefined();
if (canRemove) {
if (canImmediatelyRevoke || canSubsequentlyRevoke) {
// expect(state.graph[targetId]).toBeUndefined();
// won't be deleted until REENCRYPT_ENVS finishes in the background
} else {
expect(state.graph[targetId]).toEqual(
expect.objectContaining({
deactivatedAt: expect.toBeNumber(),
})
);
}
if (targetCliKey) {
const shouldFailRes = await dispatch(
{
type: Client.ActionType.AUTHENTICATE_CLI_KEY,
payload: { cliKey: targetCliKey },
},
targetCliKey
);
expect(shouldFailRes.success).toBeFalse();
} else {
const shouldFailRes = await dispatch(
{
type: Client.ActionType.GET_SESSION,
},
targetId
);
expect(shouldFailRes.success).toBe(false);
}
}
}
if (canRemove) {
// console.log(`ensure pubkeyRevocationRequests were handled correctly`);
const getPubkeyRevocationRequests = async () =>
query<Api.Db.PubkeyRevocationRequest>({
pkey: orgId,
scope: "g|pubkeyRevocationRequest|",
createdAfter: start,
deleted: "any",
transactionConn: undefined,
}).then((requests) => requests.filter(R.propEq("creatorId", actorId)));
let requests = await getPubkeyRevocationRequests();
if (canImmediatelyRevoke) {
// if the user could be immediately revoked, no pubkey revocation requests should have been created by the actor after the start of the test
expect(requests.length).toBe(0);
} else if (canSubsequentlyRevoke) {
// if the user couldn't revoke immediately but could revoke on the next request, there should have been a pubkeyRevocationRequest created and processed by the actor after the start of the test
await waitForExpect(
async () => {
requests = await getPubkeyRevocationRequests();
const expectedLength = targetCliKey ? 1 : targetDevices.length;
expect(requests.length).toBe(expectedLength);
for (let i = 0; i < expectedLength; i++) {
expect(requests[i].deletedAt).toBeGreaterThan(0);
}
},
8000,
200
);
} else if (revocationRequestProcessorId) {
const expectedLength = targetCliKey ? 1 : targetDevices.length;
expect(requests.length).toBe(expectedLength);
for (let i = 0; i < expectedLength; i++) {
expect(requests[i].deletedAt).toBe(0);
}
await dispatch(
{
type: Client.ActionType.GET_SESSION,
},
revocationRequestProcessorId
);
await waitForExpect(
async () => {
requests = await getPubkeyRevocationRequests();
expect(requests.length).toBe(expectedLength);
for (let i = 0; i < expectedLength; i++) {
expect(requests[i].deletedAt).toBeGreaterThan(0);
}
},
8000,
200
);
}
if (isRemovingRoot) {
let replacements = await getRootPubkeyReplacements(orgId, start);
expect(replacements.length).toBe(1);
let replacement = replacements[0];
let orgGraph = await getOrgGraph(orgId, { transactionConn: undefined });
let orgGraphByType = graphTypes(orgGraph);
let revocationProcessorDeviceId: string | undefined;
if (revocationRequestProcessorId) {
const processorState = getState(revocationRequestProcessorId);
revocationProcessorDeviceId =
processorState.orgUserAccounts[revocationRequestProcessorId]!
.deviceId;
}
const expectKeys = R.without(
[actorDeviceId ?? actorId, revocationProcessorDeviceId ?? ""],
[
...orgGraphByType.orgUserDevices
.filter(({ deactivatedAt }) => !deactivatedAt)
.map(R.prop("id")),
...orgGraphByType.cliUsers
.filter(({ deactivatedAt }) => !deactivatedAt)
.map(R.prop("id")),
...orgGraphByType.generatedEnvkeys.map(R.prop("id")),
]
);
const expectNumKeys = expectKeys.length + (numAdditionalKeyables ?? 0);
const keys = Object.keys(replacement.processedAtById);
const numKeys = keys.length;
expect(numKeys).toBe(expectNumKeys);
if (canImmediatelyRevoke || canSubsequentlyRevoke) {
if (actor.type == "orgUser" && actorDeviceId) {
expect(replacement.processedAtById[actorDeviceId]).toBeUndefined();
} else {
expect(replacement.processedAtById[actorId]).toBeUndefined();
}
} else if (revocationRequestProcessorId) {
const processorDeviceId = getState(revocationRequestProcessorId)
.orgUserAccounts[revocationRequestProcessorId]!.deviceId;
expect(replacement.processedAtById[processorDeviceId]).toBeUndefined();
}
if (uninvolvedUserId) {
// console.log(
// `ensure an uninvolved user cannot dispatch a graph update action until queued root replacements are processed`
// );
const uninvolvedDeviceId =
getState(uninvolvedUserId).orgUserAccounts[uninvolvedUserId]!
.deviceId;
expect(replacement.processedAtById[uninvolvedDeviceId]).toBeFalse();
await dispatch(
{
type: Client.ActionType.GET_SESSION,
},
uninvolvedUserId
);
await wait(2000);
replacements = await getRootPubkeyReplacements(orgId, start);
expect(replacements.length).toBe(1);
replacement = replacements[0];
expect(replacement.processedAtById[uninvolvedDeviceId]).toBeNumber();
state = getState(uninvolvedDeviceId);
expect(graphTypes(state.graph).rootPubkeyReplacements.length).toBe(0);
}
}
if (target.type == "orgUser") {
if (!(localKeyId && localGeneratedEnvkeyId)) {
throw new Error(
"localKeyId and localGeneratedEnvkeyId should be defined"
);
}
// console.log(`ensure all local key blobs are deleted`);
const blobs = await Promise.all([
getUserEncryptedKeys(
{
orgId,
userId: targetId,
deviceId: targetDeviceId ?? "cli",
blobType: "env",
},
{ transactionConn: undefined }
),
query({
pkey: ["envkey", localGeneratedEnvkeyId].join("|"),
transactionConn: undefined,
}),
]).then(R.flatten);
expect(blobs).toEqual([]);
}
// console.log(`ensure device grants can no longer be accepted`);
if (generatedDeviceGrant) {
const [{ skey: deviceGrantEmailToken }] =
await query<Api.Db.DeviceGrantPointer>({
pkey: ["deviceGrant", generatedDeviceGrant.identityHash].join("|"),
transactionConn: undefined,
}),
deviceGrantLoadRes = await dispatch<
Client.Action.ClientActions["LoadDeviceGrant"]
>(
{
type: Client.ActionType.LOAD_DEVICE_GRANT,
payload: {
emailToken: deviceGrantEmailToken,
encryptionToken: [
generatedDeviceGrant.identityHash,
generatedDeviceGrant.encryptionKey,
].join("_"),
},
},
undefined
);
expect(deviceGrantLoadRes.success).toBeFalse();
}
// console.log(
// `ensure recovery keys can no longer be redeemed (if applicable)`
// );
if (isRemovingOwner) {
if (!recoveryEncryptionKey) {
throw new Error("recoveryEncryptionKey should be defined");
}
const recoveryKeyLoadRes = await dispatch<
Client.Action.ClientActions["LoadRecoveryKey"]
>(
{
type: Client.ActionType.LOAD_RECOVERY_KEY,
payload: {
encryptionKey: recoveryEncryptionKey,
hostUrl,
},
},
targetId
);
expect(recoveryKeyLoadRes.success).toBeFalse();
expect(
(recoveryKeyLoadRes.resultAction as any).payload.error.type
).not.toBe("requiresEmailAuthError");
}
}
}; | the_stack |
import once = require('lodash/once');
import type { BalenaRequestStreamResult } from 'balena-request';
import type { InjectedDependenciesParam, InjectedOptionsParam } from '..';
export interface BillingAccountAddressInfo {
address1: string;
address2: string;
city: string;
state: string;
zip: string;
country: string;
phone: string;
}
export interface BillingAccountInfo {
account_state: string;
first_name: string;
last_name: string;
company_name: string;
cc_emails: string;
vat_number: string;
address: BillingAccountAddressInfo;
}
export type BillingInfoType = 'bank_account' | 'credit_card' | 'paypal';
export interface BillingInfo {
full_name: string;
first_name: string;
last_name: string;
company: string;
vat_number: string;
address1: string;
address2: string;
city: string;
state: string;
zip: string;
country: string;
phone: string;
type?: BillingInfoType;
}
export interface CardBillingInfo extends BillingInfo {
card_type: string;
year: string;
month: string;
first_one: string;
last_four: string;
}
export interface BankAccountBillingInfo extends BillingInfo {
account_type: string;
last_four: string;
name_on_account: string;
routing_number: string;
}
export interface TokenBillingSubmitInfo {
token_id: string;
'g-recaptcha-response'?: string;
}
export interface BillingPlanInfo {
name: string;
title: string;
code: string;
tier: string;
currentPeriodEndDate?: string;
intervalUnit?: string;
intervalLength?: string;
addonPlan?: BillingAddonPlanInfo;
billing: BillingPlanBillingInfo;
support: {
name: string;
title: string;
};
}
export interface BillingAddonPlanInfo {
code: string;
currentPeriodEndDate?: string;
billing: BillingPlanBillingInfo;
addOns: Array<{
code: string;
unitCostCents?: string;
quantity?: string;
}>;
}
export interface BillingPlanBillingInfo {
currency: string;
totalCostCents: string;
charges: Array<{
itemType: string;
name: string;
code: string;
unitCostCents: string;
quantity: string;
isQuantifiable?: boolean;
}>;
}
export interface InvoiceInfo {
closed_at: string;
created_at: string;
due_on: string;
currency: string;
invoice_number: string;
subtotal_in_cents: string;
total_in_cents: string;
uuid: string;
state: 'pending' | 'paid' | 'failed' | 'past_due';
}
export interface PlanChangeOptions {
tier: string;
cycle: 'monthly' | 'annual';
planChangeReason?: string;
}
const getBillingModel = function (
deps: InjectedDependenciesParam,
opts: InjectedOptionsParam,
) {
const { request } = deps;
const { apiUrl, isBrowser } = opts;
const organizationModel = once(() =>
(require('./organization') as typeof import('./organization')).default(
deps,
opts,
),
);
const getOrgId = async (organization: string | number): Promise<number> => {
const { id } = await organizationModel().get(organization, {
$select: 'id',
});
return id;
};
const exports = {
/**
* @summary Get the user's billing account
* @name getAccount
* @public
* @function
* @memberof balena.models.billing
*
* @param {(String|Number)} organization - handle (string) or id (number) of the target organization.
*
* @fulfil {Object} - billing account
* @returns {Promise}
*
* @example
* balena.models.billing.getAccount(orgId).then(function(billingAccount) {
* console.log(billingAccount);
* });
*
* @example
* balena.models.billing.getAccount(orgId, function(error, billingAccount) {
* if (error) throw error;
* console.log(billingAccount);
* });
*/
getAccount: async (
organization: string | number,
): Promise<BillingAccountInfo> => {
const orgId = await getOrgId(organization);
const { body } = await request.send({
method: 'GET',
url: `/billing/v1/account/${orgId}`,
baseUrl: apiUrl,
});
return body;
},
/**
* @summary Get the current billing plan
* @name getPlan
* @public
* @function
* @memberof balena.models.billing
*
* @fulfil {Object} - billing plan
* @returns {Promise}
*
* @param {(String|Number)} organization - handle (string) or id (number) of the target organization.
*
* @example
* balena.models.billing.getPlan(orgId).then(function(billingPlan) {
* console.log(billingPlan);
* });
*
* @example
* balena.models.billing.getPlan(orgId, function(error, billingPlan) {
* if (error) throw error;
* console.log(billingPlan);
* });
*/
getPlan: async (
organization: string | number,
): Promise<BillingPlanInfo> => {
const orgId = await getOrgId(organization);
const { body } = await request.send({
method: 'GET',
url: `/billing/v1/account/${orgId}/plan`,
baseUrl: apiUrl,
});
return body;
},
/**
* @summary Get the current billing information
* @name getBillingInfo
* @public
* @function
* @memberof balena.models.billing
*
* @param {(String|Number)} organization - handle (string) or id (number) of the target organization.
*
* @fulfil {Object} - billing information
* @returns {Promise}
*
* @example
* balena.models.billing.getBillingInfo(orgId).then(function(billingInfo) {
* console.log(billingInfo);
* });
*
* @example
* balena.models.billing.getBillingInfo(orgId, function(error, billingInfo) {
* if (error) throw error;
* console.log(billingInfo);
* });
*/
getBillingInfo: async (
organization: string | number,
): Promise<BillingInfo> => {
const orgId = await getOrgId(organization);
const { body } = await request.send({
method: 'GET',
url: `/billing/v1/account/${orgId}/info`,
baseUrl: apiUrl,
});
return body;
},
/**
* @summary Update the current billing information
* @name updateBillingInfo
* @public
* @function
* @memberof balena.models.billing
*
* @param {(String|Number)} organization - handle (string) or id (number) of the target organization.
* @param {Object} billingInfo - an object containing a billing info token_id
*
* @param {String} billingInfo.token_id - the token id generated for the billing info form
* @param {(String|undefined)} [billingInfo.'g-recaptcha-response'] - the captcha response
* @fulfil {Object} - billing information
* @returns {Promise}
*
* @example
* balena.models.billing.updateBillingInfo(orgId, { token_id: 'xxxxxxx' }).then(function(billingInfo) {
* console.log(billingInfo);
* });
*
* @example
* balena.models.billing.updateBillingInfo(orgId, { token_id: 'xxxxxxx' }, function(error, billingInfo) {
* if (error) throw error;
* console.log(billingInfo);
* });
*/
updateBillingInfo: async (
organization: string | number,
billingInfo: TokenBillingSubmitInfo,
): Promise<BillingInfo> => {
const orgId = await getOrgId(organization);
const { body } = await request.send({
method: 'PATCH',
url: `/billing/v1/account/${orgId}/info`,
baseUrl: apiUrl,
body: billingInfo,
});
return body;
},
/**
* @summary Change the current billing plan
* @name changePlan
* @public
* @function
* @memberof balena.models.billing
*
* @param {(String|Number)} organization - handle (string) or id (number) of the target organization.
* @param {Object} planChangeOptions - an object containing the billing plan change options
*
* @param {String} billingInfo.tier - the code of the target billing plan
* @param {String} billingInfo.cycle - the billing cycle
* @param {String} [billingInfo.planChangeReason] - the reason for changing the current plan
*
* @returns {Promise}
*
* @example
* balena.models.billing.changePlan(orgId, { billingCode: 'prototype-v2', cycle: 'annual' }).then(function() {
* console.log('Plan changed!');
* });
*/
changePlan: async (
organization: string | number,
{ cycle, ...restPlanChangeOptions }: PlanChangeOptions,
): Promise<void> => {
const orgId = await getOrgId(organization);
await request.send({
method: 'PATCH',
url: `/billing/v1/account/${orgId}/plan`,
baseUrl: apiUrl,
body: {
annual: cycle === 'annual',
...restPlanChangeOptions,
},
});
},
/**
* @summary Get the available invoices
* @name getInvoices
* @public
* @function
* @memberof balena.models.billing
*
* @param {(String|Number)} organization - handle (string) or id (number) of the target organization.
*
* @fulfil {Object} - invoices
* @returns {Promise}
*
* @example
* balena.models.billing.getInvoices(orgId).then(function(invoices) {
* console.log(invoices);
* });
*
* @example
* balena.models.billing.getInvoices(orgId, function(error, invoices) {
* if (error) throw error;
* console.log(invoices);
* });
*/
getInvoices: async (
organization: string | number,
): Promise<InvoiceInfo[]> => {
const orgId = await getOrgId(organization);
const { body } = await request.send({
method: 'GET',
url: `/billing/v1/account/${orgId}/invoices`,
baseUrl: apiUrl,
});
return body;
},
/**
* @summary Download a specific invoice
* @name downloadInvoice
* @public
* @function
* @memberof balena.models.billing
*
* @param {(String|Number)} organization - handle (string) or id (number) of the target organization.
* @param {String} - an invoice number
*
* @fulfil {Blob|ReadableStream} - blob on the browser, download stream on node
* @returns {Promise}
*
* @example
* # Browser
* balena.models.billing.downloadInvoice(orgId, '0000').then(function(blob) {
* console.log(blob);
* });
* # Node
* balena.models.billing.downloadInvoice(orgId, '0000').then(function(stream) {
* stream.pipe(fs.createWriteStream('foo/bar/invoice-0000.pdf'));
* });
*/
async downloadInvoice(
organization: string | number,
invoiceNumber: string,
): Promise<Blob | BalenaRequestStreamResult> {
const orgId = await getOrgId(organization);
const url = `/billing/v1/account/${orgId}/invoices/${invoiceNumber}/download`;
if (!isBrowser) {
return request.stream({
method: 'GET',
url,
baseUrl: apiUrl,
});
}
const { body } = await request.send({
method: 'GET',
url,
baseUrl: apiUrl,
responseFormat: 'blob',
});
return body;
},
};
return exports;
};
export default getBillingModel; | the_stack |
* @module WebGL
*/
import { assert, dispose } from "@itwin/core-bentley";
import { FillFlags, RenderMode, TextureTransparency, ViewFlags } from "@itwin/core-common";
import { SurfaceType } from "../primitives/SurfaceParams";
import { VertexIndices } from "../primitives/VertexTable";
import { RenderMemory } from "../RenderMemory";
import { AttributeMap } from "./AttributeMap";
import { ShaderProgramParams } from "./DrawCommand";
import { GL } from "./GL";
import { BufferHandle, BufferParameters, BuffersContainer } from "./AttributeBuffers";
import { MaterialInfo } from "./Material";
import { Pass, RenderOrder, RenderPass, SurfaceBitIndex } from "./RenderFlags";
import { System } from "./System";
import { Target } from "./Target";
import { TechniqueId } from "./TechniqueId";
import { MeshData } from "./MeshData";
import { MeshGeometry } from "./MeshGeometry";
/** @internal */
export function wantMaterials(vf: ViewFlags): boolean {
return vf.materials && RenderMode.SmoothShade === vf.renderMode;
}
function wantLighting(vf: ViewFlags) {
return RenderMode.SmoothShade === vf.renderMode && vf.lighting;
}
/** @internal */
export class SurfaceGeometry extends MeshGeometry {
private readonly _buffers: BuffersContainer;
private readonly _indices: BufferHandle;
public get lutBuffers() { return this._buffers; }
public static create(mesh: MeshData, indices: VertexIndices): SurfaceGeometry | undefined {
const indexBuffer = BufferHandle.createArrayBuffer(indices.data);
return undefined !== indexBuffer ? new SurfaceGeometry(indexBuffer, indices.length, mesh) : undefined;
}
public get isDisposed(): boolean {
return this._buffers.isDisposed
&& this._indices.isDisposed;
}
public dispose() {
dispose(this._buffers);
dispose(this._indices);
}
public collectStatistics(stats: RenderMemory.Statistics): void {
stats.addSurface(this._indices.bytesUsed);
}
public get isLit() { return SurfaceType.Lit === this.surfaceType || SurfaceType.TexturedLit === this.surfaceType; }
public get isTexturedType() { return SurfaceType.Textured === this.surfaceType || SurfaceType.TexturedLit === this.surfaceType; }
public get hasTexture() { return this.isTexturedType && undefined !== this.texture; }
public get isGlyph() { return this.mesh.isGlyph; }
public override get alwaysRenderTranslucent() { return this.isGlyph; }
public get isTileSection() { return undefined !== this.texture && this.texture.isTileSection; }
public get isClassifier() { return SurfaceType.VolumeClassifier === this.surfaceType; }
public override get supportsThematicDisplay() {
return !this.isGlyph;
}
public override get allowColorOverride() {
// Text background color should not be overridden by feature symbology overrides - otherwise it becomes unreadable...
// We don't actually know if we have text.
// We do know that text background color uses blanking fill. So do ImageGraphics, so they're also going to forbid overriding their color.
return FillFlags.Blanking !== (this.fillFlags & FillFlags.Blanking);
}
public override get asSurface() { return this; }
public override get asEdge() { return undefined; }
public override get asSilhouette() { return undefined; }
protected _draw(numInstances: number, instanceBuffersContainer?: BuffersContainer): void {
const system = System.instance;
// If we can't write depth in the fragment shader, use polygonOffset to force blanking regions to draw behind.
const offset = RenderOrder.BlankingRegion === this.renderOrder && !system.supportsLogZBuffer;
if (offset) {
system.context.enable(GL.POLYGON_OFFSET_FILL);
system.context.polygonOffset(1.0, 1.0);
}
const bufs = instanceBuffersContainer !== undefined ? instanceBuffersContainer : this._buffers;
bufs.bind();
system.drawArrays(GL.PrimitiveType.Triangles, 0, this._numIndices, numInstances);
bufs.unbind();
if (offset)
system.context.disable(GL.POLYGON_OFFSET_FILL);
}
public override wantMixMonochromeColor(target: Target): boolean {
// Text relies on white-on-white reversal.
return !this.isGlyph && (this.isLitSurface || this.wantTextures(target, this.hasTexture));
}
public get techniqueId(): TechniqueId { return TechniqueId.Surface; }
public override get isLitSurface() { return this.isLit; }
public override get hasBakedLighting() { return this.mesh.hasBakedLighting; }
public override get hasFixedNormals() { return this.mesh.hasFixedNormals; }
public get renderOrder(): RenderOrder {
if (FillFlags.Behind === (this.fillFlags & FillFlags.Behind))
return RenderOrder.BlankingRegion;
let order = this.isLit ? RenderOrder.LitSurface : RenderOrder.UnlitSurface;
if (this.isPlanar)
order = order | RenderOrder.PlanarBit;
return order;
}
public override getColor(target: Target) {
if (FillFlags.Background === (this.fillFlags & FillFlags.Background))
return target.uniforms.style.backgroundColorInfo;
else
return this.colorInfo;
}
public override getPass(target: Target): Pass {
// Classifiers have a dedicated pass
if (this.isClassifier)
return "classification";
let opaquePass: Pass = this.isPlanar ? "opaque-planar" : "opaque";
// When reading pixels, glyphs are always opaque. Otherwise always transparent (for anti-aliasing).
if (this.isGlyph)
return target.isReadPixelsInProgress ? opaquePass : "translucent";
const vf = target.currentViewFlags;
// When rendering thematic isolines, we need translucency because they have anti-aliasing.
if (target.wantThematicDisplay && this.supportsThematicDisplay && target.uniforms.thematic.wantIsoLines)
return "translucent";
// In wireframe, unless fill is explicitly enabled for planar region, surface does not draw
if (RenderMode.Wireframe === vf.renderMode && !this.mesh.isTextureAlwaysDisplayed) {
const fillFlags = this.fillFlags;
const showFill = FillFlags.Always === (fillFlags & FillFlags.Always) || (vf.fill && FillFlags.ByView === (fillFlags & FillFlags.ByView));
if (!showFill)
return "none";
}
// If transparency disabled by render mode or view flag, always draw opaque.
if (!vf.transparency || RenderMode.SolidFill === vf.renderMode || RenderMode.HiddenLine === vf.renderMode)
return opaquePass;
// We have 3 sources of alpha: the material, the texture, and the color.
// Base alpha comes from the material if it overrides it; otherwise from the color.
// The texture's alpha is multiplied by the base alpha.
// So we must draw in the translucent pass if the texture has transparency OR the base alpha is less than 1.
let hasAlpha = false;
const mat = wantMaterials(vf) ? this.mesh.materialInfo : undefined;
if (undefined !== mat && mat.overridesAlpha)
hasAlpha = mat.hasTranslucency;
else
hasAlpha = this.getColor(target).hasTranslucency;
if (!hasAlpha) {
// ###TODO handle TextureTransparency.Mixed; remove Texture.hasTranslucency.
const tex = this.wantTextures(target, true) ? this.texture : undefined;
switch (tex?.transparency) {
case TextureTransparency.Translucent:
hasAlpha = true;
break;
case TextureTransparency.Mixed:
opaquePass = `${opaquePass}-translucent`;
break;
}
}
return hasAlpha ? "translucent" : opaquePass;
}
protected _wantWoWReversal(target: Target): boolean {
const fillFlags = this.fillFlags;
if (FillFlags.None !== (fillFlags & FillFlags.Background))
return false; // fill color explicitly from background
if (FillFlags.None !== (fillFlags & FillFlags.Always))
return true; // fill displayed even in wireframe
const vf = target.currentViewFlags;
if (RenderMode.Wireframe === vf.renderMode || vf.visibleEdges)
return false; // never invert surfaces when edges are displayed
if (this.isLit && wantLighting(vf))
return false;
// Don't invert white pixels of textures...
return !this.wantTextures(target, this.hasTexture);
}
public override get materialInfo(): MaterialInfo | undefined { return this.mesh.materialInfo; }
public useTexture(params: ShaderProgramParams): boolean {
return this.wantTextures(params.target, this.hasTexture);
}
public computeSurfaceFlags(params: ShaderProgramParams, flags: Int32Array): void {
const target = params.target;
const vf = target.currentViewFlags;
const useMaterial = wantMaterials(vf);
flags[SurfaceBitIndex.IgnoreMaterial] = useMaterial ? 0 : 1;
flags[SurfaceBitIndex.HasMaterialAtlas] = useMaterial && this.hasMaterialAtlas ? 1 : 0;
flags[SurfaceBitIndex.ApplyLighting] = 0;
flags[SurfaceBitIndex.NoFaceFront] = 0;
flags[SurfaceBitIndex.HasColorAndNormal] = 0;
if (this.isLit) {
flags[SurfaceBitIndex.HasNormals] = 1;
if (wantLighting(vf)) {
flags[SurfaceBitIndex.ApplyLighting] = 1;
if (this.hasFixedNormals)
flags[SurfaceBitIndex.NoFaceFront] = 1;
}
// Textured meshes store normal in place of color index.
// Untextured lit meshes store normal where textured meshes would store UV coords.
// Tell shader where to find normal.
if (!this.isTexturedType) {
flags[SurfaceBitIndex.HasColorAndNormal] = 1;
}
} else {
flags[SurfaceBitIndex.HasNormals] = 0;
}
flags[SurfaceBitIndex.HasTexture] = this.useTexture(params) ? 1 : 0;
// The transparency threshold controls how transparent a surface must be to allow light to pass through; more opaque surfaces cast shadows.
flags[SurfaceBitIndex.TransparencyThreshold] = params.target.isDrawingShadowMap ? 1 : 0;
flags[SurfaceBitIndex.BackgroundFill] = 0;
switch (params.renderPass) {
// NB: We need this for opaque pass due to SolidFill (must compute transparency, discard below threshold, render opaque at or above threshold)
case RenderPass.OpaqueLinear:
case RenderPass.OpaquePlanar:
case RenderPass.OpaqueGeneral:
case RenderPass.Translucent:
case RenderPass.WorldOverlay:
case RenderPass.OpaqueLayers:
case RenderPass.TranslucentLayers:
case RenderPass.OverlayLayers: {
const mode = vf.renderMode;
if (!this.isGlyph && (RenderMode.HiddenLine === mode || RenderMode.SolidFill === mode)) {
flags[SurfaceBitIndex.TransparencyThreshold] = 1;
if (RenderMode.HiddenLine === mode && FillFlags.Always !== (this.fillFlags & FillFlags.Always)) {
// fill flags test for text - doesn't render with bg fill in hidden line mode.
flags[SurfaceBitIndex.BackgroundFill] = 1;
}
break;
}
}
}
}
private constructor(indices: BufferHandle, numIndices: number, mesh: MeshData) {
super(mesh, numIndices);
this._buffers = BuffersContainer.create();
const attrPos = AttributeMap.findAttribute("a_pos", TechniqueId.Surface, false);
assert(undefined !== attrPos);
this._buffers.addBuffer(indices, [BufferParameters.create(attrPos.location, 3, GL.DataType.UnsignedByte, false, 0, 0, false)]);
this._indices = indices;
}
private wantTextures(target: Target, surfaceTextureExists: boolean): boolean {
if (this.hasScalarAnimation && undefined !== target.analysisTexture)
return true;
if (!surfaceTextureExists)
return false;
if (this.mesh.isTextureAlwaysDisplayed)
return true;
if (this.supportsThematicDisplay && target.wantThematicDisplay)
return false;
const fill = this.fillFlags;
const flags = target.currentViewFlags;
// ###TODO need to distinguish between gradient fill and actual textures...
switch (flags.renderMode) {
case RenderMode.SmoothShade:
return flags.textures;
case RenderMode.Wireframe:
return FillFlags.Always === (fill & FillFlags.Always) || (flags.fill && FillFlags.ByView === (fill & FillFlags.ByView));
default:
return FillFlags.Always === (fill & FillFlags.Always);
}
}
} | the_stack |
import type {
AlgoliaSearchHelper,
SearchParameters,
SearchResults,
} from 'algoliasearch-helper';
import {
checkRendering,
createDocumentationLink,
createDocumentationMessageGenerator,
noop,
warning,
} from '../../lib/utils';
import type {
Connector,
InstantSearch,
CreateURL,
WidgetRenderState,
} from '../../types';
import type { InsightsEvent } from '../../middlewares';
const withUsage = createDocumentationMessageGenerator({
name: 'rating-menu',
connector: true,
});
const $$type = 'ais.ratingMenu';
const MAX_VALUES_PER_FACET_API_LIMIT = 1000;
const STEP = 1;
type SendEvent = (...args: [InsightsEvent] | [string, string, string?]) => void;
type CreateSendEvent = (createSendEventArgs: {
instantSearchInstance: InstantSearch;
helper: AlgoliaSearchHelper;
getRefinedStar: () => number | number[] | undefined;
attribute: string;
}) => SendEvent;
const createSendEvent: CreateSendEvent =
({ instantSearchInstance, helper, getRefinedStar, attribute }) =>
(...args) => {
if (args.length === 1) {
instantSearchInstance.sendEventToInsights(args[0]);
return;
}
const [eventType, facetValue, eventName = 'Filter Applied'] = args;
if (eventType !== 'click') {
return;
}
const isRefined = getRefinedStar() === Number(facetValue);
if (!isRefined) {
instantSearchInstance.sendEventToInsights({
insightsMethod: 'clickedFilters',
widgetType: $$type,
eventType,
payload: {
eventName,
index: helper.getIndex(),
filters: [`${attribute}>=${facetValue}`],
},
attribute,
});
}
};
type StarRatingItems = {
/**
* Name corresponding to the number of stars.
*/
name: string;
/**
* Human-readable name corresponding to the number of stars.
*/
label: string;
/**
* Number of stars as string.
*/
value: string;
/**
* Count of matched results corresponding to the number of stars.
*/
count: number;
/**
* Array of length of maximum rating value with stars to display or not.
*/
stars: boolean[];
/**
* Indicates if star rating refinement is applied.
*/
isRefined: boolean;
};
export type RatingMenuConnectorParams = {
/**
* Name of the attribute for faceting (eg. "free_shipping").
*/
attribute: string;
/**
* The maximum rating value.
*/
max?: number;
};
export type RatingMenuRenderState = {
/**
* Possible star ratings the user can apply.
*/
items: StarRatingItems[];
/**
* Creates an URL for the next state (takes the item value as parameter). Takes the value of an item as parameter.
*/
createURL: CreateURL<string>;
/**
* Indicates if search state can be refined.
*/
canRefine: boolean;
/**
* Selects a rating to filter the results (takes the filter value as parameter). Takes the value of an item as parameter.
*/
refine: (value: string) => void;
/**
* `true` if the last search contains no result.
*/
hasNoResults: boolean;
/**
* Send event to insights middleware
*/
sendEvent: SendEvent;
};
export type RatingMenuWidgetDescription = {
$$type: 'ais.ratingMenu';
renderState: RatingMenuRenderState;
indexRenderState: {
ratingMenu: {
[attribute: string]: WidgetRenderState<
RatingMenuRenderState,
RatingMenuConnectorParams
>;
};
};
indexUiState: {
ratingMenu: {
[attribute: string]: number;
};
};
};
export type RatingMenuConnector = Connector<
RatingMenuWidgetDescription,
RatingMenuConnectorParams
>;
/**
* **StarRating** connector provides the logic to build a custom widget that will let
* the user refine search results based on ratings.
*
* The connector provides to the rendering: `refine()` to select a value and
* `items` that are the values that can be selected. `refine` should be used
* with `items.value`.
*/
const connectRatingMenu: RatingMenuConnector = function connectRatingMenu(
renderFn,
unmountFn = noop
) {
checkRendering(renderFn, withUsage());
return (widgetParams) => {
const { attribute, max = 5 } = widgetParams || {};
let sendEvent: SendEvent;
if (!attribute) {
throw new Error(withUsage('The `attribute` option is required.'));
}
const getRefinedStar = (state: SearchParameters) => {
const values = state.getNumericRefinements(attribute);
if (!values['>=']?.length) {
return undefined;
}
return values['>='][0];
};
const getFacetsMaxDecimalPlaces = (
facetResults: SearchResults.FacetValue[]
) => {
let maxDecimalPlaces = 0;
facetResults.forEach((facetResult) => {
const [, decimal = ''] = facetResult.name.split('.');
maxDecimalPlaces = Math.max(maxDecimalPlaces, decimal.length);
});
return maxDecimalPlaces;
};
const getFacetValuesWarningMessage = ({
maxDecimalPlaces,
maxFacets,
maxValuesPerFacet,
}: {
maxDecimalPlaces: number;
maxFacets: number;
maxValuesPerFacet: number;
}) => {
const maxDecimalPlacesInRange = Math.max(
0,
Math.floor(Math.log10(MAX_VALUES_PER_FACET_API_LIMIT / max))
);
const maxFacetsInRange = Math.min(
MAX_VALUES_PER_FACET_API_LIMIT,
Math.pow(10, maxDecimalPlacesInRange) * max
);
const solutions: string[] = [];
if (maxFacets > MAX_VALUES_PER_FACET_API_LIMIT) {
solutions.push(
`- Update your records to lower the precision of the values in the "${attribute}" attribute (for example: ${(5.123456789).toPrecision(
maxDecimalPlaces + 1
)} to ${(5.123456789).toPrecision(maxDecimalPlacesInRange + 1)})`
);
}
if (maxValuesPerFacet < maxFacetsInRange) {
solutions.push(
`- Increase the maximum number of facet values to ${maxFacetsInRange} using the "configure" widget ${createDocumentationLink(
{ name: 'configure' }
)} and the "maxValuesPerFacet" parameter https://www.algolia.com/doc/api-reference/api-parameters/maxValuesPerFacet/`
);
}
return `The ${attribute} attribute can have ${maxFacets} different values (0 to ${max} with a maximum of ${maxDecimalPlaces} decimals = ${maxFacets}) but you retrieved only ${maxValuesPerFacet} facet values. Therefore the number of results that match the refinements can be incorrect.
${
solutions.length
? `To resolve this problem you can:\n${solutions.join('\n')}`
: ``
}`;
};
function getRefinedState(state: SearchParameters, facetValue: string) {
const isRefined = getRefinedStar(state) === Number(facetValue);
const emptyState = state.resetPage().removeNumericRefinement(attribute);
if (!isRefined) {
return emptyState
.addNumericRefinement(attribute, '<=', max)
.addNumericRefinement(attribute, '>=', Number(facetValue));
}
return emptyState;
}
const toggleRefinement = (
helper: AlgoliaSearchHelper,
facetValue: string
) => {
sendEvent('click', facetValue);
helper.setState(getRefinedState(helper.state, facetValue)).search();
};
type ConnectorState = {
toggleRefinementFactory: (
helper: AlgoliaSearchHelper
) => (facetValue: string) => void;
createURLFactory: ({
state,
createURL,
}: {
state: SearchParameters;
createURL: (createURLState: SearchParameters) => string;
}) => (value: string) => string;
};
const connectorState: ConnectorState = {
toggleRefinementFactory: (helper) => toggleRefinement.bind(null, helper),
createURLFactory:
({ state, createURL }) =>
(value) =>
createURL(getRefinedState(state, value)),
};
return {
$$type,
init(initOptions) {
const { instantSearchInstance } = initOptions;
renderFn(
{
...this.getWidgetRenderState(initOptions),
instantSearchInstance,
},
true
);
},
render(renderOptions) {
const { instantSearchInstance } = renderOptions;
renderFn(
{
...this.getWidgetRenderState(renderOptions),
instantSearchInstance,
},
false
);
},
getRenderState(renderState, renderOptions) {
return {
...renderState,
ratingMenu: {
...renderState.ratingMenu,
[attribute]: this.getWidgetRenderState(renderOptions),
},
};
},
getWidgetRenderState({
helper,
results,
state,
instantSearchInstance,
createURL,
}) {
let facetValues: StarRatingItems[] = [];
if (!sendEvent) {
sendEvent = createSendEvent({
instantSearchInstance,
helper,
getRefinedStar: () => getRefinedStar(helper.state),
attribute,
});
}
if (results) {
const facetResults = results.getFacetValues(
attribute,
{}
) as SearchResults.FacetValue[];
const maxValuesPerFacet = facetResults.length;
const maxDecimalPlaces = getFacetsMaxDecimalPlaces(facetResults);
const maxFacets = Math.pow(10, maxDecimalPlaces) * max;
warning(
maxFacets <= maxValuesPerFacet,
getFacetValuesWarningMessage({
maxDecimalPlaces,
maxFacets,
maxValuesPerFacet,
})
);
const refinedStar = getRefinedStar(state);
for (let star = STEP; star < max; star += STEP) {
const isRefined = refinedStar === star;
const count = facetResults
.filter((f) => Number(f.name) >= star && Number(f.name) <= max)
.map((f) => f.count)
.reduce((sum, current) => sum + current, 0);
if (refinedStar && !isRefined && count === 0) {
// skip count==0 when at least 1 refinement is enabled
// eslint-disable-next-line no-continue
continue;
}
const stars = [...new Array(Math.floor(max / STEP))].map(
(_v, i) => i * STEP < star
);
facetValues.push({
stars,
name: String(star),
label: String(star),
value: String(star),
count,
isRefined,
});
}
}
facetValues = facetValues.reverse();
return {
items: facetValues,
hasNoResults: results ? results.nbHits === 0 : true,
canRefine: facetValues.length > 0,
refine: connectorState.toggleRefinementFactory(helper),
sendEvent,
createURL: connectorState.createURLFactory({ state, createURL }),
widgetParams,
};
},
dispose({ state }) {
unmountFn();
return state.removeNumericRefinement(attribute);
},
getWidgetUiState(uiState, { searchParameters }) {
const value = getRefinedStar(searchParameters);
if (typeof value !== 'number') {
return uiState;
}
return {
...uiState,
ratingMenu: {
...uiState.ratingMenu,
[attribute]: value,
},
};
},
getWidgetSearchParameters(searchParameters, { uiState }) {
const value = uiState.ratingMenu && uiState.ratingMenu[attribute];
const withoutRefinements = searchParameters.clearRefinements(attribute);
const withDisjunctiveFacet =
withoutRefinements.addDisjunctiveFacet(attribute);
if (!value) {
return withDisjunctiveFacet.setQueryParameters({
numericRefinements: {
...withDisjunctiveFacet.numericRefinements,
[attribute]: {},
},
});
}
return withDisjunctiveFacet
.addNumericRefinement(attribute, '<=', max)
.addNumericRefinement(attribute, '>=', value);
},
};
};
};
export default connectRatingMenu; | the_stack |
// namespace
namespace cf {
// interface
export interface IMicrophoneBridgeOptions{
el: HTMLElement;
button: UserInputSubmitButton;
microphoneObj: IUserInput;
eventTarget: EventDispatcher;
}
export const MicrophoneBridgeEvent = {
ERROR: "cf-microphone-bridge-error",
TERMNIAL_ERROR: "cf-microphone-bridge-terminal-error"
}
// class
export class MicrophoneBridge{
private equalizer: SimpleEqualizer;
private el: HTMLElement;
private button: UserInputSubmitButton;
private currentTextResponse: string = "";
private recordChunks: Array<any>;
// private equalizer: SimpleEqualizer;
private promise: Promise<any>;
private currentStream: MediaStream;
private _hasUserMedia: boolean = false;
private inputErrorCount: number = 0;
private inputCurrentError: string = "";
private microphoneObj: IUserInput;
private eventTarget: EventDispatcher;
private flowUpdateCallback: () => void;
private set hasUserMedia(value: boolean){
this._hasUserMedia = value;
if(!value){
// this.submitButton.classList.add("permission-waiting");
}else{
// this.submitButton.classList.remove("permission-waiting");
}
}
public set active(value: boolean){
if(this.equalizer){
this.equalizer.disabled = !value;
}
}
constructor(options: IMicrophoneBridgeOptions){
this.el = options.el;
this.button = options.button;
this.eventTarget = options.eventTarget;
// data object
this.microphoneObj = options.microphoneObj;
this.flowUpdateCallback = this.onFlowUpdate.bind(this);
this.eventTarget.addEventListener(FlowEvents.FLOW_UPDATE, this.flowUpdateCallback, false);
}
public cancel(){
this.button.loading = false;
if(this.microphoneObj.cancelInput){
this.microphoneObj.cancelInput();
}
}
public onFlowUpdate(){
this.currentTextResponse = null;
if(!this._hasUserMedia){
// check if user has granted
let hasGranted: boolean = false;
if((<any> window).navigator.mediaDevices){
(<any> window).navigator.mediaDevices.enumerateDevices().then((devices: any) => {
devices.forEach((device: any) => {
if(!hasGranted && device.label !== ""){
hasGranted = true;
}
});
if(hasGranted){
// user has previously granted, so call getusermedia, as this wont prombt user
this.getUserMedia();
}else{
// await click on button, wait state
}
});
}
}else{
// user has granted ready to go go
if(!this.microphoneObj.awaitingCallback){
this.callInput();
}
}
}
public getUserMedia(){
try{
// from https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia#Using_the_new_API_in_older_browsers
// Older browsers might not implement mediaDevices at all, so we set an empty object first
if (navigator.mediaDevices === undefined) {
(<any>navigator).mediaDevices = {};
}
// Some browsers partially implement mediaDevices. We can't just assign an object
// with getUserMedia as it would overwrite existing properties.
// Here, we will just add the getUserMedia property if it's missing.
if (navigator.mediaDevices.getUserMedia === undefined) {
navigator.mediaDevices.getUserMedia = function(constraints) {
// First get ahold of the legacy getUserMedia, if present
var getUserMedia = navigator.getUserMedia || (<any>window).navigator.webkitGetUserMedia || (<any>window).navigator.mozGetUserMedia;
// Some browsers just don't implement it - return a rejected promise with an error
// to keep a consistent interface
if (!getUserMedia) {
return Promise.reject(new Error('getUserMedia is not implemented in this browser'));
}
// Otherwise, wrap the call to the old navigator.getUserMedia with a Promise
return new Promise(function(resolve, reject) {
getUserMedia.call(navigator, constraints, resolve, reject);
});
}
}
(<any> navigator.mediaDevices).getUserMedia(<any> {audio: true})
.then((stream: MediaStream) => {
this.currentStream = stream;
if(stream.getAudioTracks().length > 0){
// interface is active and available, so call it immidiatly
this.hasUserMedia = true;
this.setupEqualizer();
if(!this.microphoneObj.awaitingCallback){
// microphone interface awaits speak out loud callback
this.callInput();
}
}else{
// code for when both devices are available
// interface is not active, button should be clicked
this.hasUserMedia = false;
}
})
.catch((error: any) => {
// Promise catch
this.hasUserMedia = false;
this.eventTarget.dispatchEvent(new Event(MicrophoneBridgeEvent.TERMNIAL_ERROR));
});
}catch(error){
// try catch
// whoops no getUserMedia, so roll back to standard UI
this.hasUserMedia = false;
this.eventTarget.dispatchEvent(new Event(MicrophoneBridgeEvent.TERMNIAL_ERROR));
}
}
public dealloc(){
this.cancel();
this.promise = null;
this.currentStream = null;
if(this.equalizer){
this.equalizer.dealloc();
}
this.equalizer = null;
this.eventTarget.removeEventListener(FlowEvents.FLOW_UPDATE, this.flowUpdateCallback, false);
this.flowUpdateCallback = null;
}
public callInput(messageTime: number = 0){
// remove current error message after x time
// clearTimeout(this.clearMessageTimer);
// this.clearMessageTimer = setTimeout(() =>{
// this.el.removeAttribute("message");
// }, messageTime);
this.button.loading = true;
if(this.equalizer){
this.equalizer.disabled = false;
}
// call API, SpeechRecognintion etc. you decide, passing along the stream from getUserMedia can be used.. as long as the resolve is called with string attribute
this.promise = new Promise((resolve: any, reject: any) => this.microphoneObj.input(resolve, reject, this.currentStream) )
.then((result) => {
// api contacted
this.promise = null;
// save response so it's available in getFlowDTO
this.currentTextResponse = result.toString();
if(!this.currentTextResponse || this.currentTextResponse == ""){
this.showError(Dictionary.get("user-audio-reponse-invalid"));
// invalid input, so call API again
this.callInput();
return;
}
this.inputErrorCount = 0;
this.inputCurrentError = "";
this.button.loading = false;
// continue flow
let dto: FlowDTO = <FlowDTO> {
text: this.currentTextResponse
};
ConversationalForm.illustrateFlow(this, "dispatch", UserInputEvents.SUBMIT, dto);
this.eventTarget.dispatchEvent(new CustomEvent(UserInputEvents.SUBMIT, {
detail: dto
}));
}).catch((error) => {
// API error
// ConversationalForm.illustrateFlow(this, "dispatch", MicrophoneBridgeEvent.ERROR, error);
// this.eventTarget.dispatchEvent(new CustomEvent(MicrophoneBridgeEvent.ERROR, {
// detail: error
// }));
if(this.isErrorTerminal(error)){
// terminal error, fallback to
this.eventTarget.dispatchEvent(new CustomEvent(MicrophoneBridgeEvent.TERMNIAL_ERROR,{
detail: Dictionary.get("microphone-terminal-error")
}));
if(!ConversationalForm.suppressLog) console.log("Conversational Form: Terminal error: ", error);
}else{
if(this.inputCurrentError != error){
// api failed ...
// show result in UI
this.inputErrorCount = 0;
this.inputCurrentError = error;
}else{
}
this.inputErrorCount++;
if(this.inputErrorCount > 2){
this.showError(error);
}else{
this.eventTarget.dispatchEvent(new CustomEvent(MicrophoneBridgeEvent.TERMNIAL_ERROR,{
detail: Dictionary.get("microphone-terminal-error")
}));
if(!ConversationalForm.suppressLog) console.log("Conversational Form: Terminal error: ", error);
}
}
});
}
protected isErrorTerminal(error: string): boolean{
const terminalErrors: Array<string> = ["network"];
if(terminalErrors.indexOf(error) !== -1)
return true;
return false;
}
private showError(error: string){
const dto: FlowDTO = {
errorText: error
};
ConversationalForm.illustrateFlow(this, "dispatch", FlowEvents.USER_INPUT_INVALID, dto)
this.eventTarget.dispatchEvent(new CustomEvent(FlowEvents.USER_INPUT_INVALID, {
detail: dto
}));
this.callInput();
}
private setupEqualizer(){
const eqEl: HTMLElement = <HTMLElement> this.el.getElementsByTagName("cf-icon-audio-eq")[0];
if(SimpleEqualizer.supported && eqEl){
this.equalizer = new SimpleEqualizer({
stream: this.currentStream,
elementToScale: eqEl
});
}
}
}
class SimpleEqualizer{
private context: AudioContext;
private analyser: AnalyserNode;
private mic: MediaStreamAudioSourceNode;
private javascriptNode: ScriptProcessorNode;
private elementToScale: HTMLElement;
private maxBorderWidth: number = 0;
private _disabled: boolean = false;
public set disabled(value: boolean){
this._disabled = value;
this.elementToScale.style.borderWidth = 0 + "px";
}
constructor(options: any){
this.elementToScale = options.elementToScale;
this.context = new AudioContext();
this.analyser = this.context.createAnalyser();
this.mic = this.context.createMediaStreamSource(options.stream);
this.javascriptNode = this.context.createScriptProcessor(2048, 1, 1);
this.analyser.smoothingTimeConstant = 0.3;
this.analyser.fftSize = 1024;
this.mic.connect(this.analyser);
this.analyser.connect(this.javascriptNode);
this.javascriptNode.connect(this.context.destination);
this.javascriptNode.onaudioprocess = () => {
this.onAudioProcess();
};
}
private onAudioProcess(){
if(this._disabled)
return;
var array = new Uint8Array(this.analyser.frequencyBinCount);
this.analyser.getByteFrequencyData(array);
var values = 0;
var length = array.length;
for (var i = 0; i < length; i++) {
values += array[i];
}
var average = values / length;
const percent: number = Math.min(1, Math.max(0, 1 - ((50 - average) / 50)));
if(!this.maxBorderWidth){
this.maxBorderWidth = this.elementToScale.offsetWidth * 0.5;
}
this.elementToScale.style.borderWidth = (this.maxBorderWidth * percent) + "px";
}
public dealloc(){
this.javascriptNode.onaudioprocess = null;
this.javascriptNode = null;
this.analyser = null;
this.mic = null;
this.elementToScale = null;
this.context = null;
}
public static supported():boolean{
(<any>window).AudioContext = (<any>window).AudioContext || (<any>window).webkitAudioContext;
if((<any>window).AudioContext){
return true;
}
else {
return false;
}
}
}
} | the_stack |
import { TextDocument, TextEdit } from 'vscode-languageserver-textdocument';
import type { Connection, TextDocumentChangeEvent } from 'vscode-languageserver';
import type LSP from 'vscode-languageserver-protocol';
import { TextDocuments } from 'vscode-languageserver/node';
import {
DidChangeConfigurationNotification,
InitializedNotification,
TextDocumentSyncKind,
} from 'vscode-languageserver-protocol';
// eslint-disable-next-line node/no-unpublished-import
import type stylelint from 'stylelint';
import type winston from 'winston';
import { getFixes } from '../utils/documents';
import { displayError, CommandManager, NotificationManager } from '../utils/lsp';
import { mergeAssign, mergeOptionsWithDefaults } from '../utils/objects';
import { StylelintRunner, LintDiagnostics } from '../utils/stylelint';
import { StylelintResolver, StylelintResolutionResult } from '../utils/packages';
import {
LanguageServerOptions,
LanguageServerContext,
LanguageServerModule,
LanguageServerConstructorParameters,
LanguageServerHandlerParameters,
LanguageServerHandlerReturnValues,
Notification,
} from './types';
const defaultOptions: LanguageServerOptions = {
codeAction: {
disableRuleComment: {
location: 'separateLine',
},
},
config: null,
configFile: '',
configBasedir: '',
customSyntax: '',
ignoreDisables: false,
packageManager: 'npm',
reportInvalidScopeDisables: false,
reportNeedlessDisables: false,
snippet: ['css', 'postcss'],
stylelintPath: '',
validate: ['css', 'postcss'],
};
/**
* Stylelint language server.
*/
export class StylelintLanguageServer {
/**
* The language server connection.
*/
#connection: Connection;
/**
* The logger to use, if any.
*/
#logger: winston.Logger | undefined;
/**
* The notification manager for the connection.
*/
#notifications: NotificationManager;
/**
* The command manager for the connection.
*/
#commands: CommandManager;
/**
* The global language server options, used if the client does not support
* the `workspace/configuration` request.
*/
#globalOptions: LanguageServerOptions;
/**
* The resolver used to resolve the Stylelint package.
*/
#resolver: StylelintResolver;
/**
* The runner used to run Stylelint.
*/
#runner: StylelintRunner;
/**
* The text document manager.
*/
#documents: TextDocuments<TextDocument>;
/**
* The language server context passed between modules.
*/
#context: LanguageServerContext;
/**
* Registered modules.
*/
#modules: Map<string, LanguageServerModule> = new Map();
/**
* Whether or not the client supports the `workspace/configuration` request.
*/
#hasConfigurationCapability = false;
/**
* Configuration per resource.
*/
#scopedOptions = new Map<string, LanguageServerOptions>();
/**
* Creates a new Stylelint language server.
*/
constructor({ connection, logger, modules }: LanguageServerConstructorParameters) {
this.#connection = connection;
this.#logger = logger?.child({ component: 'language-server' });
this.#notifications = new NotificationManager(connection, this.#logger);
this.#commands = new CommandManager(connection, this.#logger);
this.#globalOptions = defaultOptions;
this.#resolver = new StylelintResolver(connection, this.#logger);
this.#runner = new StylelintRunner(connection, this.#logger, this.#resolver);
this.#documents = new TextDocuments(TextDocument);
this.#context = {
connection: this.#connection,
notifications: this.#notifications,
commands: this.#commands,
documents: this.#documents,
runner: this.#runner,
getOptions: this.#getOptions.bind(this),
getModule: this.#getModule.bind(this),
getFixes: this.#getFixes.bind(this),
displayError: this.#displayError.bind(this),
lintDocument: this.#lintDocument.bind(this),
resolveStylelint: this.#resolveStylelint.bind(this),
};
const contextReadOnlyProxy = new Proxy(this.#context, {
get(target, name) {
return target[name as keyof typeof target];
},
set() {
throw new Error('Cannot set read-only property');
},
});
if (modules) {
for (const Module of modules) {
this.#logger?.info('Registering module', { module: Module.id });
if (!Module.id) {
throw new Error('Modules must have an ID');
}
if (typeof Module.id !== 'string') {
throw new Error('Module IDs must be strings');
}
const module = new Module({
context: contextReadOnlyProxy,
logger: logger?.child({ component: `language-server:${Module.id}` }),
});
if (this.#modules.has(Module.id)) {
throw new Error(`Module with ID "${Module.id}" already registered`);
}
this.#modules.set(Module.id, module);
this.#logger?.info('Module registered', { module: Module.id });
}
}
}
/**
* Starts the language server.
*/
start(): void {
this.#logger?.info('Starting language server');
this.#documents.listen(this.#connection);
this.#connection.listen();
this.#registerHandlers();
this.#logger?.info('Language server started');
}
#displayError(error: unknown): void {
displayError(this.#connection, error);
}
async #getOptions(resource: string): Promise<LanguageServerOptions> {
if (!this.#hasConfigurationCapability) {
return this.#globalOptions;
}
const cached = this.#scopedOptions.get(resource);
if (cached) {
this.#logger?.debug('Returning cached options', { resource });
return cached;
}
this.#logger?.debug('Requesting options from client', { resource });
const options = (await this.#connection.workspace.getConfiguration({
scopeUri: resource,
section: 'stylelint',
})) as unknown;
this.#logger?.debug('Received options from client', { resource, options });
const withDefaults = mergeOptionsWithDefaults(options, defaultOptions);
Object.freeze(withDefaults);
this.#scopedOptions.set(resource, withDefaults);
this.#logger?.debug('Returning options', { resource, options: withDefaults });
return withDefaults;
}
/**
* Resolves the Stylelint package for the given document.
*/
async #resolveStylelint(document: TextDocument): Promise<StylelintResolutionResult | undefined> {
this.#logger?.debug('Resolving Stylelint', { uri: document.uri });
try {
const options = await this.#getOptions(document.uri);
const result = await this.#resolver.resolve(options, document);
if (result) {
this.#logger?.debug('Stylelint resolved', {
uri: document.uri,
resolvedPath: result.resolvedPath,
});
} else {
this.#logger?.warn('Failed to resolve Stylelint', { uri: document.uri });
}
return result;
} catch (error) {
this.#displayError(error);
this.#logger?.error('Error resolving Stylelint', { uri: document.uri, error });
return undefined;
}
}
/**
* Lints a document using Stylelint.
*/
async #lintDocument(
document: TextDocument,
linterOptions: Partial<stylelint.LinterOptions> = {},
): Promise<LintDiagnostics | undefined> {
this.#logger?.debug('Linting document', { uri: document.uri, linterOptions });
try {
const options = await this.#getOptions(document.uri);
const results = await this.#runner.lintDocument(document, linterOptions, options);
this.#logger?.debug('Lint run complete', { uri: document.uri, results });
return results;
} catch (err) {
this.#displayError(err);
this.#logger?.error('Error running lint', { uri: document.uri, error: err });
return undefined;
}
}
/**
* Gets text edits for fixes made by Stylelint.
*/
async #getFixes(
document: TextDocument,
linterOptions: stylelint.LinterOptions = {},
): Promise<TextEdit[]> {
try {
const options = await this.#getOptions(document.uri);
const edits = await getFixes(this.#runner, document, linterOptions, options);
this.#logger?.debug('Fixes retrieved', { uri: document.uri, edits });
return edits;
} catch (error) {
this.#displayError(error);
this.#logger?.error('Error getting fixes', { uri: document.uri, error });
return [];
}
}
/**
* Gets the registered module with the given ID if it exists.
*/
#getModule(id: string): LanguageServerModule | undefined {
return this.#modules.get(id);
}
/**
* Registers handlers on the language server connection, then invokes the
* `onDidRegisterHandlers` event for each registered module to allow them
* to register their handlers.
*/
#registerHandlers(): void {
this.#logger?.info('Registering handlers');
this.#connection.onInitialize(this.#onInitialize.bind(this));
this.#logger?.debug('connection.onInitialize handler registered');
this.#notifications.on(InitializedNotification.type, this.#onInitialized.bind(this));
this.#logger?.debug('connection.onInitialized handler registered');
this.#commands.register();
this.#notifications.on(
DidChangeConfigurationNotification.type,
this.#onDidChangeConfiguration.bind(this),
);
this.#logger?.debug('connection.onDidChangeConfiguration handler registered');
this.#documents.onDidClose(this.#onDidCloseDocument.bind(this));
this.#logger?.debug('documents.onDidClose handler registered');
this.#invokeHandlers('onDidRegisterHandlers');
this.#logger?.info('Handlers registered');
}
/**
* Calls the given handler for all registered modules.
*/
#invokeHandlers<
K extends keyof LanguageServerHandlerParameters,
P extends LanguageServerHandlerParameters[K],
R extends LanguageServerHandlerReturnValues[K],
>(handlerName: K, ...params: P): { [moduleName: string]: R[] } {
this.#logger?.debug(`Invoking ${String(handlerName)}`);
const returnValues = Object.create(null) as { [moduleName: string]: R[] };
for (const [id, module] of this.#modules) {
const handler = module[handlerName] as (...args: P) => R;
if (handler) {
try {
returnValues[id] = handler.apply(module, params);
this.#logger?.debug(`Invoked ${String(handlerName)}`, {
module: id,
returnValue: returnValues[id],
});
} catch (error) {
this.#displayError(error);
this.#logger?.error(`Error invoking ${String(handlerName)}`, {
module: id,
error,
});
}
}
}
return returnValues;
}
#onInitialize(params: LSP.InitializeParams): LSP.InitializeResult {
this.#logger?.debug('received onInitialize', { params });
const result: LSP.InitializeResult = {
capabilities: {
textDocumentSync: {
openClose: true,
change: TextDocumentSyncKind.Full,
},
},
};
if (params.capabilities.workspace?.configuration) {
this.#logger?.debug(
'Client reports workspace configuration support; using scoped configuration',
);
this.#hasConfigurationCapability = true;
}
for (const [, moduleResult] of Object.entries(this.#invokeHandlers('onInitialize', params))) {
if (moduleResult) {
mergeAssign(result, moduleResult);
}
}
this.#logger?.debug('Returning initialization results', { result });
return result;
}
async #onInitialized(params: LSP.InitializedParams): Promise<void> {
this.#logger?.debug('received onInitialized', { params });
if (this.#hasConfigurationCapability) {
this.#logger?.debug('Registering DidChangeConfigurationNotification');
await this.#connection.client.register(DidChangeConfigurationNotification.type, {
section: 'stylelint',
});
}
}
#onDidCloseDocument({ document }: TextDocumentChangeEvent<TextDocument>): void {
this.#logger?.debug('received documents.onDidClose, clearing cached options', {
uri: document.uri,
});
this.#scopedOptions.delete(document.uri);
}
#onDidChangeConfiguration(params: LSP.DidChangeConfigurationParams): void {
if (this.#hasConfigurationCapability) {
this.#logger?.debug('received onDidChangeConfiguration, clearing cached options', { params });
this.#scopedOptions.clear();
this.#invokeHandlers('onDidChangeConfiguration');
this.#connection.sendNotification(Notification.DidResetConfiguration);
return;
}
this.#logger?.debug('received onDidChangeConfiguration', { params });
this.#globalOptions = mergeOptionsWithDefaults(
(params.settings as { stylelint: unknown }).stylelint,
defaultOptions,
);
Object.freeze(this.#globalOptions);
this.#logger?.debug('Global options updated', { options: this.#globalOptions });
this.#invokeHandlers('onDidChangeConfiguration');
}
} | the_stack |
import * as XmlNames from '../defs/xml-names';
import * as XmlUtils from './../utils/xml-utils';
import { KdbxBinaries, KdbxBinary, KdbxBinaryWithHash } from './kdbx-binaries';
import { KdbxDeletedObject } from './kdbx-deleted-object';
import { KdbxGroup } from './kdbx-group';
import { KdbxMeta, KdbxMetaEditState } from './kdbx-meta';
import { KdbxCredentials } from './kdbx-credentials';
import { KdbxHeader } from './kdbx-header';
import { KdbxError } from '../errors/kdbx-error';
import { Defaults, ErrorCodes, Icons } from '../defs/consts';
import { KdbxFormat } from './kdbx-format';
import { KdbxEntry, KdbxEntryEditState } from './kdbx-entry';
import { KdbxUuid } from './kdbx-uuid';
import { KdbxContext } from './kdbx-context';
export interface KdbxEditState {
entries?: { [name: string]: KdbxEntryEditState };
meta?: KdbxMetaEditState;
}
export interface MergeObjectMap {
entries: Map<string, KdbxEntry>;
groups: Map<string, KdbxGroup>;
remoteEntries: Map<string, KdbxEntry>;
remoteGroups: Map<string, KdbxGroup>;
deleted: Map<string, Date>;
}
export class Kdbx {
header = new KdbxHeader();
credentials = new KdbxCredentials(null);
meta = new KdbxMeta();
xml: Document | undefined;
binaries = new KdbxBinaries();
groups: KdbxGroup[] = [];
deletedObjects: KdbxDeletedObject[] = [];
get versionMajor(): number {
return this.header.versionMajor;
}
get versionMinor(): number {
return this.header.versionMinor;
}
/**
* Creates a new database
*/
static create(credentials: KdbxCredentials, name: string): Kdbx {
if (!(credentials instanceof KdbxCredentials)) {
throw new KdbxError(ErrorCodes.InvalidArg, 'credentials');
}
const kdbx = new Kdbx();
kdbx.credentials = credentials;
kdbx.header = KdbxHeader.create();
kdbx.meta = KdbxMeta.create();
kdbx.meta._name = name;
kdbx.createDefaultGroup();
kdbx.createRecycleBin();
kdbx.meta._lastSelectedGroup = kdbx.getDefaultGroup().uuid;
kdbx.meta._lastTopVisibleGroup = kdbx.getDefaultGroup().uuid;
return kdbx;
}
/**
* Load a kdbx file
* If there was an error loading file, throws an exception
*/
static load(
data: ArrayBuffer,
credentials: KdbxCredentials,
options?: { preserveXml?: boolean }
): Promise<Kdbx> {
if (!(data instanceof ArrayBuffer)) {
return Promise.reject(new KdbxError(ErrorCodes.InvalidArg, 'data'));
}
if (!(credentials instanceof KdbxCredentials)) {
return Promise.reject(new KdbxError(ErrorCodes.InvalidArg, 'credentials'));
}
const kdbx = new Kdbx();
kdbx.credentials = credentials;
const format = new KdbxFormat(kdbx);
format.preserveXml = options?.preserveXml || false;
return format.load(data);
}
/**
* Import database from an xml file
* If there was an error loading file, throws an exception
*/
static loadXml(data: string, credentials: KdbxCredentials): Promise<Kdbx> {
if (typeof data !== 'string') {
return Promise.reject(new KdbxError(ErrorCodes.InvalidArg, 'data'));
}
if (!(credentials instanceof KdbxCredentials)) {
return Promise.reject(new KdbxError(ErrorCodes.InvalidArg, 'credentials'));
}
const kdbx = new Kdbx();
kdbx.credentials = credentials;
const format = new KdbxFormat(kdbx);
return format.loadXml(data);
}
/**
* Save the db to ArrayBuffer
*/
save(): Promise<ArrayBuffer> {
const format = new KdbxFormat(this);
return format.save();
}
/**
* Save the db as XML string
*/
saveXml(prettyPrint = false): Promise<string> {
const format = new KdbxFormat(this);
return format.saveXml(prettyPrint);
}
/**
* Creates a default group, if it's not yet created
*/
createDefaultGroup(): void {
if (this.groups.length) {
return;
}
const defaultGroup = KdbxGroup.create(this.meta.name || '');
defaultGroup.icon = Icons.FolderOpen;
defaultGroup.expanded = true;
this.groups.push(defaultGroup);
}
/**
* Creates a recycle bin group, if it's not yet created
*/
createRecycleBin(): void {
this.meta.recycleBinEnabled = true;
if (this.meta.recycleBinUuid && this.getGroup(this.meta.recycleBinUuid)) {
return;
}
const defGrp = this.getDefaultGroup();
const recycleBin = KdbxGroup.create(Defaults.RecycleBinName, defGrp);
recycleBin.icon = Icons.TrashBin;
recycleBin.enableAutoType = false;
recycleBin.enableSearching = false;
this.meta.recycleBinUuid = recycleBin.uuid;
defGrp.groups.push(recycleBin);
}
/**
* Adds a new group to an existing group
*/
createGroup(group: KdbxGroup, name: string): KdbxGroup {
const subGroup = KdbxGroup.create(name, group);
group.groups.push(subGroup);
return subGroup;
}
/**
* Adds a new entry to a group
*/
createEntry(group: KdbxGroup): KdbxEntry {
const entry = KdbxEntry.create(this.meta, group);
group.entries.push(entry);
return entry;
}
/**
* Gets the default group
*/
getDefaultGroup(): KdbxGroup {
if (!this.groups[0]) {
throw new KdbxError(ErrorCodes.InvalidState, 'empty default group');
}
return this.groups[0];
}
/**
* Get a group by uuid, returns undefined if it's not found
*/
getGroup(uuid: KdbxUuid | string, parentGroup?: KdbxGroup): KdbxGroup | undefined {
const groups = parentGroup ? parentGroup.groups : this.groups;
for (const group of groups) {
if (group.uuid.equals(uuid)) {
return group;
}
const res = this.getGroup(uuid, group);
if (res) {
return res;
}
}
}
/**
* Move an object from one group to another
* @param object - object to be moved
* @param toGroup - target parent group
* @param atIndex - index in target group (by default, insert to the end of the group)
*/
move<T extends KdbxEntry | KdbxGroup>(
object: T,
toGroup: KdbxGroup | undefined | null,
atIndex?: number
): void {
const containerProp = object instanceof KdbxGroup ? 'groups' : 'entries';
const fromContainer = <T[]>object.parentGroup?.[containerProp];
const ix = fromContainer?.indexOf(object);
if (typeof ix !== 'number' || ix < 0) {
return;
}
fromContainer.splice(ix, 1);
if (toGroup) {
const toContainer = <T[]>toGroup[containerProp];
if (typeof atIndex === 'number' && atIndex >= 0) {
toContainer.splice(atIndex, 0, object);
} else {
toContainer.push(object);
}
} else {
const now = new Date();
if (object instanceof KdbxGroup) {
for (const item of object.allGroupsAndEntries()) {
const uuid = item.uuid;
this.addDeletedObject(uuid, now);
}
} else {
if (object.uuid) {
this.addDeletedObject(object.uuid, now);
}
}
}
object.previousParentGroup = object.parentGroup?.uuid;
object.parentGroup = toGroup ?? undefined;
object.times.locationChanged = new Date();
}
/**
* Adds a so-called deleted object, this is used to keep track of objects during merging
* @param uuid - object uuid
* @param dt - deletion date
*/
addDeletedObject(uuid: KdbxUuid, dt: Date): void {
const deletedObject = new KdbxDeletedObject();
deletedObject.uuid = uuid;
deletedObject.deletionTime = dt;
this.deletedObjects.push(deletedObject);
}
/**
* Delete an entry or a group
* Depending on settings, removes either to trash, or completely
*/
remove<T extends KdbxEntry | KdbxGroup>(object: T): void {
let toGroup = undefined;
if (this.meta.recycleBinEnabled && this.meta.recycleBinUuid) {
this.createRecycleBin();
toGroup = this.getGroup(this.meta.recycleBinUuid);
}
this.move(object, toGroup);
}
/**
* Creates a binary in the db and returns an object that can be put to entry.binaries
*/
createBinary(value: KdbxBinary): Promise<KdbxBinaryWithHash> {
return this.binaries.add(value);
}
/**
* Import an entry from another file
* It's up to caller to decide what should happen to the original entry in the source file
* Returns the new entry
* @param entry - entry to be imported
* @param group - target parent group
* @param file - the source file containing the group
*/
importEntry(entry: KdbxEntry, group: KdbxGroup, file: Kdbx): KdbxEntry {
const newEntry = new KdbxEntry();
const uuid = KdbxUuid.random();
newEntry.copyFrom(entry);
newEntry.uuid = uuid;
for (const historyEntry of entry.history) {
const newHistoryEntry = new KdbxEntry();
newHistoryEntry.copyFrom(historyEntry);
newHistoryEntry.uuid = uuid;
newEntry.history.push(newHistoryEntry);
}
const binaries = new Map<string, KdbxBinaryWithHash>();
const customIcons = new Set<string>();
for (const e of newEntry.history.concat(newEntry)) {
if (e.customIcon) {
customIcons.add(e.customIcon.id);
}
for (const binary of e.binaries.values()) {
if (KdbxBinaries.isKdbxBinaryWithHash(binary)) {
binaries.set(binary.hash, binary);
}
}
}
for (const binary of binaries.values()) {
const fileBinary = file.binaries.getValueByHash(binary.hash);
if (fileBinary && !this.binaries.getValueByHash(binary.hash)) {
this.binaries.addWithHash(binary);
}
}
for (const customIconId of customIcons) {
const customIcon = file.meta.customIcons.get(customIconId);
if (customIcon) {
this.meta.customIcons.set(customIconId, customIcon);
}
}
group.entries.push(newEntry);
newEntry.parentGroup = group;
newEntry.times.update();
return newEntry;
}
/**
* Perform database cleanup
* @param settings.historyRules - remove extra history, it it doesn't match defined rules, e.g. records number
* @param settings.customIcons - remove unused custom icons
* @param settings.binaries - remove unused binaries
*/
cleanup(settings?: {
historyRules?: boolean;
customIcons?: boolean;
binaries?: boolean;
}): void {
const now = new Date();
const historyMaxItems =
settings?.historyRules &&
typeof this.meta.historyMaxItems === 'number' &&
this.meta.historyMaxItems >= 0
? this.meta.historyMaxItems
: Infinity;
const usedCustomIcons = new Set<string>();
const usedBinaries = new Set<string>();
const processEntry = (entry: KdbxEntry) => {
if (entry.customIcon) {
usedCustomIcons.add(entry.customIcon.id);
}
for (const binary of entry.binaries.values()) {
if (KdbxBinaries.isKdbxBinaryWithHash(binary)) {
usedBinaries.add(binary.hash);
}
}
};
for (const item of this.getDefaultGroup().allGroupsAndEntries()) {
if (item instanceof KdbxEntry) {
if (item.history.length > historyMaxItems) {
item.removeHistory(0, item.history.length - historyMaxItems);
}
processEntry(item);
if (item.history) {
for (const historyEntry of item.history) {
processEntry(historyEntry);
}
}
} else {
if (item.customIcon) {
usedCustomIcons.add(item.customIcon.id);
}
}
}
if (settings?.customIcons) {
for (const customIcon of this.meta.customIcons.keys()) {
if (!usedCustomIcons.has(customIcon)) {
const uuid = new KdbxUuid(customIcon);
this.addDeletedObject(uuid, now);
this.meta.customIcons.delete(customIcon);
}
}
}
if (settings?.binaries) {
for (const binary of this.binaries.getAllWithHashes()) {
if (!usedBinaries.has(binary.hash)) {
this.binaries.deleteWithHash(binary.hash);
}
}
}
}
/**
* Merge the db with another db
* Some parts of the remote DB are copied by reference, so it should NOT be modified after merge
* Suggested use case:
* - open the local db
* - get a remote db somehow and open in
* - merge the remote db into the local db: local.merge(remote)
* - close the remote db
* @param remote - database to merge in
*/
merge(remote: Kdbx): void {
const root = this.getDefaultGroup();
const remoteRoot = remote.getDefaultGroup();
if (!root || !remoteRoot) {
throw new KdbxError(ErrorCodes.MergeError, 'no default group');
}
if (!root.uuid.equals(remoteRoot.uuid)) {
throw new KdbxError(ErrorCodes.MergeError, 'default group is different');
}
const objectMap = this.getObjectMap();
for (const rem of remote.deletedObjects) {
if (rem.uuid && rem.deletionTime && !objectMap.deleted.has(rem.uuid.id)) {
this.deletedObjects.push(rem);
objectMap.deleted.set(rem.uuid.id, rem.deletionTime);
}
}
for (const remoteBinary of remote.binaries.getAllWithHashes()) {
if (!this.binaries.getValueByHash(remoteBinary.hash)) {
this.binaries.addWithHash(remoteBinary);
}
}
const remoteObjectMap = remote.getObjectMap();
objectMap.remoteEntries = remoteObjectMap.entries;
objectMap.remoteGroups = remoteObjectMap.groups;
this.meta.merge(remote.meta, objectMap);
root.merge(objectMap);
this.cleanup({ historyRules: true, customIcons: true, binaries: true });
}
/**
* Gets editing state tombstones (for successful merge)
* The replica must save this state with the db, assign in on opening the db,
* and call removeLocalEditState on successful upstream push.
* This state is JSON serializable.
*/
getLocalEditState(): KdbxEditState {
const editingState: KdbxEditState = {
entries: {}
};
for (const entry of this.getDefaultGroup().allEntries()) {
if (entry._editState && entry.uuid && editingState.entries) {
editingState.entries[entry.uuid.id] = entry._editState;
}
}
if (this.meta._editState) {
editingState.meta = this.meta._editState;
}
return editingState;
}
/**
* Sets editing state tombstones returned previously by getLocalEditState
* The replica must call this method on opening the db to the state returned previously on getLocalEditState.
* @param editingState - result of getLocalEditState invoked before on saving the db
*/
setLocalEditState(editingState: KdbxEditState): void {
for (const entry of this.getDefaultGroup().allEntries()) {
if (editingState.entries?.[entry.uuid.id]) {
entry._editState = editingState.entries[entry.uuid.id];
}
}
if (editingState.meta) {
this.meta._editState = editingState.meta;
}
}
/**
* Removes editing state tombstones
* Immediately after successful upstream push the replica must:
* - call this method
* - discard any previous state obtained by getLocalEditState call before
*/
removeLocalEditState(): void {
for (const entry of this.getDefaultGroup().allEntries()) {
entry._editState = undefined;
}
this.meta._editState = undefined;
}
/**
* Upgrade the file to latest version
*/
upgrade(): void {
this.setVersion(KdbxHeader.MaxFileVersion);
}
/**
* Set the file version to a specified number
*/
setVersion(version: 3 | 4): void {
this.meta.headerHash = undefined;
this.meta.settingsChanged = new Date();
this.header.setVersion(version);
}
/**
* Set file key derivation function
* @param kdf - KDF id, from KdfId
*/
setKdf(kdf: string): void {
this.meta.headerHash = undefined;
this.meta.settingsChanged = new Date();
this.header.setKdf(kdf);
}
private getObjectMap(): MergeObjectMap {
const objectMap: MergeObjectMap = {
entries: new Map<string, KdbxEntry>(),
groups: new Map<string, KdbxGroup>(),
remoteEntries: new Map<string, KdbxEntry>(),
remoteGroups: new Map<string, KdbxGroup>(),
deleted: new Map<string, Date>()
};
for (const item of this.getDefaultGroup().allGroupsAndEntries()) {
if (objectMap.entries.has(item.uuid.id)) {
throw new KdbxError(ErrorCodes.MergeError, `duplicate: ${item.uuid}`);
}
if (item instanceof KdbxEntry) {
objectMap.entries.set(item.uuid.id, item);
} else {
objectMap.groups.set(item.uuid.id, item);
}
}
for (const deletedObject of this.deletedObjects) {
if (deletedObject.uuid && deletedObject.deletionTime) {
objectMap.deleted.set(deletedObject.uuid.id, deletedObject.deletionTime);
}
}
return objectMap;
}
loadFromXml(ctx: KdbxContext): Promise<Kdbx> {
if (!this.xml) {
throw new KdbxError(ErrorCodes.InvalidState, 'xml is not set');
}
const doc = this.xml.documentElement;
if (doc.tagName !== XmlNames.Elem.DocNode) {
throw new KdbxError(ErrorCodes.FileCorrupt, 'bad xml root');
}
this.parseMeta(ctx);
return this.binaries.computeHashes().then(() => {
this.parseRoot(ctx);
return this;
});
}
private parseMeta(ctx: KdbxContext): void {
if (!this.xml) {
throw new KdbxError(ErrorCodes.InvalidState, 'xml is not set');
}
const node = XmlUtils.getChildNode(
this.xml.documentElement,
XmlNames.Elem.Meta,
'no meta node'
);
this.meta = KdbxMeta.read(node, ctx);
}
private parseRoot(ctx: KdbxContext): void {
if (!this.xml) {
throw new KdbxError(ErrorCodes.InvalidState, 'xml is not set');
}
this.groups = [];
this.deletedObjects = [];
const node = XmlUtils.getChildNode(
this.xml.documentElement,
XmlNames.Elem.Root,
'no root node'
);
for (let i = 0, cn = node.childNodes, len = cn.length; i < len; i++) {
const childNode = <Element>cn[i];
switch (childNode.tagName) {
case XmlNames.Elem.Group:
this.readGroup(childNode, ctx);
break;
case XmlNames.Elem.DeletedObjects:
this.readDeletedObjects(childNode);
break;
}
}
}
private readDeletedObjects(node: Node): void {
for (let i = 0, cn = node.childNodes, len = cn.length; i < len; i++) {
const childNode = <Element>cn[i];
switch (childNode.tagName) {
case XmlNames.Elem.DeletedObject:
this.deletedObjects.push(KdbxDeletedObject.read(childNode));
break;
}
}
}
private readGroup(node: Node, ctx: KdbxContext): void {
this.groups.push(KdbxGroup.read(node, ctx));
}
buildXml(ctx: KdbxContext): void {
const xml = XmlUtils.create(XmlNames.Elem.DocNode);
this.meta.write(xml.documentElement, ctx);
const rootNode = XmlUtils.addChildNode(xml.documentElement, XmlNames.Elem.Root);
for (const g of this.groups) {
g.write(rootNode, ctx);
}
const delObjNode = XmlUtils.addChildNode(rootNode, XmlNames.Elem.DeletedObjects);
for (const d of this.deletedObjects) {
d.write(delObjNode, ctx);
}
this.xml = xml;
}
versionIsAtLeast(major: number, minor: number): boolean {
return (
this.versionMajor > major || (this.versionMajor === major && this.versionMinor >= minor)
);
}
} | the_stack |
import { App, Modal, Setting, TextComponent, Notice, ButtonComponent, ExtraButtonComponent, ToggleComponent } from "obsidian"
import SuperchargedLinks from "main"
import Field from "src/Field"
import FieldSetting from "src/settings/FieldSetting"
export default class FieldSettingsModal extends Modal {
namePromptComponent: TextComponent
valuesPromptComponents: Array<TextComponent> = []
isMultiTogglerComponent: ToggleComponent
isCycleTogglerComponent: ToggleComponent
listNotePathComponent: TextComponent
saved: boolean = false
property: Field
plugin: SuperchargedLinks
initialProperty: Field
parentSetting: Setting
new: boolean = true
parentSettingContainer: HTMLElement
constructor(app: App, plugin: SuperchargedLinks, parentSettingContainer: HTMLElement, parentSetting?: Setting, property?: Field) {
super(app)
this.plugin = plugin
this.parentSetting = parentSetting
this.initialProperty = new Field()
this.parentSettingContainer = parentSettingContainer
if (property) {
this.new = false
this.property = property
this.initialProperty.name = property.name
this.initialProperty.id = property.id
Object.keys(property.values).forEach(k => {
this.initialProperty.values[k] = property.values[k]
})
} else {
let newId = 1
this.plugin.initialProperties.forEach(prop => {
if (parseInt(prop.id) && parseInt(prop.id) >= newId) {
newId = parseInt(prop.id) + 1
}
})
this.property = new Field()
this.property.id = newId.toString()
this.initialProperty.id = newId.toString()
}
}
onOpen(): void {
if (this.property.name == "") {
this.titleEl.setText(`Add a property and set predefined`)
} else {
this.titleEl.setText(`Manage settings values for ${this.property.name}`)
}
this.createForm()
}
onClose(): void {
Object.assign(this.property, this.initialProperty)
if (!this.new) {
this.parentSetting.infoEl.textContent =
`${this.property.name}: [${Object.keys(this.property.values).map(k => this.property.values[k]).join(', ')}]`
} else if (this.saved) {
new FieldSetting(this.parentSettingContainer, this.property, this.app, this.plugin)
}
}
setValueListText(header: HTMLDivElement): void {
header.setText(`Preset values: ${Object.values(this.property.values).join(', ')}`)
}
createnameInputContainer(parentNode: HTMLDivElement): TextComponent {
const propertyNameContainerLabel = parentNode.createDiv()
propertyNameContainerLabel.setText(`Property Name:`)
const input = new TextComponent(parentNode)
const name = this.property.name
input.setValue(name)
input.setPlaceholder("Name of the property")
input.onChange(value => {
this.property.name = value
this.titleEl.setText(`Manage predefined values for ${this.property.name}`)
FieldSettingsModal.removeValidationError(input)
})
return input
}
createTogglerContainer(parentNode: HTMLDivElement, label: string): ToggleComponent {
const propertyContainerLabel = parentNode.createDiv({
cls: 'frontmatter-checkbox-toggler'
})
propertyContainerLabel.setText(label)
const toggler = new ToggleComponent(parentNode)
return toggler
}
createListNoteContainer(parentNode: HTMLDivElement): TextComponent {
const listNoteContainerLabel = parentNode.createDiv()
listNoteContainerLabel.setText(`Path of the note containing the values:`)
const input = new TextComponent(parentNode)
const listNotePath = this.property.valuesListNotePath
input.setValue(listNotePath)
input.setPlaceholder("Path/of/the/note.md")
input.onChange(value => this.property.valuesListNotePath = value)
return input
}
removePresetValue(key: string): void {
let newValues: Record<string, string> = {}
for (let _key in this.property.values) {
if (key !== _key) {
newValues[_key] = this.property.values[_key]
}
}
this.property.values = newValues
}
createValueContainer(parentNode: HTMLDivElement, header: HTMLDivElement, key: string): TextComponent {
const values = this.property.values
const presetValue = values[key]
const valueContainer = parentNode.createDiv({
cls: 'frontmatter-prompt-container',
})
const input = new TextComponent(valueContainer)
input.setValue(presetValue)
input.onChange(value => {
this.property.values[key] = value
this.setValueListText(header)
FieldSettingsModal.removeValidationError(input)
})
const valueRemoveButton = new ButtonComponent(valueContainer)
valueRemoveButton.setIcon("trash")
.onClick((evt: MouseEvent) => {
evt.preventDefault
this.removePresetValue(key)
this.setValueListText(header)
parentNode.removeChild(valueContainer)
this.valuesPromptComponents.remove(input)
})
if (key != Object.keys(this.property.values)[0]) {
const valueUpgradeButton = new ButtonComponent(valueContainer)
valueUpgradeButton.setButtonText("▲")
valueUpgradeButton.onClick((evt: MouseEvent) => {
const thisValue = values[key]
const upperComponent = this.valuesPromptComponents[this.valuesPromptComponents.indexOf(input) - 1]
if (upperComponent) {
const upperValue = upperComponent.inputEl.value
const upperKey = Object.keys(values).filter(k => values[k] == upperValue)[0]
if (upperKey) {
upperComponent.setValue(thisValue)
values[upperKey] = thisValue
input.setValue(upperValue)
values[key] = upperValue
}
}
})
}
return input
}
createForm(): void {
const div = this.contentEl.createDiv({
cls: "frontmatter-prompt-div"
})
const mainDiv = div.createDiv({
cls: "frontmatter-prompt-form"
})
/* Property Name Section */
const nameContainer = mainDiv.createDiv()
this.namePromptComponent = this.createnameInputContainer(nameContainer)
mainDiv.createDiv({ cls: 'frontmatter-separator' }).createEl("hr")
/* Property is Multi section*/
const multiContainer = mainDiv.createDiv()
this.isMultiTogglerComponent = this.createTogglerContainer(multiContainer, "Is Multi: ")
this.isMultiTogglerComponent.setValue(this.property.isMulti)
this.isMultiTogglerComponent.setTooltip("Can this property have multiple values?")
this.isMultiTogglerComponent.onChange(value => {
this.property.isMulti = value
if (this.property.isCycle && this.property.isMulti) {
this.property.isCycle = false
this.isCycleTogglerComponent.setValue(false)
}
})
mainDiv.createDiv({ cls: 'frontmatter-separator' }).createEl("hr")
/* Property is Cycle section*/
const cycleContainer = mainDiv.createDiv()
this.isCycleTogglerComponent = this.createTogglerContainer(cycleContainer, "Is Cycle: ")
this.isCycleTogglerComponent.setValue(this.property.isCycle)
this.isCycleTogglerComponent.setTooltip("Is this property's values set in cycle mode?")
this.isCycleTogglerComponent.onChange(value => {
this.property.isCycle = value
if (this.property.isCycle && this.property.isMulti) {
this.property.isMulti = false
this.isMultiTogglerComponent.setValue(false)
}
})
mainDiv.createDiv({ cls: 'frontmatter-separator' }).createEl("hr")
/* Property's note for list of Values */
const listNotePathContainer = mainDiv.createDiv()
this.listNotePathComponent = this.createListNoteContainer(listNotePathContainer)
mainDiv.createDiv({ cls: 'frontmatter-separator' }).createEl("hr")
/* Property Values */
const valuesList = mainDiv.createDiv()
const valuesListHeader = valuesList.createDiv()
valuesListHeader.createEl("h2")
valuesListHeader.setText(`Preset values: ${Object.values(this.property.values).join(', ')}`)
const valuesListBody = valuesList.createDiv()
Object.keys(this.property.values).forEach(key => {
this.valuesPromptComponents.push(this.createValueContainer(valuesListBody, valuesListHeader, key))
})
/* Add a new Values */
const valuesListFooter = valuesList.createDiv()
const addValue = valuesListFooter.createEl('button')
addValue.type = 'button'
addValue.textContent = 'Add'
addValue.onClickEvent((evt: MouseEvent) => {
evt.preventDefault
this.property.insertNewValue("")
.then(newKey => { this.createValueContainer(valuesListBody, valuesListHeader, newKey) })
})
mainDiv.createDiv({ cls: 'frontmatter-separator' }).createEl("hr")
/* footer buttons*/
const footerEl = this.contentEl.createDiv()
const footerButtons = new Setting(footerEl)
footerButtons.addButton((b) => this.createSaveButton(b))
footerButtons.addExtraButton((b) => this.createCancelButton(b));
}
createSaveButton(b: ButtonComponent): ButtonComponent {
b.setTooltip("Save")
.setIcon("checkmark")
.onClick(async () => {
let error = false
if (/^[#>-]/.test(this.property.name)) {
FieldSettingsModal.setValidationError(
this.namePromptComponent, this.namePromptComponent.inputEl,
"Property name cannot start with #, >, -"
);
error = true;
}
if (this.property.name == "") {
FieldSettingsModal.setValidationError(
this.namePromptComponent, this.namePromptComponent.inputEl,
"Property name can not be Empty"
);
error = true
}
this.valuesPromptComponents.forEach(input => {
if (/^[#>-]/.test(input.inputEl.value)) {
FieldSettingsModal.setValidationError(
input, input.inputEl.parentElement.lastElementChild,
"Values cannot cannot start with #, >, -"
);
error = true;
}
if (/[,]/gu.test(input.inputEl.value)) {
FieldSettingsModal.setValidationError(
input, input.inputEl.parentElement.lastElementChild,
"Values cannot contain a comma"
);
error = true;
}
if (input.inputEl.value == "") {
FieldSettingsModal.setValidationError(
input, input.inputEl.parentElement.lastElementChild,
"Values can't be null."
);
error = true;
}
})
if (error) {
new Notice("Fix errors before saving.");
return;
}
this.saved = true;
const currentExistingProperty = this.plugin.initialProperties.filter(p => p.id == this.property.id)[0]
if (currentExistingProperty) {
Field.copyProperty(currentExistingProperty, this.property)
} else {
this.plugin.initialProperties.push(this.property)
}
this.initialProperty = this.property
this.plugin.saveSettings()
this.close();
})
return b
}
createCancelButton(b: ExtraButtonComponent): ExtraButtonComponent {
b.setIcon("cross")
.setTooltip("Cancel")
.onClick(() => {
this.saved = false;
/* reset values from settings */
if (this.initialProperty.name != "") {
Object.assign(this.property, this.initialProperty)
}
this.close();
});
return b;
}
/* utils functions */
static setValidationError(textInput: TextComponent, insertAfter: Element, message?: string) {
textInput.inputEl.addClass("is-invalid");
if (message) {
let mDiv = textInput.inputEl.parentElement.querySelector(
".invalid-feedback"
) as HTMLDivElement;
if (!mDiv) {
mDiv = createDiv({ cls: "invalid-feedback" });
}
mDiv.innerText = message;
mDiv.insertAfter(insertAfter);
}
}
static removeValidationError(textInput: TextComponent) {
if (textInput.inputEl.hasClass("is-invalid")) {
textInput.inputEl.removeClass("is-invalid")
textInput.inputEl.parentElement.removeChild(
textInput.inputEl.parentElement.lastElementChild
)
}
}
} | the_stack |
import { Component, OnInit, OnDestroy, ElementRef, ViewChild } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';
import { FormGroup, FormBuilder, AbstractControl, Validators } from '@angular/forms';
import { Store, select } from '@ngrx/store';
import { NgrxStateAtom } from '../../ngrx.reducers';
import { Subject } from 'rxjs';
import { distinctUntilKeyChanged, takeUntil, filter } from 'rxjs/operators';
import { pendingState } from 'app/entities/entities';
import { LayoutFacadeService, Sidebar } from 'app/entities/layout/layout.facade';
import {
automateSettingsState,
changeConfiguration
} from '../../entities/automate-settings/automate-settings.selectors';
import {
GetSettings,
ConfigureSettings
} from '../../entities/automate-settings/automate-settings.actions';
import {
JobSchedulerStatus,
IngestJob,
IngestJobs,
NonNestedJobName,
NestedJobName,
DefaultFormData,
JobCategories
} from '../../entities/automate-settings/automate-settings.model';
import { TelemetryService } from '../../services/telemetry/telemetry.service';
import { ProductDeployedService } from 'app/services/product-deployed/product-deployed.service';
@Component({
templateUrl: './automate-settings.component.html',
styleUrls: ['./automate-settings.component.scss']
})
export class AutomateSettingsComponent implements OnInit, OnDestroy {
@ViewChild('dataLifeCycleFormElement', {read: ElementRef}) dataLifeCycleFormElement: ElementRef;
public isDesktopView = false;
// Event Feed
eventFeedRemoveData: FormGroup;
eventFeedServerActions: FormGroup;
// Service Groups
serviceGroupNoHealthChecks: FormGroup;
serviceGroupRemoveServices: FormGroup;
// Client Runs
clientRunsRemoveData: FormGroup;
clientRunsLabelMissing: FormGroup;
clientRunsRemoveNodes: FormGroup;
// Compliance
complianceRemoveReports: FormGroup;
complianceRemoveScans: FormGroup;
automateSettingsForm: FormGroup;
jobSchedulerStatus: JobSchedulerStatus;
// Are settings currently saving
saving = false;
// Change origin boolean for formControl directive
shouldResetValues = false;
// Notification bits
notificationVisible = false;
notificationType = 'info';
notificationMessage = 'Settings saved.';
private isDestroyed = new Subject<boolean>();
constructor(
private store: Store<NgrxStateAtom>,
private layoutFacade: LayoutFacadeService,
private fb: FormBuilder,
private telemetryService: TelemetryService,
private productDeployedService: ProductDeployedService
) {
this.isDesktopView = this.productDeployedService.isProductDeployed('desktop');
const formDetails = this.getDefaultFormData(this.isDesktopView);
// EventFeed
this.eventFeedRemoveData = this.fb.group(formDetails.eventFeedRemoveData);
this.eventFeedServerActions = this.fb.group(formDetails.eventFeedServerActions);
// Service Groups
this.serviceGroupNoHealthChecks = this.fb.group(formDetails.serviceGroupNoHealthChecks);
this.serviceGroupRemoveServices = this.fb.group(formDetails.serviceGroupRemoveServices);
// Client Runs
this.clientRunsRemoveData = this.fb.group(formDetails.clientRunsRemoveData);
this.clientRunsLabelMissing = this.fb.group(formDetails.clientRunsLabelMissing);
this.clientRunsRemoveNodes = this.fb.group(formDetails.clientRunsRemoveNodes);
// Compliance
this.complianceRemoveReports = this.fb.group(formDetails.complianceRemoveReports);
this.complianceRemoveScans = this.fb.group(formDetails.complianceRemoveScans);
// Put the whole form together
this.automateSettingsForm = this.fb.group({
// Event Feed
eventFeedRemoveData: this.eventFeedRemoveData,
eventFeedServerActions: this.eventFeedServerActions,
// Service Groups
serviceGroupNoHealthChecks: this.serviceGroupNoHealthChecks,
serviceGroupRemoveServices: this.serviceGroupRemoveServices,
// Client Runs
clientRunsRemoveData: this.clientRunsRemoveData,
clientRunsLabelMissing: this.clientRunsLabelMissing,
clientRunsRemoveNodes: this.clientRunsRemoveNodes,
// Compliance
complianceRemoveReports: this.complianceRemoveReports,
complianceRemoveScans: this.complianceRemoveScans
});
}
ngOnInit() {
this.layoutFacade.showSidebar(Sidebar.Settings);
this.store.dispatch(new GetSettings({}));
this.store.select(automateSettingsState).pipe(
takeUntil(this.isDestroyed),
distinctUntilKeyChanged('jobSchedulerStatus')
)
.subscribe((automateSettingsSelector) => {
if (automateSettingsSelector.errorResp !== null) {
const error = automateSettingsSelector.errorResp;
const errMsg = 'Unable to load settings.';
this.showErrorNotification(error, errMsg);
} else {
this.jobSchedulerStatus = automateSettingsSelector.jobSchedulerStatus;
this.telemetryService.track('lifecycleConfiguration', this.jobSchedulerStatus);
this.updateForm(this.jobSchedulerStatus);
}
});
// subscribe to changeConfiguration
this.store.pipe(
select(changeConfiguration),
filter(change => this.saving && !pendingState(change)),
takeUntil(this.isDestroyed)
)
.subscribe((changeConfigurationSelector) => {
if (changeConfigurationSelector.errorResp !== null) {
const error = changeConfigurationSelector.errorResp;
const errMsg = 'Unable to update one or more settings.';
this.showErrorNotification(error, errMsg);
this.store.dispatch(new GetSettings({})); // reset form to previously stored settings
this.automateSettingsForm.markAsPristine();
this.saving = false;
} else if (changeConfigurationSelector.status === 'loadingSuccess') {
this.showSuccessNotification();
this.saving = false;
// After a successful save, trigger a notification to FormControlDirective
// to consider the newly updated values as the new "original" values
this.shouldResetValues = true;
this.automateSettingsForm.markAsPristine();
}
});
}
ngOnDestroy(): void {
this.isDestroyed.next(true);
this.isDestroyed.complete();
}
// This prevents a user from being allowed to enter negative numbers
// or other actions that we don't want to allow
public preventNegatives(key: string) {
const allowedKeys = [
'1', '2', '3', '4', '5', '6', '7', '8', '9', '0',
'Backspace', 'ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Tab'
];
return allowedKeys.includes(key);
}
// Update the width of input when greater than one digit
public autoUpdateInputWidth(element: HTMLInputElement): void {
// Keep default in sync with input width in automate-settings.component.scss
const DEFAULT_WIDTH_PIXELS = 64;
const numDigits = element.value.length;
if (numDigits > 1) {
element.style.width = `${DEFAULT_WIDTH_PIXELS + (9 * (numDigits - 1))}px`;
} else {
element.style.width = `${DEFAULT_WIDTH_PIXELS}px`;
}
}
private setEnabled(control: AbstractControl, enabled: boolean): void {
if (enabled) {
control.enable();
control.setValidators([Validators.required]);
control.updateValueAndValidity();
} else {
control.disable();
}
}
public handleFormActivation(form: FormGroup, checked: boolean): void {
// patchValue does not mark the form dirty, so we need to do it manually;
form.get('disabled').markAsDirty();
// patchValue is a workaround for the chef-checkbox because we need to be
// able to store a reference to it being checked or not
form.patchValue({
disabled: !checked
});
// this disables the relevant controls;
this.setEnabled(form.controls.unit, checked);
this.setEnabled(form.controls.threshold, checked);
}
// Apply the changes that the user updated in the forms
public applyChanges() {
this.saving = true;
this.shouldResetValues = false;
// Note: Services are currently not enabled through the form
const jobs: IngestJob[] = [
// Event Feed
IngestJobs.EventFeedRemoveData,
IngestJobs.EventFeedServerActions,
// Service Groups
IngestJobs.ServiceGroupNoHealthChecks,
IngestJobs.ServiceGroupRemoveServices,
// Client Runs
IngestJobs.ClientRunsRemoveData,
IngestJobs.ClientRunsLabelMissing,
IngestJobs.ClientRunsRemoveNodes,
// Compliance
IngestJobs.ComplianceRemoveReports,
IngestJobs.ComplianceRemoveScans
].map(jobName => {
// Extract the raw values from the formGroup so that
// we can make sure to keep disabled inputs populated in the UI
const jobForm = this[jobName].getRawValue();
const isNested = jobForm.nested_name ? true : false;
const job = new IngestJob(null, null);
job.category = jobForm.category;
job.name = jobForm.name;
job.disabled = jobForm.disabled;
// If the user doesn't enter any number at all - this defaults to 0
jobForm.threshold === null
// When not nested, threshold needs to be a string ex: '4w'
? job.threshold = '0' + jobForm.unit
: job.threshold = jobForm.threshold + jobForm.unit;
if ( isNested ) {
// When nested, threshold needs to be a number ex: 16
job.nested_name = jobForm.nested_name;
job.threshold = jobForm.threshold; // Automatically becomes a 0 from
// parseInt in request if left blank
}
return job;
});
this.store.dispatch(new ConfigureSettings({jobs: jobs}));
}
// Hides the notification banner
public hideNotification() {
this.notificationVisible = false;
}
// Returns timeout depending on the type of notification is being displayed
public notificationTimeout() {
switch (this.notificationType) {
case 'error':
return 8;
default:
return 4;
}
}
private showErrorNotification(error: HttpErrorResponse, msg: string) {
// Extract the error message from the HttpErrorResponse
// if it is available inside the body.
//
// The format looks similar like:
// {
// "error":"invalid time unit: '-1d'",
// "code":3,
// "details":[]
// }
if (error.error.error) {
msg = msg + ' [' + error.error.error + ']';
}
console.error(error.message);
this.notificationType = 'error';
this.notificationMessage = msg;
this.notificationVisible = true;
}
private showSuccessNotification() {
this.notificationType = 'info';
this.notificationMessage = 'All settings have been updated successfully';
this.notificationVisible = true;
}
// Update forms until we get the job scheduler status
public updateForm(jobSchedulerStatus: JobSchedulerStatus) {
if (jobSchedulerStatus === null) {
return;
}
jobSchedulerStatus.jobs.forEach((job: IngestJob) => {
switch (job.category) {
case 'services':
case 'infra': {
this.populateNonNested(job);
}
break;
case 'compliance': // fallthrough
case 'event_feed': {
this.populateNested(job);
}
break;
default:
break;
}
});
// Update all number inputs to grow if holding number larger than two digits
const numberInputs = Array.from(
this.dataLifeCycleFormElement.nativeElement.querySelectorAll('.auto-update-width'));
numberInputs.forEach((element: HTMLInputElement) => this.autoUpdateInputWidth(element));
// After a successful load of initial values, trigger a notification
// to FormControlDirective to treat them as the "original" values.
this.shouldResetValues = true;
this.automateSettingsForm.markAsPristine();
}
// Splits a packed threshold into a number and a unit, where unit is a single character
// example: '12d' => ['12', 'd']
private splitThreshold(threshold: string): [string, string] {
return [
threshold.slice(0, threshold.length - 1),
threshold.slice(-1)
];
}
private populateNonNested(job: IngestJob): void {
let formThreshold, formUnit;
switch (job.name) {
case NonNestedJobName.MissingNodesForDeletion: {
if (!this.isDesktopView) {
this.handleDisable(this.clientRunsRemoveNodes, job.disabled);
}
[formThreshold, formUnit] = this.splitThreshold(job.threshold);
this.clientRunsRemoveNodes.patchValue({
unit: formUnit,
threshold: formThreshold,
disabled: job.disabled
});
}
break;
case NonNestedJobName.MissingNodes: {
if (!this.isDesktopView) {
this.handleDisable(this.clientRunsLabelMissing, job.disabled);
}
[formThreshold, formUnit] = this.splitThreshold(job.threshold);
this.clientRunsLabelMissing.patchValue({
unit: formUnit,
threshold: formThreshold,
disabled: job.disabled
});
}
break;
case NonNestedJobName.DeleteNodes: {
// delete_nodes not yet implemented
}
break;
case NonNestedJobName.PeriodicPurgeTimeseries: {
this.populateNested(job);
}
break;
case NonNestedJobName.DisconnectedServices:
this.handleDisable(this.serviceGroupNoHealthChecks, job.disabled);
[formThreshold, formUnit] = this.splitThreshold(job.threshold);
this.serviceGroupNoHealthChecks.patchValue({
unit: formUnit,
threshold: formThreshold,
disabled: job.disabled
});
break;
case NonNestedJobName.DeleteDisconnectedServices:
this.handleDisable(this.serviceGroupRemoveServices, job.disabled);
[formThreshold, formUnit] = this.splitThreshold(job.threshold);
this.serviceGroupRemoveServices.patchValue({
unit: formUnit,
threshold: formThreshold,
disabled: job.disabled
});
break;
default:
break;
}
}
private populateNested(job: IngestJob): void {
const _jobs = job.purge_policies.elasticsearch;
_jobs.forEach(_job => {
const form = {
threshold: _job.older_than_days,
disabled: _job.disabled
};
switch (_job.name) {
case NestedJobName.ComplianceReports: {
this.handleDisable(this.complianceRemoveReports, _job.disabled);
this.complianceRemoveReports.patchValue(form);
}
break;
case NestedJobName.ComplianceScans: {
this.handleDisable(this.complianceRemoveScans, _job.disabled);
this.complianceRemoveScans.patchValue(form);
}
break;
case NestedJobName.Feed: {
this.handleDisable(this.eventFeedRemoveData, _job.disabled);
this.eventFeedRemoveData.patchValue(form);
}
break;
case NestedJobName.Actions: {
this.handleDisable(this.eventFeedServerActions, _job.disabled);
this.eventFeedServerActions.patchValue(form);
}
break;
case NestedJobName.ConvergeHistory: {
this.handleDisable(this.clientRunsRemoveData, _job.disabled);
this.clientRunsRemoveData.patchValue(form);
}
break;
default:
break;
}
});
}
private handleDisable(form: FormGroup, disabled: boolean = false): void {
// this disables the relevant controls
// We have to pass in !disabled because the function is initially build for enabling
this.setEnabled(form.controls.unit, !disabled);
this.setEnabled(form.controls.threshold, !disabled);
}
private getDefaultFormData(isDesktopView: boolean): DefaultFormData {
return {
eventFeedRemoveData: {
category: JobCategories.EventFeed,
name: NonNestedJobName.PeriodicPurge,
nested_name: NestedJobName.Feed,
unit: { value: 'd', disabled: false },
threshold: [{ value: '30', disabled: false}, Validators.required],
disabled: false
},
eventFeedServerActions: {
category: JobCategories.Infra,
name: NonNestedJobName.PeriodicPurgeTimeseries,
nested_name: NestedJobName.Actions,
unit: { value: 'd', disabled: false },
threshold: [{ value: '30', disabled: false }, Validators.required],
disabled: false
},
serviceGroupNoHealthChecks: {
category: JobCategories.Services,
name: NonNestedJobName.DisconnectedServices,
unit: { value: 'm', disabled: false},
threshold: [{ value: '5', disabled: false }, Validators.required],
disabled: false
},
serviceGroupRemoveServices: {
category: JobCategories.Services,
name: NonNestedJobName.DeleteDisconnectedServices,
unit: { value: 'd', disabled: false },
threshold: [{ value: '5', disabled: false }, Validators.required],
disabled: false
},
clientRunsRemoveData: {
category: JobCategories.Infra,
name: NonNestedJobName.PeriodicPurgeTimeseries,
nested_name: NestedJobName.ConvergeHistory,
unit: { value: 'd', disabled: false },
threshold: [{ value: '30', disabled: false }, Validators.required],
disabled: false
},
clientRunsLabelMissing: {
category: JobCategories.Infra,
name: NonNestedJobName.MissingNodes,
unit: { value: 'd', disabled: isDesktopView },
threshold: [{ value: '30', disabled: isDesktopView }, Validators.required],
disabled: isDesktopView
},
clientRunsRemoveNodes: {
category: JobCategories.Infra,
name: NonNestedJobName.MissingNodesForDeletion,
unit: { value: 'd', disabled: isDesktopView },
threshold: [{ value: '30', disabled: isDesktopView }, Validators.required],
disabled: isDesktopView
},
complianceRemoveReports: {
category: JobCategories.Compliance,
name: NonNestedJobName.PeriodicPurge,
nested_name: NestedJobName.ComplianceReports,
unit: { value: 'd', disabled: false },
threshold: [{ value: '30', disabled: false }, Validators.required],
disabled: false
},
complianceRemoveScans: {
category: JobCategories.Compliance,
name: NonNestedJobName.PeriodicPurge,
nested_name: NestedJobName.ComplianceScans,
unit: { value: 'd', disabled: false },
threshold: [{ value: '30', disabled: false }, Validators.required],
disabled: false
}
};
}
} | the_stack |
import { Fun, Block } from "./ssa"
import { BlockTree } from "./blocktree"
import { debuglog as dlog } from "../util"
export class Loop {
header :Block // The header node of this (reducible) loop
outer :Loop|null = null // loop containing this loop
// By default, children, exits, and depth are not initialized.
children :Loop[] // loops nested directly within this loop. Initialized by assembleChildren().
exits :Block[] // exits records blocks reached by exits from this loop. Initialized by findExits().
// Next three fields used by regalloc and/or
// aid in computation of inner-ness and list of blocks.
nBlocks :int // Number of blocks in this loop but not within inner loops
depth :int // Nesting depth of the loop; 1 is outermost. Initialized by calculateDepths().
isInner :bool // True if never discovered to contain a loop
// register allocation uses this.
containsUnavoidableCall :bool // True if all paths through the loop have a call
constructor(header :Block, isInner :bool) {
this.header = header
isInner = isInner
}
// nearestOuterLoop returns the outer loop of loop most nearly
// containing block b; the header must dominate b. loop itself
// is assumed to not be that loop. For acceptable performance,
// we're relying on loop nests to not be terribly deep.
nearestOuterLoop(sdom :BlockTree, b :Block) :Loop|null {
let o: Loop|null = this.outer
for (; o && !sdom.isAncestorEq(o.header, b); o = o.outer) {}
return o
}
setDepth(d :int) {
this.depth = d
for (let c of this.children) {
c.setDepth(d + 1)
}
}
// iterationEnd checks if block b ends iteration of loop l.
// Ending iteration means either escaping to outer loop/code or
// going back to header
iterationEnd(b :Block, b2l :Loop[]) :bool {
return (
b === this.header ||
b2l[b.id] == null ||
(b2l[b.id] !== this && b2l[b.id].depth <= this.depth)
)
}
// recordIfExit checks sl (the loop containing b) to see if it is outside of
// this loop, and if so, records b as an exit block from l and returns true.
recordIfExit(sl :Loop|null, b :Block) :bool {
const l = this
if (sl !== l) {
if (!sl || sl.depth <= l.depth) {
l.exits.push(b)
return true
}
// sl is not nil, and is deeper than l
// it's possible for this to be a goto into an irreducible loop made from gotos.
while (sl!.depth > l.depth) {
sl = sl!.outer
}
if (sl !== l) {
l.exits.push(b)
return true
}
}
return false
}
}
export class LoopNest {
f :Fun
b2l :Loop[]
po :Block[]
sdom :BlockTree
loops :Loop[]
hasIrreducible :bool
// Record which of the lazily initialized fields have actually been initialized.
initializedChildren :bool = false
initializedDepth :bool = false
initializedExits :bool = false
constructor(
f :Fun,
b2l :Loop[],
po :Block[],
sdom :BlockTree,
loops :Loop[],
hasIrreducible :bool,
) {
this.f = f
this.b2l = b2l
this.po = po
this.sdom = sdom
this.loops = loops
this.hasIrreducible = hasIrreducible
}
// assembleChildren initializes the children field of each loop in the nest.
// Loop A is a child of loop B if A is directly nested within B
// (based on the reducible-loops detection above)
assembleChildren() {
const ln = this
if (ln.initializedChildren) {
return
}
for (let l of ln.loops) {
if (l.outer) {
l.outer.children.push(l)
}
}
ln.initializedChildren = true
}
// calculateDepths uses the children field of loops to determine the nesting
// depth (outer=1) of each loop. This is helpful for finding exit edges.
calculateDepths() {
const ln = this
if (ln.initializedDepth) {
return
}
ln.assembleChildren()
for (let l of ln.loops) {
if (!l.outer) {
l.setDepth(1)
}
}
ln.initializedDepth = true
}
// findExits uses loop depth information to find the exits from a loop.
findExits() {
const ln = this
if (ln.initializedExits) {
return
}
ln.calculateDepths()
let b2l = ln.b2l
for (let b of ln.po) {
let l = b2l[b.id]
if (l && b.succs.length == 2) {
let sl = b2l[b.succs[0].id]
if (l.recordIfExit(sl, b.succs[0])) {
continue
}
sl = b2l[b.succs[1].id]
if (l.recordIfExit(sl, b.succs[1])) {
continue
}
}
}
ln.initializedExits = true
}
}
export function loopnest(f :Fun) :LoopNest {
let po = f.postorder()
let sdom = f.sdom()
let numblocks = f.numBlocks()
let b2l = new Array<Loop>(numblocks)
let loops = [] as Loop[]
let visited = new Array<bool>(numblocks)
let sawIrred = false
po = f.blocks.slice().reverse()
// Reducible-loop-nest-finding.
for (let b of po) {
dlog(`loop finding at ${b}`)
let innermost :Loop|null = null // innermost header reachable from this block
// IF any successor s of b is in a loop headed by h
// AND h dominates b
// THEN b is in the loop headed by h.
//
// Choose the first/innermost such h.
//
// IF s itself dominates b, then s is a loop header;
// and there may be more than one such s.
// Since there's at most 2 successors, the inner/outer ordering
// between them can be established with simple comparisons.
for (let bb of b.succs) {
// bb := e.b
let l :Loop|null = b2l[bb.id]
if (sdom.isAncestorEq(bb, b)) { // Found a loop header
dlog(`loop finding succ ${bb} of ${b} is header`)
if (l) {
l = new Loop(bb, /*isInner*/ true)
loops.push(l)
b2l[bb.id] = l
}
} else if (!visited[bb.id]) { // Found an irreducible loop
sawIrred = true
dlog(`loop finding succ ${bb} of ${b} is IRREDUCABLE, in ${f}`)
} else if (l) {
// TODO handle case where l is irreducible.
// Perhaps a loop header is inherited.
// is there any loop containing our successor whose header dominates b?
if (!sdom.isAncestorEq(l.header, b)) {
l = l.nearestOuterLoop(sdom, b)
}
if (l) {
dlog(`loop finding succ ${bb} of ${b} provides loop with header ${l.header}`)
// } else {
// dlog(`loop finding succ ${bb} of ${b} has no loop`)
}
// } else { // No loop
// dlog(`loop finding succ ${bb} of ${b} has no loop`)
}
if (!l || innermost === l) {
continue
}
if (!innermost) {
innermost = l
continue
}
if (sdom.isAncestor(innermost.header, l.header)) {
outerinner(sdom, innermost, l)
innermost = l
} else if (sdom.isAncestor(l.header, innermost.header)) {
outerinner(sdom, l, innermost)
}
}
if (innermost) {
b2l[b.id] = innermost
innermost.nBlocks++
}
visited[b.id] = true
}
let ln = new LoopNest(f, b2l, po, sdom, loops, sawIrred)
// Calculate containsUnavoidableCall for regalloc
let dominatedByCall = new Array<bool>(f.numBlocks())
for (let b of po) {
if (b.containsCall()) {
dominatedByCall[b.id] = true
}
}
// Run dfs to find path through the loop that avoids all calls.
// Such path either escapes loop or return back to header.
// It isn't enough to have exit not dominated by any call, for example:
// ... some loop
// call1 call2
// \ /
// exit
// ...
// exit is not dominated by any call, but we don't have call-free path to it.
for (let l of loops) {
// Header contains call.
if (dominatedByCall[l.header.id]) {
l.containsUnavoidableCall = true
continue
}
let callfreepath = false
let tovisit = [] as Block[]
// Push all non-loop non-exit successors of header onto toVisit.
for (let nb of l.header.succs) {
// This corresponds to loop with zero iterations.
if (!l.iterationEnd(nb, b2l)) {
tovisit.push(nb)
}
}
while (tovisit.length > 0) {
let cur = tovisit.pop()! ; assert(cur)
if (dominatedByCall[cur.id]) {
continue
}
// Record visited in dominatedByCall.
dominatedByCall[cur.id] = true
for (let nb of cur.succs) {
if (l.iterationEnd(nb, b2l)) {
callfreepath = true
}
if (!dominatedByCall[nb.id]) {
tovisit.push(nb)
}
}
if (callfreepath) {
break
}
}
if (!callfreepath) {
l.containsUnavoidableCall = true
}
}
dlog(`f.config.loopstats=${f.config.loopstats}, loops.length=${loops.length}`)
if (f.config.loopstats && loops.length > 0) {
ln.assembleChildren()
ln.calculateDepths()
ln.findExits()
// Note stats for non-innermost loops are slightly flawed because
// they don't account for inner loop exits that span multiple levels.
for (let l of loops) {
let x = l.exits.length
let cf = 0
if (!l.containsUnavoidableCall) {
cf = 1
}
let inner = 0
if (l.isInner) {
inner++
}
let stats :[string,any][] = [
["depth", l.depth],
["exits", x],
["is_inner", inner],
["always_calls", cf],
["n_blocks", l.nBlocks],
]
let longestStatName = stats.reduce((a, s) => Math.max(a, s[0].length), 0)
let spaces = " "
print(
`loopstats:` + stats.map(s =>
`${s[0]}${spaces.substr(0, longestStatName - s[0].length)} ${s[1]}\n`
).join("")
)
}
}
// if f.pass != nil && f.pass.debug > 1 && len(loops) > 0 {
// fmt.Printf("Loops in %s:\n", f.Name)
// for _, l := range loops {
// fmt.Printf("%s, b=", l.LongString())
// for _, b := range f.Blocks {
// if b2l[b.id] == l {
// fmt.Printf(" %s", b)
// }
// }
// fmt.Print("\n")
// }
// fmt.Printf("Nonloop blocks in %s:", f.Name)
// for _, b := range f.Blocks {
// if b2l[b.id] == nil {
// fmt.Printf(" %s", b)
// }
// }
// fmt.Print("\n")
// }
return ln
}
// outerinner records that outer contains inner
function outerinner(sdom :BlockTree, outer :Loop, inner :Loop) {
// There could be other outer loops found in some random order,
// locate the new outer loop appropriately among them.
// Outer loop headers dominate inner loop headers.
// Use this to put the "new" "outer" loop in the right place.
let oldouter = inner.outer
let inn = inner as Loop|null
while (oldouter && sdom.isAncestor(outer.header, oldouter.header)) {
inn = oldouter
oldouter = inn.outer
}
if (outer === oldouter) {
return
}
if (oldouter) {
outerinner(sdom, oldouter, outer)
}
inner.outer = outer
outer.isInner = false
} | the_stack |
import DisplayObject = etch.drawing.DisplayObject;
import {IApp} from '../IApp';
import IDisplayContext = etch.drawing.IDisplayContext
import Point = etch.primitives.Point;
declare var App: IApp;
export class BlockSprites {
public Ctx: CanvasRenderingContext2D;
private _Scaled: boolean;
private _Position: Point;
private _XOffset: number;
private _YOffset: number;
DrawSprite(ctx: IDisplayContext, pos: Point, scaled: boolean, blockType: string, pos2?: Point) {
this.Ctx = ctx.Ctx;
this._Scaled = scaled;
this._Position = pos;
this._XOffset = 0;
this._YOffset = 0;
var grd = App.GridSize;
switch (blockType) {
// All block cases must be lower case
case App.L10n.Blocks.Effect.Blocks.AutoWah.name.toLowerCase():
if (!this._Scaled) {
this._XOffset = (grd*0.5);
this._YOffset = (grd*0.5);
}
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[3].toString();// BLUE
App.FillColor(this.Ctx,App.Palette[3]);
this.DrawMoveTo(0,-1);
this.DrawLineTo(1,-1);
this.DrawLineTo(1,1);
this.DrawLineTo(-2,1);
this.Ctx.closePath();
this.Ctx.fill();
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[8].toString();// WHITE
App.FillColor(this.Ctx,App.Palette[8]);
this.DrawMoveTo(1,-1);
this.DrawLineTo(1,1);
this.DrawLineTo(-1,1);
this.Ctx.closePath();
this.Ctx.fill();
break;
case App.L10n.Blocks.Effect.Blocks.BitCrusher.name.toLowerCase():
if (!this._Scaled) {
this._YOffset = grd;
}
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[7].toString();// RED
App.FillColor(this.Ctx,App.Palette[7]);
this.DrawMoveTo(-1,0);
this.DrawLineTo(1,-2);
this.DrawLineTo(1,0);
this.DrawLineTo(0,1);
this.DrawLineTo(-1,1);
this.Ctx.closePath();
this.Ctx.fill();
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[3].toString();// BLUE
App.FillColor(this.Ctx,App.Palette[3]);
this.DrawMoveTo(-1,0);
this.DrawLineTo(1,-2);
this.DrawLineTo(1,-1);
this.DrawLineTo(0,0);
this.Ctx.closePath();
this.Ctx.fill();
break;
case App.L10n.Blocks.Effect.Blocks.Chomp.name.toLowerCase():
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[7].toString();// RED
App.FillColor(this.Ctx,App.Palette[7]);
this.DrawMoveTo(-1,0);
this.DrawLineTo(0,-1);
this.DrawLineTo(1,0);
this.DrawLineTo(1,1);
this.DrawLineTo(0,2);
this.DrawLineTo(-1,2);
this.Ctx.closePath();
this.Ctx.fill();
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[8].toString();// WHITE
App.FillColor(this.Ctx,App.Palette[8]);
this.DrawMoveTo(-1,0);
this.DrawLineTo(0,-1);
this.DrawLineTo(0,1);
this.DrawLineTo(-1,2);
this.Ctx.closePath();
this.Ctx.fill();
break;
case App.L10n.Blocks.Effect.Blocks.Chopper.name.toLowerCase():
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[3].toString();// BLUE
App.FillColor(this.Ctx,App.Palette[3]);
this.DrawMoveTo(-1,0);
this.DrawLineTo(0,-1);
this.DrawLineTo(1,-1);
this.DrawLineTo(1,1);
this.DrawLineTo(0,2);
this.DrawLineTo(-1,1);
this.Ctx.closePath();
this.Ctx.fill();
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[4].toString();// GREEN
App.FillColor(this.Ctx,App.Palette[4]);
this.DrawMoveTo(0,0);
this.DrawLineTo(1,-1);
this.DrawLineTo(1,1);
this.DrawLineTo(0,2);
this.Ctx.closePath();
this.Ctx.fill();
break;
case App.L10n.Blocks.Effect.Blocks.Chorus.name.toLowerCase():
if (!this._Scaled) {
this._YOffset = (grd*0.5);
}
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[10].toString();// ORANGE
App.FillColor(this.Ctx,App.Palette[10]);
this.DrawMoveTo(-1,-1);
this.DrawLineTo(0,-1);
this.DrawLineTo(1,0);
this.DrawLineTo(0,1);
this.DrawLineTo(-1,1);
this.Ctx.closePath();
this.Ctx.fill();
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[6].toString();// YELLOW
App.FillColor(this.Ctx,App.Palette[6]);
this.DrawMoveTo(-1,-1);
this.DrawLineTo(0,0);
this.DrawLineTo(-1,1);
this.Ctx.closePath();
this.Ctx.fill();
break;
case App.L10n.Blocks.Effect.Blocks.Convolution.name.toLowerCase():
if (!this._Scaled) {
this._XOffset = -(grd*0.5);
}
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[8].toString();// WHITE
App.FillColor(this.Ctx,App.Palette[8]);
this.DrawMoveTo(-1,-1);
this.DrawLineTo(1,-1);
this.DrawLineTo(2,0);
this.DrawLineTo(0,2);
this.DrawLineTo(-1,1);
this.Ctx.closePath();
this.Ctx.fill();
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[4].toString();// GREEN
App.FillColor(this.Ctx,App.Palette[4]);
this.DrawMoveTo(-1,-1);
this.DrawLineTo(0,0);
this.DrawLineTo(0,2);
this.DrawLineTo(-1,1);
this.Ctx.closePath();
this.Ctx.fill();
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[6].toString();// YELLOW
App.FillColor(this.Ctx,App.Palette[6]);
this.DrawMoveTo(0,0);
this.DrawLineTo(1,0);
this.DrawLineTo(0,1);
this.Ctx.closePath();
this.Ctx.fill();
break;
case App.L10n.Blocks.Effect.Blocks.StereoDelay.name.toLowerCase():
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[7].toString();// RED
App.FillColor(this.Ctx,App.Palette[7]);
this.DrawMoveTo(-1,0);
this.DrawLineTo(0,-1);
this.DrawLineTo(1,0);
this.DrawLineTo(1,2);
this.DrawLineTo(0,1);
this.DrawLineTo(-1,2);
this.Ctx.closePath();
this.Ctx.fill();
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[3].toString();// BLUE
App.FillColor(this.Ctx,App.Palette[3]);
this.DrawMoveTo(-1,1);
this.DrawLineTo(0,0);
this.DrawLineTo(1,1);
this.DrawLineTo(1,2);
this.DrawLineTo(0,1);
this.DrawLineTo(-1,2);
this.Ctx.closePath();
this.Ctx.fill();
break;
case App.L10n.Blocks.Effect.Blocks.Distortion.name.toLowerCase():
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[7].toString();// RED
App.FillColor(this.Ctx,App.Palette[7]);
this.DrawMoveTo(-1,-1);
this.DrawLineTo(1,-1);
this.DrawLineTo(1,0);
this.DrawLineTo(-1,2);
this.Ctx.closePath();
this.Ctx.fill();
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[9].toString();// PINK
App.FillColor(this.Ctx,App.Palette[9]);
this.DrawLineTo(-1,-1);
this.DrawLineTo(0,-1);
this.DrawLineTo(0,0);
this.DrawLineTo(-1,1);
this.Ctx.closePath();
this.Ctx.fill();
break;
case App.L10n.Blocks.Effect.Blocks.Envelope.name.toLowerCase():
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[6].toString();// YELLOW
App.FillColor(this.Ctx,App.Palette[6]);
this.DrawMoveTo(-1,-1);
this.DrawLineTo(1,-1);
this.DrawLineTo(1,1);
this.DrawLineTo(0,2);
this.DrawLineTo(-1,1);
this.Ctx.closePath();
this.Ctx.fill();
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[3].toString();// BLUE
App.FillColor(this.Ctx,App.Palette[3]);
this.DrawMoveTo(0,0);
this.DrawLineTo(1,-1);
this.DrawLineTo(1,1);
this.DrawLineTo(0,2);
this.Ctx.closePath();
this.Ctx.fill();
break;
case App.L10n.Blocks.Effect.Blocks.Eq.name.toLowerCase():
if (!this._Scaled) {
this._XOffset = -(grd*0.5);
this._YOffset = (grd*0.5);
}
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[3].toString();// BLUE
App.FillColor(this.Ctx,App.Palette[3]);
this.DrawMoveTo(-1,0);
this.DrawLineTo(0,-1);
this.DrawLineTo(1,-1);
this.DrawLineTo(2,0);
this.DrawLineTo(1,1);
this.DrawLineTo(0,1);
this.Ctx.closePath();
this.Ctx.fill();
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[8].toString();// WHITE
App.FillColor(this.Ctx,App.Palette[8]);
this.DrawMoveTo(0,0);
this.DrawLineTo(1,-1);
this.DrawLineTo(2,0);
this.Ctx.closePath();
this.Ctx.fill();
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[4].toString();// GREEN
App.FillColor(this.Ctx,App.Palette[4]);
this.DrawLineTo(0,0);
this.DrawLineTo(1,1);
this.DrawLineTo(2,0);
this.Ctx.closePath();
this.Ctx.fill();
break;
case App.L10n.Blocks.Effect.Blocks.Filter.name.toLowerCase():
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[4].toString();// GREEN
App.FillColor(this.Ctx,App.Palette[4]);
this.DrawMoveTo(-1,-2);
this.DrawLineTo(1,0);
this.DrawLineTo(1,2);
this.DrawLineTo(-1,0);
this.Ctx.closePath();
this.Ctx.fill();
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[6].toString();// YELLOW
App.FillColor(this.Ctx,App.Palette[6]);
this.DrawMoveTo(0,-1);
this.DrawLineTo(1,0);
this.DrawLineTo(1,2);
this.DrawLineTo(0,1);
this.Ctx.closePath();
this.Ctx.fill();
break;
case App.L10n.Blocks.Effect.Blocks.Volume.name.toLowerCase():
if (!this._Scaled) {
this._XOffset = -(grd*0.5);
this._YOffset = (grd*0.5);
}
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[5].toString();// PURPLE
App.FillColor(this.Ctx,App.Palette[5]);
this.DrawMoveTo(-1,0);
this.DrawLineTo(0,-1);
this.DrawLineTo(2,1);
this.DrawLineTo(0,1);
this.Ctx.closePath();
this.Ctx.fill();
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[3].toString();// BLUE
App.FillColor(this.Ctx,App.Palette[3]);
this.DrawMoveTo(-1,0);
this.DrawLineTo(0,0);
this.DrawLineTo(1,1);
this.DrawLineTo(0,1);
this.Ctx.closePath();
this.Ctx.fill();
break;
case App.L10n.Blocks.Effect.Blocks.Vibrato.name.toLowerCase():
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[9].toString();// PINK
App.FillColor(this.Ctx,App.Palette[9]);
this.DrawMoveTo(-1,0);
this.DrawLineTo(0,-1);
this.DrawLineTo(1,0);
this.DrawLineTo(1,2);
this.Ctx.closePath();
this.Ctx.fill();
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[6].toString();// YELLOW
App.FillColor(this.Ctx,App.Palette[6]);
this.DrawMoveTo(0,0);
this.DrawLineTo(0,-1);
this.DrawLineTo(1,0);
this.DrawLineTo(1,1);
this.Ctx.closePath();
this.Ctx.fill();
break;
//case "panner":
//
// this.Ctx.beginPath();
// //this.Ctx.fillStyle = App.Palette[9].toString();// PINK
// App.FillColor(this.Ctx,App.Palette[9]);
// this.DrawMoveTo(-1,0);
// this.DrawLineTo(0,-1);
// this.DrawLineTo(1,0);
// this.DrawLineTo(0,1);
// this.Ctx.closePath();
// this.Ctx.fill();
//
// this.Ctx.beginPath();
// //this.Ctx.fillStyle = App.Palette[7].toString();// RED
// App.FillColor(this.Ctx,App.Palette[7]);
// this.DrawMoveTo(0,-1);
// this.DrawLineTo(1,0);
// this.DrawLineTo(0,1);
// this.Ctx.closePath();
// this.Ctx.fill();
//
// break;
case App.L10n.Blocks.Effect.Blocks.Phaser.name.toLowerCase():
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[9].toString();// PINK
App.FillColor(this.Ctx,App.Palette[9]);
this.DrawMoveTo(-1,0);
this.DrawLineTo(-1,-2);
this.DrawLineTo(1,0);
this.DrawLineTo(1,2);
this.Ctx.closePath();
this.Ctx.fill();
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[8].toString();// WHITE
App.FillColor(this.Ctx,App.Palette[8]);
this.DrawMoveTo(-1,0);
this.DrawLineTo(-1,-1);
this.DrawLineTo(1,1);
this.DrawLineTo(1,2);
this.Ctx.closePath();
this.Ctx.fill();
break;
case App.L10n.Blocks.Effect.Blocks.PitchShifter.name.toLowerCase():
if (!this._Scaled) {
this._XOffset = -(grd*0.5);
this._YOffset = (grd*0.5);
}
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[3].toString();// WHITE
App.FillColor(this.Ctx,App.Palette[3]);
this.DrawMoveTo(-1,0);
this.DrawLineTo(0,-1);
this.DrawLineTo(2,-1);
this.DrawLineTo(0,1);
this.Ctx.closePath();
this.Ctx.fill();
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[5].toString();// PURPLE
App.FillColor(this.Ctx,App.Palette[5]);
this.DrawMoveTo(-1,0);
this.DrawLineTo(0,0);
this.DrawLineTo(0,1);
this.Ctx.closePath();
this.Ctx.fill();
break;
case App.L10n.Blocks.Effect.Blocks.Reverb.name.toLowerCase():
if (!this._Scaled) {
this._XOffset = -(grd*0.5);
}
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[4].toString();// GREEN
App.FillColor(this.Ctx,App.Palette[4]);
this.DrawMoveTo(-1,-1);
this.DrawLineTo(1,-1);
this.DrawLineTo(2,0);
this.DrawLineTo(0,2);
this.DrawLineTo(-1,1);
this.Ctx.closePath();
this.Ctx.fill();
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[8].toString();// WHITE
App.FillColor(this.Ctx,App.Palette[8]);
this.DrawMoveTo(-1,-1);
this.DrawLineTo(0,0);
this.DrawLineTo(0,2);
this.DrawLineTo(-1,1);
this.Ctx.closePath();
this.Ctx.fill();
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[6].toString();// YELLOW
App.FillColor(this.Ctx,App.Palette[6]);
this.DrawMoveTo(0,0);
this.DrawLineTo(1,0);
this.DrawLineTo(0,1);
this.Ctx.closePath();
this.Ctx.fill();
break;
case App.L10n.Blocks.Effect.Blocks.Scuzz.name.toLowerCase():
if (!this._Scaled) {
this._YOffset = grd;
}
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[10].toString();// ORANGE
App.FillColor(this.Ctx,App.Palette[10]);
this.DrawMoveTo(-1,-1);
this.DrawLineTo(2,-1);
this.DrawLineTo(0,1);
this.DrawLineTo(-1,0);
this.Ctx.closePath();
this.Ctx.fill();
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[7].toString();// RED
App.FillColor(this.Ctx,App.Palette[7]);
this.DrawMoveTo(-1,-1);
this.DrawLineTo(1,-1);
this.DrawLineTo(0,0);
this.Ctx.closePath();
this.Ctx.fill();
break;
case App.L10n.Blocks.Source.Blocks.Tone.name.toLowerCase():
if (!this._Scaled) {
this._YOffset = (grd*0.5);
}
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[5].toString();// PURPLE
App.FillColor(this.Ctx,App.Palette[5]);
this.DrawMoveTo(-2,0);
this.DrawLineTo(0,-2);
this.DrawLineTo(2,0);
this.DrawLineTo(1,1);
this.DrawLineTo(-1,1);
this.Ctx.closePath();
this.Ctx.fill();
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[8].toString();// WHITE
App.FillColor(this.Ctx,App.Palette[8]);
this.DrawMoveTo(-2,0);
this.DrawLineTo(0,-2);
this.DrawLineTo(0,0);
this.DrawLineTo(-1,1);
this.Ctx.closePath();
this.Ctx.fill();
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[4].toString();// GREEN
App.FillColor(this.Ctx,App.Palette[4]);
this.DrawMoveTo(0,-2);
this.DrawLineTo(1,-1);
this.DrawLineTo(0,0);
this.Ctx.closePath();
this.Ctx.fill();
break;
case App.L10n.Blocks.Source.Blocks.Noise.name.toLowerCase():
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[4].toString();// GREEN
App.FillColor(this.Ctx,App.Palette[4]);
this.DrawMoveTo(-1,0);
this.DrawLineTo(0,-1);
this.DrawLineTo(1,-1);
this.DrawLineTo(1,0);
this.DrawLineTo(-1,2);
this.Ctx.closePath();
this.Ctx.fill();
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[8].toString();// WHITE
App.FillColor(this.Ctx,App.Palette[8]);
this.DrawMoveTo(-1,0);
this.DrawLineTo(0,-1);
this.DrawLineTo(1,-1);
this.DrawLineTo(0,0);
this.Ctx.closePath();
this.Ctx.fill();
break;
case App.L10n.Blocks.Source.Blocks.Microphone.name.toLowerCase():
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[8].toString();// WHITE
App.FillColor(this.Ctx,App.Palette[8]);
this.DrawMoveTo(-1,0);
this.DrawLineTo(0,-1);
this.DrawLineTo(1,0);
this.DrawLineTo(1,1);
this.DrawLineTo(0,2);
this.DrawLineTo(-1,1);
this.Ctx.closePath();
this.Ctx.fill();
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[9].toString();// PINK
App.FillColor(this.Ctx,App.Palette[9]);
this.DrawMoveTo(0,-1);
this.DrawLineTo(1,0);
this.DrawLineTo(0,1);
this.Ctx.closePath();
this.Ctx.fill();
break;
case App.L10n.Blocks.Source.Blocks.Sample.name.toLowerCase():
if (!this._Scaled) {
this._XOffset = -(grd*0.5);
this._YOffset = (grd*0.5);
}
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[7].toString();// RED
App.FillColor(this.Ctx,App.Palette[7]);
this.DrawMoveTo(-1,0);
this.DrawLineTo(0,-1);
this.DrawLineTo(1,-1);
this.DrawLineTo(2,0);
this.DrawLineTo(1,1);
this.DrawLineTo(0,1);
this.Ctx.closePath();
this.Ctx.fill();
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[10].toString();// ORANGE
App.FillColor(this.Ctx,App.Palette[10]);
this.DrawMoveTo(1,0);
this.DrawLineTo(2,0);
this.DrawLineTo(1,1);
this.DrawLineTo(0,1);
this.Ctx.closePath();
this.Ctx.fill();
break;
case App.L10n.Blocks.Source.Blocks.Granular.name.toLowerCase():
if (!this._Scaled) {
this._XOffset = -(grd*0.5);
}
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[4].toString();// GREEN
App.FillColor(this.Ctx,App.Palette[4]);
this.DrawMoveTo(-1,0);
this.DrawLineTo(0,-1);
this.DrawLineTo(1,-1);
this.DrawLineTo(1,2);
this.Ctx.closePath();
this.Ctx.fill();
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[5].toString();// PURPLE
App.FillColor(this.Ctx,App.Palette[5]);
this.DrawMoveTo(0,0);
this.DrawLineTo(1,-1);
this.DrawLineTo(2,0);
this.DrawLineTo(2,1);
this.DrawLineTo(1,2);
this.DrawLineTo(1,1);
this.Ctx.closePath();
this.Ctx.fill();
break;
case App.L10n.Blocks.Source.Blocks.Recorder.name.toLowerCase():
if (!this._Scaled) {
this._XOffset = -(grd*0.5);
}
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[9].toString();// PINK
App.FillColor(this.Ctx,App.Palette[9]);
this.DrawMoveTo(-1,0);
this.DrawLineTo(0,-1);
this.DrawLineTo(1,-1);
this.DrawLineTo(1,2);
this.Ctx.closePath();
this.Ctx.fill();
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[8].toString();// WHITE
App.FillColor(this.Ctx,App.Palette[8]);
this.DrawMoveTo(1,-1);
this.DrawLineTo(2,0);
this.DrawLineTo(2,1);
this.DrawLineTo(1,2);
this.Ctx.closePath();
this.Ctx.fill();
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[7].toString();// RED
App.FillColor(this.Ctx,App.Palette[7]);
this.DrawMoveTo(0,0);
this.DrawLineTo(1,-1);
this.DrawLineTo(1,1);
this.Ctx.closePath();
this.Ctx.fill();
break;
case App.L10n.Blocks.Source.Blocks.SampleGen.name.toLowerCase():
/*if (!this._Scaled) {
this._XOffset = -(grd*0.5);
}*/
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[5].toString();// PINK
App.FillColor(this.Ctx,App.Palette[5]);
this.DrawMoveTo(-1,-1);
this.DrawLineTo(0,-1);
this.DrawLineTo(1,0);
this.DrawLineTo(1,2);
this.DrawLineTo(0,2);
this.DrawLineTo(-1,1);
this.Ctx.closePath();
this.Ctx.fill();
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[10].toString();// WHITE
App.FillColor(this.Ctx,App.Palette[10]);
this.DrawMoveTo(0,-1);
this.DrawLineTo(1,0);
this.DrawLineTo(1,2);
this.DrawLineTo(0,2);
this.Ctx.closePath();
this.Ctx.fill();
break;
case App.L10n.Blocks.Interaction.Blocks.ComputerKeyboard.name.toLowerCase():
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[8].toString();// WHITE
App.FillColor(this.Ctx,App.Palette[8]);
this.DrawMoveTo(-1,0);
this.DrawLineTo(0,-1);
this.DrawLineTo(2,1);
this.DrawLineTo(1,2);
this.DrawLineTo(-1,2);
this.Ctx.closePath();
this.Ctx.fill();
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[4].toString();// GREEN
App.FillColor(this.Ctx,App.Palette[4]);
this.DrawLineTo(0,-1);
this.DrawLineTo(0,1);
this.DrawLineTo(1,1);
this.DrawLineTo(1,0);
this.Ctx.closePath();
this.Ctx.fill();
break;
case App.L10n.Blocks.Interaction.Blocks.MIDIController.name.toLowerCase():
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[8].toString();// WHITE
App.FillColor(this.Ctx,App.Palette[8]);
this.DrawMoveTo(-1,-1);
this.DrawLineTo(0,-1);
this.DrawLineTo(2,1);
this.DrawLineTo(1,2);
this.DrawLineTo(-1,2);
this.Ctx.closePath();
this.Ctx.fill();
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[4].toString(); //GREEN
App.FillColor(this.Ctx,App.Palette[4]);
this.DrawLineTo(0,-1);
this.DrawLineTo(-1,1);
this.DrawLineTo(1,1);
this.DrawLineTo(1,0);
this.Ctx.closePath();
this.Ctx.fill();
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[9].toString(); //PINK
App.FillColor(this.Ctx,App.Palette[9]);
this.DrawLineTo(-1,-1);
this.DrawLineTo(-1,1);
this.DrawLineTo(0,1);
this.DrawLineTo(0,-1);
this.Ctx.closePath();
this.Ctx.fill();
break;
case App.L10n.Blocks.Power.Blocks.ParticleEmitter.name.toLowerCase():
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[5].toString();// PURPLE
App.FillColor(this.Ctx,App.Palette[5]);
this.DrawMoveTo(-2,0);
this.DrawLineTo(2,0);
this.DrawLineTo(0,2);
this.Ctx.closePath();
this.Ctx.fill();
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[7].toString();// RED
App.FillColor(this.Ctx,App.Palette[7]);
this.DrawMoveTo(-1,0);
this.DrawLineTo(0,-1);
this.DrawLineTo(1,0);
this.DrawLineTo(0,1);
this.Ctx.closePath();
this.Ctx.fill();
break;
case App.L10n.Blocks.Power.Blocks.Power.name.toLowerCase():
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[3].toString();// BLUE
App.FillColor(this.Ctx,App.Palette[3]);
this.DrawMoveTo(-1,0);
this.DrawLineTo(1,-2);
this.DrawLineTo(2,-1);
this.DrawLineTo(2,0);
this.DrawLineTo(0,2);
this.DrawLineTo(-1,1);
this.Ctx.closePath();
this.Ctx.fill();
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[4].toString();// GREEN
App.FillColor(this.Ctx,App.Palette[4]);
this.DrawMoveTo(0,0);
this.DrawLineTo(1,-1);
this.DrawLineTo(2,0);
this.DrawLineTo(0,2);
this.Ctx.closePath();
this.Ctx.fill();
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[8].toString();// WHITE
App.FillColor(this.Ctx,App.Palette[8]);
this.DrawMoveTo(-1,0);
this.DrawLineTo(1,-2);
this.DrawLineTo(1,-1);
this.DrawLineTo(0,0);
this.Ctx.closePath();
this.Ctx.fill();
break;
case App.L10n.Blocks.Power.Blocks.TogglePower.name.toLowerCase():
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[3].toString(); // BLUE
App.FillColor(this.Ctx,App.Palette[3]);
this.DrawMoveTo(-1,-1);
this.DrawLineTo(0,-1);
this.DrawLineTo(1,0);
this.DrawLineTo(1,2);
this.DrawLineTo(0,2);
this.DrawLineTo(-1,1);
this.Ctx.closePath();
this.Ctx.fill();
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[7].toString(); // RED
App.FillColor(this.Ctx,App.Palette[7]);
this.DrawMoveTo(-1,-1);
this.DrawLineTo(0,0);
this.DrawLineTo(0,1);
this.DrawLineTo(1,2);
this.DrawLineTo(0,2);
this.DrawLineTo(-1,1);
this.Ctx.closePath();
this.Ctx.fill();
break;
case App.L10n.Blocks.Power.Blocks.PulsePower.name.toLowerCase():
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[3].toString(); // BLUE
App.FillColor(this.Ctx,App.Palette[3]);
this.DrawMoveTo(-1,0);
this.DrawLineTo(0,-1);
this.DrawLineTo(1,-1);
this.DrawLineTo(1,1);
this.DrawLineTo(0,2);
this.DrawLineTo(-1,2);
this.Ctx.closePath();
this.Ctx.fill();
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[5].toString(); // PURPLE
App.FillColor(this.Ctx,App.Palette[5]);
this.DrawMoveTo(0,1);
this.DrawLineTo(0,0);
this.DrawLineTo(1,-1);
this.DrawLineTo(1,1);
this.DrawLineTo(0,2);
this.DrawLineTo(-1,2);
this.Ctx.closePath();
this.Ctx.fill();
break;
case App.L10n.Blocks.Power.Blocks.Laser.name.toLowerCase():
if (!this._Scaled) {
this._YOffset = (grd*0.5);
}
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[3].toString();// BLUE
App.FillColor(this.Ctx,App.Palette[3]);
this.DrawMoveTo(-1,-1);
this.DrawLineTo(0,-1);
this.DrawLineTo(0,1);
this.DrawLineTo(-1,0);
this.Ctx.closePath();
this.Ctx.fill();
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[4].toString();// GREEN
App.FillColor(this.Ctx,App.Palette[4]);
this.DrawMoveTo(0,-1);
this.DrawLineTo(1,-1);
this.DrawLineTo(1,0);
this.DrawLineTo(0,1);
this.Ctx.closePath();
this.Ctx.fill();
this.Ctx.beginPath();
//this.Ctx.fillStyle = App.Palette[7].toString();// RED
App.FillColor(this.Ctx,App.Palette[7]);
this.DrawMoveTo(-1,-1);
this.DrawLineTo(1,-1);
this.DrawLineTo(0,0);
this.Ctx.closePath();
this.Ctx.fill();
break;
case App.L10n.Blocks.Power.Blocks.Void.name.toLowerCase():
/*if (!this._Scaled) {
this._YOffset = (grd*0.5);
}*/
//this.Ctx.fillStyle = App.Palette[14].toString();// DARK
App.FillColor(this.Ctx,App.Palette[14]);
/*if (!this._Scaled) {
this.Ctx.fillStyle = App.Palette[14].toString();// DARK
}*/
this.Ctx.beginPath();
this.DrawMoveTo(-1,0);
this.DrawLineTo(0,-1);
this.DrawLineTo(1,0);
this.DrawLineTo(0,1);
this.Ctx.closePath();
this.Ctx.fill();
//this.Ctx.fillStyle = App.Palette[8].toString();// WHITE
App.FillColor(this.Ctx,App.Palette[8]);
if (!this._Scaled) {
this.DrawPixel(-1,2,2);
} else {
this.DrawPixel(pos2.x,pos2.y,2);
}
this.DrawPixel(-3,-8,1);
this.DrawPixel(1,-4,1);
this.DrawPixel(8,-3,1);
this.DrawPixel(-8,1,1);
this.DrawPixel(1,9,1);
break;
default:
console.log("block not found");
}
}
DrawPixel(x,y,size) {
var s = size * 0.5;
this.Ctx.beginPath();
this.DrawFloatMoveTo(x,y);
this.DrawFloatLineTo(x+s,y);
this.DrawFloatLineTo(x+s,y+s);
this.DrawFloatLineTo(x,y+s);
this.Ctx.closePath();
this.Ctx.fill();
}
DrawMoveTo(x, y) {
var pos = new Point(this._Position.x + this._XOffset, this._Position.y + this._YOffset);
var p;
var grd = App.GridSize;
if (this._Scaled) {
p = App.Metrics.GetRelativePoint(pos, new Point(x, y));
p = App.Metrics.PointOnGrid(p);
} else {
p = new Point(pos.x + (x*grd),pos.y + (y*grd));
}
this.Ctx.moveTo(p.x, p.y);
}
DrawLineTo(x, y) {
var pos = new Point(this._Position.x + this._XOffset, this._Position.y + this._YOffset);
var p;
var grd = App.GridSize;
if (this._Scaled) {
p = App.Metrics.GetRelativePoint(pos, new Point(x, y));
p = App.Metrics.PointOnGrid(p);
} else {
p = new Point(pos.x + (x*grd),pos.y + (y*grd));
}
this.Ctx.lineTo(p.x, p.y);
}
DrawFloatMoveTo(x, y) {
var pos = new Point(this._Position.x + this._XOffset, this._Position.y + this._YOffset);
var p;
if (this._Scaled) {
p = App.Metrics.PointOnGrid(new Point(pos.x + ((x/App.GridSize)*App.Unit),pos.y + ((y/App.GridSize)*App.Unit)));
} else {
p = new Point(pos.x + (x*App.Unit),pos.y + (y*App.Unit));
}
this.Ctx.moveTo(p.x, p.y);
}
DrawFloatLineTo(x, y) {
var pos = new Point(this._Position.x + this._XOffset, this._Position.y + this._YOffset);
var p;
if (this._Scaled) {
p = App.Metrics.PointOnGrid(new Point(pos.x + ((x/App.GridSize)*App.Unit),pos.y + ((y/App.GridSize)*App.Unit)));
} else {
p = new Point(pos.x + (x*App.Unit),pos.y + (y*App.Unit));
}
this.Ctx.lineTo(p.x, p.y);
}
} | the_stack |
import { parseJsonAndExpect, parseJsonAndExpectOnlyPools, parseJsonAndExpectOnlyPoolsAndFlowNodes, parseJsonAndExpectOnlyPoolsAndLanes, verifyShape } from './JsonTestUtils';
import { ShapeBpmnElementKind } from '../../../../../src/model/bpmn/internal';
import { BpmnJsonModel } from '../../../../../src/model/bpmn/json/BPMN20';
describe('parse bpmn as json for process/pool', () => {
describe.each([
['vertical', false],
['horizontal', true],
])('Dedicated tests for %s orientation', (title: string, isHorizontal: boolean) => {
it(`json containing one ${title} participant referencing a process`, () => {
const json: BpmnJsonModel = {
definitions: {
targetNamespace: '',
collaboration: {
participant: { id: 'Participant_1', processRef: 'Process_1' },
},
process: {
id: 'Process_1',
isExecutable: false,
},
BPMNDiagram: {
BPMNPlane: {
BPMNShape: [
{
id: 'shape_Participant_1',
bpmnElement: 'Participant_1',
isHorizontal: isHorizontal,
Bounds: { x: 158, y: 50, width: 1620, height: 430 },
},
],
},
},
},
};
const model = parseJsonAndExpectOnlyPoolsAndLanes(json, 1, 0);
const pool = model.pools[0];
verifyShape(pool, {
shapeId: 'shape_Participant_1',
bpmnElementId: 'Participant_1',
bpmnElementName: undefined,
bpmnElementKind: ShapeBpmnElementKind.POOL,
parentId: undefined,
bounds: {
x: 158,
y: 50,
width: 1620,
height: 430,
},
isHorizontal: isHorizontal,
});
});
it(`json containing one ${title} participant without related process`, () => {
const json = {
definitions: {
targetNamespace: '',
collaboration: {
participant: { id: 'Participant_1', name: 'Participant without process ref' },
},
BPMNDiagram: {
BPMNPlane: {
BPMNShape: [
{
id: 'shape_Participant_1',
bpmnElement: 'Participant_1',
isHorizontal: isHorizontal,
Bounds: { x: 158, y: 50, width: 1620, height: 430 },
},
],
},
},
},
};
const model = parseJsonAndExpectOnlyPoolsAndLanes(json, 1, 0);
const pool = model.pools[0];
verifyShape(pool, {
shapeId: 'shape_Participant_1',
bpmnElementId: 'Participant_1',
bpmnElementName: 'Participant without process ref',
bpmnElementKind: ShapeBpmnElementKind.POOL,
parentId: undefined,
isHorizontal: isHorizontal,
bounds: {
x: 158,
y: 50,
width: 1620,
height: 430,
},
});
});
});
it("json containing one participant referencing a process without 'isHorizontal' attribute", () => {
const json: BpmnJsonModel = {
definitions: {
targetNamespace: '',
collaboration: {
participant: { id: 'Participant_1', processRef: 'Process_1' },
},
process: {
id: 'Process_1',
isExecutable: false,
},
BPMNDiagram: {
BPMNPlane: {
BPMNShape: [
{
id: 'shape_Participant_1',
bpmnElement: 'Participant_1',
Bounds: { x: 158, y: 50, width: 1620, height: 430 },
},
],
},
},
},
};
const model = parseJsonAndExpectOnlyPoolsAndLanes(json, 1, 0);
const pool = model.pools[0];
verifyShape(pool, {
shapeId: 'shape_Participant_1',
bpmnElementId: 'Participant_1',
bpmnElementName: undefined,
bpmnElementKind: ShapeBpmnElementKind.POOL,
parentId: undefined,
bounds: {
x: 158,
y: 50,
width: 1620,
height: 430,
},
isHorizontal: true,
});
});
it('json containing one participant without name and the related process has a name', () => {
const json = {
definitions: {
targetNamespace: '',
collaboration: {
participant: { id: 'Participant_1', processRef: 'Process_1' },
},
process: {
id: 'Process_1',
name: 'Process 1',
isExecutable: false,
},
BPMNDiagram: {
BPMNPlane: {
BPMNShape: [
{
id: 'shape_Participant_1',
bpmnElement: 'Participant_1',
isHorizontal: true,
Bounds: { x: 158, y: 50, width: 1620, height: 430 },
},
],
},
},
},
};
const model = parseJsonAndExpectOnlyPoolsAndLanes(json, 1, 0);
const pool = model.pools[0];
verifyShape(pool, {
shapeId: 'shape_Participant_1',
bpmnElementId: 'Participant_1',
bpmnElementName: 'Process 1',
bpmnElementKind: ShapeBpmnElementKind.POOL,
parentId: undefined,
isHorizontal: true,
bounds: {
x: 158,
y: 50,
width: 1620,
height: 430,
},
});
});
it('json containing one process with pool and a single lane without flowNodeRef', () => {
const json = {
definitions: {
targetNamespace: '',
collaboration: {
participant: { id: 'Participant_0nuvj8r', name: 'Pool 1', processRef: 'Process_0vbjbkf' },
},
process: {
id: 'Process_0vbjbkf',
name: 'RequestLoan',
isExecutable: false,
lane: { id: 'Lane_12u5n6x' },
},
BPMNDiagram: {
BPMNPlane: {
BPMNShape: [
{
id: 'shape_Participant_0nuvj8r',
bpmnElement: 'Participant_0nuvj8r',
isHorizontal: true,
Bounds: { x: 158, y: 50, width: 1620, height: 430 },
},
{
id: 'shape_Lane_1h5yeu4',
bpmnElement: 'Lane_12u5n6x',
Bounds: { x: 362, y: 232, width: 36, height: 45 },
},
],
},
},
},
};
const model = parseJsonAndExpectOnlyPoolsAndLanes(json, 1, 1);
const pool = model.pools[0];
verifyShape(pool, {
shapeId: 'shape_Participant_0nuvj8r',
bpmnElementId: 'Participant_0nuvj8r',
bpmnElementName: 'Pool 1',
bpmnElementKind: ShapeBpmnElementKind.POOL,
parentId: undefined,
isHorizontal: true,
bounds: {
x: 158,
y: 50,
width: 1620,
height: 430,
},
});
const lane = model.lanes[0];
verifyShape(lane, {
shapeId: 'shape_Lane_1h5yeu4',
bpmnElementId: 'Lane_12u5n6x',
bpmnElementName: undefined,
bpmnElementKind: ShapeBpmnElementKind.LANE,
parentId: 'Participant_0nuvj8r',
isHorizontal: true,
bounds: {
x: 362,
y: 232,
width: 36,
height: 45,
},
});
});
it('json containing several processes and participants (with lane or laneset)', () => {
const json = {
definitions: {
targetNamespace: '',
collaboration: {
participant: [
{ id: 'Participant_1', name: 'Pool 1', processRef: 'Process_1' },
{ id: 'Participant_2', name: 'Pool 2', processRef: 'Process_2' },
],
},
process: [
{
id: 'Process_1',
name: 'process 1',
isExecutable: false,
lane: { id: 'Lane_1_1' },
},
{
id: 'Process_2',
name: 'process 2',
isExecutable: true,
laneSet: {
id: 'LaneSet_2',
lane: { id: 'Lane_2_1' },
},
},
],
BPMNDiagram: {
BPMNPlane: {
BPMNShape: [
{
id: 'shape_Participant_1',
bpmnElement: 'Participant_1',
isHorizontal: true,
Bounds: { x: 158, y: 50, width: 1620, height: 430 },
},
{
id: 'shape_Lane_1_1',
bpmnElement: 'Lane_1_1',
Bounds: { x: 362, y: 232, width: 36, height: 45 },
},
{
id: 'Participant_2_di',
bpmnElement: 'Participant_2',
isHorizontal: true,
Bounds: { x: 158, y: 1050, width: 1620, height: 430 },
},
{
id: 'shape_Lane_2_1',
bpmnElement: 'Lane_2_1',
Bounds: { x: 362, y: 1232, width: 36, height: 45 },
},
],
},
},
},
};
const model = parseJsonAndExpectOnlyPoolsAndLanes(json, 2, 2);
verifyShape(model.pools[0], {
shapeId: 'shape_Participant_1',
bpmnElementId: 'Participant_1',
bpmnElementName: 'Pool 1',
bpmnElementKind: ShapeBpmnElementKind.POOL,
parentId: undefined,
isHorizontal: true,
bounds: {
x: 158,
y: 50,
width: 1620,
height: 430,
},
});
verifyShape(model.pools[1], {
shapeId: 'Participant_2_di',
bpmnElementId: 'Participant_2',
bpmnElementName: 'Pool 2',
bpmnElementKind: ShapeBpmnElementKind.POOL,
parentId: undefined,
isHorizontal: true,
bounds: {
x: 158,
y: 1050,
width: 1620,
height: 430,
},
});
verifyShape(model.lanes[0], {
shapeId: 'shape_Lane_1_1',
bpmnElementId: 'Lane_1_1',
bpmnElementName: undefined,
bpmnElementKind: ShapeBpmnElementKind.LANE,
parentId: 'Participant_1',
isHorizontal: true,
bounds: {
x: 362,
y: 232,
width: 36,
height: 45,
},
});
verifyShape(model.lanes[1], {
shapeId: 'shape_Lane_2_1',
bpmnElementId: 'Lane_2_1',
bpmnElementName: undefined,
bpmnElementKind: ShapeBpmnElementKind.LANE,
parentId: 'Participant_2',
isHorizontal: true,
bounds: {
x: 362,
y: 1232,
width: 36,
height: 45,
},
});
});
it('participant without processRef are not considered as pool', () => {
const json = {
definitions: {
targetNamespace: '',
collaboration: {
participant: [
{ id: 'Participant_1', name: 'Pool 1', processRef: 'Process_1' },
{ id: 'Participant_2', name: 'Not a process' },
],
},
process: {
id: 'Process_1',
name: 'Process 1',
isExecutable: false,
},
BPMNDiagram: {
BPMNPlane: {
BPMNShape: [
{
id: 'shape_Participant_1',
bpmnElement: 'Participant_1',
isHorizontal: true,
Bounds: { x: 158, y: 50, width: 1620, height: 430 },
},
],
},
},
},
};
const model = parseJsonAndExpectOnlyPools(json, 1);
const pool = model.pools[0];
verifyShape(pool, {
shapeId: 'shape_Participant_1',
bpmnElementId: 'Participant_1',
bpmnElementName: 'Pool 1',
bpmnElementKind: ShapeBpmnElementKind.POOL,
parentId: undefined,
isHorizontal: true,
bounds: {
x: 158,
y: 50,
width: 1620,
height: 430,
},
});
});
it('json containing one process and flownode without lane and related participant', () => {
const json = {
definitions: {
targetNamespace: '',
collaboration: {
participant: [
{ id: 'Participant_1', name: 'Pool 1', processRef: 'Process_1' },
{ id: 'Participant_2', name: 'Not a process' },
],
},
process: {
id: 'Process_1',
name: 'Process 1',
isExecutable: false,
startEvent: { id: 'event_id_0' },
},
BPMNDiagram: {
BPMNPlane: {
BPMNShape: [
{
id: 'shape_Participant_1',
bpmnElement: 'Participant_1',
isHorizontal: true,
Bounds: { x: 158, y: 50, width: 1620, height: 630 },
},
{
id: 'shape_startEvent_id_0',
bpmnElement: 'event_id_0',
Bounds: { x: 362, y: 232, width: 36, height: 45 },
},
],
},
},
},
};
const model = parseJsonAndExpectOnlyPoolsAndFlowNodes(json, 1, 1);
const pool = model.pools[0];
verifyShape(pool, {
shapeId: 'shape_Participant_1',
bpmnElementId: 'Participant_1',
bpmnElementName: 'Pool 1',
bpmnElementKind: ShapeBpmnElementKind.POOL,
parentId: undefined,
isHorizontal: true,
bounds: {
x: 158,
y: 50,
width: 1620,
height: 630,
},
});
const flowNode = model.flowNodes[0];
verifyShape(flowNode, {
shapeId: 'shape_startEvent_id_0',
bpmnElementId: 'event_id_0',
bpmnElementName: undefined,
bpmnElementKind: ShapeBpmnElementKind.EVENT_START,
parentId: 'Participant_1',
bounds: {
x: 362,
y: 232,
width: 36,
height: 45,
},
});
});
it('json containing one process, bpmn elements but no participant', () => {
// json generated from https://github.com/bpmn-miwg/bpmn-miwg-test-suite/blob/b1569235563b58d7216caa880c447bafee3e23cf/Reference/A.1.0.bpmn
const json = {
definitions: {
id: '_1373649849716',
name: 'A.1.0',
targetNamespace: 'http://www.trisotech.com/definitions/_1373649849716',
process: {
isExecutable: false,
id: 'WFP-6-',
startEvent: {
name: 'Start Event',
id: '_93c466ab-b271-4376-a427-f4c353d55ce8',
outgoing: '_e16564d7-0c4c-413e-95f6-f668a3f851fb',
},
task: [
{
completionQuantity: 1,
isForCompensation: false,
startQuantity: 1,
name: 'Task 1',
id: '_ec59e164-68b4-4f94-98de-ffb1c58a84af',
incoming: '_e16564d7-0c4c-413e-95f6-f668a3f851fb',
outgoing: '_d77dd5ec-e4e7-420e-bbe7-8ac9cd1df599',
},
{
completionQuantity: 1,
isForCompensation: false,
startQuantity: 1,
name: 'Task 2',
id: '_820c21c0-45f3-473b-813f-06381cc637cd',
incoming: '_d77dd5ec-e4e7-420e-bbe7-8ac9cd1df599',
outgoing: '_2aa47410-1b0e-4f8b-ad54-d6f798080cb4',
},
{
completionQuantity: 1,
isForCompensation: false,
startQuantity: 1,
name: 'Task 3',
id: '_e70a6fcb-913c-4a7b-a65d-e83adc73d69c',
incoming: '_2aa47410-1b0e-4f8b-ad54-d6f798080cb4',
outgoing: '_8e8fe679-eb3b-4c43-a4d6-891e7087ff80',
},
],
endEvent: {
name: 'End Event',
id: '_a47df184-085b-49f7-bb82-031c84625821',
incoming: '_8e8fe679-eb3b-4c43-a4d6-891e7087ff80',
},
sequenceFlow: [
{
sourceRef: '_93c466ab-b271-4376-a427-f4c353d55ce8',
targetRef: '_ec59e164-68b4-4f94-98de-ffb1c58a84af',
name: '',
id: '_e16564d7-0c4c-413e-95f6-f668a3f851fb',
},
{
sourceRef: '_ec59e164-68b4-4f94-98de-ffb1c58a84af',
targetRef: '_820c21c0-45f3-473b-813f-06381cc637cd',
name: '',
id: '_d77dd5ec-e4e7-420e-bbe7-8ac9cd1df599',
},
{
sourceRef: '_820c21c0-45f3-473b-813f-06381cc637cd',
targetRef: '_e70a6fcb-913c-4a7b-a65d-e83adc73d69c',
name: '',
id: '_2aa47410-1b0e-4f8b-ad54-d6f798080cb4',
},
{
sourceRef: '_e70a6fcb-913c-4a7b-a65d-e83adc73d69c',
targetRef: '_a47df184-085b-49f7-bb82-031c84625821',
name: '',
id: '_8e8fe679-eb3b-4c43-a4d6-891e7087ff80',
},
],
},
BPMNDiagram: {
documentation: '',
id: 'Trisotech_Visio-_6',
name: 'A.1.0',
resolution: 96.00000267028808,
BPMNPlane: {
bpmnElement: 'WFP-6-',
BPMNShape: [
{
bpmnElement: '_93c466ab-b271-4376-a427-f4c353d55ce8',
id: 'S1373649849857__93c466ab-b271-4376-a427-f4c353d55ce8',
Bounds: {
height: 30,
width: 30,
x: 186,
y: 336,
},
BPMNLabel: {
labelStyle: 'LS1373649849858',
Bounds: {
height: 12.804751171875008,
width: 94.93333333333335,
x: 153.67766754457273,
y: 371.3333333333333,
},
},
},
{
bpmnElement: '_ec59e164-68b4-4f94-98de-ffb1c58a84af',
id: 'S1373649849859__ec59e164-68b4-4f94-98de-ffb1c58a84af',
Bounds: {
height: 68,
width: 83,
x: 258,
y: 317,
},
BPMNLabel: {
labelStyle: 'LS1373649849858',
Bounds: {
height: 12.804751171875008,
width: 72.48293963254594,
x: 263.3333333333333,
y: 344.5818763825664,
},
},
},
{
bpmnElement: '_820c21c0-45f3-473b-813f-06381cc637cd',
id: 'S1373649849860__820c21c0-45f3-473b-813f-06381cc637cd',
Bounds: {
height: 68,
width: 83,
x: 390,
y: 317,
},
BPMNLabel: {
labelStyle: 'LS1373649849858',
Bounds: {
height: 12.804751171875008,
width: 72.48293963254594,
x: 395.3333333333333,
y: 344.5818763825664,
},
},
},
{
bpmnElement: '_e70a6fcb-913c-4a7b-a65d-e83adc73d69c',
id: 'S1373649849861__e70a6fcb-913c-4a7b-a65d-e83adc73d69c',
Bounds: {
height: 68,
width: 83,
x: 522,
y: 317,
},
BPMNLabel: {
labelStyle: 'LS1373649849858',
Bounds: {
height: 12.804751171875008,
width: 72.48293963254594,
x: 527.3333333333334,
y: 344.5818763825664,
},
},
},
{
bpmnElement: '_a47df184-085b-49f7-bb82-031c84625821',
id: 'S1373649849862__a47df184-085b-49f7-bb82-031c84625821',
Bounds: {
height: 32,
width: 32,
x: 648,
y: 335,
},
BPMNLabel: {
labelStyle: 'LS1373649849858',
Bounds: {
height: 12.804751171875008,
width: 94.93333333333335,
x: 616.5963254593177,
y: 372.3333333333333,
},
},
},
],
BPMNEdge: [
{
bpmnElement: '_d77dd5ec-e4e7-420e-bbe7-8ac9cd1df599',
id: 'E1373649849864__d77dd5ec-e4e7-420e-bbe7-8ac9cd1df599',
waypoint: [
{
x: 342,
y: 351,
},
{
x: 390,
y: 351,
},
],
BPMNLabel: '',
},
{
bpmnElement: '_e16564d7-0c4c-413e-95f6-f668a3f851fb',
id: 'E1373649849865__e16564d7-0c4c-413e-95f6-f668a3f851fb',
waypoint: [
{
x: 216,
y: 351,
},
{
x: 234,
y: 351,
},
{
x: 258,
y: 351,
},
],
BPMNLabel: '',
},
{
bpmnElement: '_2aa47410-1b0e-4f8b-ad54-d6f798080cb4',
id: 'E1373649849866__2aa47410-1b0e-4f8b-ad54-d6f798080cb4',
waypoint: [
{
x: 474,
y: 351,
},
{
x: 522,
y: 351,
},
],
BPMNLabel: '',
},
{
bpmnElement: '_8e8fe679-eb3b-4c43-a4d6-891e7087ff80',
id: 'E1373649849867__8e8fe679-eb3b-4c43-a4d6-891e7087ff80',
waypoint: [
{
x: 606,
y: 351,
},
{
x: 624,
y: 351,
},
{
x: 648,
y: 351,
},
],
BPMNLabel: '',
},
],
},
BPMNLabelStyle: {
id: 'LS1373649849858',
Font: {
isBold: false,
isItalic: false,
isStrikeThrough: false,
isUnderline: false,
name: 'Arial',
size: 11,
},
},
},
},
};
const model = parseJsonAndExpect(json, 0, 0, 5, 4);
model.flowNodes.map(flowNode => flowNode.bpmnElement).forEach(bpmnElement => expect(bpmnElement.parentId).toBeUndefined);
});
}); | the_stack |
import React, { Component } from 'react'
import {
StyleSheet,
Text,
View,
RefreshControl,
InteractionManager,
SectionList,
Animated,
Alert,
Button,
Dimensions
} from 'react-native'
import { idColor } from '../../constant/colorConfig'
import Ionicons from 'react-native-vector-icons/Ionicons'
import { getCustomAPI } from '../../dao'
import { postSetting } from '../../dao/post'
const AnimatedSectionList = Animated.createAnimatedComponent(SectionList)
let toolbarActions = []
import PhotoItem from '../../component/PhotoItem'
const renderSectionHeader = ({ section }) => {
return (
<View style={{
backgroundColor: section.modeInfo.backgroundColor,
flex: -1,
padding: 7,
elevation: 2
}}>
<Text numberOfLines={1}
style={{ fontSize: 20, color: idColor, textAlign: 'left', lineHeight: 25, marginLeft: 2, marginTop: 2 }}
>{section.key}</Text>
</View>
)
}
export default class Custom extends Component<any, any> {
constructor(props) {
super(props)
this.state = {
isLoading: false,
data: {
joinedList : [],
ownedList : []
}
}
}
componentWillMount() {
this.fetch()
}
fetch = () => {
this.setState({
isLoading: true
})
InteractionManager.runAfterInteractions(() => {
getCustomAPI('https://psnine.com/my/setting').then(data => {
this.setState({
data,
isLoading: false
})
})
})
}
onNavClicked = () => {
this.props.navigation.goBack()
}
ITEM_HEIGHT = 74 + 7
renderAD = () => {
const { modeInfo } = this.props.screenProps
const adopen = this.state.data.form.adopen
return (
<View style={{ flex: 1, padding: 10 }}>
<Button title={(adopen === '0' ? '显示' : '隐藏') + '广告'} color={adopen !== '0' ? modeInfo.standardColor : modeInfo.standardTextColor}
onPress={() => {
Alert.alert(
'广告设定',
`是否${adopen === '1' ? '显示' : '隐藏'}广告?`,
[
{text: '取消', style: 'cancel'},
{text: '确定', onPress: () => this.setSetting({
adopen: adopen === '0' ? '1' : '0'
})}
]
)
}}/>
</View>
)
}
renderVIP = () => {
const { modeInfo } = this.props.screenProps
// console.log(index, rowData)
const bgvip = this.state.data.form.bgvip
const avavip = this.state.data.form.avavip
return (
<View style={{ flex: 1, padding: 10 }}>
<Button title={'自定义背景图'} color={bgvip !== 0 ? modeInfo.standardColor : modeInfo.standardTextColor}
onPress={() => {
this.props.navigation.navigate('UserPhoto', {
URL: 'https://psnine.com/my/photo?page=1',
afterAlert: ({ url }) => {
this.setSetting({
bgvip: url.split('/').pop().split('.')[0]
})
},
alertText: '是否将此图片设置为自定义背景图?'
})
}}
/>
<Button title={'自定义头像'} color={avavip !== 0 ? modeInfo.standardColor : modeInfo.standardTextColor}
onPress={() => {
Alert.alert(
'个性设定',
'请选择功能',
[
{text: '清除自定义头像', onPress: () => this.setSetting({
avavip: ''
})},
{text: '自定义头像', onPress: () => this.props.navigation.navigate('UserPhoto', {
URL: 'https://psnine.com/my/photo?page=1',
afterAlert: ({ url }) => {
this.setSetting({
avavip: url.split('/').pop().split('.')[0]
})
},
alertText: '是否将此图片设置为自定义头像?'
})}
]
)
}}
/>
</View>
)
}
renderShow = () => {
const { modeInfo } = this.props.screenProps
// console.log(index, rowData)
const home = this.state.data.form.home
return (
<View style={{ flex: 1, padding: 10 }}>
<Button title={'游戏'} color={home === 'psngame' ? modeInfo.standardColor : modeInfo.standardTextColor}
onPress={() => {
Alert.alert(
'个性设定',
'是否将个人主页默认展示模块更改为游戏?',
[
{text: '取消', style: 'cancel'},
{text: '确定', onPress: () => this.setSetting({
home: 'psngame'
})}
]
)
}}/>
<Button title={'日志'} color={home === 'diary' ? modeInfo.standardColor : modeInfo.standardTextColor}
onPress={() => {
Alert.alert(
'个性设定',
'是否将个人主页默认展示模块更改为日志?',
[
{text: '取消', style: 'cancel'},
{text: '确定', onPress: () => this.setSetting({
home: 'diary'
})}
]
)
}}/>
</View>
)
}
renderTheme = () => {
const { modeInfo } = this.props.screenProps
// console.log(index, rowData)
const topicopen = this.state.data.form.topicopen
return (
<View style={{ flex: 1, padding: 10 }}>
<Button title={'显示主题'} color={topicopen === '0' ? modeInfo.standardColor : modeInfo.standardTextColor}
onPress={() => {
Alert.alert(
'个性设定',
`是否在个人主页中${topicopen === '0' ? '隐藏' : '显示'}主题?`,
[
{text: '取消', style: 'cancel'},
{text: '确定', onPress: () => this.setSetting({
topicopen: topicopen === '0' ? '1' : '0'
})}
]
)
}}/>
</View>
)
}
renderGene = () => {
const { modeInfo } = this.props.screenProps
// console.log(index, rowData)
const geneopen = this.state.data.form.geneopen
return (
<View style={{ flex: 1, padding: 10 }}>
<Button title={'显示机因'} color={geneopen === '0' ? modeInfo.standardColor : modeInfo.standardTextColor}
onPress={() => {
Alert.alert(
'个性设定',
`是否在个人主页中${geneopen === '0' ? '隐藏' : '显示'}机因?`,
[
{text: '取消', style: 'cancel'},
{text: '确定', onPress: () => this.setSetting({
geneopen: geneopen === '0' ? '1' : '0'
})}
]
)
}}/>
</View>
)
}
renderBG = ({ item: rowData}) => {
const { modeInfo } = this.props.screenProps
const { navigation } = this.props
const { width: SCREEN_WIDTH} = Dimensions.get('window')
const items = rowData.items.map((rowData, index) => <PhotoItem key={index} {...{
modeInfo,
navigation,
rowData,
width: SCREEN_WIDTH / 4 - 10,
ITEM_HEIGHT: SCREEN_WIDTH / 4,
isChecked: this.state.data.form.bg === rowData.value,
onPress: () => {
Alert.alert(
'个性设定',
'是否将此图片设置为个人主页背景?',
[
{text: '取消', style: 'cancel'},
{text: '确定', onPress: () => this.setSetting({
bg: rowData.value,
bgvip: ''
})}
]
)
}
}}/>)
return (
<View style={{ flexDirection: 'row', flexWrap: 'wrap'}}>
{items}
</View>
)
}
setSetting = (form) => {
const obj = Object.assign({}, this.state.data.form, form)
return postSetting(obj).then(res => {
// console.log(res)
return res.text()
}).then(() => {
this.fetch()
// console.log(text)
}).catch(err => console.log(err))
}
render() {
const { modeInfo } = this.props.screenProps
const { data } = this.state
// console.log(data, '===>')
let sections = data.sections ? data.sections.map((item, index) => ({
key: item,
modeInfo,
data: (() => {
if (index === 0) {
return [{ items: data.bg.items, id: 'bg' }]
} else if (index === 1) {
return data.isVIP ? [[{
text: '游戏',
value: 'psngame'
}, {
text: '日志',
value: 'diary'
}]] : []
} else if (index === 2) {
return [[
{
text: '自定义背景图'
},
{
text: '自定义头像'
}
]]
} else if (index === 3) {
return [[
{
text: '显示主题'
}
]]
} else if (index === 4) {
return [[
{
text: '显示机因'
}
]]
} else if (index === 5) {
return [[{
text: '广告设定'
}]]
}
})(),
renderItem: [
this.renderBG,
this.renderShow,
this.renderTheme,
this.renderGene,
this.renderVIP,
this.renderAD
][index]
})) : []
if (!this.state.data.isVIP && data.sections) {
sections = [
sections[0],
sections[2],
sections[3]
]
}
// console.log(sections)
return (
<View
style={{ flex: 1, backgroundColor: modeInfo.backgroundColor }}
onStartShouldSetResponder={() => false}
onMoveShouldSetResponder={() => false}
>
<Ionicons.ToolbarAndroid
navIconName='md-arrow-back'
overflowIconName='md-more'
iconColor={modeInfo.isNightMode ? '#000' : '#fff'}
title={'个性设定'}
style={{ backgroundColor: modeInfo.standardColor, height: 56, elevation: 4 }}
titleColor={modeInfo.isNightMode ? '#000' : '#fff'}
actions={toolbarActions}
onIconClicked={this.onNavClicked}
/>
<AnimatedSectionList
enableVirtualization={false}
refreshControl={
<RefreshControl
refreshing={this.state.isLoading}
colors={[modeInfo.accentColor]}
progressBackgroundColor={modeInfo.backgroundColor}
/>
}
disableVirtualization={true}
keyExtractor={(item, index) => `${item.id || item.href}${index}`}
renderSectionHeader={renderSectionHeader}
stickySectionHeadersEnabled
sections={sections}
/>
</View>
)
}
} | the_stack |
/*
* Copyright(c) 2017 Microsoft Corporation. All rights reserved.
*
* This code is licensed under the MIT License (MIT).
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/********************************************
* Spider Clustering Manager
* Author: Ricky Brundritt
* License: MIT
* Based on: https://github.com/jawj/OverlappingMarkerSpiderfier-Leaflet
*********************************************/
/// <reference path="../../Common/typings/MicrosoftMaps/Microsoft.Maps.d.ts"/>
/**
* Options used to customize how the SpiderClusterManager renders clusters.
*/
interface ISpiderClusterOptions {
/** Minimium number of pushpins in cluster before switching from circle to spiral spider layout. */
circleSpiralSwitchover?: number;
/** The minium pixel distance between pushpins and the cluster, when rendering spider layout as a circle. */
minCircleLength?: number;
/** The minium angle between pushpins in the spiral. */
minSpiralAngleSeperation?: number;
/** A factor that is used to grow the pixel distance of each pushpin from the center in the spiral. */
spiralDistanceFactor?: number;
/** Style of the stick connecting the pins to cluster. */
stickStyle?: Microsoft.Maps.IPolylineOptions;
/** Style of the sticks when a pin is hovered. */
stickHoverStyle?: Microsoft.Maps.IPolylineOptions;
/**
* A callback function that is fired when an individual pin is clicked.
* If the pin is part of a cluster, the cluster will also be returned in the callback.
*/
pinSelected?: (pin: Microsoft.Maps.Pushpin, cluster: Microsoft.Maps.ClusterPushpin) => void;
/** A callback that is fired when a pin is unselected or a spider cluster is collapsed. */
pinUnselected?: () => void;
/** A boolean indicating if the cluster layer is visible or not. */
visible?: boolean;
}
/**
* An extened pushpin which is used to represent an individual pushpin in the spider cluster.
*/
class SpiderPushpin extends Microsoft.Maps.Pushpin {
/** The parent pushpin in which the spider pushpin is derived from. */
public parentPin: Microsoft.Maps.Pushpin;
/** The stick that connects the spider pushpin to the cluster. */
public stick: Microsoft.Maps.Polyline;
}
/**
* Adds a clustering layer to the map which expands clusters into a spiral spider layout.
*/
class SpiderClusterManager {
/**********************
* Private Properties
***********************/
private _map: Microsoft.Maps.Map;
private _data: Microsoft.Maps.Pushpin[];
private _spiderLayer: Microsoft.Maps.Layer;
private _events: Microsoft.Maps.IHandlerId[] = [];
private _currentCluster: Microsoft.Maps.ClusterPushpin;
private _clusterLayer: Microsoft.Maps.ClusterLayer;
private _options: ISpiderClusterOptions = {
circleSpiralSwitchover: 9,
minCircleLength: 30,
minSpiralAngleSeperation: 25,
spiralDistanceFactor: 5,
stickStyle: {
strokeColor: 'black',
strokeThickness: 2
},
stickHoverStyle: {
strokeColor: 'red'
},
pinSelected: null,
pinUnselected: null
};
/**********************
* Constructor
***********************/
/**
* @constructor
* A cluster manager that expands clusters when selectd into a spiral layout.
* @param map A map instance to add the cluster layer to.
* @param data An array of pushpins to cluster in the layer.
* @param options A combination of SpiderClusterManager and Cluster options.
*/
constructor(map: Microsoft.Maps.Map, data: Microsoft.Maps.Pushpin[], options: ISpiderClusterOptions) {
this._map = map;
this._data = data;
this._clusterLayer = new Microsoft.Maps.ClusterLayer(data, options);
map.layers.insert(this._clusterLayer);
this._spiderLayer = new Microsoft.Maps.Layer();
map.layers.insert(this._spiderLayer);
this.setOptions(options);
this._events.push(Microsoft.Maps.Events.addHandler(map, 'click', (e) => { this.hideSpiderCluster(); }));
this._events.push(Microsoft.Maps.Events.addHandler(map, 'viewchangestart', (e) => { this.hideSpiderCluster(); }));
this._events.push(Microsoft.Maps.Events.addHandler(this._clusterLayer, 'click', (e) => { this._layerClickEvent(e); }));
this._events.push(Microsoft.Maps.Events.addHandler(this._spiderLayer, 'mouseover', (e) => {
if (e.primitive instanceof SpiderPushpin) {
(<SpiderPushpin>e.primitive).stick.setOptions(this._options.stickHoverStyle);
}
}));
this._events.push(Microsoft.Maps.Events.addHandler(this._spiderLayer, 'mouseout', (e) => {
if (e.primitive instanceof SpiderPushpin) {
(<SpiderPushpin>e.primitive).stick.setOptions(this._options.stickStyle);
}
}));
this._events.push(Microsoft.Maps.Events.addHandler(this._spiderLayer, 'click', (e) => { this._layerClickEvent(e); }));
}
/**********************
* Public Functions
***********************/
/**
* Disposes the SpiderClusterManager and releases it's resources.
*/
public dispose(): void {
this._spiderLayer.clear();
this._map.layers.remove(this._spiderLayer);
this._spiderLayer = null;
for (var i = 0, len = this._events.length; i < len; i++) {
Microsoft.Maps.Events.removeHandler(this._events[i]);
}
this._events = null;
}
/**
* Gets the base ClusterLayer used by the SpiderClusterManager.
* @returns The base ClusterLayer used by the SpiderClusterManager.
*/
public getClusterLayer(): Microsoft.Maps.ClusterLayer {
return this._clusterLayer;
}
/**
* Collapses any open spider clusters.
*/
private hideSpiderCluster(): void {
//Show cluster and hide spider.
if (this._currentCluster) {
this._currentCluster.setOptions({ visible: true });
this._spiderLayer.clear();
this._currentCluster = null;
}
}
/**
* Sets the options used to customize how the SpiderClusterManager renders clusters.
* @param options The options used to customize how the SpiderClusterManager renders clusters.
*/
public setOptions(options: ISpiderClusterOptions): void {
this.hideSpiderCluster();
if (options) {
if (typeof options.circleSpiralSwitchover === 'number') {
this._options.circleSpiralSwitchover = options.circleSpiralSwitchover;
}
if (typeof options.minSpiralAngleSeperation === 'number') {
this._options.minSpiralAngleSeperation = options.minSpiralAngleSeperation;
}
if (typeof options.spiralDistanceFactor === 'number') {
this._options.spiralDistanceFactor = options.spiralDistanceFactor;
}
if (typeof options.minCircleLength === 'number') {
this._options.minCircleLength = options.minCircleLength;
}
if (options.stickHoverStyle) {
this._options.stickHoverStyle = options.stickHoverStyle;
}
if (options.stickStyle) {
this._options.stickStyle = options.stickStyle;
}
if (options.pinSelected) {
this._options.pinSelected = options.pinSelected;
}
if (options.pinUnselected) {
this._options.pinUnselected = options.pinUnselected;
}
if (typeof options.visible === 'boolean') {
this._options.visible = options.visible;
}
this._clusterLayer.setOptions(options);
}
}
/**
* Expands a cluster into it's open spider layout.
* @param cluster The cluster to show in it's open spider layout..
*/
public showSpiderCluster(cluster: Microsoft.Maps.ClusterPushpin): void {
this.hideSpiderCluster();
this._currentCluster = cluster;
if (cluster && cluster.containedPushpins) {
//Create spider data.
var pins = cluster.containedPushpins;
var center = cluster.getLocation();
var centerPoint = <Microsoft.Maps.Point>this._map.tryLocationToPixel(center, Microsoft.Maps.PixelReference.control);
var point: Microsoft.Maps.Point;
var loc: Microsoft.Maps.Location;
var pin: SpiderPushpin;
var stick: Microsoft.Maps.Polyline;
var angle: number = 0;
var makeSpiral: boolean = pins.length > this._options.circleSpiralSwitchover;
var legPixelLength: number;
var stepAngle: number;
var stepLength: number;
if (makeSpiral) {
legPixelLength = this._options.minCircleLength / Math.PI;
stepLength = 2 * Math.PI * this._options.spiralDistanceFactor;
} else {
stepAngle = 2 * Math.PI / pins.length;
legPixelLength = (this._options.spiralDistanceFactor / stepAngle / Math.PI / 2) * pins.length;
if (legPixelLength < this._options.minCircleLength) {
legPixelLength = this._options.minCircleLength;
}
}
for (var i = 0, len = pins.length; i < len; i++) {
//Calculate spider pin location.
if (makeSpiral) {
angle += this._options.minSpiralAngleSeperation / legPixelLength + i * 0.0005;
legPixelLength += stepLength / angle;
} else {
angle = stepAngle * i;
}
point = new Microsoft.Maps.Point(
centerPoint.x + legPixelLength * Math.cos(angle),
centerPoint.y + legPixelLength * Math.sin(angle));
loc = <Microsoft.Maps.Location>this._map.tryPixelToLocation(point, Microsoft.Maps.PixelReference.control);
//Create stick to pin.
stick = new Microsoft.Maps.Polyline([center, loc], this._options.stickStyle);
this._spiderLayer.add(stick);
//Create pin in spiral that contains same metadata as parent pin.
pin = new SpiderPushpin(loc);
pin.metadata = pins[i].metadata;
pin.stick = stick;
pin.parentPin = pins[i];
pin.setOptions(this._getBasicPushpinOptions(pins[i]));
this._spiderLayer.add(pin);
}
//Hide Cluster
this._currentCluster.setOptions({ visible: false });
}
}
/**********************
* Private Functions
***********************/
/**
* Click event handler for when a shape in the cluster layer is clicked.
* @param e The mouse event argurment from the click event.
*/
private _layerClickEvent(e: Microsoft.Maps.IMouseEventArgs): void {
if (e.primitive instanceof Microsoft.Maps.ClusterPushpin) {
if (this._options.pinUnselected) {
this._options.pinUnselected();
}
this.showSpiderCluster(<Microsoft.Maps.ClusterPushpin>e.primitive);
} else {
if (this._options.pinSelected) {
var pin = <Microsoft.Maps.Pushpin>e.primitive;
if (e.primitive instanceof SpiderPushpin) {
this._options.pinSelected((<SpiderPushpin>pin).parentPin, this._currentCluster);
} else {
this._options.pinSelected(pin, null);
}
}
this.hideSpiderCluster();
}
}
/**
* Creates a copy of a pushpins basic options.
* @param pin Pushpin to copy options from.
* @returns A copy of a pushpins basic options.
*/
private _getBasicPushpinOptions(pin: Microsoft.Maps.Pushpin): Microsoft.Maps.IPushpinOptions {
return {
anchor: pin.getAnchor(),
color: pin.getColor(),
icon: pin.getIcon(),
roundClickableArea: pin.getRoundClickableArea(),
text: pin.getText(),
textOffset: pin.getTextOffset()
};
}
}
//Load Custering module which is a dependancy.
Microsoft.Maps.loadModule('Microsoft.Maps.Clustering', () => {
Microsoft.Maps.moduleLoaded('SpiderClusterManager');
}); | the_stack |
import { ElementHandle, Frame } from "puppeteer-core";
import { AxiosPost } from "../../electron/axios";
import { StoreGet } from "../../types/setting";
import { sleep } from "../common/utils";
import similarity from "string-similarity";
import https from "https";
import { Task } from "../../electron/task";
import { Logger } from "../../electron/logger";
const logger = Logger.of("qa");
export interface AnswerType {
success: number;
question: string;
answer: string;
}
// 分割答案
function sliptAnswer(str: string) {
let spl = str.split(/\n|\s|===|---|#|&|;/).filter((s) => !!s);
if (spl.length > 4) {
return [];
} else {
return spl;
}
}
export interface QACallback {
success?: () => any;
error?: () => any;
}
/**
* 查题
* @param question 题目
* @returns
*/
export async function queryAnswer(question: string): Promise<AnswerType> {
// 查题
const agent = new https.Agent({
rejectUnauthorized: false,
});
const { data: res } = await AxiosPost({
url: "https://wk.enncy.cn/chati",
httpsAgent: agent,
data: {
chatiId: StoreGet("setting").script.account.queryToken,
question,
},
});
console.log("queryAnswer", {
chatiId: StoreGet("setting").script.account.queryToken,
question,
res,
});
const { success, question: q, answer } = res;
return { success, question: q, answer };
}
export interface QAHandlerType {
questionDivSelector: string;
titleDivSelector: string;
typeResolver: (questionDiv: ElementHandle<HTMLDivElement>) => Promise<"choice" | "judgment" | "completion" | undefined>;
titleTransform: (title: string) => string;
choice: {
clickableSelector: string;
textSelector: string;
};
judgment: {
clickableSelector: string;
};
completion: {};
// 答题错误
onError: () => Promise<void>;
// 答题成功
onSuccess: (rate: number) => Promise<void>;
// 保存答案
onSave: (rate: number) => Promise<void>;
}
export interface HandlerOptions {
task: Task;
frame: Frame;
autoReport: boolean;
passRate: number;
}
export class QAHandler implements QAHandlerType {
questionDivSelector: string;
titleDivSelector: string;
// 题目类型处理器
typeResolver: (questionDiv: ElementHandle<HTMLDivElement>) => Promise<"choice" | "judgment" | "completion" | undefined>;
// 标题处理器
titleTransform: (title: string) => string;
choice: { clickableSelector: string; textSelector: string };
judgment: { clickableSelector: string };
completion: {};
// 答题错误
onError: () => Promise<void>;
// 答题成功
onSuccess: (rate: number) => Promise<void>;
// 保存答案
onSave: (rate: number) => Promise<void>;
constructor({ questionDivSelector, titleDivSelector, choice, judgment, completion, onError, onSave, onSuccess, typeResolver, titleTransform }: QAHandlerType) {
this.questionDivSelector = questionDivSelector;
this.titleDivSelector = titleDivSelector;
this.choice = choice;
this.judgment = judgment;
this.completion = completion;
this.onError = onError;
this.onSave = onSave;
this.onSuccess = onSuccess;
this.typeResolver = typeResolver;
this.titleTransform = titleTransform;
}
async handle({ task, frame, autoReport, passRate }: HandlerOptions) {
const Questions = await frame.$$(this.questionDivSelector);
if (Questions.length !== 0) {
if (!StoreGet("setting").script.account.queryToken) {
task.error("未设置查题码,不能答题,即将跳转下个任务");
await sleep(3000);
return;
}
task.process(`正在自动答题,一共${Questions.length}个题目`);
// 完成的题目数量
let finishCount = 0;
for (const question of Questions) {
try {
let title: string = await frame.evaluate((div, selector) => (div.querySelector(selector) as any)?.innerText || undefined, question, this.titleDivSelector);
const type = await this.typeResolver(question);
if (!title) {
continue;
}
// 去掉冗余字段
title = this.titleTransform(title);
task.process(`【${type === "choice" ? "选择题" : type === "judgment" ? "判断题" : type === "completion" ? "填空题" : "未知题型"}】:` + title);
const answerType = await queryAnswer(title);
// 页面上的输出样式
let success = "background-color: #f6ffed; border: 1px solid #b7eb8f;";
let err = "background-color: #fff1f0;border: 1px solid #ffa39e;";
// 页面输出
const PageAlert = async (style: string) => {
await frame.evaluate(
(div, selector, question, answer, style) => {
let qaDiv = document.createElement("div");
qaDiv.setAttribute("style", style + ";padding:2px;font-size:12px;line-height: 16px;");
let q = document.createElement("div");
q.innerHTML = "<span style='font-weight:bold'>题目</span> :" + question;
let a = document.createElement("div");
a.innerHTML = "<span style='font-weight:bold'>回答</span> :" + answer;
let node = div.querySelector(selector);
if (node) {
qaDiv.appendChild(q);
qaDiv.appendChild(a);
node.appendChild(qaDiv);
}
},
question,
this.titleDivSelector,
answerType.question,
answerType.answer,
style
);
};
// 匹配答案
if (answerType.success) {
await PageAlert(success);
// 选择题
if (type === "choice") {
const { clickableSelector, textSelector } = this.choice;
await ChoiceHandler(answerType, frame, question, {
optionClickableSelector: clickableSelector,
optionTextSelector: textSelector,
success() {
finishCount++;
},
});
} else if (type === "judgment") {
// 判断题
const { clickableSelector } = this.judgment;
await JudgmentHandler(answerType, frame, question, {
clickableSelector: clickableSelector,
success() {
finishCount++;
},
});
} else if (type === "completion") {
// 填空题
await completionHandler(answerType, frame, question, {
success() {
task.process("选择题完成");
finishCount++;
},
error() {
task.error("选择题未能完成");
},
});
} else {
logger.info("不支持的题目类型");
}
} else {
await PageAlert(err);
console.log(answerType);
logger.error(answerType);
task.error(answerType.answer);
}
} catch (err) {
console.log(err);
this.onError();
logger.error(err);
}
await sleep(3000);
}
// 如果超过通过率,则自动提交,否则暂时保存
if (Questions.length !== 0 && autoReport) {
let rate = (finishCount / Questions.length) * 100;
logger.info("通过率:", passRate, "结果:", rate);
if (rate >= passRate) {
await this.onSuccess(parseInt(rate.toFixed(2)));
} else {
await this.onSave(parseInt(rate.toFixed(2)));
}
}
}
}
}
/**
* 选择题处理器
* @param answerType 答案选项
* @param frame 执行上下文
* @param params
*
* optionDivSelector 选项div元素
* optionTextSelector 每个选项的选择器
* optionClickableSelector 可点击选项的选择器
*
*/
export async function ChoiceHandler(
answerType: AnswerType,
frame: Frame,
questionDiv: ElementHandle<Element>,
{ optionTextSelector, optionClickableSelector, success, error }: { optionTextSelector: string; optionClickableSelector: string } & QACallback
) {
const { question, answer } = answerType;
// 获取选项
const options = await frame.evaluate(
(div: HTMLDivElement, optionSelector: string) => {
console.log({ div, optionSelector, li: div.querySelectorAll(optionSelector), res: Array.from(div.querySelectorAll(optionSelector)).map((li) => (li as any)?.innerText) });
return Array.from(div.querySelectorAll(optionSelector)).map((li) => (li as any)?.innerText);
},
questionDiv,
optionTextSelector
);
let answers;
if (/^[A-F]+$/.test(answer)) {
// 如果直接给出答案,例如 ADC,则答案为对应选择: A:xxx , D:xxx , C:xxx,再传入进行判断
answers = answer.split("").map((char) => options[char.charCodeAt(0) - "A".charCodeAt(0)]);
} else {
// 分割答案
answers = sliptAnswer(answer);
}
const bestMatchIndexes = answers.map((a) => similarity.findBestMatch(a, options).bestMatchIndex);
console.log({ answerType, answers, options, bestMatchIndexes });
if (bestMatchIndexes.length !== 0) {
success?.();
for (let i of Array.from(new Set(bestMatchIndexes))) {
await sleep(1000);
await frame.evaluate(
(div, clickable, index) => {
div.querySelectorAll(clickable)[parseInt(index)]?.click();
},
questionDiv,
optionClickableSelector,
i
);
}
} else {
error?.();
}
}
/**
*
* 判断题的处理器
*/
export async function JudgmentHandler({ question, answer }: AnswerType, frame: Frame, questionDiv: ElementHandle<Element>, { success, error, clickableSelector }: { clickableSelector: string } & QACallback) {
const rightWord = "是|对|正确|√|对的|是的|正确的|true|yes|YES|Yes";
const wrongWord = "否|错|错误|×|错的|不正确的|不正确|不是|不是的|false|no|NO|No";
const { target } = similarity.findBestMatch(answer, rightWord.split("|").concat(wrongWord.split("|"))).bestMatch;
console.log("判断题", { question, answer }, target);
// 开始选择
if (RegExp(rightWord).test(target)) {
await frame.evaluate(
(div, clickable) => {
div.querySelectorAll(clickable)[0]?.click();
},
questionDiv,
clickableSelector
);
} else if (RegExp(wrongWord).test(target)) {
await frame.evaluate(
(div, clickable) => {
div.querySelectorAll(clickable)[1]?.click();
},
questionDiv,
clickableSelector
);
}
if (RegExp(rightWord).test(target) || RegExp(wrongWord).test(target)) {
success?.();
} else {
error?.();
}
logger.info(JSON.stringify({ type: "判断题", question, answer, ratings: target }));
}
/**
*
* 填空处理器
*/
export async function completionHandler({ question, answer }: AnswerType, frame: Frame, questionDiv: ElementHandle<Element>, { success, error }: QACallback) {
const ans = sliptAnswer(answer);
console.log("填空题", { question, answer }, ans);
const finish = await frame.evaluate(
(div: HTMLDivElement, answers) => {
let iframes = Array.from(div.querySelectorAll("iframe"));
let textareas = Array.from(div.querySelectorAll("textarea"));
if (textareas.length === answers.length) {
for (let i = 0; i < textareas.length; i++) {
textareas[i].value = answers[i] || "不知道";
let frame = iframes[i];
if (frame && frame.contentWindow) {
frame.contentWindow.document.body.innerHTML = "<p>" + (answers[i] || "不知道") + "</p>";
}
}
return true;
}
return false;
},
questionDiv,
ans
);
if (finish) {
success?.();
} else {
error?.();
}
logger.info(JSON.stringify({ type: "填空题", question, answer, completions: ans }));
} | the_stack |
import { DataType, IContainerType } from './types';
/**
* Elements of document type description
* Derived from https://github.com/tungol/EBML/blob/master/doctypes/matroska.dtd
* Extended with:
* https://www.matroska.org/technical/specs/index.html
*/
export const elements: IContainerType = {
0x1a45dfa3: { // 5.1
name: 'ebml',
container: {
0x4286: {name: 'ebmlVersion', value: DataType.uint}, // 5.1.1
0x42f7: {name: 'ebmlReadVersion', value: DataType.uint}, // 5.1.2
0x42f2: {name: 'ebmlMaxIDWidth', value: DataType.uint}, // 5.1.3
0x42f3: {name: 'ebmlMaxSizeWidth', value: DataType.uint}, // 5.1.4
0x4282: {name: 'docType', value: DataType.string}, // 5.1.5
0x4287: {name: 'docTypeVersion', value: DataType.uint}, // 5.1.6
0x4285: {name: 'docTypeReadVersion', value: DataType.uint} // 5.1.7
}
},
// Matroska segments
0x18538067: {
name: 'segment',
container: {
// Meta Seek Information
0x114d9b74: {
name: 'seekHead',
container: {
0x4dbb: {
name: 'seek',
container: {
0x53ab: {name: 'seekId', value: DataType.binary},
0x53ac: {name: 'seekPosition', value: DataType.uint}
}
}
}
},
// Segment Information
0x1549a966: {
name: 'info',
container: {
0x73a4: {name: 'uid', value: DataType.uid},
0x7384: {name: 'filename', value: DataType.string},
0x3cb923: {name: 'prevUID', value: DataType.uid},
0x3c83ab: {name: 'prevFilename', value: DataType.string},
0x3eb923: {name: 'nextUID', value: DataType.uid},
0x3e83bb: {name: 'nextFilename', value: DataType.string},
0x2ad7b1: {name: 'timecodeScale', value: DataType.uint},
0x4489: {name: 'duration', value: DataType.float},
0x4461: {name: 'dateUTC', value: DataType.uint},
0x7ba9: {name: 'title', value: DataType.string},
0x4d80: {name: 'muxingApp', value: DataType.string},
0x5741: {name: 'writingApp', value: DataType.string}
}
},
// Cluster
0x1f43b675: {
name: 'cluster',
multiple: true,
container: {
0xe7: {name: 'timecode', value: DataType.uid},
0xa3: {name: 'unknown', value: DataType.binary},
0xa7: {name: 'position', value: DataType.uid},
0xab: {name: 'prevSize', value: DataType.uid}
}
},
// Track
0x1654ae6b: {
name: 'tracks',
container: {
0xae: {
name: 'entries',
multiple: true,
container: {
0xd7: {name: 'trackNumber', value: DataType.uint},
0x73c5: {name: 'uid', value: DataType.uid},
0x83: {name: 'trackType', value: DataType.uint},
0xb9: {name: 'flagEnabled', value: DataType.bool},
0x88: {name: 'flagDefault', value: DataType.bool},
0x55aa: {name: 'flagForced', value: DataType.bool}, // extended
0x9c: {name: 'flagLacing', value: DataType.bool},
0x6de7: {name: 'minCache', value: DataType.uint},
0x6de8: {name: 'maxCache', value: DataType.uint},
0x23e383: {name: 'defaultDuration', value: DataType.uint},
0x23314f: {name: 'timecodeScale', value: DataType.float},
0x536e: {name: 'name', value: DataType.string},
0x22b59c: {name: 'language', value: DataType.string},
0x86: {name: 'codecID', value: DataType.string},
0x63a2: {name: 'codecPrivate', value: DataType.binary},
0x258688: {name: 'codecName', value: DataType.string},
0x3a9697: {name: 'codecSettings', value: DataType.string},
0x3b4040: {name: 'codecInfoUrl', value: DataType.string},
0x26b240: {name: 'codecDownloadUrl', value: DataType.string},
0xaa: {name: 'codecDecodeAll', value: DataType.bool},
0x6fab: {name: 'trackOverlay', value: DataType.uint},
// Video
0xe0: {
name: 'video',
container: {
0x9a: {name: 'flagInterlaced', value: DataType.bool},
0x53b8: {name: 'stereoMode', value: DataType.uint},
0xb0: {name: 'pixelWidth', value: DataType.uint},
0xba: {name: 'pixelHeight', value: DataType.uint},
0x54b0: {name: 'displayWidth', value: DataType.uint},
0x54ba: {name: 'displayHeight', value: DataType.uint},
0x54b3: {name: 'aspectRatioType', value: DataType.uint},
0x2eb524: {name: 'colourSpace', value: DataType.uint},
0x2fb523: {name: 'gammaValue', value: DataType.float}
}
},
// Audio
0xe1: {
name: 'audio',
container: {
0xb5: {name: 'samplingFrequency', value: DataType.float},
0x78b5: {name: 'outputSamplingFrequency', value: DataType.float},
0x9f: {name: 'channels', value: DataType.uint}, // https://www.matroska.org/technical/specs/index.html
0x94: {name: 'channels', value: DataType.uint},
0x7d7b: {name: 'channelPositions', value: DataType.binary},
0x6264: {name: 'bitDepth', value: DataType.uint}
}
},
// Content Encoding
0x6d80: {
name: 'contentEncodings',
container: {
0x6240: {
name: 'contentEncoding',
container: {
0x5031: {name: 'order', value: DataType.uint},
0x5032: {name: 'scope', value: DataType.bool},
0x5033: {name: 'type', value: DataType.uint},
0x5034: {
name: 'contentEncoding',
container: {
0x4254: {name: 'contentCompAlgo', value: DataType.uint},
0x4255: {name: 'contentCompSettings', value: DataType.binary}
}
},
0x5035: {
name: 'contentEncoding',
container: {
0x47e1: {name: 'contentEncAlgo', value: DataType.uint},
0x47e2: {name: 'contentEncKeyID', value: DataType.binary},
0x47e3: {name: 'contentSignature ', value: DataType.binary},
0x47e4: {name: 'ContentSigKeyID ', value: DataType.binary},
0x47e5: {name: 'contentSigAlgo ', value: DataType.uint},
0x47e6: {name: 'contentSigHashAlgo ', value: DataType.uint}
}
},
0x6264: {name: 'bitDepth', value: DataType.uint}
}
}
}
}
}
}
}
},
// Cueing Data
0x1c53bb6b: {
name: 'cues',
container: {
0xbb: {
name: 'cuePoint',
container: {
0xb3: {name: 'cueTime', value: DataType.uid},
0xb7: {
name: 'positions',
container: {
0xf7: {name: 'track', value: DataType.uint},
0xf1: {name: 'clusterPosition', value: DataType.uint},
0x5378: {name: 'blockNumber', value: DataType.uint},
0xea: {name: 'codecState', value: DataType.uint},
0xdb: {
name: 'reference', container: {
0x96: {name: 'time', value: DataType.uint},
0x97: {name: 'cluster', value: DataType.uint},
0x535f: {name: 'number', value: DataType.uint},
0xeb: {name: 'codecState', value: DataType.uint}
}
},
0xf0: {name: 'relativePosition', value: DataType.uint} // extended
}
}
}
}
}
},
// Attachment
0x1941a469: {
name: 'attachments',
container: {
0x61a7: {
name: 'attachedFiles',
multiple: true,
container: {
0x467e: {name: 'description', value: DataType.string},
0x466e: {name: 'name', value: DataType.string},
0x4660: {name: 'mimeType', value: DataType.string},
0x465c: {name: 'data', value: DataType.binary},
0x46ae: {name: 'uid', value: DataType.uid}
}
}
}
},
// Chapters
0x1043a770: {
name: 'chapters',
container: {
0x45b9: {
name: 'editionEntry',
container: {
0xb6: {
name: 'chapterAtom',
container: {
0x73c4: {name: 'uid', value: DataType.uid},
0x91: {name: 'timeStart', value: DataType.uint},
0x92: {name: 'timeEnd', value: DataType.uid},
0x98: {name: 'hidden', value: DataType.bool},
0x4598: {name: 'enabled', value: DataType.uid},
0x8f: {name: 'track', container: {
0x89: {name: 'trackNumber', value: DataType.uid},
0x80: {
name: 'display', container: {
0x85: {name: 'string', value: DataType.string},
0x437c: {name: 'language ', value: DataType.string},
0x437e: {name: 'country ', value: DataType.string}
}
}
}
}
}
}
}
}
}
},
// Tagging
0x1254c367: {
name: 'tags',
container: {
0x7373: {
name: 'tag',
multiple: true,
container: {
0x63c0: {
name: 'target',
container: {
0x63c5: {name: 'tagTrackUID', value: DataType.uid},
0x63c4: {name: 'tagChapterUID', value: DataType.uint},
0x63c6: {name: 'tagAttachmentUID', value: DataType.uid},
0x63ca: {name: 'targetType', value: DataType.string}, // extended
0x68ca: {name: 'targetTypeValue', value: DataType.uint}, // extended
0x63c9: {name: 'tagEditionUID', value: DataType.uid} // extended
}
},
0x67c8: {
name: 'simpleTags',
multiple: true,
container: {
0x45a3: {name: 'name', value: DataType.string},
0x4487: {name: 'string', value: DataType.string},
0x4485: {name: 'binary', value: DataType.binary},
0x447a: {name: 'language', value: DataType.string}, // extended
0x447b: {name: 'languageIETF', value: DataType.string}, // extended
0x4484: {name: 'default', value: DataType.bool} // extended
}
}
}
}
}
}
}
}
}; | the_stack |
module Kiwi.Files {
/**
* Used for the loading of files and game assets. This usually happens when a State is at the 'loading' stage (executing the 'preload' method).
*
* @class Loader
* @namespace Kiwi.Files
* @constructor
* @param game {Kiwi.Game} The game that this loader belongs to.
* @return {Kiwi.Files.Loader} This Object
*
*/
export class Loader {
constructor(game: Kiwi.Game) {
this.game = game;
}
/**
* The type of object this is.
* @method objType
* @return {String} "Loader"
* @public
*/
public objType() {
return "Loader";
}
/**
* The game this loader is attached to.
* @property game
* @type Kiwi.Game
* @public
*/
public game: Kiwi.Game;
/**
* A list of files that can be loaded in parallel to one another.
* This list of files are currently being loaded.
*
* @property _loadingParallel
* @type Array
* @since 1.2.0
* @private
*/
private _loadingParallel: Kiwi.Files.File[];
/**
* List of files that cannot load in parallel to one another
* and so need to wait for previous files to load first.
* Generally files loaded via XHR.
*
* @property _loadingQueue
* @type Array
* @since 1.2.0
* @private
*/
private _loadingQueue: Kiwi.Files.File[];
/**
* List of files that are to be loaded.
* These files will be placed in the '_loadingQueue' or '_loadingParallel'
* lists when the queue is told to 'start' loading.
*
* @property _loadingList
* @type Array
* @since 1.2.0
* @private
*/
private _loadingList: Kiwi.Files.File[];
/**
* A Signal which dispatches callbacks when all files in the 'loadingList' have been loaded.
* When adding callbacks make sure to 'remove' them (or to use the 'addOnce' method)
* otherwise will fire when other sections use the loader.
*
* @method onQueueComplete
* @type Kiwi.Signal
* @since 1.2.0
* @public
*/
public onQueueComplete: Kiwi.Signal;
/**
* A Signal which dispatches callbacks each time a file in the 'loadingList' have been loaded.
* Callbacks dispatched are passed the following arguments in order.
* 1. percent - The percentage of files loaded. A number from 0 - 100
* 2. bytesLoaded - The number of bytes loaded
* 3. file - The latest file that was loaded. First call will be null.
*
* When adding callbacks make sure to 'remove' them (or to use the 'addOnce' method)
* otherwise will fire when other sections use the loader.
*
* @method onQueueProgress
* @type Kiwi.Signal
* @since 1.2.0
* @public
*/
public onQueueProgress: Kiwi.Signal;
/**
* A flag indicating if the files inside the file queue are loading or not.
*
* @property _fileQueueLoading
* @type Boolean
* @default false
* @since 1.2.0
* @private
*/
private _queueLoading: boolean = false;
/**
* READ ONLY: A flag indicating if the files inside the file queue are loading or not.
*
* @property fileQueueLoading
* @type Boolean
* @default false
* @readOnly
* @since 1.2.0
* @public
*/
public get queueLoading(): boolean {
return this._queueLoading;
}
/**
* When 'calculateBytes' is true the percentLoaded will be the `bytesLoaded / bytesTotal`.
* Otherwise it is based on the `filesLoaded / numberOfFilesToLoad`.
*
* @property percentLoaded
* @type Number
* @since 1.2.0
* @readOnly
* @public
*/
public percentLoaded: number = 0;
/**
* When enabled, files which can be loaded in parallel (those which are loaded via tags)
* will be loaded at the same time.
*
* The default behaviour is to have the files loading in a queued fashion instead of one after another.
*
* @property enableParallelLoading
* @type Boolean
* @default false
* @since 1.2.0
* @public
*/
public enableParallelLoading: boolean = false;
/**
* The boot method is executed when the DOM has successfully loaded and we can now start the game.
* @method boot
* @public
*/
public boot() {
this._loadingList = [];
this._loadingParallel = [];
this._loadingQueue = [];
this.onQueueComplete = new Kiwi.Signal();
this.onQueueProgress = new Kiwi.Signal();
}
/**
* Starts loading all the files which are in the file queue.
*
* To accurately use the bytesLoaded or bytesTotal properties you will need to set the 'calculateBytes' boolean to true.
* This may increase load times, as each file in the queue will firstly make XHR HEAD requests for information.
*
* When 'calculateBytes' is true the percentLoaded will be the `bytesLoaded / bytesTotal`.
* Otherwise it is based on the `filesLoaded / numberOfFilesToLoad`.
*
* @method start
* @param [calculateBytes] {Boolean} Setter for the 'calculateBytes' property.
* @since 1.2.0
* @public
*/
public start(calculateBytes: boolean = null) {
if (calculateBytes !== null) {
this._calculateBytes = calculateBytes;
}
if (this._queueLoading) {
Kiwi.Log.warn('Kiwi.Files.Loader: Files in the queue are already being loaded');
return;
}
//Reset the number of bytes laoded
this._bytesLoaded = 0;
this._bytesTotal = 0;
this.percentLoaded = 0;
if (this._calculateBytes) {
this.calculateQueuedSize(this._startLoading, this);
} else {
this._startLoading();
}
}
/**
* Loops through the file queue and starts the loading process.
*
* @method _startLoading
* @private
*/
private _startLoading() {
//Any files to load?
if (this._loadingList.length <= 0) {
Kiwi.Log.log('Kiwi.Files.Loader: No files are to load have been found.', '#loading');
this.onQueueProgress.dispatch(100, 0, null);
this.onQueueComplete.dispatch();
return;
}
//There are files to load
var i = 0,
file: Kiwi.Files.File;
while (i < this._loadingList.length) {
if (this._calculateBytes) {
this._loadingList[i].onProgress.add(this._updateFileListInformation, this);
}
this._sortFile(this._loadingList[i]);
this._loadingList[i].onComplete.addOnce(this._fileQueueUpdate, this);
i++;
}
this._queueLoading = true;
this._bytesLoaded = 0;
this._startLoadingQueue();
this._startLoadingAllParallel();
this._fileQueueUpdate(null, true);
}
/**
* Adds a file to the queue of files to be loaded.
* Files cannot be added whilst the queue is currently loading,
* the file to add is currently loading, or has been loaded before.
*
* @method addFileToQueue
* @param file {Kiwi.Files.File} The file to add.
* @return {Boolean} If the file was added to the queue or not.
* @since 1.2.0
* @public
*/
public addFileToQueue(file: Kiwi.Files.File) {
if (this._queueLoading) {
Kiwi.Log.warn('Kiwi.Files.Loader: File cannot be added to the queue whilst the queue is currently loading.', '#loading', '#filequeue');
return false;
}
if (file.loading || file.complete) {
Kiwi.Log.warn('Kiwi.Files.Loader: File could not be added as it is currently loading or has already loaded.', '#loading', '#filequeue');
return false;
}
this._loadingList.push(file);
return true;
}
/**
* Removes a file from the file queue.
* Files cannot be removed whilst the queue is loading.
*
* @method removeFileFromQueue
* @param file {Kiwi.Files.File} The file to remove.
* @return {Boolean} If the file was added to the queue or not.
* @since 1.2.0
* @public
*/
public removeFileFromQueue(file: Kiwi.Files.File): boolean {
if (this._queueLoading) {
Kiwi.Log.warn('Kiwi.Files.Loader: File cannot be remove from the queue whilst the queue is currently loading.', '#loading', '#filequeue');
return false;
}
var index = this._loadingList.indexOf(file);
if (index === -1) {
return false;
}
if (file.loading) {
Kiwi.Log.warn('Kiwi.Files.Loader: Cannot remove the file from the list as it is currently loading.', '#loading', '#filequeue');
return false;
}
this._loadingList.splice(index, 1);
return true;
}
/**
* Clears the file queue of all files.
*
* @method clearQueue
* @since 1.2.0
* @public
*/
public clearQueue() {
if (!this._queueLoading) {
this._loadingList.length = 0;
} else {
Kiwi.Log.error('Kiwi.Files.Loader: Cannot clear the file queue whilst the files are being loaded.', '#loading', '#filequeue');
}
}
/**
* Starts the process of loading a file outside of the regular queue loading process.
* Callbacks for load completion need to be added onto the file via 'onComplete' Signal.
*
* @method loadFile
* @public
*/
public loadFile(file: Kiwi.Files.File) {
if ( file.loading || file.complete ) {
Kiwi.Log.error('Kiwi.Files.Loader: Could not add file. File is already loading or has completed loading.');
return;
}
this._sortFile(file, true);
}
/**
* Sorts a file and places it into either the 'loadingParallel' or 'loadingQueue'
* depending on the method of loading it is using.
*
* @method _sortFile
* @param file {Kiwi.Files.File}
* @since 1.2.0
* @private
*/
private _sortFile(file: Kiwi.Files.File, startLoading: boolean = false) {
if (this.enableParallelLoading && file.loadInParallel) {
//Push into the tag loader queue
this._loadingParallel.push(file);
if (startLoading) {
this._startLoadingParallel(file);
}
} else {
//Push into the xhr queue
this._loadingQueue.push(file);
if (startLoading) {
this._startLoadingQueue();
}
}
}
/**
* The number of files in the file queue that have been updated.
*
* @property _completeFiles
* @type number
* @default 0
* @private
*/
private _completedFiles: number = 0;
/**
* Called each time a file has processed whilst loading, or has just completed loading.
*
* Calculates the new number of bytes loaded and
* the percentage of loading done by looping through all of the files.
*
* @method _updateFileListInformation
* @private
*/
private _updateFileListInformation() {
var i = 0;
this._completedFiles = 0;
this._bytesLoaded = 0;
while (i < this._loadingList.length) {
//Was the file loaded, but we have no bytes (must have used the tag loader) and we have their details?
if (this._loadingList[i].bytesLoaded === 0 && this._loadingList[i].success && this._loadingList[i].detailsReceived) {
this._bytesLoaded += this._loadingList[i].size;
} else {
//Add the bytes loaded to the list
this._bytesLoaded += this._loadingList[i].bytesLoaded;
}
//Calculate percentage
if (this._loadingList[i].complete) {
this._completedFiles++;
}
i++;
}
//Calculate the percentage depending on how accurate we can be.
if (this._calculateBytes) {
this.percentLoaded = (this._bytesLoaded / this._bytesTotal) * 100;
} else {
this.percentLoaded = (this._completedFiles / this._loadingList.length) * 100;
}
}
/**
* Executed by files when they have successfully been loaded.
* This method checks to see if the files are in the file queue, and dispatches the appropriate events.
*
* @method _fileQueueUpdate
* @param file {Kiwi.Files.File} The file which has been recently loaded.
* @param [forceProgressCheck=false] {Boolean} If the progress of file loading should be checked, regardless of the file being in the queue or not.
* @since 1.2.0
* @private
*/
private _fileQueueUpdate(file: Kiwi.Files.File, forceProgressCheck: boolean = false) {
//If the file loaded is in the loadingList
if (!forceProgressCheck && this._loadingList.indexOf(file) === -1) {
return;
}
//Update the file information.
this._updateFileListInformation();
//Dispatch progress event.
this.onQueueProgress.dispatch(this.percentLoaded, this.bytesLoaded, file);
if (this._completedFiles >= this._loadingList.length) {
//Clear the file queue and dispatch the loaded event
this._queueLoading = false;
this.clearQueue();
this.onQueueComplete.dispatch();
}
}
/**
* Starts the loading process in the loadingQueue.
* @method _startLoadingQueue
* @return {Boolean}
* @private
* @since 1.2.0
* @return {boolean} Whether the first file is loading
*/
private _startLoadingQueue(): boolean {
//Any files to load?
if (this._loadingQueue.length <= 0) {
Kiwi.Log.log('Kiwi.Files.Loader: No queued files to load.', '#loading');
return false;
}
//Is the first file currently loading?
if (this._loadingQueue[0].loading) {
return false;
}
//Attempt to load the file!
this._loadingQueue[0].onComplete.addOnce(this._queueFileComplete, this, 1);
this._loadingQueue[0].load();
return true;
}
/**
* Executed when a file in the 'loadingQueue' has been successfully loaded.
* Removes the file from the loadingQueue and executes the '_startLoadingQueue' to start loading the next file.
*
* @method _queueFileComplete
* @param file {Kiwi.Files.File}
* @since 1.2.0
* @private
*/
private _queueFileComplete(file: Kiwi.Files.File) {
//Remove from the loadingQueue
var index = this._loadingQueue.indexOf(file);
if (index === -1) {
Kiwi.Log.warn("Something has gone wrong? The file which executed this method doesn't exist in the loadingQueue.", '#loading', '#error');
return;
}
this._loadingQueue.splice(index, 1);
//Start loading the next file
this._startLoadingQueue();
}
/**
* Starts loading a file which can be loaded in parallel.
* @method _startLoadingParallel
* @param params file {Kiwi.Files.File}
* @since 1.2.0
* @private
*/
private _startLoadingParallel( file: Kiwi.Files.File) {
if (!file.loading) {
file.onComplete.add(this._parallelFileComplete, this, 1);
file.load();
}
}
/**
* Starts loading all files which can be loaded in parallel.
* @method _startLoadingAllParallel
* @since 1.2.0
* @private
*/
private _startLoadingAllParallel() {
var i = this._loadingParallel.length,
file: Kiwi.Files.File;
while( i-- ) {
this._startLoadingParallel( this._loadingParallel[ i ] );
}
}
/**
* Executed when a file in the 'loadingParallel' lsit has been successfully loaded.
* Removes the file from the list and get the fileQueue to check its progress.
*
* @method _parallelFileComplete
* @param file {Kiwi.Files.File}
* @since 1.2.0
* @private
*/
private _parallelFileComplete(file: Kiwi.Files.File) {
var index = this._loadingParallel.indexOf(file);
if (index === -1) {
Kiwi.Log.warn("Something has gone wrong? The file which executed this method doesn't exist in the loadingParallel.", '#loading', '#error');
return;
}
this._loadingParallel.splice(index, 1);
}
/**
* -----------------------------
* Bytes Loaded Methods
* -----------------------------
**/
/**
* If the number of bytes for each file should be calculated before the queue starts loading.
* If true each file in the queue makes a XHR HEAD request first to get the total values.
*
* @property _calculateBytes
* @type Boolean
* @private
*/
private _calculateBytes: boolean = false;
/**
* Callback for when the total number of bytes of the files in the file list has been calculated.
*
* @property onQueueSizeCalculate
* @type any
* @private
*/
private onSizeCallback: any;
/**
* Context that the onSizeCallback should be executed in.
*
* @property onSizeContext
* @type any
* @private
*/
private onSizeContext: any;
/**
* The index of the current file in the filelist thats size is being retrieved.
* @property _currentFileIndex
* @type number
* @private
*/
private _currentFileIndex: number = 0;
/**
* Total file size (in bytes) of all files in the queue to be loaded.
*
* @property _bytesTotal
* @type Number
* @private
*/
private _bytesTotal: number = 0;
/**
* READ ONLY: Returns the total number of bytes for the files in the file queue.
* Only contains a value if you use the 'calculateBytes' and are loading files
* OR if you use the 'calculateQueuedSize' method.
*
* @property bytesTotal
* @readOnly
* @default 0
* @since 1.2.0
* @type Number
* @public
*/
public get bytesTotal(): number {
return this._bytesTotal;
}
/**
* The number of bytes loaded of files in the file queue.
*
* @property _bytesLoaded
* @type Number
* @private
*/
private _bytesLoaded: number = 0;
/**
* READ ONLY: Returns the total number of bytes for the files in the file queue.
*
* If you are using this make sure you set the 'calculateBytes' property to true OR execute the 'calculateQueuedSize' method.
* Otherwise files that are loaded via tags will not be accurate!
*
* @property bytesLoaded
* @readOnly
* @default 0
* @since 1.2.0
* @type Number
* @public
*/
public get bytesLoaded(): number {
return this._bytesLoaded;
}
/**
* Loops through the file queue and gets file information (filesize, ETag, filetype) for each.
*
* To get accurate information about the bytesLoaded, bytesTotal, and the percentLoaded
* set the 'calculateBytes' property to true, as the loader will automatically execute this method before hand.
*
* Can only be executed when the file queue is not currently loading.
*
* @method calculateQueuedSize
* @param callback {any}
* @param [context=null] {any}
* @public
*/
public calculateQueuedSize(callback: any, context: any = null) {
//Is the queue currently loading files?
if (this._queueLoading) {
Kiwi.Log.warn('Kiwi.Files.Loader: Cannot calculate the size of the files in the filequeue whilst they are loading. ');
return;
}
//Set the callbacks
this.onSizeCallback = callback;
this.onSizeContext = context;
// Start the process
this._currentFileIndex = 0;
this._bytesTotal = 0;
this._queueLoading = true;
this._calculateNextFileSize();
}
/**
* Checks to see if all the file sizes have been retrieved.
* If so completes the "calculateQueuedSize" call.
* Otherwise requests the next file's details.
*
* @method _calculateNextFileSize
* @private
*/
private _calculateNextFileSize() {
if (this._currentFileIndex >= this._loadingList.length) {
this._queueLoading = false;
this.onSizeCallback.call(this.onSizeContext, this._bytesTotal);;
return;
}
var file = this._loadingList[this._currentFileIndex];
//Have we already got the details for this file?
if (file.detailsReceived) {
this._detailsReceived();
} else {
var details = file.loadDetails(this._detailsReceived, this);
//Skip to the next file if the request could not be made.
//Shouldn't happen.
if (!details) {
this._detailsReceived();
}
}
}
/**
* Executed when by '_calculateNextFileSize' when the files information has been retrieved.
* Adds its calculated size to the _bytesTotal and executes the 'nextFileSize' method.
*
* @method _detailsReceived
* @private
*/
private _detailsReceived() {
var file = this._loadingList[this._currentFileIndex];
if (file.detailsReceived) {
this._bytesTotal += file.size;
}
this._currentFileIndex++;
this._calculateNextFileSize();
}
/**
* -----------------------------
* File Addition Methods
* -----------------------------
*/
/**
* Creates a new file for an image and adds a the file to loading queue.
* @method addImage
* @param key {String} The key for the file.
* @param url {String} The url of the image to load.
* @param [width] {number} The width of the cell on the image to use once the image is loaded.
* @param [height] {number} The height of the cell on the image to use once the image is loaded.
* @param [offsetX] {number} An offset on the x axis of the cell.
* @param [offsetY] {number} An offset of the y axis of the cell.
* @param [storeAsGlobal=true] {boolean} If the image should be stored globally or not.
* @return {Kiwi.Files.File} The file which was created.
* @public
*/
public addImage(key: string, url: string, width?: number, height?: number, offsetX?: number, offsetY?: number, storeAsGlobal: boolean = true): Kiwi.Files.File {
var params:any = {
type: Kiwi.Files.File.IMAGE,
key: null,
url: null,
fileStore: this.game.fileStore,
metadata: {}
};
if ( Kiwi.Utils.Common.isObject(key) ) {
var p: any = key;
params.key = p.key;
params.url = p.url;
params.metadata = {
width: p.width,
height: p.height,
offsetX: p.offsetX,
offsetY: p.offsetY
};
if (p.xhrLoading) params.xhrLoading = p.xhrLoading;//forces blob loading
if (p.state) params.state = p.state;
if (p.tags) params.tags = p.tags;
} else {
if (!storeAsGlobal && this.game.states.current) {
params.state = this.game.states.current;
}
params.key = key;
params.url = url;
params.metadata = {
width: width,
height: height,
offsetX: offsetX,
offsetY: offsetY
};
}
var file: Kiwi.Files.File = new Kiwi.Files.TextureFile(this.game, params);
this.addFileToQueue(file);
return file;
}
/**
* Creates a new file for a spritesheet and adds the file to the loading queue.
* @method addSpriteSheet
* @param key {String} The key for the file.
* @param url {String} The url of the image to load.
* @param frameWidth {number} The width of a single cell in the spritesheet.
* @param frameHeight {number} The height of a single cell in the spritesheet.
* @param [numCells] {number} The number of cells that are in this spritesheet.
* @param [rows] {number} The number of cells that are in a row.
* @param [cols] {number} The number of cells that are in a column.
* @param [sheetOffsetX] {number} The offset of the whole spritesheet on the x axis.
* @param [sheetOffsetY] {number} The offset of the whole spritesheet on the y axis.
* @param [cellOffsetX] {number} The spacing between each cell on the x axis.
* @param [cellOffsetY] {number} The spacing between each cell on the y axis.
* @param [storeAsGlobal=true] {boolean}
* @return {Kiwi.Files.File} The file which was created.
* @public
*/
public addSpriteSheet(key: string, url: string, frameWidth: number, frameHeight: number, numCells?: number, rows?: number, cols?: number, sheetOffsetX?: number, sheetOffsetY?: number, cellOffsetX?: number, cellOffsetY?: number, storeAsGlobal: boolean = true) {
var params: any = {
type: Kiwi.Files.File.SPRITE_SHEET,
key: null,
url: null,
fileStore: this.game.fileStore,
metadata: {}
};
if (Kiwi.Utils.Common.isObject(key)) {
var p: any = key;
params.key = p.key;
params.url = p.url;
params.metadata = {
frameWidth: p.frameWidth,
frameHeight: p.frameHeight,
numCells: p.numCells,
rows: p.rows,
cols: p.cols,
sheetOffsetX: p.sheetOffsetX,
sheetOffsetY: p.sheetOffsetY,
cellOffsetX: p.cellOffsetX,
cellOffsetY: p.cellOffsetY
};
if (p.xhrLoading) params.xhrLoading = p.xhrLoading;//forces blob loading
if (p.state) params.state = p.state;
if (p.tags) params.tags = p.tags;
} else {
if (!storeAsGlobal && this.game.states.current) {
params.state = this.game.states.current;
}
params.key = key;
params.url = url;
params.metadata = {
frameWidth: frameWidth,
frameHeight: frameHeight,
numCells: numCells,
rows: rows,
cols: cols,
sheetOffsetX: sheetOffsetX,
sheetOffsetY: sheetOffsetY,
cellOffsetX: cellOffsetX,
cellOffsetY: cellOffsetY
};
}
var file = new Kiwi.Files.TextureFile(this.game, params);
this.addFileToQueue(file);
return file;
}
/**
* Creates new file's for loading a texture atlas and adds those files to the loading queue.
* @method addTextureAtlas
* @param key {String} The key for the image file.
* @param imageUrl {String} The url of the image to load.
* @param jsonID {String} A key for the JSON file.
* @param jsonURL {String} The url of the json file to load.
* @param [storeAsGlobal=true] {Boolean} If hte files should be stored globally or not.
* @return {Kiwi.Files.File} The file which was created.
* @public
*/
public addTextureAtlas(key: string, imageURL: string, jsonID: string, jsonURL: string, storeAsGlobal: boolean = true) {
var textureParams: any = {
type: Kiwi.Files.File.TEXTURE_ATLAS,
key: key,
url: imageURL,
fileStore: this.game.fileStore,
metadata: {
jsonID: jsonID
}
};
var jsonParams: any = {
type: Kiwi.Files.File.JSON,
key: jsonID,
url: jsonURL,
fileStore: this.game.fileStore,
metadata: {
imageID: key
}
};
if (!storeAsGlobal && this.game.states.current) {
textureParams.state = this.game.states.current;
jsonParams.state = this.game.states.current;
}
if (Kiwi.Utils.Common.isObject(key)) {
var p: any = key;
textureParams.key = p.textureAtlasKey;
textureParams.url = p.textureAtlasURL;
jsonParams.key = p.jsonKey;
jsonParams.url = p.jsonURL;
textureParams.metadata.jsonID = jsonParams.key;
jsonParams.metadata.imageID = textureParams.key;
if (p.state) {
textureParams.state = p.state;
jsonParams.state = p.state;
}
if (p.xhrLoading) textureParams.xhrLoading = p.xhrLoading; //forces blob loading
if (p.tags) {
jsonParams.tags = p.tags;
textureParams.tags = p.tags;
}
}
var imageFile = new Kiwi.Files.TextureFile(this.game, textureParams);
var jsonFile = new Kiwi.Files.DataFile(this.game, jsonParams);
this.addFileToQueue(imageFile);
this.addFileToQueue(jsonFile);
return imageFile;
}
/**
* Creates a new File to store a audio piece.
* This method firstly checks to see if the AUDIO file being loaded is supported or not by the browser/device before adding it to the loading queue.
* You can override this behaviour and tell the audio data to load even if not supported by setting the 'onlyIfSupported' boolean to false.
* Also you can now pass an array of filepaths, and the first audio filetype that is supported will be loaded.
*
* @method addAudio
* @param key {String} The key for the audio file.
* @param url {String} The url of the audio to load. You can pass an array of URLs, in which case the first supported audio filetype in the array will be loaded.
* @param [storeAsGlobal=true] {Boolean} If the file should be stored globally.
* @param [onlyIfSupported=true] {Boolean} If the audio file should only be loaded if Kiwi detects that the audio file could be played.
* @return {Kiwi.Files.File} The file which was created.
* @public
*/
public addAudio(key: string, url: any, storeAsGlobal: boolean = true, onlyIfSupported: boolean = true) {
var params = {
type: Kiwi.Files.File.AUDIO,
key: null,
url: null,
state: null,
fileStore: this.game.fileStore
};
if (Kiwi.Utils.Common.isObject(key)) {
params = (<any>key);
params.type = Kiwi.Files.File.AUDIO;
params.fileStore = this.game.fileStore;
} else {
params.key = key;
params.url = url;
if (!storeAsGlobal && this.game.states.current) {
params.state = this.game.states.current;
}
}
var i = 0,
urls, file;
//If it is a string then try to load that file
if (Kiwi.Utils.Common.isString(params.url)) {
urls = [params.url];
} else {
urls = params.url;
}
while (i < urls.length) {
params.url = urls[i]
file = this._attemptToAddAudio(params, onlyIfSupported);
if (file) {
return file;
}
i++;
}
return null;
}
/**
* This method firstly checks to see if the AUDIO file being loaded is supported or not by the browser/device before adding it to the loading queue.
* Returns a boolean if the audio file was successfully added or not to the file directory.
* @method _attemptToAddAudio
* @param params {Object}
* @param params.key {String} The key for the audio file.
* @param params.url {String} The url of the audio to load.
* @param [params.state=true] {Kiwi.State} The state this file should be for.
* @param [params.fileStore] {Kiwi.Files.FileStore}
* @param [onlyIfSupported=true] {Boolean} If the audio file should only be loaded if Kiwi detects that the audio file could be played.
* @return {Kiwi.Files.File} The file which was created.
* @private
*/
private _attemptToAddAudio(params:any, onlyIfSupported: boolean): Kiwi.Files.File {
var file = new Kiwi.Files.AudioFile(this.game, params);
var support = false;
switch (file.extension) {
case 'mp3':
support = Kiwi.DEVICE.mp3;
break;
case 'ogg':
case 'oga':
support = Kiwi.DEVICE.ogg;
break;
case 'm4a':
support = Kiwi.DEVICE.m4a;
break;
case 'wav':
case 'wave':
support = Kiwi.DEVICE.wav;
break;
}
if (support == true || onlyIfSupported == false) {
this.addFileToQueue(file);
return file;
} else {
Kiwi.Log.error('Kiwi.Loader: Audio Format not supported on this Device/Browser.', '#audio', '#unsupported');
return null;
}
}
/**
* Creates a new File to store JSON and adds it to the loading queue.
* @method addJSON
* @param key {String} The key for the file.
* @param url {String} The url to the json file.
* @param [storeAsGlobal=true] {Boolean} If the file should be stored globally.
* @return {Kiwi.Files.File} The file which was created.
* @public
*/
public addJSON(key: string, url: string, storeAsGlobal: boolean = true) {
var params: any = {
type: Kiwi.Files.File.JSON,
key: key,
url: url,
fileStore: this.game.fileStore
};
if (Kiwi.Utils.Common.isObject(key)) {
var p: any = key;
params.key = p.key;
params.url = p.url;
if (p.parse) params.parse = p.parse;
if (p.state) params.state = p.state;
if (p.tags) params.tags = p.tags;
} else {
if (!storeAsGlobal && this.game.states.current) {
params.state = this.game.states.current;
}
}
var file = new Kiwi.Files.DataFile(this.game, params);
this.addFileToQueue(file);
return file;
}
/**
* Creates a new File to store XML and adds it to the loading queue.
* @method addXML
* @param key {String} The key for the file.
* @param url {String} The url to the xml file.
* @param [storeAsGlobal=true] {Boolean} If the file should be stored globally.
* @return {Kiwi.Files.File} The file which was created.
* @public
*/
public addXML(key: string, url: string, storeAsGlobal: boolean = true) {
var params:any = {
type: Kiwi.Files.File.XML,
key: key,
url: url,
fileStore: this.game.fileStore
};
if (Kiwi.Utils.Common.isObject(key)) {
var p: any = key;
params.key = p.key;
params.url = p.url;
if (p.parse) params.parse = p.parse;
if (p.state) params.state = p.state;
if (p.tags) params.tags = p.tags;
} else {
if (!storeAsGlobal && this.game.states.current) {
params.state = this.game.states.current;
}
}
var file = new Kiwi.Files.DataFile(this.game, params);
this.addFileToQueue(file);
return file;
}
/**
* Creates a new File for a Binary file and adds it to the loading queue.
* @method addBinaryFile
* @param key {String} The key for the file.
* @param url {String} The url to the Binary file.
* @param [storeAsGlobal=true] {Boolean} If the file should be stored globally.
* @return {Kiwi.Files.File} The file which was created.
* @public
*/
public addBinaryFile(key: string, url: string, storeAsGlobal: boolean = true) {
var params: any = {
type: Kiwi.Files.File.BINARY_DATA,
key: key,
url: url,
fileStore: this.game.fileStore
};
if (Kiwi.Utils.Common.isObject(key)) {
var p: any = key;
params.key = p.key;
params.url = p.url;
if (p.parse) params.parse = p.parse;
if (p.state) params.state = p.state;
if (p.tags) params.tags = p.tags;
} else {
if (!storeAsGlobal && this.game.states.current) {
params.state = this.game.states.current;
}
}
var file = new Kiwi.Files.DataFile(this.game, params);
this.addFileToQueue(file);
return file;
}
/**
* Creates a new File to store a text file and adds it to the loading queue.
* @method addTextFile
* @param key {String} The key for the file.
* @param url {String} The url to the text file.
* @param [storeAsGlobal=true] {Boolean} If the file should be stored globally.
* @return {Kiwi.Files.File} The file which was created.
* @public
*/
public addTextFile(key: string, url: string, storeAsGlobal: boolean = true) {
var params: any = {
type: Kiwi.Files.File.TEXT_DATA,
key: key,
url: url,
fileStore: this.game.fileStore
};
if (Kiwi.Utils.Common.isObject(key)) {
var p: any = key;
params.key = p.key;
params.url = p.url;
if (p.parse) params.parse = p.parse;
if (p.state) params.state = p.state;
if (p.tags) params.tags = p.tags;
} else {
if (!storeAsGlobal && this.game.states.current) {
params.state = this.game.states.current;
}
}
var file = new Kiwi.Files.DataFile(this.game, params);
this.addFileToQueue(file);
return file;
}
/**
* Flags this loader for garbage collection. Only use this method if you are SURE you will no longer need it.
* Otherwise it is best to leave it alone.
*
* @method destroy
* @public
*/
public destroy() {
this.onQueueComplete.dispose();
this.onQueueProgress.dispose();
delete this.game;
delete this.onQueueComplete;
delete this.onQueueProgress;
var i = 0;
while (i < this._loadingList.length) {
this._loadingList[i].destroy();
i++;
}
this._loadingList = [];
var i = 0;
while (i < this._loadingQueue.length) {
this._loadingQueue[i].destroy();
i++;
}
this._loadingQueue = [];
var i = 0;
while (i < this._loadingParallel.length) {
this._loadingParallel[i].destroy();
i++;
}
this._loadingParallel = [];
}
/**
* -----------------------
* Deprecated - Functionality exists. Maps to its equalvent
* -----------------------
**/
/**
* Initialise the properities that are needed on this loader.
* Recommended you use the 'onQueueProgress' / 'onQueueComplete' signals instead.
*
* @method init
* @param [progress=null] {Any} Progress callback method.
* @param [complete=null] {Any} Complete callback method.
* @param [calculateBytes=false] {boolean}
* @deprecated Deprecated as of 1.2.0
* @public
*/
public init(progress: any = null, complete: any = null, calculateBytes: boolean=null) {
if (calculateBytes !== null) {
this._calculateBytes = calculateBytes;
}
if (progress !== null) {
this.onQueueProgress.addOnce( progress );
}
if (complete !== null) {
this.onQueueComplete.addOnce( complete );
}
}
/**
* Loops through all of the files that need to be loaded and start the load event on them.
* @method startLoad
* @deprecated Use 'start' instead. Deprecated as of 1.2.0
* @public
*/
public startLoad() {
this.start();
}
/**
* Returns a percentage of the amount that has been loaded so far.
* @method getPercentLoaded
* @return {Number}
* @deprecated Use 'percentLoaded' instead. Deprecated as of 1.2.0
* @public
*/
public getPercentLoaded(): number {
return this.percentLoaded;
}
/**
* Returns a boolean indicating if everything in the loading que has been loaded or not.
* @method complete
* @return {boolean}
* @deprecated Use 'percentLoaded' instead. Deprecated as of 1.2.0
* @public
*/
public complete(): boolean {
return ( this.percentLoaded === 100 );
}
/**
* Quick way of getting / setting the private variable 'calculateBytes'
* To be made into a public variable once removed.
* @method calculateBytes
* @param [value] {boolean}
* @return {boolean}
* @public
*/
public calculateBytes(value?: boolean): boolean {
if (typeof value !== "undefined") {
this._calculateBytes = value;
}
return this._calculateBytes;
}
/**
* Returns the total number of bytes that have been loaded so far from files in the file queue.
*
* @method getBytesLoaded
* @return {Number}
* @readOnly
* @deprecated Use 'bytesLoaded' instead. Deprecated as of 1.2.0
* @public
*/
public getBytesLoaded(): number {
return this.bytesLoaded;
}
}
} | the_stack |
import validator from 'validator';
import parser from 'datemath-parser';
import parseDate from 'date-fns/parse';
import formatDate from 'date-fns/lightFormat';
import differenceInMilliseconds from 'date-fns/differenceInMilliseconds';
import differenceInSeconds from 'date-fns/differenceInSeconds';
import differenceInMinutes from 'date-fns/differenceInMinutes';
import differenceInHours from 'date-fns/differenceInHours';
import differenceInDays from 'date-fns/differenceInDays';
import differenceInCalendarDays from 'date-fns/differenceInCalendarDays';
import differenceInBusinessDays from 'date-fns/differenceInBusinessDays';
import differenceInWeeks from 'date-fns/differenceInWeeks';
import differenceInCalendarISOWeeks from 'date-fns/differenceInCalendarISOWeeks';
import differenceInCalendarISOWeekYears from 'date-fns/differenceInCalendarISOWeekYears';
import differenceInMonths from 'date-fns/differenceInMonths';
import differenceInCalendarMonths from 'date-fns/differenceInCalendarMonths';
import differenceInQuarters from 'date-fns/differenceInQuarters';
import differenceInCalendarQuarters from 'date-fns/differenceInCalendarQuarters';
import differenceInYears from 'date-fns/differenceInYears';
import differenceInCalendarYears from 'date-fns/differenceInCalendarYears';
import differenceInISOWeekYears from 'date-fns/differenceInISOWeekYears';
import intervalToDuration from 'date-fns/intervalToDuration';
import formatISODuration from 'date-fns/formatISODuration';
import _isFuture from 'date-fns/isFuture';
import _isPast from 'date-fns/isPast';
import _isLeapYear from 'date-fns/isLeapYear';
import _isToday from 'date-fns/isToday';
import _isTomorrow from 'date-fns/isTomorrow';
import _isYesterday from 'date-fns/isYesterday';
import add from 'date-fns/add';
import sub from 'date-fns/sub';
import _isBefore from 'date-fns/isBefore';
import _isAfter from 'date-fns/isAfter';
import {
DateFormat,
ISO8601DateSegment,
DateTuple,
DateInputTypes,
GetTimeBetweenArgs
} from '@terascope/types';
import tzOffset from 'date-fns-tz/getTimezoneOffset';
import { getTypeOf } from './deps';
import {
bigIntToJSON, isNumber, toInteger, isInteger, inNumberRange
} from './numbers';
import { isString } from './strings';
import { isBoolean } from './booleans';
// date-fns doesn't handle utc correctly here
// https://github.com/date-fns/date-fns/issues/376
// https://github.com/date-fns/date-fns/blob/d0efa9eae1cf05c0e27461296b537b9dd46283d4/src/format/index.js#L399-L403
export const timezoneOffset = new Date().getTimezoneOffset() * 60_000;
/**
* A helper function for making an ISODate string
*/
export function makeISODate(value?: Date|number|string|null|undefined|DateTuple): string {
if (value == null) return new Date().toISOString();
const date = getValidDate(value);
if (date === false) {
throw new Error(`Invalid date ${date}`);
}
return date.toISOString();
}
/** A simplified implementation of moment(new Date(val)).isValid() */
export function isValidDate(val: unknown): boolean {
return getValidDate(val as any) !== false;
}
/**
* Coerces value into a valid date, returns false if it is invalid
*/
export function getValidDate(val: unknown): Date | false {
// this is our hot path since this is how commonly store this
if (typeof val === 'number') {
if (!Number.isInteger(val)) return false;
return new Date(val);
}
if (val == null || isBoolean(val)) return false;
if (val instanceof Date) {
if (!isValidDateInstance(val)) {
return false;
}
return val;
}
if (typeof val === 'bigint') {
// eslint-disable-next-line no-param-reassign
val = bigIntToJSON(val);
if (typeof val === 'string') return false;
}
if (isDateTuple(val)) return new Date(val[0]);
const d = new Date(val as string);
if (isValidDateInstance(d)) return d;
return false;
}
/**
* Returns a valid date or throws, {@see getValidDate}
*/
export function getValidDateOrThrow(val: unknown): Date {
const date = getValidDate(val as any);
if (date === false) {
throw new TypeError(`Expected ${val} (${getTypeOf(val)}) to be in a standard date format`);
}
return date;
}
/**
* @returns date object from date tuple
*/
function _dateTupleToDateObject(val: DateTuple): Date {
return new Date(val[0] - (val[1] * 60_000));
}
/**
* Returns a valid date with the timezone applied or throws{@see getValidDate}
*/
export function getValidDateWithTimezoneOrThrow(val: unknown): Date {
if (isDateTuple(val)) {
return _dateTupleToDateObject(val);
}
return getValidDateOrThrow(val);
}
/**
* Returns a valid date with the timezone applied {@see getValidDate}
*/
export function getValidDateWithTimezone(val: unknown): Date | false {
if (isDateTuple(val)) {
return _dateTupleToDateObject(val);
}
return getValidDate(val);
}
/**
* Returns a valid date or throws, {@see getValidDate}
*/
export function getValidDateOrNumberOrThrow(val: unknown): Date|number {
if (typeof val === 'number' && !Number.isInteger(val)) return val;
if (isDateTuple(val)) return val[0];
const date = getValidDate(val as any);
if (date === false) {
throw new TypeError(`Expected ${val} (${getTypeOf(val)}) to be in a standard date format`);
}
return date;
}
export function isValidDateInstance(val: unknown): val is Date {
// this has to use isNaN not Number.isNaN
return val instanceof Date && !isNaN(val as any);
}
/** Ensure unix time */
export function getTime(val?: DateInputTypes): number | false {
if (val == null) return Date.now();
const result = getValidDate(val);
if (result === false) return false;
return result.getTime();
}
export function getUnixTime(val?: DateInputTypes): number | false {
const time = getTime(val);
if (time !== false) return Math.floor(time / 1000);
return time;
}
/**
* Checks to see if an input is a unix time
*/
export function isUnixTime(input: unknown, allowBefore1970 = true): input is number {
const value = toInteger(input);
if (value === false) return false;
if (allowBefore1970) return true;
return value >= 0;
}
/**
* A functional version of isUnixTime
*/
export function isUnixTimeFP(allowBefore1970?: boolean) {
return function _isUnixTime(input: unknown): input is number {
return isUnixTime(input, allowBefore1970);
};
}
/**
* Checks to see if an input is a ISO 8601 date
*/
export function isISO8601(input: unknown): input is string {
if (!isString(input)) return false;
return validator.isISO8601(input);
}
/**
* Convert a value to an ISO 8601 date string.
* This should be used over makeISODate
*/
export function toISO8601(value: unknown): string {
if (isNumber(value)) {
return new Date(value).toISOString();
}
if (isDateTuple(value)) {
// this is utc so just fall back to
// to the correct timezone
if (value[1] === 0) {
return new Date(value[0]).toISOString();
}
return new Date(value[0]).toISOString().replace('Z', _genISOTimezone(value[1]));
}
return makeISODate(value as any);
}
/**
* Generate the ISO8601
*/
function _genISOTimezone(offset: number): string {
const absOffset = Math.abs(offset);
const hours = Math.floor(absOffset / 60);
const minutes = absOffset - (hours * 60);
const sign = offset < 0 ? '-' : '+';
return `${sign}${_padNum(hours)}:${_padNum(minutes)}`;
}
/**
* a simple version of pad that only deals with simple cases
*/
function _padNum(input: number): string {
return input < 10 ? `0${input}` : `${input}`;
}
/**
* Set the timezone offset of a date, returns a date tuple
*/
export function setTimezone(input: unknown, timezone: string|number): DateTuple {
const validTZ: number = isNumber(timezone) ? timezone : timezoneToOffset(timezone);
return _makeDateTuple(input, validTZ);
}
/**
* A curried version of setTimezone
*/
export function setTimezoneFP(timezone: string|number): (input: unknown) => DateTuple {
const validTZ: number = isNumber(timezone) ? timezone : timezoneToOffset(timezone);
return function _setTimezone(input: unknown): DateTuple {
return _makeDateTuple(input, validTZ);
};
}
function _makeDateTuple(input: unknown, offset: number): DateTuple {
if (isNumber(input)) return [input, offset];
if (isDateTuple(input)) return [input[0], offset];
const date = getValidDateOrThrow(input);
return [date.getTime(), offset];
}
/**
* Verify if an input is a Date Tuple
*/
export function isDateTuple(input: unknown): input is DateTuple {
return Array.isArray(input)
&& input.length === 2
&& Number.isInteger(input[0])
&& Number.isInteger(input[1])
// the timezone has to be within 24hours
// in minutes
&& input[1] <= 1440
&& input[1] >= -1440;
}
/**
* Returns a function to trim the ISO 8601 date segment
* useful for creating yearly, monthly, daily or hourly dates
*/
export function trimISODateSegment(segment: ISO8601DateSegment): (input: unknown) => number {
return function _trimISODate(input) {
const date = getValidDateWithTimezoneOrThrow(input);
if (segment === ISO8601DateSegment.hourly) {
return new Date(
date.getUTCFullYear(),
date.getUTCMonth(),
date.getUTCDate(),
date.getUTCHours(),
0,
0,
0
).getTime() - timezoneOffset;
}
if (segment === ISO8601DateSegment.daily) {
return new Date(
date.getUTCFullYear(),
date.getUTCMonth(),
date.getUTCDate(),
0,
0,
0,
0
).getTime() - timezoneOffset;
}
if (segment === ISO8601DateSegment.monthly) {
return new Date(
date.getUTCFullYear(),
date.getUTCMonth(),
1,
0,
0,
0,
0
).getTime() - timezoneOffset;
}
if (segment === ISO8601DateSegment.yearly) {
return new Date(
date.getUTCFullYear(),
0,
1,
0,
0,
0,
0
).getTime() - timezoneOffset;
}
throw new Error(`Invalid segment "${segment}" given`);
};
}
/**
* track a timeout to see if it expires
* @returns a function that will returns false if the time elapsed
*/
export function trackTimeout(timeoutMs: number): () => number | false {
const startTime = Date.now();
return (): false | number => {
const elapsed = Date.now() - startTime;
if (timeoutMs > -1 && elapsed > timeoutMs) {
return elapsed;
}
return false;
};
}
/** converts smaller than a week milliseconds to human readable time */
export function toHumanTime(ms: number): string {
const ONE_SEC = 1000;
const ONE_MIN = ONE_SEC * 60;
const ONE_HOUR = ONE_MIN * 60;
const ONE_DAY = ONE_HOUR * 24;
const minOver = 1.5;
if (ms > ONE_DAY * minOver && ms < ONE_DAY * 7) {
return `${Math.round((ms * 100) / ONE_DAY) / 100}day`;
}
if (ms > ONE_HOUR * minOver) return `${Math.round((ms * 100) / ONE_HOUR) / 100}hr`;
if (ms > ONE_MIN * minOver) return `${Math.round((ms * 100) / ONE_MIN) / 100}min`;
if (ms > ONE_SEC * minOver) {
return `${Math.round((ms * 100) / ONE_SEC) / 100}sec`;
}
if (ms < ONE_SEC * minOver) {
return `${Math.round(ms)}ms`;
}
return `${Math.round((ms * 100) / ONE_DAY) / 100}day`;
}
export function parseCustomDateFormat(
value: unknown,
format: string,
referenceDate: Date
): number {
if (typeof value !== 'string') {
throw new Error(`Expected string for formatted date fields, got ${value}`);
}
const date = parseDate(value, format, referenceDate);
if (!isValidDateInstance(date)) {
throw new Error(`Expected value ${value} to be a date string with format ${format}`);
}
// need subtract the date offset here to
// in order to deal with UTC time
return date.getTime() - (date.getTimezoneOffset() * 60_000);
}
/**
* Parse a date value (that has already been validated)
* and return the epoch millis time.
*/
export function parseDateValue(
value: unknown,
format: DateFormat|string|undefined,
referenceDate: Date
): number {
if (format === DateFormat.epoch || format === DateFormat.seconds) {
const int = toInteger(value);
if (int === false) {
throw new Error(`Expected value ${value} to be a valid time`);
}
return Math.floor(int * 1000);
}
if (format && !(format in DateFormat)) {
return parseCustomDateFormat(value, format, referenceDate);
}
const result = getTime(value as any);
if (result === false) {
throw new Error(`Expected value ${value} to be a valid date`);
}
return result;
}
/**
* Format the parsed date value
*/
export function formatDateValue(
value: Date|number|DateTuple,
format: DateFormat|string|undefined,
): string|number {
const inMs = _toMilliseconds(value);
if (format === DateFormat.epoch_millis || format === DateFormat.milliseconds) {
return inMs;
}
if (format === DateFormat.epoch || format === DateFormat.seconds) {
return Math.floor(inMs / 1000);
}
if (format && !(format in DateFormat)) {
// need add our offset here to
// deal with UTC time
return formatDate(inMs + timezoneOffset, format);
}
return toISO8601(value);
}
function _toMilliseconds(value: Date | number | DateTuple): number {
if (isDateTuple(value)) return value[0];
return value instanceof Date ? value.getTime() : value;
}
export const getDurationFunc = {
milliseconds: differenceInMilliseconds,
seconds: differenceInSeconds,
minutes: differenceInMinutes,
hours: differenceInHours,
days: differenceInDays,
calendarDays: differenceInCalendarDays,
businessDays: differenceInBusinessDays,
weeks: differenceInWeeks,
calendarWeeks: differenceInCalendarISOWeeks,
months: differenceInMonths,
calendarMonths: differenceInCalendarMonths,
quarters: differenceInQuarters,
calendarQuarters: differenceInCalendarQuarters,
years: differenceInYears,
calendarYears: differenceInCalendarYears,
calendarISOWeekYears: differenceInCalendarISOWeekYears,
ISOWeekYears: differenceInISOWeekYears
};
export function getTimeBetween(
input: unknown,
args: GetTimeBetweenArgs
): string | number {
const { interval } = args;
const [time1, time2] = _getStartEndTime(input, args);
const date1 = getValidDateWithTimezoneOrThrow(time1);
const date2 = getValidDateWithTimezoneOrThrow(time2);
if (interval === 'ISO8601') {
return formatISODuration(intervalToDuration({
start: date1,
end: date2
}));
}
return getDurationFunc[interval](date2, date1);
}
function _getStartEndTime(
input: unknown, args: GetTimeBetweenArgs
): [DateInputTypes, DateInputTypes] {
const { start, end } = args;
if (start == null && end == null) {
throw Error('Must provide a start or an end argument');
}
if (start) return [start, input as DateInputTypes];
return [input as DateInputTypes, end as DateInputTypes];
}
/**
* A functional version of getTimeBetween
*/
export function getTimeBetweenFP(args: GetTimeBetweenArgs) {
return function _getTimeBetween(input: unknown): string | number {
return getTimeBetween(input, args);
};
}
export function isSunday(input: unknown): boolean {
const date = getValidDateWithTimezone(input as any);
if (!date) return false;
return date.getDay() === 0;
}
export function isMonday(input: unknown): boolean {
const date = getValidDateWithTimezone(input as any);
if (!date) return false;
return date.getDay() === 1;
}
export function isTuesday(input: unknown): boolean {
const date = getValidDateWithTimezone(input as any);
if (!date) return false;
return date.getDay() === 2;
}
export function isWednesday(input: unknown): boolean {
const date = getValidDateWithTimezone(input as any);
if (!date) return false;
return date.getDay() === 3;
}
export function isThursday(input: unknown): boolean {
const date = getValidDateWithTimezone(input as any);
if (!date) return false;
return date.getDay() === 4;
}
export function isFriday(input: unknown): boolean {
const date = getValidDateWithTimezone(input as any);
if (!date) return false;
return date.getDay() === 5;
}
export function isSaturday(input: unknown): boolean {
const date = getValidDateWithTimezone(input as any);
if (!date) return false;
return date.getDay() === 6;
}
export function isWeekday(input: unknown): boolean {
const date = getValidDateWithTimezone(input as any);
if (!date) return false;
const day = date.getDay();
return day >= 1 && day <= 5;
}
export function isWeekend(input: unknown): boolean {
const date = getValidDateWithTimezone(input as any);
if (!date) return false;
const day = date.getDay();
return day === 0 || day === 6;
}
export function isFuture(input: unknown): boolean {
const date = getValidDateWithTimezone(input as any);
if (!date) return false;
return _isFuture(date);
}
export function isPast(input: unknown): boolean {
const date = getValidDateWithTimezone(input as any);
if (!date) return false;
return _isPast(date);
}
export function isLeapYear(input: unknown): boolean {
const date = getValidDateWithTimezone(input as any);
if (!date) return false;
return _isLeapYear(date);
}
export function isTomorrow(input: unknown): boolean {
const date = getValidDateWithTimezone(input as any);
if (!date) return false;
return _isTomorrow(date);
}
export function isToday(input: unknown): boolean {
const date = getValidDateWithTimezone(input as any);
if (!date) return false;
return _isToday(date);
}
export function isYesterday(input: unknown): boolean {
const date = getValidDateWithTimezone(input as any);
if (!date) return false;
return _isYesterday(date);
}
export type AdjustDateArgs = {
readonly expr: string;
}|{
readonly years?: number;
readonly months?: number;
readonly weeks?: number;
readonly days?: number;
readonly hours?: number;
readonly minutes?: number;
readonly seconds?: number;
readonly milliseconds?: number;
}
export function addToDate(input: unknown, args: AdjustDateArgs): number {
const date = getValidDateWithTimezoneOrThrow(input);
if ('expr' in args) {
return parser.parse(`now+${args.expr}`, date);
}
return add(date, args).getTime();
}
export function addToDateFP(args: AdjustDateArgs): (input: unknown) => number {
return function _addToDateFP(input: unknown): number {
return addToDate(input, args);
};
}
export function subtractFromDate(input: unknown, args: AdjustDateArgs): number {
const date = getValidDateWithTimezoneOrThrow(input);
if ('expr' in args) {
return parser.parse(`now-${args.expr}`, date);
}
return sub(date, args).getTime();
}
export function subtractFromDateFP(args: AdjustDateArgs): (input: unknown) => number {
return function _subtractFromDateFP(input: unknown): number {
return subtractFromDate(input, args);
};
}
export function isBefore(input: unknown, date: DateInputTypes): boolean {
const date1 = getValidDateWithTimezone(input as Date);
const date2 = getValidDateWithTimezone(date);
if (date1 && date2) {
return _isBefore(date1, date2);
}
return false;
}
export function isAfter(input: unknown, date: DateInputTypes): boolean {
const date1 = getValidDateWithTimezone(input as Date);
const date2 = getValidDateWithTimezone(date);
if (date1 && date2) {
return _isAfter(date1, date2);
}
return false;
}
export function isBetween(input: unknown, args: {
start: DateInputTypes;
end: DateInputTypes;
}): boolean {
const { start, end } = args;
const inputDate = getValidDateWithTimezone(input);
const date1 = getValidDateWithTimezone(start);
const date2 = getValidDateWithTimezone(end);
if (inputDate && date1 && date2) {
return _isAfter(inputDate, date1) && _isBefore(inputDate, date2);
}
return false;
}
/** Given a timezone, it will return the minutes of its offset from UTC time */
export function timezoneToOffset(timezone: unknown): number {
if (!isString(timezone)) {
throw new Error(`Invalid argument timezone, it must be a string, got ${getTypeOf(timezone)}`);
}
return Math.round(tzOffset(timezone) / (1000 * 60));
}
/** Given a date and timezone, it will return the offset from UTC in minutes.
* This is more accurate than timezoneToOffset as it can better account for day lights saving time
* */
export function getTimezoneOffset(input: unknown, timezone: string): number {
const date = getValidDateOrThrow(input);
if (!isString(timezone)) {
throw new Error(`Invalid argument timezone, it must be a string, got ${getTypeOf(timezone)}`);
}
return Math.round(tzOffset(timezone, date) / (1000 * 60));
}
/** Given a timezone, it will return a function that will take in dates that will
* be converted the offset in minutes. This is more accurate than timezoneToOffset
* as it can better account for day lights saving time
* */
export function getTimezoneOffsetFP(timezone: string): (input: unknown) => number {
if (!isString(timezone)) {
throw new Error(`Invalid argument timezone, it must be a string, got ${getTypeOf(timezone)}`);
}
return function _getTimezoneOffsetFP(input: unknown) {
const date = getValidDateOrThrow(input);
return Math.round(tzOffset(timezone, date) / (1000 * 60));
};
}
export function setMilliseconds(ms: number): (input: unknown) => number {
if (!isInteger(ms) || !inNumberRange(ms, { min: 0, max: 999, inclusive: true })) {
throw Error(`milliseconds value must be an integer between 0 and 999, received ${ms}`);
}
return function _setMilliseconds(input) {
const inputDate = getValidDateOrThrow(input as any);
return inputDate.setUTCMilliseconds(ms);
};
}
export function setSeconds(seconds: number): (input: unknown) => number {
if (!isInteger(seconds) || !inNumberRange(seconds, { min: 0, max: 59, inclusive: true })) {
throw Error(`seconds value must be an integer between 0 and 59, received ${seconds}`);
}
return function _setSeconds(input: unknown) {
const inputDate = getValidDateOrThrow(input as any);
return inputDate.setUTCSeconds(seconds);
};
}
export function setMinutes(minutes: number): (input: unknown) => number {
if (!isInteger(minutes) || !inNumberRange(minutes, { min: 0, max: 59, inclusive: true })) {
throw Error(`minutes value must be an integer between 0 and 59, received ${minutes}`);
}
return function _setMinutes(input: unknown) {
const inputDate = getValidDateWithTimezoneOrThrow(input as any);
return inputDate.setUTCMinutes(minutes);
};
}
export function setHours(hours: number):(input: unknown) => number {
if (!isInteger(hours) || !inNumberRange(hours, { min: 0, max: 23, inclusive: true })) {
throw Error(`hours value must be an integer between 0 and 23, received ${hours}`);
}
return function _setHours(input: unknown) {
const inputDate = getValidDateWithTimezoneOrThrow(input as any);
return inputDate.setUTCHours(hours);
};
}
export function setDate(date: number): (input: unknown) => number {
if (!isInteger(date) || !inNumberRange(date, { min: 1, max: 31, inclusive: true })) {
throw Error(`date value must be an integer between 1 and 31, received ${date}`);
}
return function _setDate(input: unknown) {
const inputDate = getValidDateWithTimezoneOrThrow(input as any);
return inputDate.setUTCDate(date);
};
}
export function setMonth(month: number): (input: unknown) => number {
if (!isInteger(month) || !inNumberRange(month, { min: 1, max: 12, inclusive: true })) {
throw Error(`month value must be an integer between 1 and 12, received ${month}`);
}
return function _setMonth(input: unknown) {
const inputDate = getValidDateWithTimezoneOrThrow(input as any);
return inputDate.setUTCMonth(month - 1);
};
}
export function setYear(year: number): (input: unknown) => number {
if (!isInteger(year)) {
throw Error(`year value must be an integer, received ${year}`);
}
return function _setYear(input: unknown) {
const inputDate = getValidDateWithTimezoneOrThrow(input as any);
return inputDate.setUTCFullYear(year);
};
}
export function getMilliseconds(input: unknown): number {
return getValidDateOrThrow(input as any).getUTCMilliseconds();
}
export function getSeconds(input: unknown): number {
return getValidDateOrThrow(input as any).getUTCSeconds();
}
export function getMinutes(input: unknown): number {
return getValidDateWithTimezoneOrThrow(input).getUTCMinutes();
}
export function getHours(input: unknown): number {
return getValidDateWithTimezoneOrThrow(input).getUTCHours();
}
export function getDate(input: unknown): number {
return getValidDateWithTimezoneOrThrow(input).getUTCDate();
}
export function getMonth(input: unknown): number {
return getValidDateWithTimezoneOrThrow(input).getUTCMonth() + 1;
}
export function getYear(input: unknown): number {
return getValidDateWithTimezoneOrThrow(input).getUTCFullYear();
}
/** Will convert a date to its epoch millisecond format or throw if invalid */
export function toEpochMSOrThrow(input: unknown): DateTuple|number {
if (isDateTuple(input)) return input;
const epochMillis = getTime(input as any);
if (epochMillis === false) {
throw new TypeError(`Expected ${input} (${getTypeOf(input)}) to be a standard date value`);
}
return epochMillis;
} | the_stack |
import chai, { expect } from 'chai'
import { solidity } from 'ethereum-waffle'
import { BigNumber, Signer } from 'ethers'
import hre from 'hardhat'
import { getMarkets, isEtheremNetwork } from '../../config'
import { getPlatformSetting, updatePlatformSetting } from '../../tasks'
import { Market } from '../../types/custom/config-types'
import {
ITellerDiamond,
MainnetNFTFacet,
TellerNFT,
TellerNFTV2,
} from '../../types/typechain'
import { LoanStatus } from '../../utils/consts'
import { fundedMarket } from '../fixtures'
import { getFunds } from '../helpers/get-funds'
import {
LoanHelpersReturn,
LoanType,
takeOutLoanWithNfts,
takeOutLoanWithoutNfts,
} from '../helpers/loans'
chai.should()
chai.use(solidity)
const { getNamedSigner, contracts, tokens, ethers, evm, toBN } = hre
describe('Loans', () => {
getMarkets(hre.network).forEach(testLoans)
function testLoans(market: Market): void {
let deployer: Signer
let diamond: ITellerDiamond & MainnetNFTFacet
// let borrower: Signer
before(async () => {
await fundedMarket(hre, {
assetSym: market.lendingToken,
amount: 100000,
keepExistingDeployments: true,
extendMaxTVL: true,
})
deployer = await getNamedSigner('deployer')
diamond = await contracts.get('TellerDiamond')
})
// tests for merged loan functions
describe('merge create loan', () => {
let helpers: any = null
before(async () => {
// update percentage submission percentage value to 0 for this test
const percentageSubmission = {
name: 'RequiredSubmissionsPercentage',
value: 0,
}
await updatePlatformSetting(percentageSubmission, hre)
// Advance time
const { value: rateLimit } = await getPlatformSetting(
'RequestLoanTermsRateLimit',
hre
)
await evm.advanceTime(rateLimit)
})
describe('without NFT', () => {
it('should create a loan', async () => {
// get helpers variables after function returns our transaction and
// helper variables
const { getHelpers } = await takeOutLoanWithoutNfts(hre, {
lendToken: market.lendingToken,
collToken: market.collateralTokens[0],
loanType: LoanType.UNDER_COLLATERALIZED,
})
helpers = await getHelpers()
// borrower data from our helpers
// borrower = helpers.details.borrower.signer
// check if loan exists
expect(helpers.details.loan).to.exist
})
it('should have collateral deposited', async () => {
// get collateral
const { collateral } = helpers
const amount = await collateral.current()
// check if collateral is > 0
amount.gt(0).should.eq(true, 'Loan must have collateral')
})
it('should be taken out', () => {
// get loanStatus from helpers and check if it's equal to 2, which means
// it's active and taken out
const loanStatus = helpers.details.loan.status
expect(loanStatus).to.equal(2)
})
it('should not be able to take out a loan when loan facet is paused', async () => {
const LOANS_ID = hre.ethers.utils.id('LOANS')
// Pause lending
await diamond
.connect(deployer)
.pause(LOANS_ID, true)
.should.emit(diamond, 'Paused')
.withArgs(LOANS_ID, await deployer.getAddress())
// trying to run the function will revert with the same error message
// written in our PausableMods file
const { tx } = await takeOutLoanWithoutNfts(hre, {
lendToken: market.lendingToken,
collToken: market.collateralTokens[0],
loanType: LoanType.UNDER_COLLATERALIZED,
})
await tx.should.be.revertedWith('Pausable: paused')
// Unpause lending
await diamond
.connect(deployer)
.pause(LOANS_ID, false)
.should.emit(diamond, 'UnPaused')
.withArgs(LOANS_ID, await deployer.getAddress())
})
// it('should not be able to take out a loan without enough collateral', async () => {
// const { tx } = await takeOutLoanWithoutNfts({
// lendToken: market.lendingToken,
// collToken: market.collateralTokens[0],
// loanType: LoanType.OVER_COLLATERALIZED,
// collAmount: 1
// })
// // Try to take out loan which should fail
// await tx.should.be.revertedWith('Teller: more collateral required')
// })
})
describe('with NFT', () => {
let tellerNFT: TellerNFT
let tellerNFTV2: TellerNFTV2
beforeEach(async () => {
await hre.deployments.fixture('protocol', {
keepExistingDeployments: true,
})
// Advance time
const { value: rateLimit } = await getPlatformSetting(
'RequestLoanTermsRateLimit',
hre
)
await evm.advanceTime(rateLimit)
tellerNFTV2 = await contracts.get('TellerNFT_V2')
})
if (isEtheremNetwork(hre.network)) {
describe('V1', () => {
let helpers: LoanHelpersReturn
it('creates a loan', async () => {
const borrower = await getNamedSigner('borrower')
const { nfts, getHelpers } = await takeOutLoanWithNfts(hre, {
amount: 100,
lendToken: market.lendingToken,
borrower,
version: 1,
})
helpers = await getHelpers()
helpers.details.loan.should.exist
helpers.details.loan.status.should.equal(
LoanStatus.Active,
'Loan is not active'
)
const loanNFTs = await diamond.getLoanNFTs(
helpers.details.loan.id
)
loanNFTs.should.eql(nfts.v1, 'Staked NFTs do not match')
})
it('should be able to create and repay a loan', async () => {
const borrower = await getNamedSigner('borrower')
const { getHelpers } = await takeOutLoanWithNfts(hre, {
amount: 100,
lendToken: market.lendingToken,
borrower: borrower,
version: 1,
})
const helpers: LoanHelpersReturn = await getHelpers()
expect(helpers.details.loan).to.exist
const loanId = helpers.details.loan.id
const lendingToken = helpers.details.lendingToken
const lendingTokenDecimals = await lendingToken.decimals()
//add lending token funds to the borrower
await getFunds({
to: borrower,
tokenSym: market.lendingToken,
amount: hre.toBN(200, lendingTokenDecimals),
hre,
})
const borrowerAddress = await borrower.getAddress()
const borrowerBalance = await lendingToken.balanceOf(
borrowerAddress
)
const balanceLeftToRepay = await diamond.getTotalOwed(loanId)
await lendingToken
.connect(borrower)
.approve(diamond.address, balanceLeftToRepay)
await diamond
.connect(borrower)
.repayLoan(loanId, hre.toBN(100, lendingTokenDecimals))
const totalOwedAfterRepay = await diamond.getTotalOwed(loanId)
const loanData = await diamond.getLoan(loanId)
borrowerBalance.should.eql(hre.toBN(200, lendingTokenDecimals))
totalOwedAfterRepay.should.eql(0)
expect(loanData.status).to.equal(LoanStatus.Closed)
})
it('should be able to create and liquidate a loan', async () => {
tellerNFT = await contracts.get('TellerNFT')
const borrower = await getNamedSigner('borrower')
const liquidator = await getNamedSigner('liquidator')
const borrowerAddress = await borrower.getAddress()
const { getHelpers } = await takeOutLoanWithNfts(hre, {
amount: 100,
lendToken: market.lendingToken,
borrower: borrower,
version: 1,
})
const helpers: LoanHelpersReturn = await getHelpers()
expect(helpers.details.loan).to.exist
const lendingToken = helpers.details.lendingToken
const lendingTokenDecimals = await lendingToken.decimals()
const loanId = helpers.details.loan.id
await getFunds({
to: borrower,
tokenSym: market.lendingToken,
amount: hre.toBN(200, lendingTokenDecimals),
hre,
})
await getFunds({
to: liquidator,
tokenSym: market.lendingToken,
amount: hre.toBN(200, lendingTokenDecimals),
hre,
})
const borrowerBalance = await lendingToken.balanceOf(
borrowerAddress
)
const balanceLeftToRepay = await diamond.getTotalOwed(loanId)
await lendingToken
.connect(borrower)
.approve(diamond.address, balanceLeftToRepay)
const loanNFTsBeforeLiquidate = await diamond.getLoanNFTs(loanId)
expect(loanNFTsBeforeLiquidate.length).to.equal(3)
const nftBalancesBeforeLiquidation = await tellerNFT.balanceOf(
diamond.address
)
const liquidationController =
await diamond.getNFTLiquidationController()
//make the loan expire
await evm.advanceTime(helpers.details.loan.duration)
await lendingToken
.connect(liquidator)
.approve(diamond.address, balanceLeftToRepay)
await diamond.connect(liquidator).liquidateLoan(loanId)
const liqControllerOwnedTokens = await tellerNFT.getOwnedTokens(
liquidationController
)
const nftBalancesAfterLiquidation = await tellerNFT.balanceOf(
diamond.address
)
//the diamond should own fewer NFTs since they were swept away
nftBalancesAfterLiquidation.should.eql(
nftBalancesBeforeLiquidation.sub(loanNFTsBeforeLiquidate.length)
)
const liqControllerOwnedTokenIds = liqControllerOwnedTokens.map(
(n) => n.toString()
)
//the liquidation controller should now own the NFTs used for the loan
for (const tokenId of loanNFTsBeforeLiquidate) {
liqControllerOwnedTokenIds.should.contain(tokenId.toString())
}
const totalOwedAfterRepay = await diamond.getTotalOwed(loanId)
const loanData = await diamond.getLoan(loanId)
totalOwedAfterRepay.should.eql(0)
expect(loanData.status).to.equal(LoanStatus.Liquidated)
})
})
}
describe('V2', () => {
let helpers: LoanHelpersReturn
it('creates a loan', async () => {
const borrower = await getNamedSigner('borrower')
const { nfts, getHelpers } = await takeOutLoanWithNfts(hre, {
amount: 100,
lendToken: market.lendingToken,
borrower,
version: 2,
})
helpers = await getHelpers()
helpers.details.loan.should.exist
const loanStatus = helpers.details.loan.status
loanStatus.should.equal(LoanStatus.Active, 'Loan is not active')
const loanNFTsV2 = await diamond.getLoanNFTsV2(
helpers.details.loan.id
)
loanNFTsV2.loanNFTs_.should.eql(
nfts.v2.ids,
'Staked NFT IDs do not match'
)
loanNFTsV2.amounts_.should.eql(
nfts.v2.balances,
'Staked NFT balances do not match'
)
})
it('should be able to create and liquidate a loan', async () => {
const borrower = await getNamedSigner('borrower')
const liquidator = await getNamedSigner('liquidator')
const borrowerAddress = await borrower.getAddress()
const { getHelpers } = await takeOutLoanWithNfts(hre, {
amount: 100,
lendToken: market.lendingToken,
borrower: borrower,
version: 2,
})
const helpers: LoanHelpersReturn = await getHelpers()
expect(helpers.details.loan).to.exist
const lendingToken = helpers.details.lendingToken
const lendingTokenDecimals = await lendingToken.decimals()
const loanId = helpers.details.loan.id
await getFunds({
to: borrower,
tokenSym: market.lendingToken,
amount: hre.toBN(200, lendingTokenDecimals),
hre,
})
await getFunds({
to: liquidator,
tokenSym: market.lendingToken,
amount: hre.toBN(200, lendingTokenDecimals),
hre,
})
const borrowerBalance = await lendingToken.balanceOf(
borrowerAddress
)
const balanceLeftToRepay = await diamond.getTotalOwed(loanId)
await lendingToken
.connect(borrower)
.approve(diamond.address, balanceLeftToRepay)
const loanNFTsBeforeLiquidate = await diamond.getLoanNFTsV2(loanId)
expect(loanNFTsBeforeLiquidate.loanNFTs_.length).to.equal(3)
const diamondOwnerArray = loanNFTsBeforeLiquidate.loanNFTs_.map(
() => diamond.address
)
const nftBalancesBeforeLiquidation =
await tellerNFTV2.balanceOfBatch(
diamondOwnerArray,
loanNFTsBeforeLiquidate.loanNFTs_
)
const liquidationController =
await diamond.getNFTLiquidationController()
//make the loan expire
await evm.advanceTime(helpers.details.loan.duration)
await lendingToken
.connect(liquidator)
.approve(diamond.address, balanceLeftToRepay)
await diamond.connect(liquidator).liquidateLoan(loanId)
const liqControllerOwnedTokens = await tellerNFTV2.getOwnedTokens(
liquidationController
)
liqControllerOwnedTokens.should.eql(
loanNFTsBeforeLiquidate.loanNFTs_
)
const liquidatorOwnerArray = loanNFTsBeforeLiquidate.loanNFTs_.map(
() => liquidationController
)
const loanNFTsAfterLiquidate = await diamond.getLoanNFTsV2(loanId)
const nftBalancesAfterLiquidation =
await tellerNFTV2.balanceOfBatch(
liquidatorOwnerArray,
loanNFTsAfterLiquidate.loanNFTs_
)
expect(nftBalancesAfterLiquidation).to.eql(
loanNFTsBeforeLiquidate.amounts_
)
const nftBalancesInDiamondAfterLiquidation =
await tellerNFTV2.balanceOfBatch(
diamondOwnerArray,
loanNFTsAfterLiquidate.loanNFTs_
)
const emptyAmounts = nftBalancesAfterLiquidation.map(() =>
BigNumber.from(0x0)
)
expect(nftBalancesInDiamondAfterLiquidation).to.eql(emptyAmounts)
const totalOwedAfterRepay = await diamond.getTotalOwed(loanId)
const loanData = await diamond.getLoan(loanId)
totalOwedAfterRepay.should.eql(0)
expect(loanData.status).to.equal(LoanStatus.Liquidated)
})
})
})
})
}
}) | the_stack |
import * as Utils from "./Utils/Utils-Index";
/** The result of a readVarIntNN() method. */
export type varIntResult =
{
/** The number of bytes read. */
length: number,
/** The value of the integer. */
value: number
};
/** Converts a 32-bit integer into a 4-byte array (little-endian format). */
export function writeInt32Fixed(value: number): Uint8Array
{
let bytes: Uint8Array = new Uint8Array(4);
checkValueToEncode(value, 32);
// Encode as little-endian
// Note: This is ~25% faster than "Buffer.alloc(4).writeInt32LE(value)"
bytes[0] = value & 0xff;
bytes[1] = (value >> 8) & 0xff;
bytes[2] = (value >> 16) & 0xff;
bytes[3] = (value >> 24);
return (bytes);
}
/** Reads a 32-bit integer from 4 bytes (little-endian format) of the specified byte array. */
export function readInt32Fixed(bytes: Uint8Array | Buffer, startIndex: number = 0): number
{
let result: number = 0;
if (bytes.length - startIndex < 4)
{
throw new Error(`The value to decode (${bytes.length} bytes) at startIndex ${startIndex} is invalid: it must contain at least 4 bytes`);
}
// Decode as little-endian
// Note: This is ~13x faster than doing "new DataView(bytes.buffer).getInt32(0, true)" which, in turn, is faster than "Buffer.from(bytes).readInt32LE(0)"
result |= bytes[startIndex];
result |= bytes[startIndex + 1] << 8;
result |= bytes[startIndex + 2] << 16;
result |= bytes[startIndex + 3] << 24;
return (result);
}
const MIN_64_BIT_VALUE: bigint = -BigInt(Math.pow(2, 63));
const MAX_64_BIT_VALUE: bigint = BigInt(Math.pow(2, 63)) - BigInt(1);
/**
* Converts a 64-bit integer (bigint) into a 8-byte array (little-endian format).\
* Note: This method is at least 25x slower than writeInt32Fixed().
*/
export function writeInt64Fixed(value: bigint): Uint8Array
{
if ((value < MIN_64_BIT_VALUE) || (value > MAX_64_BIT_VALUE))
{
throw new Error(`The supplied value (${value}) is larger than 64-bits`);
}
let bytes: Buffer = Buffer.alloc(8);
bytes.writeBigInt64LE(value);
return (bytes);
}
/**
* Reads a 64-bit integer from 8 bytes (little-endian format) of the specified byte array.\
* Note: This method is at least 25x slower than readInt32Fixed().
*/
export function readInt64Fixed(bytes: Uint8Array | Buffer, startIndex: number = 0): bigint
{
let result: bigint;
if (bytes.length - startIndex < 8)
{
throw new Error(`The value to decode (${bytes.length} bytes) at startIndex ${startIndex} is invalid: it must contain at least 8 bytes`);
}
if (bytes instanceof Buffer)
{
// This is about 40% faster than the 'else' technique, and avoids the creation of both a new Uint8Array and Buffer
result = (bytes as Buffer).readBigInt64LE(startIndex);
}
else
{
let buffer: Buffer = Buffer.from(bytes.slice(startIndex, startIndex + 8)); // TODO: Would using bytes.subarray() be faster?
result = buffer.readBigInt64LE(0);
}
return (result);
}
/** Converts a number into an 8-byte array (little-endian format). This can only handle signed integers up to 54-bits. */
export function writeInt64FixedNumber(value: number): Uint8Array
{
checkValueToEncode(value, 54);
return (writeInt64Fixed(BigInt(value)));
}
/** Reads a [integer] number from 8 bytes (little-endian format) of the specified byte array. This can only handle signed integers up to 54-bits. */
export function readInt64FixedNumber(bytes: Uint8Array, startIndex: number = 0): number
{
let value: bigint = readInt64Fixed(bytes, startIndex);
let minInt: bigint = BigInt(Number.MIN_SAFE_INTEGER); // Same as -BigInt(Math.pow(2, 53)) + BigInt(1)
let maxInt: bigint = BigInt(Number.MAX_SAFE_INTEGER); // Same as BigInt(Math.pow(2, 53)) - BigInt(1)
if ((value < minInt) || (value > maxInt))
{
throw new Error(`The value to decode (${value}) exceeds the range of a 54-bit signed integer (${minInt} to ${maxInt})`);
}
else
{
return (Number(value));
}
}
const _2Powers: number[] =
[
1,
Math.pow(2, 8 * 1), // 256
Math.pow(2, 8 * 2), // 65536
Math.pow(2, 8 * 3), // 16777216
Math.pow(2, 8 * 4), // 4294967296
Math.pow(2, 8 * 5), // 1099511627776
Math.pow(2, 8 * 6), // 281474976710656
0 // Unusable: Number.MAX_SAFE_INTEGER is 9007199254740991
];
/**
* Converts a [integer] number into an 8-byte array (little-endian format).
* Note: This can only handle signed integers up to 52-bits. This method is also about 150x slower than writeInt32Fixed(), especially for negative values.
* Note: This method does not use the Buffer class.
*/
export function writeInt64FixedNumber_NoBuffer(value: number): Uint8Array
{
let bytes = new Uint8Array(8);
let remainingValue: number = value;
checkValueToEncode(value, 52);
// Encode as little-endian without using roll left/right or other bitwise operators (because these operators automatically cast operands to signed 32-bit values)
if (value < 0)
{
// "Slow" encoding for negative values [due to lack of native support for Int64 in JavaScript]
// Note: 'Slow' means ~50x slower than encoding positive values
let binary: string = value.toString(2).substr(1); // Convert to a binary string and remove the leading "-" sign
// Create 2's-complement (flip bits and add 1)
// Note: We prefix the flipped result with "1" to preserve the leading zeros, ie. the bit count (eg. -1052818365); otherwise when we left-pad with 1's later on we'll add too many
// Note: Use the Windows 10 calculator in 'Programmer' mode to show the ground truth for a negative number's binary QWORD representation (in 2's-complement)
let flipped: string = "1" + binary.split("").map(c => c === "0" ? "1" : "0").join("");
let twosComplement: number = Number.parseInt(flipped, 2) + 1;
let tcBinary: string = twosComplement.toString(2);
if (tcBinary.length < 64)
{
tcBinary = "1".repeat(64 - tcBinary.length) + tcBinary;
}
for (let pos = tcBinary.length - 8, i = 0; pos >= 0; pos -= 8, i++)
{
let byte: number = parseInt(tcBinary.substr(pos, 8), 2);
bytes[i] = byte;
}
}
else
{
// "Fast" encoding for positive values [because we don't have to deal with 2's-complement encoding as we do for negative values]
bytes[7] = 0; // Unusable: Number.MAX_SAFE_INTEGER is 9007199254740991
for (let i = 6; i >= 0; i--)
{
bytes[i] = remainingValue / _2Powers[i];
remainingValue = remainingValue % _2Powers[i];
}
}
return (bytes);
}
/**
* Reads a [integer] number from 8 bytes (little-endian format) of the specified byte array.
* Note: This can only handle signed integers up to 52-bits. This method is also about 150x slower than readInt32Fixed(), especially for negative values.
* Note: This method does not use the Buffer class.
*/
export function readInt64FixedNumber_NoBuffer(bytes: Uint8Array): number
{
if (bytes.length !== 8)
{
throw new Error(`The value to decode (${bytes}) is invalid: it must contain exactly 8 bytes`);
}
let result: number = 0;
let isNegativeValue: boolean = (bytes[7] & 128) === 128;
// Decode as little-endian without using roll left/right or other bitwise operators (because these operators automatically cast operands to signed 32-bit values)
if (isNegativeValue)
{
// "Slow" decoding for negative values [due to lack of native support for Int64 in JavaScript]
// Note: 'Slow' means ~50x slower than decoding positive values
if ((bytes[6] < 248 ) || ( bytes[7] !== 255))
{
throw new Error(`The value to decode (${bytes}) is invalid: bytes[6] and/or bytes[7] indicate the encoded value is too small (less than -2^51) to be decoded`);
}
let binary: string = "";
for (let i = 0; i < bytes.length; i++)
{
let binaryByte: string = bytes[i].toString(2);
if (binaryByte.length < 8)
{
binaryByte = "0".repeat(8 - binaryByte.length) + binaryByte;
}
binary = binaryByte + binary;
}
// Reverse 2's-complement encoding (flip bits and subtract 1)
let flipped: string = binary.split("").map(c => c === "0" ? "1" : "0").join("");
result = -Number.parseInt(flipped, 2) - 1;
}
else
{
// "Fast" decoding for positive values [because we don't have to deal with 2's-complement encoding as we do for negative values]
if ((bytes[6] > 7) || ( bytes[7] !== 0))
{
throw new Error(`The value to decode (${bytes}) is invalid: bytes[6] and/or bytes[7] indicate the encoded value is too large (greater than 2^51 - 1) to be decoded`);
}
for (let i = 0; i < bytes.length; i++)
{
result += bytes[i] * _2Powers[i];
}
}
return (result);
}
/** Reads a VarInt32 from the specified byte array. */
export function readVarInt32(bytes: Uint8Array | Buffer, startIndex: number = 0): varIntResult
{
return (readVarInt(bytes, startIndex, 32));
}
/**
* Reads a VarInt64 from the specified byte array.\
* Note: This can only handle signed integers up to 53-bits, and is ~2x slower than readVarInt32().
*/
export function readVarInt64(bytes: Uint8Array | Buffer, startIndex: number = 0): varIntResult
{
return (readVarInt(bytes, startIndex, 53));
}
const _2Powers7Bits: number[] =
[
1,
Math.pow(2, 7 * 1), // 128
Math.pow(2, 7 * 2), // 16384
Math.pow(2, 7 * 3), // 2097152
Math.pow(2, 7 * 4), // 268435456
Math.pow(2, 7 * 5), // 34359738368
Math.pow(2, 7 * 6), // 4398046511104
Math.pow(2, 7 * 7), // 562949953421312
0 // Unusable: Number.MAX_SAFE_INTEGER is 9007199254740991
];
// A VarInt is a byte-encoding scheme [for integer values] where the most-significant bit is used to indicate that the next byte is also part of the encoded value.
// The low 7-bits of a byte are value bits. Byte 0 stores the least significant 7-bits of the value, and the last byte (whose most-significant bit will be 0) stores
// the most significant 7-bits. For example, to encoding 300 (1 0010 1100): [0] = 1 010 1100 [1] = 0 000 0010.
// However, the integer we are encoding is not a normal integer: it is a ZigZag encoded integer. ZigZag is a technique for encoding the sign (+/-)
// of an integer, where odd numbers represent negative integers and even numbers represent positive integers (ie. the LSB is the sign-bit [1 = negative]).
// For example: ZZ 0 = 0, ZZ 1 = -1, ZZ 2 = 1, ZZ 3 = -2, ZZ 4 = 2, etc. So the VarInt encoding for ZZ 300 above actually encodes integer value 150.
// For more on VarInt and ZigZag encoding see https://developers.google.com/protocol-buffers/docs/encoding.
// The varIntResult has 2 properties: number of bytes read ('length'), and the integer value ('value'). The 'value' is (by design) a JS number to
// make it easy to consume (compared to BigInt). However, this also means that it's limited to Number.MAX_SAFE_INTEGER / 2 (it's only half because ZigZag
// always encodes as a positive integer).
function readVarInt(bytes: Uint8Array | Buffer, startIndex: number, numBits: number): varIntResult
{
let result: varIntResult = { length: 0, value: 0 };
let zigZagValue: number = 0;
let pos: number = 0;
let isMostSignificantBitSet: boolean = false;
let maxExpectedBytes: number = Math.ceil(numBits / 7);
do
{
isMostSignificantBitSet = (bytes[startIndex + pos] & 128) === 128;
let low7Bits: number = bytes[startIndex + pos] & 127;
if (numBits <= 32)
{
zigZagValue |= (low7Bits << (pos * 7));
}
else
{
// Check if the value being decoded exceeds Number.MAX_SAFE_INTEGER:
// 9007199254740991 : Number.MAX_SAFE_INTEGER (Math.pow(2, 53) - 1 [or 8 petabytes])
// 562949953421312 : Math.pow(2, 49)
// 71494644084506624 : 127 * Math.pow(2, 49) => Too big for Number
// 9007199254740992 : 16 * Math.pow(2, 49) => Still too big for Number, so the limit for low7Bits is 15
if ((pos === 7) && (low7Bits > 15))
{
throw new Error(`The supplied varInt64 value (${Utils.makeDisplayBytes(bytes, startIndex, pos)}) encodes a value larger than Number.MAX_SAFE_INTEGER (${Number.MAX_SAFE_INTEGER})`);
}
zigZagValue += low7Bits * _2Powers7Bits[pos];
}
if (++pos > maxExpectedBytes)
{
throw new Error(`The supplied varInt${numBits <= 32 ? "32" : "64"} value (${Utils.makeDisplayBytes(bytes, startIndex, pos)}) encodes a value larger than ${numBits}-bits`);
}
} while (isMostSignificantBitSet);
result.length = pos;
// Decode ZigZag value
if (numBits <= 32)
{
// If zigZagValue is 5 (-3) : 0000 0000 0000 0000 0000 0000 0000 0101 (5)
// A: (zigZagValue >>> 1) : 0000 0000 0000 0000 0000 0000 0000 0010 (2)
// B: (zigZagValue & 1) : 0000 0000 0000 0000 0000 0000 0000 0001 (1) => Isolate the sign-bit
// C: -(zigZagValue & 1) : 1111 1111 1111 1111 1111 1111 1111 1111 (-1) => This "mask" would be all 0's if zigZagValue was even
// Result: A XOR C : 1111 1111 1111 1111 1111 1111 1111 1101 (-3)
result.value = (zigZagValue >>> 1) ^ (-(zigZagValue & 1));
}
else
{
// Note: We can't use any bitwise operators here because they automatically cast operands to signed 32-bit values
if (zigZagValue % 2 === 0)
{
// A positive value (or 0)
result.value = zigZagValue / 2;
}
else
{
// A negative value
result.value = -((zigZagValue + 1) / 2);
}
}
return (result);
}
/** Converts a 32-bit integer into a VarInt32 byte array. */
export function writeVarInt32(value: number): Uint8Array
{
checkValueToEncode(value, 32);
let zigZagValue: number = ((value << 1) ^ (value >> 31)); // Convert the value to ZigZag format
let varInt32: number[] = (zigZagValue === 0) ? [0] : [];
while (zigZagValue !== 0)
{
let byte: number = zigZagValue & 127;
zigZagValue = zigZagValue >>> 7;
byte |= ((zigZagValue === 0) ? 0 : 128);
varInt32.push(byte);
}
return (_bytePool.alloc(varInt32)); // return (new Uint8Array(varInt32));
}
/**
* Converts an integer into a VarInt64 byte array.\
* Note: This can only handle signed integers up to 52-bits.
*/
export function writeVarInt64(value: number): Uint8Array
{
checkValueToEncode(value, 53);
// Note: When we convert the value to ZigZag format we MUST do so without using roll left/right or other bitwise operators (because these operators automatically cast operands to signed 32-bit values)
// TODO: We're only encoding into the positive range (ie. zigZagValue will always be positive), which is why we're limiting 'value' to only 53-bits instead of the maximum 54-bits
let zigZagValue: number = (value >= 0) ? value * 2 : (Math.abs(value) * 2) - 1;
let varInt64: number[] = (zigZagValue === 0) ? [0] : [];
while (zigZagValue > 0)
{
let byte: number = zigZagValue % 128; // Equivalent of 'value & 127'
zigZagValue = Math.floor(zigZagValue / 128); // Equivalent of 'value >>> 7'
byte |= ((zigZagValue === 0) ? 0 : 128); // OK to use bitwise 'or' here as 'byte' will fit in a 32-bit value
varInt64.push(byte);
}
return (_bytePool.alloc(varInt64)); // return (new Uint8Array(varInt64));
}
const _named2Powers: { [ powerName: string ]: number } = {};
_named2Powers["2Pow31"] = Math.pow(2, 31);
_named2Powers["2Pow51"] = Math.pow(2, 51);
_named2Powers["2Pow52"] = Math.pow(2, 52);
_named2Powers["2Pow53"] = Math.pow(2, 53);
/** Throws if the specified value cannot be represented (as a signed integer) in the specified number of bits (1..54). */
function checkValueToEncode(value: number, numBits: number): void
{
if (isNaN(value) || !Number.isInteger(value))
{
throw new Error(`The value to encode (${value}) is not an integer`);
}
if ((numBits < 1) || (numBits > 54))
{
throw new Error(`numBits (${numBits}) out of range (1..54)`);
}
let maxInt: number = 0;
switch (numBits - 1)
{
// This is an optimization because checkValueToEncode() is on the "hot path"
case 31:
maxInt = _named2Powers["2Pow31"];
break;
case 51:
maxInt = _named2Powers["2Pow51"];
break;
case 52:
maxInt = _named2Powers["2Pow52"];
break;
case 53:
maxInt = _named2Powers["2Pow53"];
break;
default:
maxInt = Math.pow(2, numBits - 1);
break;
}
const minValue: number = -maxInt + (numBits === 54 ? 1 : 0); // -Number.MIN_SAFE_INTEGER === Number.MAX_SAFE_INTEGER
const maxValue: number = maxInt - 1;
if ((value < minValue) || (value > maxValue))
{
throw new Error(`The value to encode (${value}) exceeds the range of a ${numBits}-bit signed integer (${minValue} to ${maxValue})`);
}
}
/** Test utility method to compare the contents of two byte arrays. */
export function compareBytes(bytes1: Uint8Array, bytes2: Uint8Array, length: number, startIndex: number = 0): boolean
{
let isMatch: boolean = true;
if ((startIndex + length > bytes1.length) || (startIndex + length > bytes2.length))
{
throw new Error(`Either bytes1 (${bytes1.length} bytes) and/or bytes2 (${bytes2.length} bytes) do not contain enough bytes to perform the comparision (start at index ${startIndex} for ${length} bytes)`);
}
for (let i = 0; i < length; i++)
{
let pos: number = startIndex + i;
if (bytes1[pos] !== bytes2[pos])
{
isMatch = false;
break;
}
}
return (isMatch);
}
/** [Internal] This method is for **internal testing only**. */
export function runFixedIntTests()
{
let range32: number = Math.pow(2, 31);
let range64: bigint = BigInt(Math.pow(2, 63));
let startTimeInMS: number = 0;
let stepSize: number = 41;
let elapsedMS: number = 0;
let numTests: number = 0;
// First, spot-check the 3 flavors of Int64 methods for result parity
let int64ParityTestValues: number[] = [123456789, -123456789, 256, -256, 1, -1, 0, Math.pow(2, 50 - 1), -Math.pow(2, 50) - 1];
for (let i = 0; i < int64ParityTestValues.length; i++)
{
let value: number = int64ParityTestValues[i];
if (!compareBytes(writeInt64Fixed(BigInt(value)), writeInt64FixedNumber(value), 8) ||
!compareBytes(writeInt64Fixed(BigInt(value)), writeInt64FixedNumber_NoBuffer(value), 8))
{
throw new Error("Int64 encoding method parity test failed for " + value);
}
if ((readInt64Fixed(writeInt64FixedNumber(value)) !== BigInt(value)) ||
(readInt64FixedNumber(writeInt64FixedNumber_NoBuffer(value)) !== value) ||
(readInt64FixedNumber_NoBuffer(writeInt64Fixed(BigInt(value))) !== value))
{
throw new Error("Int64 decoding method parity test failed for " + value);
}
}
// Spot-check that readInt64Fixed() works with an offset
let targetValue: bigint = BigInt(-123456789);
let buf1: Buffer = writeInt64Fixed(BigInt(777777777)) as Buffer;
let buf2: Buffer = writeInt64Fixed(targetValue) as Buffer;
let buf3: Buffer = Buffer.concat([buf1, buf2]);
let offsetTestResult = readInt64Fixed(buf3, 8);
if (offsetTestResult !== targetValue)
{
throw new Error(`Error: readInt64Fixed() offset test failed: expected ${targetValue} but got ${offsetTestResult}`);
}
Utils.log("Starting FixedInt 32-bit tests...");
startTimeInMS = Date.now();
for (let value32 = -range32; value32 < range32; value32 += stepSize)
{
let encoded32: Uint8Array = writeInt32Fixed(value32);
let decoded32: number = readInt32Fixed(encoded32);
if (value32 !== decoded32)
{
throw new Error(`Decoded 32-bit value (${decoded32}) does not match encoded value (${value32})`);
}
}
elapsedMS = Date.now() - startTimeInMS;
numTests = Math.floor((range32 * 2) / stepSize);
Utils.log(`${numTests} FixedInt 32-bit tests completed in ${elapsedMS}ms (${(numTests / elapsedMS).toFixed(2)} encode/decodes per ms).`);
Utils.log("");
Utils.log("Starting FixedInt 64-bit tests...");
startTimeInMS = Date.now();
stepSize = 3242148931456; // 3242148931 (for 51-bit)
let value64: bigint = BigInt(-range64);
for (numTests = 0; value64 < range64; value64 += BigInt(stepSize), numTests++)
{
let encoded64: Uint8Array = writeInt64Fixed(value64);
let decoded64: bigint = readInt64Fixed(encoded64);
if (value64 !== decoded64)
{
throw new Error(`Decoded 64-bit value (${decoded64}) does not match encoded value (${value64})`);
}
}
elapsedMS = Date.now() - startTimeInMS;
Utils.log(`${numTests} FixedInt 64-bit tests completed in ${elapsedMS}ms (${(numTests / elapsedMS).toFixed(2)} encode/decodes per ms).`);
Utils.log("");
Utils.log("FixedInt tests finished.");
}
/** [Internal] This method is for **internal testing only**. */
export function runVarIntTests(): void
{
let range32: number = Math.pow(2, 31);
let range64: number = Math.pow(2, 51);
let startTimeInMS: number = Date.now();
let stepSize: number = 399;
let elapsedMS: number = 0;
let numTests: number = 0;
Utils.log("Running VarInt 64-bit size checks...");
// 1 byte has 7 value bits, so it can hold values up to 127, which for ZigZag encoded integers means up to +63 (ZZ 63 = 126, ZZ -64 = 127). So the spillover value to 2 bytes is +64).
// So the maximum [ZigZag encode] value that can be stored in n bytes is: (Math.pow(2, n * 7) / 2) - 1
// For example, for n = 3 the maximum is (Math.pow(2, 21) / 2) - 1 = 1,048,575
for (let n = 1; n <= 7; n++) // 7 * 7 = 49, which keeps us under Number.MAX_SAFE_INTEGER (2^53 - 1)
{
const maxValue: number = (Math.pow(2, n * 7) / 2) - 1;
let decoded32: varIntResult = readVarInt64(writeVarInt64(maxValue));
if (decoded32.length !== n)
{
throw new Error(`The largest value storable in ${n} bytes (${maxValue}) unexpectedly required ${decoded32.length} bytes`);
}
decoded32 = readVarInt64(writeVarInt64(maxValue + 1));
if (decoded32.length !== n + 1)
{
throw new Error(`The first value requiring ${n + 1} bytes (${maxValue + 1}) unexpectedly required ${decoded32.length} bytes`);
}
}
Utils.log("");
Utils.log("Starting VarInt 32-bit tests...");
for (let value32 = -range32; value32 < range32; value32 += stepSize)
{
// Utils.log((Date.now() - startTimeInMS).toString()); // This helped investigate the "breakpoints won't hit in first 30ms" bug
let encoded32: Uint8Array = writeVarInt32(value32);
let decoded32: varIntResult = readVarInt32(encoded32);
if (value32 !== decoded32.value)
{
throw new Error(`Decoded 32-bit value (${decoded32.value}) does not match encoded value (${value32})`);
}
}
elapsedMS = Date.now() - startTimeInMS;
numTests = Math.floor((range32 * 2) / stepSize);
Utils.log(`${numTests} VarInt 32-bit tests completed in ${elapsedMS}ms (${(numTests / elapsedMS).toFixed(2)} encode/decodes per ms).`);
Utils.log("");
Utils.log("Starting VarInt 64-bit tests...");
startTimeInMS = Date.now();
stepSize = 392148932;
for (let value64 = -range32; value64 < range64; value64 += stepSize)
{
let encoded64: Uint8Array = writeVarInt64(value64);
let decoded64: varIntResult = readVarInt64(encoded64);
if (value64 !== decoded64.value)
{
throw new Error(`Decoded 64-bit value (${decoded64.value}) does not match encoded value (${value64})`);
}
}
elapsedMS = Date.now() - startTimeInMS;
numTests = Math.floor((range64 * 2) / stepSize);
Utils.log(`${numTests} VarInt 64-bit tests completed in ${elapsedMS}ms (${(numTests / elapsedMS).toFixed(2)} encode/decodes per ms).`);
Utils.log("");
Utils.log("VarInt tests finished.");
}
/**
* [Internal] A class (for performance optimization) that enables creating contiguous blocks of memory from which a Uint8Array can be produced.\
* Also provides a faster alternative to "new Uint8Array(number[])".\
* The default pool size (set via constructor) is 2MB.
*/
export class BytePool
{
private _pool: Uint8Array; // Initialized in constructor
private _size: number;
private _pos: number = 0;
private _blockStartPos: number = -1;
/** The size (in bytes) of the pool. Set via constructor. */
get size(): number { return (this._size); }
/** The size (in bytes) of the active block, or -1 if there's no currently active block. */
get activeBlockSize(): number
{
return ((this._blockStartPos === -1) ? -1 : this._pos - this._blockStartPos);
}
constructor(sizeInBytes: number = 1024 * 1024 * 2)
{
this._size = sizeInBytes;
this._pool = new Uint8Array(this._size);
}
/** Starts a block of contiguous allocation. Only one block can be active at a time, and the block cannot exceed the size of the BytePool. */
startBlock(): void
{
if (this._blockStartPos !== -1)
{
let blockSize: number = this._pos - this._blockStartPos;
throw new Error(`A BytePool block has already been started (${blockSize} bytes at position ${this._blockStartPos})`);
}
this._blockStartPos = this._pos;
}
/**
* Ends a block of contiguous allocation, and returns the block (copied, by default, from the pool). Throws if there is no active block.\
* **WARNING:** Setting 'copy' to false will return a [faster] temporary-copy, but it MUST be used (copied) before the underlying pool data is overwritten.
*/
endBlock(copy: boolean = true): Uint8Array
{
if (this._blockStartPos === -1)
{
throw new Error("There is no active block; endBlock() must not be called without first calling startBlock()");
}
// Note: When 'copy' is true we return a new Uint8Array - not just a view - so that it's not temporary [ie. it won't get overwritten
// when _pool wraps]. This allows the caller to queue the returned block indefinitely (eg. when building a batch).
let block: Uint8Array = copy ? this._pool.slice(this._blockStartPos, this._pos) : this._pool.subarray(this._blockStartPos, this._pos);
this._blockStartPos = -1;
return (block);
}
/** Cancels the current block (if any), and reclaims the space it consumed. */
cancelBlock(): void
{
if (this._blockStartPos !== -1)
{
this._pos = this._blockStartPos;
this._blockStartPos = -1;
}
}
/** Throws if a block is not in-progress. If needed, moves the current block to the head of the pool, throwing if there's not enough space. */
private canAddToBlock(caller: string, addLength: number): void
{
if (this._blockStartPos === -1)
{
throw new Error(`BytePool.${caller}() can only be called between startBlock() and endBlock()`);
}
if (this._pos + addLength > this._size)
{
// Move the block to the head of the pool.
// Note: We don't split the allocated block [part at tail, part at head] so that it's always contiguous.
// The downside is that we can't use all the space in the pool (if the new allocaton won't fit in the remaining space).
let blockSize: number = this._pos - this._blockStartPos;
if (blockSize + addLength > this._blockStartPos)
{
// We're being conservative (safe) here by assuming that an overlapping copy may not work as expected in all JavaScript engines
throw new Error(`Cannot add ${addLength} bytes because the active block cannot be moved (Pool: ${this._size} bytes, Block: ${blockSize} bytes at offset ${this._blockStartPos})`);
}
if (blockSize > 0)
{
this._pool.copyWithin(0, this._blockStartPos, this._blockStartPos + blockSize);
}
this._blockStartPos = 0;
this._pos = blockSize;
// Utils.log("DEBUG: BytePool Wrapped", null, Utils.LoggingLevel.Minimal);
}
}
/** Adds (copies) the supplied buffer to the current block. Returns the number of bytes added. */
addBuffer(sourceBuffer: Uint8Array): number
{
if (sourceBuffer.length === 0)
{
return (0);
}
this.canAddToBlock("addBuffer", sourceBuffer.length);
this._pool.set(sourceBuffer, this._pos);
this._pos += sourceBuffer.length;
return (sourceBuffer.length);
}
/** Adds (copies) the supplied bytes to the current block. Returns the number of bytes added. */
addBytes(bytes: number[]): number
{
if (bytes.length === 0)
{
return (0);
}
this.canAddToBlock("addBytes", bytes.length);
for (let i = 0; i < bytes.length; i++)
{
if (!Number.isInteger(bytes[i]) || (bytes[i] < 0) || (bytes[i] > 255))
{
throw new Error(`The value (${bytes[i]}) at position ${i} is not a byte (0..255)`);
}
}
this._pool.set(bytes, this._pos);
this._pos += bytes.length;
return (bytes.length);
}
/** Adds (copies) the bytes for a VarInt32 (for the specified value) to the current block. Returns the number of bytes added. */
addVarInt32(value: number): number
{
checkValueToEncode(value, 32);
// Note: We're duplicating the code from writeVarInt32() here for performance (to avoid another function call)
let zigZagValue: number = ((value << 1) ^ (value >> 31)); // Convert the value to ZigZag format
let varInt32: number[] = (zigZagValue === 0) ? [0] : [];
while (zigZagValue !== 0)
{
let byte: number = zigZagValue & 127;
zigZagValue = zigZagValue >>> 7;
byte |= ((zigZagValue === 0) ? 0 : 128);
varInt32.push(byte);
}
return (this.addBytes(varInt32));
}
/**
* Returns a new (but temporary) Uint8Array from the specified bytes.\
* Note: The expectation is that the returned buffer will quickly (ie. within the calling
* function) be copied into another buffer, eg. via Buffer.concat().
* If too much time passes, the underlying data in the pool will be overwritten.\
* Note: NOT for use inside a block, ie. not between startBlock() and endBlock().
*/
alloc(bytes: number[]): Uint8Array
{
if (this._blockStartPos !== -1)
{
throw new Error(`BytePool.alloc() cannot be called between startBlock() and endBlock()`);
}
if (bytes.length > this._size)
{
throw new Error(`The requested allocation (${bytes.length}) is larger than the pool size (${this._size} bytes)`);
}
for (let i = 0; i < bytes.length; i++)
{
if (!Number.isInteger(bytes[i]) || (bytes[i] < 0) || (bytes[i] > 255))
{
throw new Error(`The value (${bytes[i]}) at position ${i} is not a byte (0..255)`);
}
}
if (this._pos + bytes.length > this._size)
{
// No room at the tail, so add to the head of the pool
// Utils.log("DEBUG: BytePool Wrapped", null, Utils.LoggingLevel.Minimal);
this._pos = 0;
}
this._pool.set(bytes, this._pos);
let buffer: Uint8Array = this._pool.subarray(this._pos, this._pos + bytes.length)
this._pos += bytes.length;
return (buffer);
}
}
let _bytePool: BytePool = new BytePool(16 * 1024); // Used to speed-up writeVarInt32/64() | the_stack |
import { expect } from 'chai';
import { parseModels, parseBoundRoutes, parseControllers, parseControllerJsDoc, parseModelsJsDoc } from '../lib/parsers';
import { BluePrintAction, MiddlewareType, SwaggerSailsControllers, NameKeyMap, SwaggerControllerAttribute, SwaggerModelAttribute, SwaggerSailsModel } from '../lib/interfaces';
import { blueprintActions } from '../lib/utils';
import path from 'path';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const userModel = require('../../api/models/User');
// eslint-disable-next-line @typescript-eslint/no-var-requires
const routes = require('../../config/routes');
const sailsConfig = {
paths: {
models: path.resolve('./api/models'),
controllers: path.resolve('./api/controllers')
},
routes: routes.routes,
appPath: ''
}
const sails = {
log: {
warn: () => {},
error: ()=> {}
},
config: sailsConfig
} as unknown as Sails.Sails;
describe ('Parsers', () => {
const models = {
user: {
globalId: 'User',
...userModel
},
dummy: {
attributes: {}
},
archive: {
globalId: 'Archive'
}
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(sails as any).models = models;
const boundRoutes = [
{
"path": "/user",
"verb": "get",
"options": {
"model": "user",
"associations": [],
"detectedVerb": {
"verb": "",
"original": "/user",
"path": "/user"
},
"action": "user/find",
"_middlewareType": "BLUEPRINT: find",
"skipRegex": []
}
},
{
"path": "/user/:id",
"verb": "get",
"options": {
"model": "user",
"associations": [],
"autoWatch": true,
"detectedVerb": {
"verb": "",
"original": "/user/:id",
"path": "/user/:id"
},
"action": "user/findone",
"_middlewareType": "BLUEPRINT: findone",
"skipRegex": [
{}
],
"skipAssets": true
}
},
{
"path": "/user/:id",
"verb": "put",
"options": {
"associations": [],
"autoWatch": true,
"detectedVerb": {
"verb": "",
"original": "/user/:id",
"path": "/user/:id"
},
"action": "user/update",
"_middlewareType": "BLUEPRINT: update",
"skipRegex": [
{}
],
"skipAssets": true
}
},
{
"path": "/actions2",
"verb": "get",
"options": {
"detectedVerb": {
"verb": "",
"original": "/actions2",
"path": "/actions2"
},
"action": "subdir/actions2",
"_middlewareType": "ACTION: subdir/actions2",
"skipRegex": []
}
},
{
// eslint-disable-next-line @typescript-eslint/camelcase
path: /^\/app\/.*$/,
target: '[Function]',
verb: 'get',
options: {
detectedVerb: { verb: '', original: 'r|^/app/.*$|', path: 'r|^/app/.*$|' },
skipAssets: true,
view: 'pages/homepage',
locals: { layout: false },
skipRegex: [/^[^?]*\/[^?/]+\.[^?/]+(\?.*)?$/]
},
originalFn: { /* [Function: serveView] */ _middlewareType: 'FUNCTION: serveView' }
}
];
describe ('parseModels', () => {
it(`should only consider all models except associative tables and 'Archive' model special case`, async () => {
const parsedModels = parseModels(sails);
expect(Object.keys(parsedModels).length).to.equal(1);
expect(parsedModels['user'],'key parsed models with their globalId').to.be.ok;
})
it('should load and merge swagger specification in /models/{globalId} with the model.swagger attribute', async () => {
const parsedModels = parseModels(sails);
const expectedTags = [
{
"name": "User (ORM duplicate)",
"externalDocs": {
"url": "https://somewhere.com/alternate",
"description": "Refer to these alternate docs"
}
}
]
expect(parsedModels.user.swagger.tags, 'should merge tags from swagger doc with Model.swagger.tags').to.deep.equal(expectedTags);
expect(parsedModels.user.swagger.components, 'should merge components from swagger doc with Model.swagger.components').to.deep.equal({parameters: []});
expect(parsedModels.user.swagger.actions, 'should convert and merge swagger doc path param to actions').to.contains.keys('findone');
})
})
describe ('parseModelsJsDoc', () => {
let parsedModels: NameKeyMap<SwaggerSailsModel>;
let modelsJsDoc: NameKeyMap<SwaggerModelAttribute>;
before(async () => {
parsedModels = parseModels(sails);
modelsJsDoc = await parseModelsJsDoc(sails, parsedModels);
})
it('should parse `tags` from model JSDoc', () => {
const expected = [{
name: 'User (ORM)',
description: 'A longer, multi-paragraph description\nexplaining how this all works.\n\nIt is linked to more information.\n',
externalDocs: { url: 'https://somewhere.com/yep', description: 'Refer to these docs' }
}];
expect(modelsJsDoc.user.tags).to.deep.equal(expected);
})
it('should parse `components` from model JSDoc', () => {
const expected = { examples: { modelDummy: { summary: 'A model example example', value: 'dummy' } } };
expect(modelsJsDoc.user.components).to.deep.equal(expected);
})
it('should parse model JSDoc for blueprint actions', () => {
const expected = {
find: { description: '_Alternate description_: Find a list of **User** records that match the specified criteria.\n' },
allactions: { externalDocs: { description: 'Refer to these docs for more info', url: 'https://somewhere.com/yep' } },
};
expect(modelsJsDoc.user.actions).to.deep.equal(expected);
})
})
describe('parseBoundRoutes: sails router:bind events', () => {
it('Should only parse blueprint and action routes', async () => {
const parsedModels = parseModels(sails);
const actual = parseBoundRoutes(boundRoutes as unknown as Sails.Route[], parsedModels, sails);
const expectedPaths = [ '/user', '/user/:id', '/user/:id', '/actions2' ];
expect(actual.map(r => r.path)).to.deep.equal(expectedPaths);
expect(actual.every(route => {
if(route.middlewareType === MiddlewareType.BLUEPRINT) {
return blueprintActions.includes(route.blueprintAction as BluePrintAction);
} else {
return route.middlewareType === MiddlewareType.ACTION;
}
})).to.be.true;
})
it('Should contain route model for all blueprint routes', async () => {
const parsedModels = parseModels(sails);
const actual = parseBoundRoutes(boundRoutes as unknown as Sails.Route[], parsedModels, sails);
const expectedPaths = [ '/user', '/user/:id', '/user/:id' ];
expect(actual.filter(route => route.middlewareType == MiddlewareType.BLUEPRINT && !!route.model).map(r => r.path), 'should return model for all blueprint routes').to.deep.equal(expectedPaths);
const updateUserRoute = actual.find(route => route.blueprintAction === 'update');
expect(!!updateUserRoute?.model, 'should parse blueprint routes and auto add model to routes without model (based on action)').to.be.true;
})
})
describe ('parseControllers', () => {
let parsedControllers: SwaggerSailsControllers;
before(async () => {
parsedControllers = await parseControllers(sails);
})
describe('load and parse `swagger` element exports in controller files', () => {
it('should parse `tags` from controller swagger element', () => {
const expected = [{ name: 'User List', description: 'Group just for user list operation', }];
expect(parsedControllers.controllerFiles.user.swagger.tags).to.deep.equal(expected);
})
it('should parse `components` from controller swagger element', () => {
expect(parsedControllers.controllerFiles.user.swagger.components).to.deep.equal({ parameters: [] });
})
it('should parse controller swagger element for actions', () => {
expect(parsedControllers.controllerFiles.user.swagger.actions).to.contains.keys('list');
})
})
describe('load and parse `swagger` element expoerts in actions2 files', () => {
it('should parse `tags` from actions2 action swagger element', () => {
const expected = [{ name: 'Actions2 Group', description: 'A test actions2 group', }];
expect(parsedControllers.controllerFiles['subdir/actions2'].swagger.tags).to.deep.equal(expected);
})
it('should parse `components` from actions2 action swagger element', () => {
expect(parsedControllers.controllerFiles['subdir/actions2'].swagger.components).to.deep.equal({ parameters: [] });
})
it('should parse actions2 action swagger element for actions', () => {
expect(parsedControllers.controllerFiles['subdir/actions2'].swagger.actions).to.contains.keys('actions2');
})
})
})
describe('parseControllerJsDoc', () => {
let parsedControllers: SwaggerSailsControllers;
let controllersJsDoc: NameKeyMap<SwaggerControllerAttribute>;
before(async () => {
parsedControllers = await parseControllers(sails);
controllersJsDoc = await parseControllerJsDoc(sails, parsedControllers);
})
describe('load and parse JSDoc comments in controller files', () => {
it('should parse `tags` from controller JSDoc', () => {
const expected = [ { name: 'Auth Mgt', description: 'User management and login' } ];
expect(controllersJsDoc.user.tags).to.deep.equal(expected);
})
it('should parse `components` from controller JSDoc', () => {
const expected = { examples: { dummy: { summary: 'An example example', value: 3.0 } } };
expect(controllersJsDoc.user.components).to.deep.equal(expected);
})
it('should parse controller JSDoc for actions', () => {
expect(controllersJsDoc.user.actions).to.contains.keys('logout');
})
})
describe('load and parse JSDoc comments in actions2 files', () => {
it('should parse `tags` from actions2 JSDoc', () => {
const expectedTagsActions2 = [
{ name: 'Actions2 Mgt', description: 'Actions2 testing' },
];
expect(controllersJsDoc['subdir/actions2'].tags).to.deep.equal(expectedTagsActions2);
})
it('should parse `components` from actions2 JSDoc', () => {
const expected = { examples: { dummyA2: { summary: 'Another example example', value: 4 } } };
expect(controllersJsDoc['subdir/actions2'].components).to.deep.equal(expected);
})
it('should parse actions2 JSDoc', () => {
expect(controllersJsDoc['subdir/actions2'].actions).to.contains.keys('actions2');
})
})
})
}) | the_stack |
import { localDateutilsTest, formats, LOCALDATE_TEST_TIMESTAMP } from "./test-utils";
describe("DateTime calculations", () => {
localDateutilsTest("date", (date, utils) => {
// ISO string
expect(utils.isEqual(date, utils.date(LOCALDATE_TEST_TIMESTAMP))).toBeTruthy();
// parse already date-specific object
expect(utils.isEqual(date, utils.date(utils.date(LOCALDATE_TEST_TIMESTAMP)))).toBeTruthy();
// parse null inputs
expect(utils.date(null)).toBeNull();
// undefined
expect(utils.date(undefined)).toBeTruthy();
});
localDateutilsTest("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();
});
localDateutilsTest("addDays", (date, utils, lib) => {
expect(utils.format(utils.addDays(date, 1), "dayOfMonth")).toBe("31");
expect(utils.format(utils.addDays(date, -1), "dayOfMonth")).toBe("29");
});
localDateutilsTest("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);
});
localDateutilsTest("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");
});
localDateutilsTest("startOfDay", (date, utils, lib) => {
expect(utils.formatByString(utils.startOfDay(date), formats.dateTime[lib])).toBe(
"2018-10-30 00:00"
);
});
localDateutilsTest("endOfDay", (date, utils, lib) => {
expect(utils.formatByString(utils.endOfDay(date), formats.dateTime[lib])).toBe(
"2018-10-30 23:59"
);
});
localDateutilsTest("startOfMonth", (date, utils, lib) => {
expect(utils.formatByString(utils.startOfMonth(date), formats.dateTime[lib])).toBe(
"2018-10-01 00:00"
);
});
localDateutilsTest("endOfMonth", (date, utils, lib) => {
expect(utils.formatByString(utils.endOfMonth(date), formats.dateTime[lib])).toBe(
"2018-10-31 23:59"
);
});
localDateutilsTest("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"
);
});
localDateutilsTest("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"
);
});
localDateutilsTest("getPreviousMonth", (date, utils, lib) => {
expect(
utils.formatByString(utils.getPreviousMonth(date), formats.date[lib])
).toBe("2018-09-30");
});
localDateutilsTest("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",
]);
});
localDateutilsTest("getNextMonth", (date, utils, lib) => {
expect(utils.formatByString(utils.getNextMonth(date), formats.date[lib])).toBe(
"2018-11-30"
);
});
localDateutilsTest("getYear", (date, utils) => {
expect(utils.getYear(date)).toBe(2018);
});
localDateutilsTest("getMonth", (date, utils) => {
expect(utils.getMonth(date)).toBe(9);
});
localDateutilsTest("getDaysInMonth", (date, utils) => {
expect(utils.getDaysInMonth(date)).toBe(31);
});
localDateutilsTest("setMonth", (date, utils, lib) => {
const updatedTime = utils.formatByString(
utils.setMonth(date, 4),
formats.date[lib]
);
expect(updatedTime).toBe("2018-05-30");
});
localDateutilsTest("setYear", (date, utils, lib) => {
const updatedTime = utils.formatByString(
utils.setYear(date, 2011),
formats.date[lib]
);
expect(updatedTime).toBe("2011-10-30");
});
localDateutilsTest("isAfter", (date, utils, lib) => {
expect(utils.isAfter(utils.date("2021-01-01"), utils.date(LOCALDATE_TEST_TIMESTAMP))).toBeTruthy();
expect(utils.isAfter(utils.date(LOCALDATE_TEST_TIMESTAMP), utils.date("2021-01-01"))).toBeFalsy();
});
localDateutilsTest("isBefore", (date, utils, lib) => {
expect(utils.isBefore(utils.date(LOCALDATE_TEST_TIMESTAMP), utils.date("2021-01-01"))).toBeTruthy();
expect(utils.isBefore(utils.date("2021-01-01"), utils.date(LOCALDATE_TEST_TIMESTAMP))).toBeFalsy();
});
localDateutilsTest("isAfterDay", (date, utils, lib) => {
const nextDay = utils.addDays(date, 1);
expect(utils.isAfterDay(nextDay, date)).toBeTruthy();
expect(utils.isAfterDay(date, nextDay)).toBeFalsy();
});
localDateutilsTest("isBeforeDay", (date, utils, lib) => {
const previousDay = utils.addDays(date, -1);
expect(utils.isBeforeDay(date, previousDay)).toBeFalsy();
expect(utils.isBeforeDay(previousDay, date)).toBeTruthy();
});
localDateutilsTest("isAfterYear", (date, utils, lib) => {
const nextYear = utils.setYear(date, 2019);
expect(utils.isAfterYear(nextYear, date)).toBeTruthy();
expect(utils.isAfterYear(date, nextYear)).toBeFalsy();
});
localDateutilsTest("isBeforeYear", (date, utils, lib) => {
const previousYear = utils.setYear(date, 2017);
expect(utils.isBeforeYear(date, previousYear)).toBeFalsy();
expect(utils.isBeforeYear(previousYear, date)).toBeTruthy();
});
localDateutilsTest("getWeekArray", (date, utils) => {
const weekArray = utils.getWeekArray(date);
expect(weekArray).toHaveLength(5);
for (const week of weekArray) {
expect(week).toHaveLength(7);
}
});
localDateutilsTest("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);
});
localDateutilsTest("getDiff with units", (date, utils) => {
expect(utils.getDiff(date, utils.date("2017-09-29"), "years")).toBe(1);
expect(utils.getDiff(date, utils.date("2018-08-29"), "months")).toBe(2);
expect(utils.getDiff(date, utils.date("2018-05-29"), "quarters")).toBe(
1
);
expect(utils.getDiff(date, utils.date("2018-09-29"), "days")).toBe(31);
expect(utils.getDiff(date, utils.date("2018-09-29"), "weeks")).toBe(4);
});
localDateutilsTest("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");
});
localDateutilsTest("isEqual", (date, utils) => {
expect(utils.isEqual(utils.date(null), null)).toBeTruthy();
expect(utils.isEqual(date, utils.date(LOCALDATE_TEST_TIMESTAMP))).toBeTruthy();
expect(utils.isEqual(null, utils.date(LOCALDATE_TEST_TIMESTAMP))).toBeFalsy();
});
localDateutilsTest("parse", (date, utils, lib) => {
const parsedDate = utils.parse("2018-10-30", formats.date[lib]);
expect(utils.isEqual(parsedDate, date)).toBeTruthy();
expect(utils.parse("", formats.dateTime[lib])).toBeNull();
});
localDateutilsTest("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);
});
localDateutilsTest("isNull", (date, utils, lib) => {
expect(utils.isNull(null)).toBeTruthy();
expect(utils.isNull(date)).toBeFalsy();
});
localDateutilsTest("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();
});
localDateutilsTest("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();
});
localDateutilsTest("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();
});
localDateutilsTest("getCurrentLocaleCode: returns default locale", (date, utils, lib) => {
expect(utils.getCurrentLocaleCode()).toMatch(/en/);
});
localDateutilsTest("toJsDate: returns date object", (date, utils) => {
expect(utils.toJsDate(date)).toBeInstanceOf(Date);
});
localDateutilsTest("isWithinRange: checks that dates isBetween 2 other dates", (date, utils) => {
expect(
utils.isWithinRange(utils.date("2019-10-01"), [
utils.date("2019-09-01"),
utils.date("2019-11-01"),
])
).toBeTruthy();
expect(
utils.isWithinRange(utils.date("2019-12-01"), [
utils.date("2019-09-01"),
utils.date("2019-11-01"),
])
).toBeFalsy();
});
localDateutilsTest("isWithinRange: should use inclusivity of range", (date, utils) => {
expect(
utils.isWithinRange(utils.date("2019-09-01"), [
utils.date("2019-09-01"),
utils.date("2019-12-01"),
])
).toBeTruthy();
expect(
utils.isWithinRange(utils.date("2019-12-01"), [
utils.date("2019-09-01"),
utils.date("2019-12-01"),
])
).toBeTruthy();
});
}); | the_stack |
import { IntPretty } from "./int-pretty";
import { Int } from "./int";
import { Dec } from "./decimal";
describe("Test IntPretty", () => {
it("Test creation of IntPretty", () => {
expect(new IntPretty(new Dec("1.1")).toDec().equals(new Dec("1.1"))).toBe(
true
);
expect(new IntPretty(new Dec("1.1")).maxDecimals(2).toString()).toBe(
"1.10"
);
expect(new IntPretty("1.1").toDec().equals(new Dec("1.1"))).toBe(true);
expect(new IntPretty("1.1").maxDecimals(2).toString()).toBe("1.10");
expect(new IntPretty(1.1).toDec().equals(new Dec("1.1"))).toBe(true);
expect(new IntPretty(1.1).maxDecimals(2).toString()).toBe("1.10");
expect(new IntPretty(new Int(1)).toDec().equals(new Dec("1.0"))).toBe(true);
expect(new IntPretty(new Int(1)).maxDecimals(2).toString()).toBe("1.00");
});
it("Test the maxDecimals of IntPretty", () => {
const params: {
arg: Dec | Int;
maxDecimals: number;
dec: Dec;
str: string;
}[] = [
{
arg: new Int(0),
maxDecimals: 0,
dec: new Dec(0),
str: "0",
},
{
arg: new Dec(0),
maxDecimals: 0,
dec: new Dec(0),
str: "0",
},
{
arg: new Int(100),
maxDecimals: 0,
dec: new Dec(100),
str: "100",
},
{
arg: new Dec(100),
maxDecimals: 0,
dec: new Dec(100),
str: "100",
},
{
arg: new Dec("0.01"),
maxDecimals: 2,
dec: new Dec("0.01"),
str: "0.01",
},
{
arg: new Dec("-0.01"),
maxDecimals: 2,
dec: new Dec("-0.01"),
str: "-0.01",
},
{
arg: new Dec("1.01"),
maxDecimals: 2,
dec: new Dec("1.01"),
str: "1.01",
},
{
arg: new Dec("-1.01"),
maxDecimals: 2,
dec: new Dec("-1.01"),
str: "-1.01",
},
{
arg: new Dec("10.01"),
maxDecimals: 2,
dec: new Dec("10.01"),
str: "10.01",
},
{
arg: new Dec("-10.01"),
maxDecimals: 2,
dec: new Dec("-10.01"),
str: "-10.01",
},
{
arg: new Dec("10.0100"),
maxDecimals: 2,
dec: new Dec("10.01"),
str: "10.01",
},
{
arg: new Dec("-10.0100"),
maxDecimals: 2,
dec: new Dec("-10.01"),
str: "-10.01",
},
];
for (const param of params) {
const pretty = new IntPretty(param.arg);
expect(pretty.options.maxDecimals).toBe(param.maxDecimals);
expect(pretty.toDec().equals(param.dec)).toBeTruthy();
expect(pretty.toString()).toBe(param.str);
}
});
it("Test modifying the precision of IntPretty", () => {
const tests: {
base: Dec;
delta: number;
right: boolean;
res: Dec;
resStr: string;
otherTest?: (int: IntPretty) => void;
}[] = [
{
base: new Dec("10.001"),
delta: 0,
right: false,
res: new Dec("10.001"),
resStr: "10.001",
otherTest: (int) => {
expect(int.maxDecimals(4).toString()).toBe("10.0010");
},
},
{
base: new Dec("10.001"),
delta: 1,
right: false,
res: new Dec("1.0001"),
resStr: "1.000",
otherTest: (int) => {
expect(int.maxDecimals(4).toString()).toBe("1.0001");
},
},
{
base: new Dec("10.001"),
delta: 1,
right: true,
res: new Dec("100.010"),
resStr: "100.010",
otherTest: (int) => {
expect(int.maxDecimals(4).toString()).toBe("100.0100");
},
},
{
base: new Dec("10.001"),
delta: 6,
right: true,
res: new Dec("10001000"),
resStr: "10,001,000.000",
},
{
base: new Dec("0"),
delta: 3,
right: false,
res: new Dec("0"),
resStr: "0",
},
{
base: new Dec("0"),
delta: 3,
right: true,
res: new Dec("0"),
resStr: "0",
},
{
base: new Dec("100.01"),
delta: 20,
right: true,
res: new Dec("10001000000000000000000"),
resStr: "10,001,000,000,000,000,000,000.00",
},
{
base: new Dec("100.01"),
delta: 20,
right: false,
res: new Dec("0.000000000000000001"),
resStr: "0.00",
otherTest: (int) => {
expect(int.trim(true).toString()).toBe("0");
},
},
];
for (const test of tests) {
let pretty = new IntPretty(test.base);
if (test.right) {
pretty = pretty.moveDecimalPointRight(test.delta);
} else {
pretty = pretty.moveDecimalPointLeft(test.delta);
}
expect(pretty.toDec().equals(test.res)).toBeTruthy();
expect(pretty.toString()).toBe(test.resStr);
if (test.otherTest) {
test.otherTest(pretty);
}
}
for (const test of tests) {
let pretty = new IntPretty(test.base);
if (test.right) {
pretty = pretty.decreasePrecision(test.delta);
} else {
pretty = pretty.increasePrecision(test.delta);
}
expect(pretty.toDec().equals(test.res)).toBeTruthy();
expect(pretty.toString()).toBe(test.resStr);
if (test.otherTest) {
test.otherTest(pretty);
}
}
});
it("Test the add calcutation of IntPretty", () => {
const params: {
base: Dec | Int;
target: Dec | Int;
dec: Dec;
str: string;
}[] = [
{
base: new Int(0),
target: new Int(0),
dec: new Dec(0),
str: "0",
},
{
base: new Dec(0),
target: new Int(0),
dec: new Dec(0),
str: "0",
},
{
base: new Int(0),
target: new Dec(0),
dec: new Dec(0),
str: "0",
},
{
base: new Int(1),
target: new Dec(1),
dec: new Dec(2),
str: "2",
},
{
base: new Int(1),
target: new Dec(-1),
dec: new Dec(0),
str: "0",
},
{
base: new Int(100),
target: new Dec(-1),
dec: new Dec("99"),
str: "99",
},
{
base: new Dec("100.001"),
target: new Dec(-1),
dec: new Dec("99.001"),
str: "99.001",
},
{
base: new Dec("100.00100"),
target: new Dec("-1.001"),
dec: new Dec("99"),
// Max decimals should be remain
str: "99.000",
},
{
base: new Dec("100.00100"),
target: new Dec("-0.00100"),
dec: new Dec("100"),
// Max decimals should be remain
str: "100.000",
},
{
base: new Dec("0.00100"),
target: new Dec("-1.00100"),
dec: new Dec("-1"),
// Max decimals should be remain
str: "-1.000",
},
{
base: new Dec("100.00100"),
target: new Dec("1.01"),
dec: new Dec("101.011"),
str: "101.011",
},
];
for (const param of params) {
const pretty = new IntPretty(param.base).add(new IntPretty(param.target));
expect(pretty.toDec().equals(param.dec)).toBeTruthy();
expect(pretty.toString()).toBe(param.str);
}
});
it("Test the sub calcutation of IntPretty", () => {
const params: {
base: Dec | Int;
target: Dec | Int;
dec: Dec;
str: string;
}[] = [
{
base: new Int(0),
target: new Int(0),
dec: new Dec(0),
str: "0",
},
{
base: new Dec(0),
target: new Int(0),
dec: new Dec(0),
str: "0",
},
{
base: new Int(0),
target: new Dec(0),
dec: new Dec(0),
str: "0",
},
{
base: new Int(1),
target: new Dec(1),
dec: new Dec(0),
str: "0",
},
{
base: new Int(1),
target: new Dec(-1),
dec: new Dec(2),
str: "2",
},
{
base: new Int(100),
target: new Dec(-1),
dec: new Dec("101"),
str: "101",
},
{
base: new Dec("100.001"),
target: new Dec(-1),
dec: new Dec("101.001"),
str: "101.001",
},
{
base: new Dec("100.00100"),
target: new Dec("1.001"),
dec: new Dec("99"),
// Max decimals should be remain
str: "99.000",
},
{
base: new Dec("100.00100"),
target: new Dec("0.00100"),
dec: new Dec("100"),
// Max decimals should be remain
str: "100.000",
},
{
base: new Dec("0.00100"),
target: new Dec("-1.00100"),
dec: new Dec("1.002"),
str: "1.002",
},
{
base: new Dec("100.00100"),
target: new Dec("-1.01"),
dec: new Dec("101.011"),
str: "101.011",
},
];
for (const param of params) {
const pretty = new IntPretty(param.base).sub(new IntPretty(param.target));
expect(pretty.toDec().equals(param.dec)).toBeTruthy();
expect(pretty.toString()).toBe(param.str);
}
});
it("Test the mul calcutation of IntPretty", () => {
const params: {
base: Dec | Int;
target: Dec | Int;
dec: Dec;
str: string;
}[] = [
{
base: new Int(0),
target: new Int(0),
dec: new Dec(0),
str: "0",
},
{
base: new Dec(0),
target: new Int(0),
dec: new Dec(0),
str: "0",
},
{
base: new Int(0),
target: new Dec(0),
dec: new Dec(0),
str: "0",
},
{
base: new Int(1),
target: new Dec(1),
dec: new Dec(1),
str: "1",
},
{
base: new Int(1),
target: new Dec(-1),
dec: new Dec(-1),
str: "-1",
},
{
base: new Int(100),
target: new Dec(-1),
dec: new Dec("-100"),
str: "-100",
},
{
base: new Dec("100.001"),
target: new Dec(-1),
dec: new Dec("-100.001"),
str: "-100.001",
},
{
base: new Dec("100.00100"),
target: new Dec("1.001"),
dec: new Dec("100.101001"),
// Max decimals should be remain
str: "100.101",
},
{
base: new Dec("100.00100"),
target: new Dec("0.00100"),
dec: new Dec("0.100001"),
// Max decimals should be remain
str: "0.100",
},
{
base: new Dec("100.00100"),
target: new Dec("-1.00100"),
dec: new Dec("-100.101001"),
// Max decimals should be remain
str: "-100.101",
},
{
base: new Dec("100.00100"),
target: new Dec("-0.00100"),
dec: new Dec("-0.100001"),
// Max decimals should be remain
str: "-0.100",
},
];
for (const param of params) {
const pretty = new IntPretty(param.base).mul(new IntPretty(param.target));
expect(pretty.toDec().equals(param.dec)).toBeTruthy();
expect(pretty.toString()).toBe(param.str);
}
});
it("Test the quo calcutation of IntPretty", () => {
expect(() => {
new IntPretty(new Dec("1")).quo(new IntPretty(new Int(0)));
}).toThrow();
const params: {
base: Dec | Int;
target: Dec | Int;
dec: Dec;
str: string;
}[] = [
{
base: new Int(1),
target: new Dec(1),
dec: new Dec(1),
str: "1",
},
{
base: new Int(1),
target: new Dec(-1),
dec: new Dec(-1),
str: "-1",
},
{
base: new Int(100),
target: new Dec(-1),
dec: new Dec("-100"),
str: "-100",
},
{
base: new Dec("100.001"),
target: new Dec(-1),
dec: new Dec("-100.001"),
str: "-100.001",
},
{
base: new Dec("300.00300"),
target: new Dec("3"),
dec: new Dec("100.001"),
str: "100.001",
},
{
base: new Dec("100.00500"),
target: new Dec("0.02"),
dec: new Dec("5000.25"),
// Max decimals should be remain
str: "5,000.250",
},
{
base: new Dec("300.00300"),
target: new Dec("4"),
dec: new Dec("75.00075"),
// Max decimals should be remain
str: "75.000",
},
];
for (const param of params) {
const pretty = new IntPretty(param.base).quo(new IntPretty(param.target));
expect(pretty.toDec().equals(param.dec)).toBeTruthy();
expect(pretty.toString()).toBe(param.str);
}
});
it("Test toString() of IntPretty", () => {
let pretty = new IntPretty(new Dec("1234.123456"));
expect(pretty.toString()).toBe("1,234.123456");
expect(pretty.locale(false).toString()).toBe("1234.123456");
expect(pretty.maxDecimals(3).toString()).toBe("1,234.123");
expect(pretty.maxDecimals(9).toString()).toBe("1,234.123456000");
expect(pretty.maxDecimals(9).trim(true).toString()).toBe("1,234.123456");
expect(pretty.shrink(true).toString()).toBe("1,234.123");
pretty = new IntPretty(new Dec("0.0123456"));
expect(pretty.toString()).toBe("0.0123456");
expect(pretty.locale(false).toString()).toBe("0.0123456");
expect(pretty.maxDecimals(3).toString()).toBe("0.012");
expect(pretty.maxDecimals(9).toString()).toBe("0.012345600");
expect(pretty.maxDecimals(9).trim(true).toString()).toBe("0.0123456");
expect(pretty.shrink(true).toString()).toBe("0.0123456");
});
it("Test inequalitySymbol of IntPretty", () => {
const tests: {
base: IntPretty;
maxDecimals: number;
inequalitySymbolSeparator: string;
resStr: string;
}[] = [
{
base: new IntPretty(new Dec("0")),
maxDecimals: 3,
inequalitySymbolSeparator: " ",
resStr: "0.000",
},
{
base: new IntPretty(new Dec("-0")),
maxDecimals: 3,
inequalitySymbolSeparator: " ",
resStr: "0.000",
},
{
base: new IntPretty(new Dec("0.1")),
maxDecimals: 3,
inequalitySymbolSeparator: " ",
resStr: "0.100",
},
{
base: new IntPretty(new Dec("1234.123456")),
maxDecimals: 3,
inequalitySymbolSeparator: " ",
resStr: "1,234.123",
},
{
base: new IntPretty(new Dec("0.123456")),
maxDecimals: 3,
inequalitySymbolSeparator: " ",
resStr: "0.123",
},
{
base: new IntPretty(new Dec("0.123456")).moveDecimalPointLeft(2),
maxDecimals: 3,
inequalitySymbolSeparator: " ",
resStr: "0.001",
},
{
base: new IntPretty(new Dec("0.123456")).moveDecimalPointLeft(3),
maxDecimals: 3,
inequalitySymbolSeparator: " ",
resStr: "< 0.001",
},
{
base: new IntPretty(new Dec("0.123456")),
maxDecimals: 0,
inequalitySymbolSeparator: " ",
resStr: "< 1",
},
{
base: new IntPretty(new Dec("1.123456")),
maxDecimals: 0,
inequalitySymbolSeparator: " ",
resStr: "1",
},
{
base: new IntPretty(new Dec("0.0001")),
maxDecimals: 3,
inequalitySymbolSeparator: " ",
resStr: "< 0.001",
},
{
base: new IntPretty(new Dec("0.0001")),
maxDecimals: 3,
inequalitySymbolSeparator: "",
resStr: "<0.001",
},
{
base: new IntPretty(new Dec("0.001")),
maxDecimals: 3,
inequalitySymbolSeparator: " ",
resStr: "0.001",
},
{
base: new IntPretty(new Dec("-1234.123456")),
maxDecimals: 3,
inequalitySymbolSeparator: " ",
resStr: "-1,234.123",
},
{
base: new IntPretty(new Dec("-0.123456")),
maxDecimals: 3,
inequalitySymbolSeparator: " ",
resStr: "-0.123",
},
{
base: new IntPretty(new Dec("-0.0001")),
maxDecimals: 3,
inequalitySymbolSeparator: " ",
resStr: "> -0.001",
},
{
base: new IntPretty(new Dec("-0.0001")),
maxDecimals: 3,
inequalitySymbolSeparator: "",
resStr: ">-0.001",
},
{
base: new IntPretty(new Dec("-0.001")),
maxDecimals: 3,
inequalitySymbolSeparator: " ",
resStr: "-0.001",
},
{
base: new IntPretty(new Dec("-0.123456")),
maxDecimals: 0,
inequalitySymbolSeparator: " ",
resStr: "> -1",
},
{
base: new IntPretty(new Dec("-1.123456")),
maxDecimals: 0,
inequalitySymbolSeparator: " ",
resStr: "-1",
},
];
for (const test of tests) {
expect(
test.base
.maxDecimals(test.maxDecimals)
.inequalitySymbol(true)
.inequalitySymbolSeparator(test.inequalitySymbolSeparator)
.toString()
).toBe(test.resStr);
}
});
it("Test toStringWithSymbols() of IntPretty", () => {
expect(
new IntPretty(new Dec(-123.45)).toStringWithSymbols("$", "SUFFIX")
).toBe("-$123.45SUFFIX");
expect(
new IntPretty(new Dec(-123.45))
.maxDecimals(0)
.toStringWithSymbols("$", "SUFFIX")
).toBe("-$123SUFFIX");
expect(
new IntPretty(new Dec(-0.045))
.maxDecimals(1)
.inequalitySymbol(true)
.toStringWithSymbols("$", "SUFFIX")
).toBe("> -$0.1SUFFIX");
expect(
new IntPretty(new Dec(0.045))
.maxDecimals(1)
.inequalitySymbol(true)
.toStringWithSymbols("$", "SUFFIX")
).toBe("< $0.1SUFFIX");
});
}); | the_stack |
import * as Atk from '@gi-types/atk';
import * as cairo from '@gi-types/cairo';
import * as Clutter from '@gi-types/clutter';
import * as Gcr from '@gi-types/gcr';
import * as GdkPixbuf from '@gi-types/gdkpixbuf';
import * as Gio from '@gi-types/gio';
import * as GLib from '@gi-types/glib';
import * as GObject from '@gi-types/gobject';
import * as Gtk from '@gi-types/gtk';
import * as Json from '@gi-types/json';
import * as Meta from '@gi-types/meta';
import * as NM from '@gi-types/nm';
import * as PolkitAgent from '@gi-types/polkitagent';
import * as St from '@gi-types/st';
export const KEYRING_SK_TAG: string;
export const KEYRING_SN_TAG: string;
export const KEYRING_UUID_TAG: string;
export function get_file_contents_utf8_sync(path: string): string;
export function util_check_cloexec_fds(): void;
export function util_composite_capture_images(
captures: Clutter.Capture,
n_captures: number,
x: number,
y: number,
target_width: number,
target_height: number,
target_scale: number
): cairo.Surface;
export function util_create_pixbuf_from_data(
data: Uint8Array | string,
colorspace: GdkPixbuf.Colorspace,
has_alpha: boolean,
bits_per_sample: number,
width: number,
height: number,
rowstride: number
): GdkPixbuf.Pixbuf;
export function util_get_content_for_window_actor(
window_actor: Meta.WindowActor,
window_rect: Meta.Rectangle
): Clutter.Content | null;
export function util_get_translated_folder_name(name: string): string | null;
export function util_get_uid(): number;
export function util_get_week_start(): number;
export function util_has_x11_display_extension(
display: Meta.Display,
extension: string
): boolean;
export function util_regex_escape(str: string): string;
export function util_sd_notify(): void;
export function util_set_hidden_from_pick(
actor: Clutter.Actor,
hidden: boolean
): void;
export function util_start_systemd_unit(
unit: string,
mode: string,
cancellable?: Gio.Cancellable | null
): Promise<boolean>;
export function util_start_systemd_unit(
unit: string,
mode: string,
cancellable: Gio.Cancellable | null,
callback: Gio.AsyncReadyCallback<string> | null
): void;
export function util_start_systemd_unit(
unit: string,
mode: string,
cancellable?: Gio.Cancellable | null,
callback?: Gio.AsyncReadyCallback<string> | null
): Promise<boolean> | void;
export function util_start_systemd_unit_finish(res: Gio.AsyncResult): boolean;
export function util_stop_systemd_unit(
unit: string,
mode: string,
cancellable?: Gio.Cancellable | null
): Promise<boolean>;
export function util_stop_systemd_unit(
unit: string,
mode: string,
cancellable: Gio.Cancellable | null,
callback: Gio.AsyncReadyCallback<string> | null
): void;
export function util_stop_systemd_unit(
unit: string,
mode: string,
cancellable?: Gio.Cancellable | null,
callback?: Gio.AsyncReadyCallback<string> | null
): Promise<boolean> | void;
export function util_stop_systemd_unit_finish(res: Gio.AsyncResult): boolean;
export function util_touch_file_async(file: Gio.File): Promise<boolean>;
export function util_touch_file_async(
file: Gio.File,
callback: Gio.AsyncReadyCallback<Gio.File> | null
): void;
export function util_touch_file_async(
file: Gio.File,
callback?: Gio.AsyncReadyCallback<Gio.File> | null
): Promise<boolean> | void;
export function util_touch_file_finish(
file: Gio.File,
res: Gio.AsyncResult
): boolean;
export function util_translate_time_string(str: string): string;
export function util_wifexited(status: number): [boolean, number];
export function write_string_to_stream(
stream: Gio.OutputStream,
str: string
): boolean;
export type LeisureFunction = (data?: any | null) => void;
export type PerfReplayFunction = (
time: number,
name: string,
signature: string,
arg: any
) => void;
export type PerfStatisticsCallback = (
perf_log: PerfLog,
data?: any | null
) => void;
export namespace AppLaunchGpu {
export const $gtype: GObject.GType<AppLaunchGpu>;
}
export enum AppLaunchGpu {
APP_PREF = 0,
DISCRETE = 1,
DEFAULT = 2,
}
export namespace AppState {
export const $gtype: GObject.GType<AppState>;
}
export enum AppState {
STOPPED = 0,
STARTING = 1,
RUNNING = 2,
}
export namespace BlurMode {
export const $gtype: GObject.GType<BlurMode>;
}
export enum BlurMode {
ACTOR = 0,
BACKGROUND = 1,
}
export namespace NetworkAgentResponse {
export const $gtype: GObject.GType<NetworkAgentResponse>;
}
export enum NetworkAgentResponse {
CONFIRMED = 0,
USER_CANCELED = 1,
INTERNAL_ERROR = 2,
}
export namespace SnippetHook {
export const $gtype: GObject.GType<SnippetHook>;
}
export enum SnippetHook {
VERTEX = 0,
VERTEX_TRANSFORM = 1,
FRAGMENT = 2048,
TEXTURE_COORD_TRANSFORM = 4096,
LAYER_FRAGMENT = 6144,
TEXTURE_LOOKUP = 6145,
}
export namespace ActionMode {
export const $gtype: GObject.GType<ActionMode>;
}
export enum ActionMode {
NONE = 0,
NORMAL = 1,
OVERVIEW = 2,
LOCK_SCREEN = 4,
UNLOCK_SCREEN = 8,
LOGIN_SCREEN = 16,
SYSTEM_MODAL = 32,
LOOKING_GLASS = 64,
POPUP = 128,
ALL = -1,
}
export namespace App {
export interface ConstructorProperties
extends GObject.Object.ConstructorProperties {
[key: string]: any;
action_group: Gio.ActionGroup;
actionGroup: Gio.ActionGroup;
app_info: Gio.DesktopAppInfo;
appInfo: Gio.DesktopAppInfo;
busy: boolean;
id: string;
state: AppState;
}
}
export class App extends GObject.Object {
static $gtype: GObject.GType<App>;
constructor(
properties?: Partial<App.ConstructorProperties>,
...args: any[]
);
_init(
properties?: Partial<App.ConstructorProperties>,
...args: any[]
): void;
// Properties
action_group: Gio.ActionGroup;
actionGroup: Gio.ActionGroup;
app_info: Gio.DesktopAppInfo;
appInfo: Gio.DesktopAppInfo;
busy: boolean;
id: string;
state: AppState;
// Signals
connect(id: string, callback: (...args: any[]) => any): number;
connect_after(id: string, callback: (...args: any[]) => any): number;
emit(id: string, ...args: any[]): void;
connect(
signal: 'windows-changed',
callback: (_source: this) => void
): number;
connect_after(
signal: 'windows-changed',
callback: (_source: this) => void
): number;
emit(signal: 'windows-changed'): void;
// Members
activate(): void;
activate_full(workspace: number, timestamp: number): void;
activate_window(window: Meta.Window | null, timestamp: number): void;
can_open_new_window(): boolean;
compare(other: App): number;
compare_by_name(other: App): number;
create_icon_texture(size: number): Clutter.Actor;
get_app_info(): Gio.DesktopAppInfo;
get_busy(): boolean;
get_description(): string;
get_icon(): Gio.Icon;
get_id(): string;
get_n_windows(): number;
get_name(): string;
get_pids(): number[];
get_state(): AppState;
get_windows(): Meta.Window[];
is_on_workspace(workspace: Meta.Workspace): boolean;
is_window_backed(): boolean;
launch(
timestamp: number,
workspace: number,
gpu_pref: AppLaunchGpu
): boolean;
launch_action(
action_name: string,
timestamp: number,
workspace: number
): void;
open_new_window(workspace: number): void;
request_quit(): boolean;
update_app_actions(window: Meta.Window): void;
update_window_actions(window: Meta.Window): void;
}
export namespace AppSystem {
export interface ConstructorProperties
extends GObject.Object.ConstructorProperties {
[key: string]: any;
}
}
export class AppSystem extends GObject.Object {
static $gtype: GObject.GType<AppSystem>;
constructor(
properties?: Partial<AppSystem.ConstructorProperties>,
...args: any[]
);
_init(
properties?: Partial<AppSystem.ConstructorProperties>,
...args: any[]
): void;
// Signals
connect(id: string, callback: (...args: any[]) => any): number;
connect_after(id: string, callback: (...args: any[]) => any): number;
emit(id: string, ...args: any[]): void;
connect(
signal: 'app-state-changed',
callback: (_source: this, object: App) => void
): number;
connect_after(
signal: 'app-state-changed',
callback: (_source: this, object: App) => void
): number;
emit(signal: 'app-state-changed', object: App): void;
connect(
signal: 'installed-changed',
callback: (_source: this) => void
): number;
connect_after(
signal: 'installed-changed',
callback: (_source: this) => void
): number;
emit(signal: 'installed-changed'): void;
// Members
get_installed(): Gio.AppInfo[];
get_running(): App[];
lookup_app(id: string): App;
lookup_desktop_wmclass(wmclass?: string | null): App;
lookup_heuristic_basename(id: string): App;
lookup_startup_wmclass(wmclass?: string | null): App;
static get_default(): AppSystem;
static search(search_string: string): string[][];
}
export namespace AppUsage {
export interface ConstructorProperties
extends GObject.Object.ConstructorProperties {
[key: string]: any;
}
}
export class AppUsage extends GObject.Object {
static $gtype: GObject.GType<AppUsage>;
constructor(
properties?: Partial<AppUsage.ConstructorProperties>,
...args: any[]
);
_init(
properties?: Partial<AppUsage.ConstructorProperties>,
...args: any[]
): void;
// Members
compare(id_a: string, id_b: string): number;
get_most_used(): App[];
static get_default(): AppUsage;
}
export namespace BlurEffect {
export interface ConstructorProperties
extends Clutter.Effect.ConstructorProperties {
[key: string]: any;
brightness: number;
mode: BlurMode;
sigma: number;
}
}
export class BlurEffect extends Clutter.Effect {
static $gtype: GObject.GType<BlurEffect>;
constructor(
properties?: Partial<BlurEffect.ConstructorProperties>,
...args: any[]
);
_init(
properties?: Partial<BlurEffect.ConstructorProperties>,
...args: any[]
): void;
// Properties
brightness: number;
mode: BlurMode;
sigma: number;
// Constructors
static ['new'](): BlurEffect;
// Members
get_brightness(): number;
get_mode(): BlurMode;
get_sigma(): number;
set_brightness(brightness: number): void;
set_mode(mode: BlurMode): void;
set_sigma(sigma: number): void;
}
export namespace EmbeddedWindow {
export interface ConstructorProperties
extends Gtk.Window.ConstructorProperties {
[key: string]: any;
}
}
export class EmbeddedWindow
extends Gtk.Window
implements Atk.ImplementorIface, Gtk.Buildable {
static $gtype: GObject.GType<EmbeddedWindow>;
constructor(
properties?: Partial<EmbeddedWindow.ConstructorProperties>,
...args: any[]
);
_init(
properties?: Partial<EmbeddedWindow.ConstructorProperties>,
...args: any[]
): void;
// Constructors
static ['new'](): EmbeddedWindow;
static ['new'](...args: never[]): never;
// Implemented Members
add_child(
builder: Gtk.Builder,
child: GObject.Object,
type?: string | null
): void;
construct_child<T = GObject.Object>(builder: Gtk.Builder, name: string): T;
custom_finished(
builder: Gtk.Builder,
child: GObject.Object | null,
tagname: string,
data?: any | null
): void;
custom_tag_end(
builder: Gtk.Builder,
child: GObject.Object | null,
tagname: string,
data?: any | null
): void;
custom_tag_start(
builder: Gtk.Builder,
child: GObject.Object | null,
tagname: string
): [boolean, GLib.MarkupParser, any | null];
get_internal_child<T = GObject.Object>(
builder: Gtk.Builder,
childname: string
): T;
get_name(): string;
parser_finished(builder: Gtk.Builder): void;
set_buildable_property(
builder: Gtk.Builder,
name: string,
value: any
): void;
set_name(name: string): void;
vfunc_add_child(
builder: Gtk.Builder,
child: GObject.Object,
type?: string | null
): void;
vfunc_construct_child<T = GObject.Object>(
builder: Gtk.Builder,
name: string
): T;
vfunc_custom_finished(
builder: Gtk.Builder,
child: GObject.Object | null,
tagname: string,
data?: any | null
): void;
vfunc_custom_tag_end(
builder: Gtk.Builder,
child: GObject.Object | null,
tagname: string,
data?: any | null
): void;
vfunc_custom_tag_start(
builder: Gtk.Builder,
child: GObject.Object | null,
tagname: string
): [boolean, GLib.MarkupParser, any | null];
vfunc_get_internal_child<T = GObject.Object>(
builder: Gtk.Builder,
childname: string
): T;
vfunc_get_name(): string;
vfunc_parser_finished(builder: Gtk.Builder): void;
vfunc_set_buildable_property(
builder: Gtk.Builder,
name: string,
value: any
): void;
vfunc_set_name(name: string): void;
}
export namespace GLSLEffect {
export interface ConstructorProperties
extends Clutter.OffscreenEffect.ConstructorProperties {
[key: string]: any;
}
}
export class GLSLEffect extends Clutter.OffscreenEffect {
static $gtype: GObject.GType<GLSLEffect>;
constructor(
properties?: Partial<GLSLEffect.ConstructorProperties>,
...args: any[]
);
_init(
properties?: Partial<GLSLEffect.ConstructorProperties>,
...args: any[]
): void;
// Members
add_glsl_snippet(
hook: SnippetHook,
declarations: string,
code: string,
is_replace: boolean
): void;
get_uniform_location(name: string): number;
set_uniform_float(
uniform: number,
n_components: number,
value: number[]
): void;
vfunc_build_pipeline(): void;
}
export namespace Global {
export interface ConstructorProperties
extends GObject.Object.ConstructorProperties {
[key: string]: any;
backend: Meta.Backend;
datadir: string;
display: Meta.Display;
focus_manager: St.FocusManager;
focusManager: St.FocusManager;
frame_finish_timestamp: boolean;
frameFinishTimestamp: boolean;
frame_timestamps: boolean;
frameTimestamps: boolean;
imagedir: string;
screen_height: number;
screenHeight: number;
screen_width: number;
screenWidth: number;
session_mode: string;
sessionMode: string;
settings: Gio.Settings;
stage: Clutter.Actor;
switcheroo_control: Gio.DBusProxy;
switcherooControl: Gio.DBusProxy;
top_window_group: Clutter.Actor;
topWindowGroup: Clutter.Actor;
userdatadir: string;
window_group: Clutter.Actor;
windowGroup: Clutter.Actor;
window_manager: WM;
windowManager: WM;
workspace_manager: Meta.WorkspaceManager;
workspaceManager: Meta.WorkspaceManager;
}
}
export class Global extends GObject.Object {
static $gtype: GObject.GType<Global>;
constructor(
properties?: Partial<Global.ConstructorProperties>,
...args: any[]
);
_init(
properties?: Partial<Global.ConstructorProperties>,
...args: any[]
): void;
// Properties
backend: Meta.Backend;
datadir: string;
display: Meta.Display;
focus_manager: St.FocusManager;
focusManager: St.FocusManager;
frame_finish_timestamp: boolean;
frameFinishTimestamp: boolean;
frame_timestamps: boolean;
frameTimestamps: boolean;
imagedir: string;
screen_height: number;
screenHeight: number;
screen_width: number;
screenWidth: number;
session_mode: string;
sessionMode: string;
settings: Gio.Settings;
stage: Clutter.Actor;
switcheroo_control: Gio.DBusProxy;
switcherooControl: Gio.DBusProxy;
top_window_group: Clutter.Actor;
topWindowGroup: Clutter.Actor;
userdatadir: string;
window_group: Clutter.Actor;
windowGroup: Clutter.Actor;
window_manager: WM;
windowManager: WM;
workspace_manager: Meta.WorkspaceManager;
workspaceManager: Meta.WorkspaceManager;
// Signals
connect(id: string, callback: (...args: any[]) => any): number;
connect_after(id: string, callback: (...args: any[]) => any): number;
emit(id: string, ...args: any[]): void;
connect(
signal: 'locate-pointer',
callback: (_source: this) => void
): number;
connect_after(
signal: 'locate-pointer',
callback: (_source: this) => void
): number;
emit(signal: 'locate-pointer'): void;
connect(
signal: 'notify-error',
callback: (_source: this, object: string, p0: string) => void
): number;
connect_after(
signal: 'notify-error',
callback: (_source: this, object: string, p0: string) => void
): number;
emit(signal: 'notify-error', object: string, p0: string): void;
// Members
begin_modal(timestamp: number, options: Meta.ModalOptions): boolean;
begin_work(): void;
create_app_launch_context(
timestamp: number,
workspace: number
): Gio.AppLaunchContext;
end_modal(timestamp: number): void;
end_work(): void;
get_current_time(): number;
get_display(): Meta.Display;
get_persistent_state(
property_type: string,
property_name: string
): GLib.Variant;
get_pointer(): [number, number, Clutter.ModifierType];
get_runtime_state(
property_type: string,
property_name: string
): GLib.Variant;
get_session_mode(): string;
get_settings(): Gio.Settings;
get_stage(): Clutter.Stage;
get_switcheroo_control(): Gio.DBusProxy;
get_window_actors(): Meta.WindowActor[];
notify_error(msg: string, details: string): void;
reexec_self(): void;
run_at_leisure(func: LeisureFunction): void;
set_persistent_state(
property_name: string,
variant?: GLib.Variant | null
): void;
set_runtime_state(
property_name: string,
variant?: GLib.Variant | null
): void;
set_stage_input_region(rectangles: Meta.Rectangle[]): void;
sync_pointer(): void;
static get(): Global;
}
export namespace GtkEmbed {
export interface ConstructorProperties<
A extends Clutter.Actor = Clutter.Actor
> extends Clutter.Clone.ConstructorProperties<A> {
[key: string]: any;
window: EmbeddedWindow;
}
}
export class GtkEmbed<A extends Clutter.Actor = Clutter.Actor>
extends Clutter.Clone<A>
implements
Atk.ImplementorIface,
Clutter.Animatable,
Clutter.Container<A>,
Clutter.Scriptable {
static $gtype: GObject.GType<GtkEmbed>;
constructor(
properties?: Partial<GtkEmbed.ConstructorProperties<A>>,
...args: any[]
);
_init(
properties?: Partial<GtkEmbed.ConstructorProperties<A>>,
...args: any[]
): void;
// Properties
window: EmbeddedWindow;
// Constructors
static ['new'](window: EmbeddedWindow): GtkEmbed;
static ['new'](...args: never[]): never;
// Implemented Members
find_property(property_name: string): GObject.ParamSpec;
get_actor(): Clutter.Actor;
get_initial_state(property_name: string, value: any): void;
interpolate_value(
property_name: string,
interval: Clutter.Interval,
progress: number
): [boolean, unknown];
set_final_state(property_name: string, value: any): void;
vfunc_find_property(property_name: string): GObject.ParamSpec;
vfunc_get_actor(): Clutter.Actor;
vfunc_get_initial_state(property_name: string, value: any): void;
vfunc_interpolate_value(
property_name: string,
interval: Clutter.Interval,
progress: number
): [boolean, unknown];
vfunc_set_final_state(property_name: string, value: any): void;
add_actor(actor: A): void;
child_get_property(child: A, property: string, value: any): void;
child_notify(child: A, pspec: GObject.ParamSpec): void;
child_set_property(child: A, property: string, value: any): void;
create_child_meta(actor: A): void;
destroy_child_meta(actor: A): void;
find_child_by_name(child_name: string): A;
get_child_meta(actor: A): Clutter.ChildMeta;
get_children(): A[];
get_children(...args: never[]): never;
lower_child(actor: A, sibling?: A | null): void;
raise_child(actor: A, sibling?: A | null): void;
remove_actor(actor: A): void;
sort_depth_order(): void;
vfunc_actor_added(actor: A): void;
vfunc_actor_removed(actor: A): void;
vfunc_add(actor: A): void;
vfunc_child_notify(child: A, pspec: GObject.ParamSpec): void;
vfunc_create_child_meta(actor: A): void;
vfunc_destroy_child_meta(actor: A): void;
vfunc_get_child_meta(actor: A): Clutter.ChildMeta;
vfunc_lower(actor: A, sibling?: A | null): void;
vfunc_raise(actor: A, sibling?: A | null): void;
vfunc_remove(actor: A): void;
vfunc_sort_depth_order(): void;
get_id(): string;
parse_custom_node(
script: Clutter.Script,
value: any,
name: string,
node: Json.Node
): boolean;
set_custom_property(script: Clutter.Script, name: string, value: any): void;
set_id(id_: string): void;
vfunc_get_id(): string;
vfunc_parse_custom_node(
script: Clutter.Script,
value: any,
name: string,
node: Json.Node
): boolean;
vfunc_set_custom_property(
script: Clutter.Script,
name: string,
value: any
): void;
vfunc_set_id(id_: string): void;
}
export namespace InvertLightnessEffect {
export interface ConstructorProperties
extends Clutter.OffscreenEffect.ConstructorProperties {
[key: string]: any;
}
}
export class InvertLightnessEffect extends Clutter.OffscreenEffect {
static $gtype: GObject.GType<InvertLightnessEffect>;
constructor(
properties?: Partial<InvertLightnessEffect.ConstructorProperties>,
...args: any[]
);
_init(
properties?: Partial<InvertLightnessEffect.ConstructorProperties>,
...args: any[]
): void;
// Constructors
static ['new'](): InvertLightnessEffect;
}
export namespace KeyringPrompt {
export interface ConstructorProperties
extends GObject.Object.ConstructorProperties {
[key: string]: any;
choice_visible: boolean;
choiceVisible: boolean;
confirm_actor: Clutter.Text;
confirmActor: Clutter.Text;
confirm_visible: boolean;
confirmVisible: boolean;
password_actor: Clutter.Text;
passwordActor: Clutter.Text;
password_visible: boolean;
passwordVisible: boolean;
warning_visible: boolean;
warningVisible: boolean;
}
}
export class KeyringPrompt extends GObject.Object implements Gcr.Prompt {
static $gtype: GObject.GType<KeyringPrompt>;
constructor(
properties?: Partial<KeyringPrompt.ConstructorProperties>,
...args: any[]
);
_init(
properties?: Partial<KeyringPrompt.ConstructorProperties>,
...args: any[]
): void;
// Properties
choice_visible: boolean;
choiceVisible: boolean;
confirm_actor: Clutter.Text;
confirmActor: Clutter.Text;
confirm_visible: boolean;
confirmVisible: boolean;
password_actor: Clutter.Text;
passwordActor: Clutter.Text;
password_visible: boolean;
passwordVisible: boolean;
warning_visible: boolean;
warningVisible: boolean;
// Signals
connect(id: string, callback: (...args: any[]) => any): number;
connect_after(id: string, callback: (...args: any[]) => any): number;
emit(id: string, ...args: any[]): void;
connect(signal: 'show-confirm', callback: (_source: this) => void): number;
connect_after(
signal: 'show-confirm',
callback: (_source: this) => void
): number;
emit(signal: 'show-confirm'): void;
connect(signal: 'show-password', callback: (_source: this) => void): number;
connect_after(
signal: 'show-password',
callback: (_source: this) => void
): number;
emit(signal: 'show-password'): void;
// Implemented Properties
caller_window: string;
callerWindow: string;
cancel_label: string;
cancelLabel: string;
choice_chosen: boolean;
choiceChosen: boolean;
choice_label: string;
choiceLabel: string;
continue_label: string;
continueLabel: string;
description: string;
message: string;
password_new: boolean;
passwordNew: boolean;
password_strength: number;
passwordStrength: number;
title: string;
warning: string;
// Constructors
static ['new'](): KeyringPrompt;
// Members
cancel(): void;
complete(): boolean;
get_confirm_actor(): Clutter.Text | null;
get_password_actor(): Clutter.Text | null;
set_confirm_actor(confirm_actor?: Clutter.Text | null): void;
set_password_actor(password_actor?: Clutter.Text | null): void;
// Implemented Members
close(): void;
confirm(cancellable?: Gio.Cancellable | null): Gcr.PromptReply;
confirm_async(
cancellable?: Gio.Cancellable | null
): Promise<Gcr.PromptReply>;
confirm_async(
cancellable: Gio.Cancellable | null,
callback: Gio.AsyncReadyCallback<this> | null
): void;
confirm_async(
cancellable?: Gio.Cancellable | null,
callback?: Gio.AsyncReadyCallback<this> | null
): Promise<Gcr.PromptReply> | void;
confirm_finish(result: Gio.AsyncResult): Gcr.PromptReply;
confirm_run(cancellable?: Gio.Cancellable | null): Gcr.PromptReply;
get_caller_window(): string;
get_cancel_label(): string;
get_choice_chosen(): boolean;
get_choice_label(): string;
get_continue_label(): string;
get_description(): string;
get_message(): string;
get_password_new(): boolean;
get_password_strength(): number;
get_title(): string;
get_warning(): string;
password(cancellable?: Gio.Cancellable | null): string;
password_async(cancellable?: Gio.Cancellable | null): Promise<string>;
password_async(
cancellable: Gio.Cancellable | null,
callback: Gio.AsyncReadyCallback<this> | null
): void;
password_async(
cancellable?: Gio.Cancellable | null,
callback?: Gio.AsyncReadyCallback<this> | null
): Promise<string> | void;
password_finish(result: Gio.AsyncResult): string;
password_run(cancellable?: Gio.Cancellable | null): string;
reset(): void;
set_caller_window(window_id: string): void;
set_cancel_label(cancel_label: string): void;
set_choice_chosen(chosen: boolean): void;
set_choice_label(choice_label?: string | null): void;
set_continue_label(continue_label: string): void;
set_description(description: string): void;
set_message(message: string): void;
set_password_new(new_password: boolean): void;
set_title(title: string): void;
set_warning(warning?: string | null): void;
vfunc_prompt_close(): void;
vfunc_prompt_confirm_async(
cancellable?: Gio.Cancellable | null
): Promise<Gcr.PromptReply>;
vfunc_prompt_confirm_async(
cancellable: Gio.Cancellable | null,
callback: Gio.AsyncReadyCallback<this> | null
): void;
vfunc_prompt_confirm_async(
cancellable?: Gio.Cancellable | null,
callback?: Gio.AsyncReadyCallback<this> | null
): Promise<Gcr.PromptReply> | void;
vfunc_prompt_confirm_finish(result: Gio.AsyncResult): Gcr.PromptReply;
vfunc_prompt_password_async(
cancellable?: Gio.Cancellable | null
): Promise<string>;
vfunc_prompt_password_async(
cancellable: Gio.Cancellable | null,
callback: Gio.AsyncReadyCallback<this> | null
): void;
vfunc_prompt_password_async(
cancellable?: Gio.Cancellable | null,
callback?: Gio.AsyncReadyCallback<this> | null
): Promise<string> | void;
vfunc_prompt_password_finish(result: Gio.AsyncResult): string;
}
export namespace MountOperation {
export interface ConstructorProperties
extends Gio.MountOperation.ConstructorProperties {
[key: string]: any;
}
}
export class MountOperation extends Gio.MountOperation {
static $gtype: GObject.GType<MountOperation>;
constructor(
properties?: Partial<MountOperation.ConstructorProperties>,
...args: any[]
);
_init(
properties?: Partial<MountOperation.ConstructorProperties>,
...args: any[]
): void;
// Signals
connect(id: string, callback: (...args: any[]) => any): number;
connect_after(id: string, callback: (...args: any[]) => any): number;
emit(id: string, ...args: any[]): void;
connect(
signal: 'show-processes-2',
callback: (_source: this) => void
): number;
connect_after(
signal: 'show-processes-2',
callback: (_source: this) => void
): number;
emit(signal: 'show-processes-2'): void;
// Constructors
static ['new'](): MountOperation;
// Members
get_show_processes_choices(): string[];
get_show_processes_message(): string;
get_show_processes_pids(): GLib.Pid[];
}
export namespace NetworkAgent {
export interface ConstructorProperties
extends NM.SecretAgentOld.ConstructorProperties {
[key: string]: any;
}
}
export class NetworkAgent
extends NM.SecretAgentOld
implements Gio.AsyncInitable<NetworkAgent>, Gio.Initable {
static $gtype: GObject.GType<NetworkAgent>;
constructor(
properties?: Partial<NetworkAgent.ConstructorProperties>,
...args: any[]
);
_init(
properties?: Partial<NetworkAgent.ConstructorProperties>,
...args: any[]
): void;
// Signals
connect(id: string, callback: (...args: any[]) => any): number;
connect_after(id: string, callback: (...args: any[]) => any): number;
emit(id: string, ...args: any[]): void;
connect(
signal: 'cancel-request',
callback: (_source: this, object: string) => void
): number;
connect_after(
signal: 'cancel-request',
callback: (_source: this, object: string) => void
): number;
emit(signal: 'cancel-request', object: string): void;
connect(
signal: 'new-request',
callback: (
_source: this,
object: string,
p0: NM.Connection,
p1: string,
p2: string[],
p3: number
) => void
): number;
connect_after(
signal: 'new-request',
callback: (
_source: this,
object: string,
p0: NM.Connection,
p1: string,
p2: string[],
p3: number
) => void
): number;
emit(
signal: 'new-request',
object: string,
p0: NM.Connection,
p1: string,
p2: string[],
p3: number
): void;
// Members
add_vpn_secret(
request_id: string,
setting_key: string,
setting_value: string
): void;
respond(request_id: string, response: NetworkAgentResponse): void;
search_vpn_plugin(service: string): Promise<NM.VpnPluginInfo | null>;
search_vpn_plugin(
service: string,
callback: Gio.AsyncReadyCallback<this> | null
): void;
search_vpn_plugin(
service: string,
callback?: Gio.AsyncReadyCallback<this> | null
): Promise<NM.VpnPluginInfo | null> | void;
search_vpn_plugin_finish(result: Gio.AsyncResult): NM.VpnPluginInfo | null;
set_password(
request_id: string,
setting_key: string,
setting_value: string
): void;
// Implemented Members
init_async(
io_priority: number,
cancellable?: Gio.Cancellable | null
): Promise<boolean>;
init_async(
io_priority: number,
cancellable: Gio.Cancellable | null,
callback: Gio.AsyncReadyCallback<this> | null
): void;
init_async(
io_priority: number,
cancellable?: Gio.Cancellable | null,
callback?: Gio.AsyncReadyCallback<this> | null
): Promise<boolean> | void;
init_finish(res: Gio.AsyncResult): boolean;
new_finish(res: Gio.AsyncResult): NetworkAgent;
vfunc_init_async(
io_priority: number,
cancellable?: Gio.Cancellable | null
): Promise<boolean>;
vfunc_init_async(
io_priority: number,
cancellable: Gio.Cancellable | null,
callback: Gio.AsyncReadyCallback<this> | null
): void;
vfunc_init_async(
io_priority: number,
cancellable?: Gio.Cancellable | null,
callback?: Gio.AsyncReadyCallback<this> | null
): Promise<boolean> | void;
vfunc_init_finish(res: Gio.AsyncResult): boolean;
init(cancellable?: Gio.Cancellable | null): boolean;
vfunc_init(cancellable?: Gio.Cancellable | null): boolean;
}
export namespace PerfLog {
export interface ConstructorProperties
extends GObject.Object.ConstructorProperties {
[key: string]: any;
}
}
export class PerfLog extends GObject.Object {
static $gtype: GObject.GType<PerfLog>;
constructor(
properties?: Partial<PerfLog.ConstructorProperties>,
...args: any[]
);
_init(
properties?: Partial<PerfLog.ConstructorProperties>,
...args: any[]
): void;
// Members
add_statistics_callback(callback: PerfStatisticsCallback): void;
collect_statistics(): void;
define_event(name: string, description: string, signature: string): void;
define_statistic(
name: string,
description: string,
signature: string
): void;
dump_events(out: Gio.OutputStream): boolean;
dump_log(out: Gio.OutputStream): boolean;
event(name: string): void;
event_i(name: string, arg: number): void;
event_s(name: string, arg: string): void;
event_x(name: string, arg: number): void;
replay(replay_function: PerfReplayFunction): void;
set_enabled(enabled: boolean): void;
update_statistic_i(name: string, value: number): void;
update_statistic_x(name: string, value: number): void;
static get_default(): PerfLog;
}
export namespace PolkitAuthenticationAgent {
export interface ConstructorProperties
extends PolkitAgent.Listener.ConstructorProperties {
[key: string]: any;
}
}
export class PolkitAuthenticationAgent extends PolkitAgent.Listener {
static $gtype: GObject.GType<PolkitAuthenticationAgent>;
constructor(
properties?: Partial<PolkitAuthenticationAgent.ConstructorProperties>,
...args: any[]
);
_init(
properties?: Partial<PolkitAuthenticationAgent.ConstructorProperties>,
...args: any[]
): void;
// Signals
connect(id: string, callback: (...args: any[]) => any): number;
connect_after(id: string, callback: (...args: any[]) => any): number;
emit(id: string, ...args: any[]): void;
connect(signal: 'cancel', callback: (_source: this) => void): number;
connect_after(signal: 'cancel', callback: (_source: this) => void): number;
emit(signal: 'cancel'): void;
connect(
signal: 'initiate',
callback: (
_source: this,
object: string,
p0: string,
p1: string,
p2: string,
p3: string[]
) => void
): number;
connect_after(
signal: 'initiate',
callback: (
_source: this,
object: string,
p0: string,
p1: string,
p2: string,
p3: string[]
) => void
): number;
emit(
signal: 'initiate',
object: string,
p0: string,
p1: string,
p2: string,
p3: string[]
): void;
// Constructors
static ['new'](): PolkitAuthenticationAgent;
// Members
complete(dismissed: boolean): void;
register(): void;
register(...args: never[]): never;
unregister(): void;
unregister(...args: never[]): never;
}
export namespace Screenshot {
export interface ConstructorProperties
extends GObject.Object.ConstructorProperties {
[key: string]: any;
}
}
export class Screenshot extends GObject.Object {
static $gtype: GObject.GType<Screenshot>;
constructor(
properties?: Partial<Screenshot.ConstructorProperties>,
...args: any[]
);
_init(
properties?: Partial<Screenshot.ConstructorProperties>,
...args: any[]
): void;
// Constructors
static ['new'](): Screenshot;
// Members
pick_color(x: number, y: number): Promise<[Clutter.Color]>;
pick_color(
x: number,
y: number,
callback: Gio.AsyncReadyCallback<this> | null
): void;
pick_color(
x: number,
y: number,
callback?: Gio.AsyncReadyCallback<this> | null
): Promise<[Clutter.Color]> | void;
pick_color_finish(result: Gio.AsyncResult): [boolean, Clutter.Color];
screenshot(
include_cursor: boolean,
stream: Gio.OutputStream
): Promise<[cairo.RectangleInt]>;
screenshot(
include_cursor: boolean,
stream: Gio.OutputStream,
callback: Gio.AsyncReadyCallback<this> | null
): void;
screenshot(
include_cursor: boolean,
stream: Gio.OutputStream,
callback?: Gio.AsyncReadyCallback<this> | null
): Promise<[cairo.RectangleInt]> | void;
screenshot_area(
x: number,
y: number,
width: number,
height: number,
stream: Gio.OutputStream
): Promise<[cairo.RectangleInt]>;
screenshot_area(
x: number,
y: number,
width: number,
height: number,
stream: Gio.OutputStream,
callback: Gio.AsyncReadyCallback<this> | null
): void;
screenshot_area(
x: number,
y: number,
width: number,
height: number,
stream: Gio.OutputStream,
callback?: Gio.AsyncReadyCallback<this> | null
): Promise<[cairo.RectangleInt]> | void;
screenshot_area_finish(
result: Gio.AsyncResult
): [boolean, cairo.RectangleInt];
screenshot_finish(result: Gio.AsyncResult): [boolean, cairo.RectangleInt];
screenshot_window(
include_frame: boolean,
include_cursor: boolean,
stream: Gio.OutputStream
): Promise<[cairo.RectangleInt]>;
screenshot_window(
include_frame: boolean,
include_cursor: boolean,
stream: Gio.OutputStream,
callback: Gio.AsyncReadyCallback<this> | null
): void;
screenshot_window(
include_frame: boolean,
include_cursor: boolean,
stream: Gio.OutputStream,
callback?: Gio.AsyncReadyCallback<this> | null
): Promise<[cairo.RectangleInt]> | void;
screenshot_window_finish(
result: Gio.AsyncResult
): [boolean, cairo.RectangleInt];
}
export namespace SecureTextBuffer {
export interface ConstructorProperties
extends Clutter.TextBuffer.ConstructorProperties {
[key: string]: any;
}
}
export class SecureTextBuffer extends Clutter.TextBuffer {
static $gtype: GObject.GType<SecureTextBuffer>;
constructor(
properties?: Partial<SecureTextBuffer.ConstructorProperties>,
...args: any[]
);
_init(
properties?: Partial<SecureTextBuffer.ConstructorProperties>,
...args: any[]
): void;
// Constructors
static ['new'](): SecureTextBuffer;
}
export namespace Stack {
export interface ConstructorProperties<
A extends Clutter.Actor = Clutter.Actor
> extends St.Widget.ConstructorProperties {
[key: string]: any;
}
}
export class Stack<A extends Clutter.Actor = Clutter.Actor>
extends St.Widget
implements
Atk.ImplementorIface,
Clutter.Animatable,
Clutter.Container<A>,
Clutter.Scriptable {
static $gtype: GObject.GType<Stack>;
constructor(
properties?: Partial<Stack.ConstructorProperties<A>>,
...args: any[]
);
_init(
properties?: Partial<Stack.ConstructorProperties<A>>,
...args: any[]
): void;
// Implemented Members
find_property(property_name: string): GObject.ParamSpec;
get_actor(): Clutter.Actor;
get_initial_state(property_name: string, value: any): void;
interpolate_value(
property_name: string,
interval: Clutter.Interval,
progress: number
): [boolean, unknown];
set_final_state(property_name: string, value: any): void;
vfunc_find_property(property_name: string): GObject.ParamSpec;
vfunc_get_actor(): Clutter.Actor;
vfunc_get_initial_state(property_name: string, value: any): void;
vfunc_interpolate_value(
property_name: string,
interval: Clutter.Interval,
progress: number
): [boolean, unknown];
vfunc_set_final_state(property_name: string, value: any): void;
add_actor(actor: A): void;
child_get_property(child: A, property: string, value: any): void;
child_notify(child: A, pspec: GObject.ParamSpec): void;
child_set_property(child: A, property: string, value: any): void;
create_child_meta(actor: A): void;
destroy_child_meta(actor: A): void;
find_child_by_name(child_name: string): A;
get_child_meta(actor: A): Clutter.ChildMeta;
get_children(): A[];
get_children(...args: never[]): never;
lower_child(actor: A, sibling?: A | null): void;
raise_child(actor: A, sibling?: A | null): void;
remove_actor(actor: A): void;
sort_depth_order(): void;
vfunc_actor_added(actor: A): void;
vfunc_actor_removed(actor: A): void;
vfunc_add(actor: A): void;
vfunc_child_notify(child: A, pspec: GObject.ParamSpec): void;
vfunc_create_child_meta(actor: A): void;
vfunc_destroy_child_meta(actor: A): void;
vfunc_get_child_meta(actor: A): Clutter.ChildMeta;
vfunc_lower(actor: A, sibling?: A | null): void;
vfunc_raise(actor: A, sibling?: A | null): void;
vfunc_remove(actor: A): void;
vfunc_sort_depth_order(): void;
get_id(): string;
parse_custom_node(
script: Clutter.Script,
value: any,
name: string,
node: Json.Node
): boolean;
set_custom_property(script: Clutter.Script, name: string, value: any): void;
set_id(id_: string): void;
vfunc_get_id(): string;
vfunc_parse_custom_node(
script: Clutter.Script,
value: any,
name: string,
node: Json.Node
): boolean;
vfunc_set_custom_property(
script: Clutter.Script,
name: string,
value: any
): void;
vfunc_set_id(id_: string): void;
}
export namespace TrayIcon {
export interface ConstructorProperties<
A extends Clutter.Actor = Clutter.Actor
> extends GtkEmbed.ConstructorProperties<A> {
[key: string]: any;
pid: number;
title: string;
wm_class: string;
wmClass: string;
}
}
export class TrayIcon<A extends Clutter.Actor = Clutter.Actor>
extends GtkEmbed<A>
implements
Atk.ImplementorIface,
Clutter.Animatable,
Clutter.Container<A>,
Clutter.Scriptable {
static $gtype: GObject.GType<TrayIcon>;
constructor(
properties?: Partial<TrayIcon.ConstructorProperties<A>>,
...args: any[]
);
_init(
properties?: Partial<TrayIcon.ConstructorProperties<A>>,
...args: any[]
): void;
// Properties
pid: number;
title: string;
wm_class: string;
wmClass: string;
// Constructors
static ['new'](window: EmbeddedWindow): TrayIcon;
static ['new'](...args: never[]): never;
// Members
click(event: Clutter.Event): void;
// Implemented Members
find_property(property_name: string): GObject.ParamSpec;
get_actor(): Clutter.Actor;
get_initial_state(property_name: string, value: any): void;
interpolate_value(
property_name: string,
interval: Clutter.Interval,
progress: number
): [boolean, unknown];
set_final_state(property_name: string, value: any): void;
vfunc_find_property(property_name: string): GObject.ParamSpec;
vfunc_get_actor(): Clutter.Actor;
vfunc_get_initial_state(property_name: string, value: any): void;
vfunc_interpolate_value(
property_name: string,
interval: Clutter.Interval,
progress: number
): [boolean, unknown];
vfunc_set_final_state(property_name: string, value: any): void;
add_actor(actor: A): void;
child_get_property(child: A, property: string, value: any): void;
child_notify(child: A, pspec: GObject.ParamSpec): void;
child_set_property(child: A, property: string, value: any): void;
create_child_meta(actor: A): void;
destroy_child_meta(actor: A): void;
find_child_by_name(child_name: string): A;
get_child_meta(actor: A): Clutter.ChildMeta;
get_children(): A[];
get_children(...args: never[]): never;
lower_child(actor: A, sibling?: A | null): void;
raise_child(actor: A, sibling?: A | null): void;
remove_actor(actor: A): void;
sort_depth_order(): void;
vfunc_actor_added(actor: A): void;
vfunc_actor_removed(actor: A): void;
vfunc_add(actor: A): void;
vfunc_child_notify(child: A, pspec: GObject.ParamSpec): void;
vfunc_create_child_meta(actor: A): void;
vfunc_destroy_child_meta(actor: A): void;
vfunc_get_child_meta(actor: A): Clutter.ChildMeta;
vfunc_lower(actor: A, sibling?: A | null): void;
vfunc_raise(actor: A, sibling?: A | null): void;
vfunc_remove(actor: A): void;
vfunc_sort_depth_order(): void;
get_id(): string;
parse_custom_node(
script: Clutter.Script,
value: any,
name: string,
node: Json.Node
): boolean;
set_custom_property(script: Clutter.Script, name: string, value: any): void;
set_id(id_: string): void;
vfunc_get_id(): string;
vfunc_parse_custom_node(
script: Clutter.Script,
value: any,
name: string,
node: Json.Node
): boolean;
vfunc_set_custom_property(
script: Clutter.Script,
name: string,
value: any
): void;
vfunc_set_id(id_: string): void;
}
export namespace TrayManager {
export interface ConstructorProperties
extends GObject.Object.ConstructorProperties {
[key: string]: any;
bg_color: Clutter.Color;
bgColor: Clutter.Color;
}
}
export class TrayManager extends GObject.Object {
static $gtype: GObject.GType<TrayManager>;
constructor(
properties?: Partial<TrayManager.ConstructorProperties>,
...args: any[]
);
_init(
properties?: Partial<TrayManager.ConstructorProperties>,
...args: any[]
): void;
// Properties
bg_color: Clutter.Color;
bgColor: Clutter.Color;
// Signals
connect(id: string, callback: (...args: any[]) => any): number;
connect_after(id: string, callback: (...args: any[]) => any): number;
emit(id: string, ...args: any[]): void;
connect(
signal: 'tray-icon-added',
callback: (_source: this, object: Clutter.Actor) => void
): number;
connect_after(
signal: 'tray-icon-added',
callback: (_source: this, object: Clutter.Actor) => void
): number;
emit(signal: 'tray-icon-added', object: Clutter.Actor): void;
connect(
signal: 'tray-icon-removed',
callback: (_source: this, object: Clutter.Actor) => void
): number;
connect_after(
signal: 'tray-icon-removed',
callback: (_source: this, object: Clutter.Actor) => void
): number;
emit(signal: 'tray-icon-removed', object: Clutter.Actor): void;
// Constructors
static ['new'](): TrayManager;
// Members
manage_screen(theme_widget: St.Widget): void;
unmanage_screen(): void;
}
export namespace WM {
export interface ConstructorProperties
extends GObject.Object.ConstructorProperties {
[key: string]: any;
}
}
export class WM extends GObject.Object {
static $gtype: GObject.GType<WM>;
constructor(properties?: Partial<WM.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<WM.ConstructorProperties>, ...args: any[]): void;
// Signals
connect(id: string, callback: (...args: any[]) => any): number;
connect_after(id: string, callback: (...args: any[]) => any): number;
emit(id: string, ...args: any[]): void;
connect(
signal: 'confirm-display-change',
callback: (_source: this) => void
): number;
connect_after(
signal: 'confirm-display-change',
callback: (_source: this) => void
): number;
emit(signal: 'confirm-display-change'): void;
connect(
signal: 'create-close-dialog',
callback: (_source: this, window: Meta.Window) => Meta.CloseDialog
): number;
connect_after(
signal: 'create-close-dialog',
callback: (_source: this, window: Meta.Window) => Meta.CloseDialog
): number;
emit(signal: 'create-close-dialog', window: Meta.Window): void;
connect(
signal: 'create-inhibit-shortcuts-dialog',
callback: (
_source: this,
window: Meta.Window
) => Meta.InhibitShortcutsDialog
): number;
connect_after(
signal: 'create-inhibit-shortcuts-dialog',
callback: (
_source: this,
window: Meta.Window
) => Meta.InhibitShortcutsDialog
): number;
emit(signal: 'create-inhibit-shortcuts-dialog', window: Meta.Window): void;
connect(
signal: 'destroy',
callback: (_source: this, object: Meta.WindowActor) => void
): number;
connect_after(
signal: 'destroy',
callback: (_source: this, object: Meta.WindowActor) => void
): number;
emit(signal: 'destroy', object: Meta.WindowActor): void;
connect(
signal: 'filter-keybinding',
callback: (_source: this, object: Meta.KeyBinding) => boolean
): number;
connect_after(
signal: 'filter-keybinding',
callback: (_source: this, object: Meta.KeyBinding) => boolean
): number;
emit(signal: 'filter-keybinding', object: Meta.KeyBinding): void;
connect(
signal: 'hide-tile-preview',
callback: (_source: this) => void
): number;
connect_after(
signal: 'hide-tile-preview',
callback: (_source: this) => void
): number;
emit(signal: 'hide-tile-preview'): void;
connect(
signal: 'kill-switch-workspace',
callback: (_source: this) => void
): number;
connect_after(
signal: 'kill-switch-workspace',
callback: (_source: this) => void
): number;
emit(signal: 'kill-switch-workspace'): void;
connect(
signal: 'kill-window-effects',
callback: (_source: this, object: Meta.WindowActor) => void
): number;
connect_after(
signal: 'kill-window-effects',
callback: (_source: this, object: Meta.WindowActor) => void
): number;
emit(signal: 'kill-window-effects', object: Meta.WindowActor): void;
connect(
signal: 'map',
callback: (_source: this, object: Meta.WindowActor) => void
): number;
connect_after(
signal: 'map',
callback: (_source: this, object: Meta.WindowActor) => void
): number;
emit(signal: 'map', object: Meta.WindowActor): void;
connect(
signal: 'minimize',
callback: (_source: this, object: Meta.WindowActor) => void
): number;
connect_after(
signal: 'minimize',
callback: (_source: this, object: Meta.WindowActor) => void
): number;
emit(signal: 'minimize', object: Meta.WindowActor): void;
connect(
signal: 'show-tile-preview',
callback: (
_source: this,
object: Meta.Window,
p0: Meta.Rectangle,
p1: number
) => void
): number;
connect_after(
signal: 'show-tile-preview',
callback: (
_source: this,
object: Meta.Window,
p0: Meta.Rectangle,
p1: number
) => void
): number;
emit(
signal: 'show-tile-preview',
object: Meta.Window,
p0: Meta.Rectangle,
p1: number
): void;
connect(
signal: 'show-window-menu',
callback: (
_source: this,
object: Meta.Window,
p0: number,
p1: Meta.Rectangle
) => void
): number;
connect_after(
signal: 'show-window-menu',
callback: (
_source: this,
object: Meta.Window,
p0: number,
p1: Meta.Rectangle
) => void
): number;
emit(
signal: 'show-window-menu',
object: Meta.Window,
p0: number,
p1: Meta.Rectangle
): void;
connect(
signal: 'size-change',
callback: (
_source: this,
object: Meta.WindowActor,
p0: Meta.SizeChange,
p1: Meta.Rectangle,
p2: Meta.Rectangle
) => void
): number;
connect_after(
signal: 'size-change',
callback: (
_source: this,
object: Meta.WindowActor,
p0: Meta.SizeChange,
p1: Meta.Rectangle,
p2: Meta.Rectangle
) => void
): number;
emit(
signal: 'size-change',
object: Meta.WindowActor,
p0: Meta.SizeChange,
p1: Meta.Rectangle,
p2: Meta.Rectangle
): void;
connect(
signal: 'size-changed',
callback: (_source: this, object: Meta.WindowActor) => void
): number;
connect_after(
signal: 'size-changed',
callback: (_source: this, object: Meta.WindowActor) => void
): number;
emit(signal: 'size-changed', object: Meta.WindowActor): void;
connect(
signal: 'switch-workspace',
callback: (
_source: this,
object: number,
p0: number,
p1: number
) => void
): number;
connect_after(
signal: 'switch-workspace',
callback: (
_source: this,
object: number,
p0: number,
p1: number
) => void
): number;
emit(
signal: 'switch-workspace',
object: number,
p0: number,
p1: number
): void;
connect(
signal: 'unminimize',
callback: (_source: this, object: Meta.WindowActor) => void
): number;
connect_after(
signal: 'unminimize',
callback: (_source: this, object: Meta.WindowActor) => void
): number;
emit(signal: 'unminimize', object: Meta.WindowActor): void;
// Constructors
static ['new'](plugin: Meta.Plugin): WM;
// Members
complete_display_change(ok: boolean): void;
completed_destroy(actor: Meta.WindowActor): void;
completed_map(actor: Meta.WindowActor): void;
completed_minimize(actor: Meta.WindowActor): void;
completed_size_change(actor: Meta.WindowActor): void;
completed_switch_workspace(): void;
completed_unminimize(actor: Meta.WindowActor): void;
}
export namespace WindowTracker {
export interface ConstructorProperties
extends GObject.Object.ConstructorProperties {
[key: string]: any;
focus_app: App;
focusApp: App;
}
}
export class WindowTracker extends GObject.Object {
static $gtype: GObject.GType<WindowTracker>;
constructor(
properties?: Partial<WindowTracker.ConstructorProperties>,
...args: any[]
);
_init(
properties?: Partial<WindowTracker.ConstructorProperties>,
...args: any[]
): void;
// Properties
focus_app: App;
focusApp: App;
// Signals
connect(id: string, callback: (...args: any[]) => any): number;
connect_after(id: string, callback: (...args: any[]) => any): number;
emit(id: string, ...args: any[]): void;
connect(
signal: 'startup-sequence-changed',
callback: (_source: this, object: Meta.StartupSequence) => void
): number;
connect_after(
signal: 'startup-sequence-changed',
callback: (_source: this, object: Meta.StartupSequence) => void
): number;
emit(
signal: 'startup-sequence-changed',
object: Meta.StartupSequence
): void;
connect(
signal: 'tracked-windows-changed',
callback: (_source: this) => void
): number;
connect_after(
signal: 'tracked-windows-changed',
callback: (_source: this) => void
): number;
emit(signal: 'tracked-windows-changed'): void;
// Members
get_app_from_pid(pid: number): App;
get_startup_sequences(): Meta.StartupSequence[];
get_window_app(metawin: Meta.Window): App;
static get_default(): WindowTracker;
}
export class MemoryInfo {
static $gtype: GObject.GType<MemoryInfo>;
constructor(
properties?: Partial<{
glibc_uordblks?: number;
js_bytes?: number;
gjs_boxed?: number;
gjs_gobject?: number;
gjs_function?: number;
gjs_closure?: number;
last_gc_seconds_ago?: number;
}>
);
constructor(copy: MemoryInfo);
// Fields
glibc_uordblks: number;
js_bytes: number;
gjs_boxed: number;
gjs_gobject: number;
gjs_function: number;
gjs_closure: number;
last_gc_seconds_ago: number;
}
export class NetworkAgentPrivate {
static $gtype: GObject.GType<NetworkAgentPrivate>;
constructor(copy: NetworkAgentPrivate);
} | the_stack |
* Extension startup/teardown
*/
'use strict';
import * as chokidar from 'chokidar';
import * as path from 'path';
import * as vscode from 'vscode';
import * as cpt from 'vscode-cpptools';
import * as nls from 'vscode-nls';
import { CMakeCache } from '@cmt/cache';
import { CMakeTools, ConfigureType, ConfigureTrigger } from '@cmt/cmakeTools';
import { ConfigurationReader, TouchBarConfig } from '@cmt/config';
import { CppConfigurationProvider, DiagnosticsCpptools } from '@cmt/cpptools';
import { CMakeToolsFolderController, CMakeToolsFolder, DiagnosticsConfiguration, DiagnosticsSettings } from '@cmt/folders';
import {
Kit,
USER_KITS_FILEPATH,
findCLCompilerPath,
scanForKitsIfNeeded
} from '@cmt/kit';
import { IExperimentationService } from 'vscode-tas-client';
import { KitsController } from '@cmt/kitsController';
import * as logging from '@cmt/logging';
import { fs } from '@cmt/pr';
import { FireNow, FireLate } from '@cmt/prop';
import rollbar from '@cmt/rollbar';
import { StateManager } from './state';
import { StatusBar } from '@cmt/status';
import { CMakeTaskProvider } from '@cmt/cmakeTaskProvider';
import * as telemetry from '@cmt/telemetry';
import { ProjectOutlineProvider, TargetNode, SourceFileNode, WorkspaceFolderNode } from '@cmt/tree';
import * as util from '@cmt/util';
import { ProgressHandle, DummyDisposable, reportProgress } from '@cmt/util';
import { DEFAULT_VARIANTS } from '@cmt/variant';
import { expandString, KitContextVars } from '@cmt/expand';
import paths from '@cmt/paths';
import { CMakeDriver, CMakePreconditionProblems } from './drivers/cmakeDriver';
import { platform } from 'os';
nls.config({ messageFormat: nls.MessageFormat.bundle, bundleFormat: nls.BundleFormat.standalone })();
const localize: nls.LocalizeFunc = nls.loadMessageBundle();
export const cmakeTaskProvider: CMakeTaskProvider = new CMakeTaskProvider();
let taskProvider: vscode.Disposable;
const log = logging.createLogger('extension');
const multiRootModeKey = 'cmake:multiRoot';
const hideLaunchCommandKey = 'cmake:hideLaunchCommand';
const hideDebugCommandKey = 'cmake:hideDebugCommand';
const hideBuildCommandKey = 'cmake:hideBuildCommand';
/**
* The global extension manager. There is only one of these, even if multiple
* backends.
*/
let extensionManager: ExtensionManager | null = null;
type CMakeToolsMapFn = (cmt: CMakeTools) => Thenable<any>;
type CMakeToolsQueryMapFn = (cmt: CMakeTools) => Thenable<string | string[] | null>;
interface Diagnostics {
os: string;
vscodeVersion: string;
cmtVersion: string;
configurations: DiagnosticsConfiguration[];
settings: DiagnosticsSettings[];
cpptoolsIntegration: DiagnosticsCpptools;
}
/**
* A class to manage the extension.
*
* Yeah, yeah. It's another "Manager", but this is to be the only one.
*
* This is the true "singleton" of the extension. It acts as the glue between
* the lower layers and the VSCode UX. When a user presses a button to
* necessitate user input, this class acts as intermediary and will send
* important information down to the lower layers.
*/
class ExtensionManager implements vscode.Disposable {
constructor(public readonly extensionContext: vscode.ExtensionContext) {
telemetry.activate(extensionContext);
this.showCMakeLists = new Promise<boolean>(resolve => {
const experimentationService: Promise<IExperimentationService | undefined> | undefined = telemetry.getExperimentationService();
if (experimentationService) {
void experimentationService
.then(expSrv => expSrv!.getTreatmentVariableAsync<boolean>("vscode", "partialActivation_showCMakeLists"))
.then(showCMakeLists => {
if (showCMakeLists !== undefined) {
resolve(showCMakeLists);
} else {
resolve(false);
}
});
} else {
resolve(false);
}
});
this.folders.onAfterAddFolder(async cmtFolder => {
console.assert(this.folders.size === vscode.workspace.workspaceFolders?.length);
if (this.folders.size === 1) {
// First folder added
await this.setActiveFolder(vscode.workspace.workspaceFolders![0]);
} else if (this.folders.isMultiRoot) {
// Call initActiveFolder instead of just setupSubscriptions, since the active editor/file may not
// be in currently opened workspaces, and may be in the newly opened workspace.
await this.initActiveFolder();
await util.setContextValue(multiRootModeKey, true);
// sub go text edit change event in multiroot mode
if (this.workspaceConfig.autoSelectActiveFolder) {
this.onDidChangeActiveTextEditorSub.dispose();
this.onDidChangeActiveTextEditorSub = vscode.window.onDidChangeActiveTextEditor(e => this.onDidChangeActiveTextEditor(e), this);
}
}
const newCmt = cmtFolder.cmakeTools;
this.projectOutlineProvider.addFolder(cmtFolder.folder);
if (this.codeModelUpdateSubs.get(newCmt.folder.uri.fsPath)) {
// We already have this folder, do nothing
} else {
const subs: vscode.Disposable[] = [];
subs.push(newCmt.onCodeModelChanged(FireLate, () => this.updateCodeModel(cmtFolder)));
subs.push(newCmt.onTargetNameChanged(FireLate, () => this.updateCodeModel(cmtFolder)));
subs.push(newCmt.onLaunchTargetNameChanged(FireLate, () => this.updateCodeModel(cmtFolder)));
subs.push(newCmt.onActiveBuildPresetChanged(FireLate, () => this.updateCodeModel(cmtFolder)));
this.codeModelUpdateSubs.set(newCmt.folder.uri.fsPath, subs);
}
rollbar.takePromise('Post-folder-open', { folder: cmtFolder.folder }, this.postWorkspaceOpen(cmtFolder));
});
this.folders.onAfterRemoveFolder(async folder => {
console.assert((vscode.workspace.workspaceFolders === undefined && this.folders.size === 0) ||
(vscode.workspace.workspaceFolders !== undefined && vscode.workspace.workspaceFolders.length === this.folders.size));
this.codeModelUpdateSubs.delete(folder.uri.fsPath);
if (!vscode.workspace.workspaceFolders?.length) {
await this.setActiveFolder(undefined);
} else {
if (this.folders.activeFolder?.folder.uri.fsPath === folder.uri.fsPath) {
await this.setActiveFolder(vscode.workspace.workspaceFolders[0]);
} else {
this.setupSubscriptions();
}
await util.setContextValue(multiRootModeKey, this.folders.isMultiRoot);
// Update the full/partial view of the workspace by verifying if after the folder removal
// it still has at least one CMake project.
await enableFullFeatureSet(await this.workspaceHasCMakeProject());
}
this.onDidChangeActiveTextEditorSub.dispose();
if (this.folders.isMultiRoot && this.workspaceConfig.autoSelectActiveFolder) {
this.onDidChangeActiveTextEditorSub = vscode.window.onDidChangeActiveTextEditor(e => this.onDidChangeActiveTextEditor(e), this);
} else {
this.onDidChangeActiveTextEditorSub = new DummyDisposable();
}
this.projectOutlineProvider.removeFolder(folder);
});
this.workspaceConfig.onChange('autoSelectActiveFolder', v => {
if (this.folders.isMultiRoot) {
telemetry.logEvent('configChanged.autoSelectActiveFolder', { autoSelectActiveFolder: `${v}` });
this.onDidChangeActiveTextEditorSub.dispose();
if (v) {
this.onDidChangeActiveTextEditorSub = vscode.window.onDidChangeActiveTextEditor(e => this.onDidChangeActiveTextEditor(e), this);
} else {
this.onDidChangeActiveTextEditorSub = new DummyDisposable();
}
}
this.statusBar.setAutoSelectActiveFolder(v);
});
}
private onDidChangeActiveTextEditorSub: vscode.Disposable = new DummyDisposable();
private onUseCMakePresetsChangedSub: vscode.Disposable = new DummyDisposable();
private readonly workspaceConfig: ConfigurationReader = ConfigurationReader.create();
private updateTouchBarVisibility(config: TouchBarConfig) {
const touchBarVisible = config.visibility === "default";
void util.setContextValue("cmake:enableTouchBar", touchBarVisible);
void util.setContextValue("cmake:enableTouchBar.build", touchBarVisible && !(config.advanced?.build === "hidden"));
void util.setContextValue("cmake:enableTouchBar.configure", touchBarVisible && !(config.advanced?.configure === "hidden"));
void util.setContextValue("cmake:enableTouchBar.debug", touchBarVisible && !(config.advanced?.debug === "hidden"));
void util.setContextValue("cmake:enableTouchBar.launch", touchBarVisible && !(config.advanced?.launch === "hidden"));
}
/**
* Second-phase async init
*/
private async init() {
this.updateTouchBarVisibility(this.workspaceConfig.touchbar);
this.workspaceConfig.onChange('touchbar', config => this.updateTouchBarVisibility(config));
let isMultiRoot = false;
if (vscode.workspace.workspaceFolders) {
await this.folders.loadAllCurrent();
isMultiRoot = this.folders.isMultiRoot;
await util.setContextValue(multiRootModeKey, isMultiRoot);
this.projectOutlineProvider.addAllCurrentFolders();
if (this.workspaceConfig.autoSelectActiveFolder && isMultiRoot) {
this.statusBar.setAutoSelectActiveFolder(true);
this.onDidChangeActiveTextEditorSub.dispose();
this.onDidChangeActiveTextEditorSub = vscode.window.onDidChangeActiveTextEditor(e => this.onDidChangeActiveTextEditor(e), this);
}
await this.initActiveFolder();
for (const cmtFolder of this.folders) {
this.onUseCMakePresetsChangedSub = cmtFolder.onUseCMakePresetsChanged(useCMakePresets => this.statusBar.useCMakePresets(useCMakePresets));
this.codeModelUpdateSubs.set(cmtFolder.folder.uri.fsPath, [
cmtFolder.cmakeTools.onCodeModelChanged(FireLate, () => this.updateCodeModel(cmtFolder)),
cmtFolder.cmakeTools.onTargetNameChanged(FireLate, () => this.updateCodeModel(cmtFolder)),
cmtFolder.cmakeTools.onLaunchTargetNameChanged(FireLate, () => this.updateCodeModel(cmtFolder)),
cmtFolder.cmakeTools.onActiveBuildPresetChanged(FireLate, () => this.updateCodeModel(cmtFolder))
]);
rollbar.takePromise('Post-folder-open', { folder: cmtFolder.folder }, this.postWorkspaceOpen(cmtFolder));
}
}
const isFullyActivated: boolean = await this.workspaceHasCMakeProject();
if (isFullyActivated) {
await enableFullFeatureSet(true);
}
const telemetryProperties: telemetry.Properties = {
isMultiRoot: `${isMultiRoot}`,
isFullyActivated: `${isFullyActivated}`
};
if (isMultiRoot) {
telemetryProperties['autoSelectActiveFolder'] = `${this.workspaceConfig.autoSelectActiveFolder}`;
}
telemetry.sendOpenTelemetry(telemetryProperties);
}
public getFolderContext(folder: vscode.WorkspaceFolder): StateManager {
return new StateManager(this.extensionContext, folder);
}
public showStatusBar(fullFeatureSet: boolean) {
this.statusBar.setVisible(fullFeatureSet);
}
public getCMTFolder(folder: vscode.WorkspaceFolder): CMakeToolsFolder | undefined {
return this.folders.get(folder);
}
public isActiveFolder(cmt: CMakeToolsFolder): boolean {
return this.folders.activeFolder === cmt;
}
/**
* Create a new extension manager instance. There must only be one!
* @param ctx The extension context
*/
static async create(ctx: vscode.ExtensionContext) {
const inst = new ExtensionManager(ctx);
await inst.init();
return inst;
}
private showCMakeLists: Promise<boolean>;
public showCMakeListsExperiment(): Promise<boolean> {
return this.showCMakeLists;
}
/**
* The folder controller manages multiple instances. One per folder.
*/
private readonly folders = new CMakeToolsFolderController(this.extensionContext);
/**
* The map caching for each folder whether it is a CMake project or not.
*/
private readonly isCMakeFolder: Map<string, boolean> = new Map<string, boolean>();
/**
* The status bar controller
*/
private readonly statusBar = new StatusBar(this.workspaceConfig);
// Subscriptions for status bar items:
private statusMessageSub: vscode.Disposable = new DummyDisposable();
private targetNameSub: vscode.Disposable = new DummyDisposable();
private buildTypeSub: vscode.Disposable = new DummyDisposable();
private launchTargetSub: vscode.Disposable = new DummyDisposable();
private ctestEnabledSub: vscode.Disposable = new DummyDisposable();
private testResultsSub: vscode.Disposable = new DummyDisposable();
private isBusySub: vscode.Disposable = new DummyDisposable();
private activeConfigurePresetSub: vscode.Disposable = new DummyDisposable();
private activeBuildPresetSub: vscode.Disposable = new DummyDisposable();
private activeTestPresetSub: vscode.Disposable = new DummyDisposable();
// Watch the code model so that we may update teh tree view
// <fspath, sub>
private readonly codeModelUpdateSubs = new Map<string, vscode.Disposable[]>();
/**
* The project outline tree data provider
*/
private readonly projectOutlineProvider = new ProjectOutlineProvider();
private readonly projectOutlineTreeView = vscode.window.createTreeView('cmake.outline', {
treeDataProvider: this.projectOutlineProvider,
showCollapseAll: true
});
/**
* CppTools project configuration provider. Tells cpptools how to search for
* includes, preprocessor defs, etc.
*/
private readonly configProvider = new CppConfigurationProvider();
private cppToolsAPI?: cpt.CppToolsApi;
private configProviderRegistered?: boolean = false;
private checkFolderArgs(folder?: vscode.WorkspaceFolder): CMakeToolsFolder | undefined {
let cmtFolder: CMakeToolsFolder | undefined;
if (folder) {
cmtFolder = this.folders.get(folder);
} else if (this.folders.activeFolder) {
cmtFolder = this.folders.activeFolder;
}
return cmtFolder;
}
private checkStringFolderArgs(folder?: vscode.WorkspaceFolder | string): vscode.WorkspaceFolder | undefined {
if (vscode.workspace.workspaceFolders && vscode.workspace.workspaceFolders.length === 1) {
// We don't want to break existing setup for single root projects.
return vscode.workspace.workspaceFolders[0];
}
if (util.isString(folder)) {
// Expected schema is file...
return vscode.workspace.getWorkspaceFolder(vscode.Uri.file(folder as string));
}
const workspaceFolder = folder as vscode.WorkspaceFolder;
if (util.isNullOrUndefined(folder) || util.isNullOrUndefined(workspaceFolder.uri)) {
return this.folders.activeFolder?.folder;
}
return workspaceFolder;
}
private async pickFolder() {
const selection = await vscode.window.showWorkspaceFolderPick();
if (selection) {
const cmtFolder = this.folders.get(selection);
console.assert(cmtFolder, 'Folder not found in folder controller.');
return cmtFolder;
}
}
/**
* Ensure that there is an active kit or configure preset for the current CMakeTools.
*
* @returns `false` if there is not active CMakeTools, or it has no active kit
* and the user cancelled the kit selection dialog.
*/
private async ensureActiveConfigurePresetOrKit(cmt?: CMakeTools): Promise<boolean> {
if (!cmt) {
cmt = this.folders.activeFolder?.cmakeTools;
}
if (!cmt) {
// No CMakeTools. Probably no workspace open.
return false;
}
if (cmt.useCMakePresets) {
if (cmt.configurePreset) {
return true;
}
const didChoosePreset = await this.selectConfigurePreset(cmt.folder);
if (!didChoosePreset && !cmt.configurePreset) {
return false;
}
return !!cmt.configurePreset;
} else {
if (cmt.activeKit) {
// We have an active kit. We're good.
return true;
}
// No kit? Ask the user what they want.
const didChooseKit = await this.selectKit(cmt.folder);
if (!didChooseKit && !cmt.activeKit) {
// The user did not choose a kit and kit isn't set in other way such as setKitByName
return false;
}
// Return whether we have an active kit defined.
return !!cmt.activeKit;
}
}
/**
* Ensure that there is an active build preset for the current CMakeTools.
* We pass this in function calls so make it an lambda instead of a function.
*
* @returns `false` if there is not active CMakeTools, or it has no active preset
* and the user cancelled the preset selection dialog.
*/
private readonly ensureActiveBuildPreset = async (cmt?: CMakeTools): Promise<boolean> => {
if (!cmt) {
cmt = this.folders.activeFolder?.cmakeTools;
}
if (!cmt) {
// No CMakeTools. Probably no workspace open.
return false;
}
if (cmt.useCMakePresets) {
if (cmt.buildPreset) {
return true;
}
const didChoosePreset = await this.selectBuildPreset(cmt.folder);
if (!didChoosePreset && !cmt.buildPreset) {
return false;
}
return !!cmt.buildPreset;
}
return true;
};
private readonly ensureActiveTestPreset = async (cmt?: CMakeTools): Promise<boolean> => {
if (!cmt) {
cmt = this.folders.activeFolder?.cmakeTools;
}
if (!cmt) {
// No CMakeTools. Probably no workspace open.
return false;
}
if (cmt.useCMakePresets) {
if (cmt.testPreset) {
return true;
}
const didChoosePreset = await this.selectTestPreset(cmt.folder);
if (!didChoosePreset && !cmt.testPreset) {
return false;
}
return !!cmt.testPreset;
}
return true;
};
/**
* Dispose of the CMake Tools extension.
*
* If you can, prefer to call `asyncDispose`, which awaits on the children.
*/
dispose() {
rollbar.invokeAsync(localize('dispose.cmake.tools', 'Dispose of CMake Tools'), () => this.asyncDispose());
}
/**
* Asynchronously dispose of all the child objects.
*/
async asyncDispose() {
this.disposeSubs();
this.codeModelUpdateSubs.forEach(
subs => subs.forEach(
sub => sub.dispose()
)
);
this.onDidChangeActiveTextEditorSub.dispose();
this.onUseCMakePresetsChangedSub.dispose();
void this.kitsWatcher.close();
this.projectOutlineTreeView.dispose();
if (this.cppToolsAPI) {
this.cppToolsAPI.dispose();
}
// Dispose of each CMake Tools we still have loaded
for (const cmtf of this.folders) {
await cmtf.cmakeTools.asyncDispose();
}
this.folders.dispose();
await telemetry.deactivate();
}
async configureExtensionInternal(trigger: ConfigureTrigger, cmt: CMakeTools): Promise<void> {
if (!await this.ensureActiveConfigurePresetOrKit(cmt)) {
return;
}
await cmt.configureInternal(trigger, [], ConfigureType.Normal);
}
// This method evaluates whether the given folder represents a CMake project
// (does have a valid CMakeLists.txt at the location pointed to by the "cmake.sourceDirectory" setting)
// and also stores the answer in a map for later use.
async folderIsCMakeProject(cmt: CMakeTools): Promise<boolean> {
if (this.isCMakeFolder.get(cmt.folderName)) {
return true;
}
const optsVars: KitContextVars = {
userHome: paths.userHome,
workspaceFolder: cmt.workspaceContext.folder.uri.fsPath,
workspaceFolderBasename: cmt.workspaceContext.folder.name,
workspaceRoot: cmt.workspaceContext.folder.uri.fsPath,
workspaceRootFolderName: cmt.workspaceContext.folder.name,
// sourceDirectory cannot be defined based on any of the below variables.
buildKit: "",
buildType: "",
generator: "",
buildKitVendor: "",
buildKitTriple: "",
buildKitVersion: "",
buildKitHostOs: "",
buildKitTargetOs: "",
buildKitTargetArch: "",
buildKitVersionMajor: "",
buildKitVersionMinor: "",
workspaceHash: ""
};
const sourceDirectory: string = cmt.workspaceContext.config.sourceDirectory;
let expandedSourceDirectory: string = util.lightNormalizePath(await expandString(sourceDirectory, { vars: optsVars }));
if (path.basename(expandedSourceDirectory).toLocaleLowerCase() !== "cmakelists.txt") {
expandedSourceDirectory = path.join(expandedSourceDirectory, "CMakeLists.txt");
}
const isCMake = await fs.exists(expandedSourceDirectory);
this.isCMakeFolder.set(cmt.folderName, isCMake);
return isCMake;
}
async postWorkspaceOpen(info: CMakeToolsFolder) {
const ws = info.folder;
const cmt = info.cmakeTools;
// Scan for kits even under presets mode, so we can create presets from compilers.
// Silent re-scan when detecting a breaking change in the kits definition.
// Do this only for the first folder, to avoid multiple rescans taking place in a multi-root workspace.
const silentScanForKitsNeeded: boolean = vscode.workspace.workspaceFolders !== undefined &&
vscode.workspace.workspaceFolders[0] === cmt.folder &&
await scanForKitsIfNeeded(cmt);
let shouldConfigure = cmt.workspaceContext.config.configureOnOpen;
if (shouldConfigure === null && !util.isTestMode()) {
interface Choice1 {
title: string;
doConfigure: boolean;
}
const chosen = await vscode.window.showInformationMessage<Choice1>(
localize('configure.this.project', 'Would you like to configure project {0}?', `"${ws.name}"`),
{},
{ title: localize('yes.button', 'Yes'), doConfigure: true },
{ title: localize('not.now.button', 'Not now'), doConfigure: false }
);
if (!chosen) {
// User cancelled.
shouldConfigure = null;
} else {
const persistMessage = chosen.doConfigure ?
localize('always.configure.on.open', 'Always configure projects upon opening?') :
localize('never.configure.on.open', 'Configure projects on opening?');
const buttonMessages = chosen.doConfigure ?
[localize('yes.button', 'Yes'), localize('no.button', 'No')] :
[localize('never.button', 'Never'), localize('never.for.this.workspace.button', 'Not this workspace')];
interface Choice2 {
title: string;
persistMode: 'user' | 'workspace';
}
// Try to persist the user's selection to a `settings.json`
const prompt = vscode.window.showInformationMessage<Choice2>(
persistMessage,
{},
{ title: buttonMessages[0], persistMode: 'user' },
{ title: buttonMessages[1], persistMode: 'workspace' })
.then(async choice => {
if (!choice) {
// Use cancelled. Do nothing.
return;
}
const config = vscode.workspace.getConfiguration(undefined, ws.uri);
let configTarget = vscode.ConfigurationTarget.Global;
if (choice.persistMode === 'workspace') {
configTarget = vscode.ConfigurationTarget.WorkspaceFolder;
}
await config.update('cmake.configureOnOpen', chosen.doConfigure, configTarget);
});
rollbar.takePromise(localize('persist.config.on.open.setting', 'Persist config-on-open setting'), {}, prompt);
shouldConfigure = chosen.doConfigure;
}
}
if (!await this.folderIsCMakeProject(cmt)) {
await cmt.cmakePreConditionProblemHandler(CMakePreconditionProblems.MissingCMakeListsFile, false, this.workspaceConfig);
} else {
if (shouldConfigure === true) {
// We've opened a new workspace folder, and the user wants us to
// configure it now.
log.debug(localize('configuring.workspace.on.open', 'Configuring workspace on open {0}', ws.uri.toString()));
await this.configureExtensionInternal(ConfigureTrigger.configureOnOpen, cmt);
} else {
const configureButtonMessage = localize('configure.now.button', 'Configure Now');
let result: string | undefined;
if (silentScanForKitsNeeded) {
// This popup will show up the first time after deciding not to configure, if a version change has been detected
// in the kits definition. This may happen during a CMake Tools extension upgrade.
// The warning is emitted only once because scanForKitsIfNeeded returns true only once after such change,
// being tied to a global state variable.
result = await vscode.window.showWarningMessage(localize('configure.recommended', 'It is recommended to reconfigure after upgrading to a new kits definition.'), configureButtonMessage);
}
if (result === configureButtonMessage) {
await this.configureExtensionInternal(ConfigureTrigger.buttonNewKitsDefinition, cmt);
} else {
log.debug(localize('using.cache.to.configure.workspace.on.open', 'Using cache to configure workspace on open {0}', ws.uri.toString()));
await this.configureExtensionInternal(ConfigureTrigger.configureWithCache, cmt);
}
}
}
this.updateCodeModel(info);
}
private async onDidChangeActiveTextEditor(editor: vscode.TextEditor | undefined): Promise<void> {
if (vscode.workspace.workspaceFolders) {
let ws: vscode.WorkspaceFolder | undefined;
if (editor) {
ws = vscode.workspace.getWorkspaceFolder(editor.document.uri);
}
if (ws && (!this.folders.activeFolder || ws.uri.fsPath !== this.folders.activeFolder.folder.uri.fsPath)) {
// active folder changed.
await this.setActiveFolder(ws);
} else if (!ws && !this.folders.activeFolder && vscode.workspace.workspaceFolders.length >= 1) {
await this.setActiveFolder(vscode.workspace.workspaceFolders[0]);
} else if (!ws) {
// When adding a folder but the focus is on somewhere else
// Do nothing but make sure we are showing the active folder correctly
this.statusBar.update();
}
}
}
/**
* Show UI to allow the user to select an active kit
*/
async selectActiveFolder() {
if (vscode.workspace.workspaceFolders?.length) {
const lastActiveFolderPath = this.folders.activeFolder?.folder.uri.fsPath;
const selection = await vscode.window.showWorkspaceFolderPick();
if (selection) {
// Ingore if user cancelled
await this.setActiveFolder(selection);
telemetry.logEvent("selectactivefolder");
// this.folders.activeFolder must be there at this time
const currentActiveFolderPath = this.folders.activeFolder!.folder.uri.fsPath;
await this.extensionContext.workspaceState.update('activeFolder', currentActiveFolderPath);
if (lastActiveFolderPath !== currentActiveFolderPath) {
rollbar.takePromise('Post-folder-open', { folder: selection }, this.postWorkspaceOpen(this.folders.activeFolder!));
}
}
}
}
private initActiveFolder() {
if (vscode.window.activeTextEditor && this.workspaceConfig.autoSelectActiveFolder) {
return this.onDidChangeActiveTextEditor(vscode.window.activeTextEditor);
}
const activeFolder = this.extensionContext.workspaceState.get<string>('activeFolder');
let folder: vscode.WorkspaceFolder | undefined;
if (activeFolder) {
folder = vscode.workspace.getWorkspaceFolder(vscode.Uri.parse(activeFolder));
}
if (!folder) {
folder = vscode.workspace.workspaceFolders![0];
}
return this.setActiveFolder(folder);
}
/**
* Set the active workspace folder. This reloads a lot of different bits and
* pieces to control which backend has control and receives user input.
* @param ws The workspace to activate
*/
private async setActiveFolder(ws: vscode.WorkspaceFolder | undefined) {
// Set the new workspace
this.folders.setActiveFolder(ws);
this.statusBar.setActiveFolderName(ws?.name || '');
const activeFolder = this.folders.activeFolder;
const useCMakePresets = activeFolder?.useCMakePresets || false;
this.statusBar.useCMakePresets(useCMakePresets);
if (!useCMakePresets) {
this.statusBar.setActiveKitName(activeFolder?.cmakeTools.activeKit?.name || '');
}
this.projectOutlineProvider.setActiveFolder(ws);
this.setupSubscriptions();
}
private disposeSubs() {
for (const sub of [this.statusMessageSub, this.targetNameSub, this.buildTypeSub, this.launchTargetSub, this.ctestEnabledSub, this.testResultsSub, this.isBusySub, this.activeConfigurePresetSub, this.activeBuildPresetSub, this.activeTestPresetSub]) {
sub.dispose();
}
}
private cpptoolsNumFoldersReady: number = 0;
private updateCodeModel(folder: CMakeToolsFolder) {
const cmt: CMakeTools = folder.cmakeTools;
this.projectOutlineProvider.updateCodeModel(
cmt.workspaceContext.folder,
cmt.codeModelContent,
{
defaultTarget: cmt.defaultBuildTarget || undefined,
launchTargetName: cmt.launchTargetName
}
);
rollbar.invokeAsync(localize('update.code.model.for.cpptools', 'Update code model for cpptools'), {}, async () => {
if (vscode.workspace.getConfiguration('C_Cpp', folder.folder).get<string>('intelliSenseEngine')?.toLocaleLowerCase() === 'disabled') {
log.debug(localize('update.intellisense.disabled', 'Not updating the configuration provider because {0} is set to {1}', '"C_Cpp.intelliSenseEngine"', '"Disabled"'));
return;
}
if (!this.cppToolsAPI) {
this.cppToolsAPI = await cpt.getCppToolsApi(cpt.Version.v5).catch(_err => undefined);
}
if (this.cppToolsAPI && (cmt.activeKit || cmt.configurePreset)) {
const cpptools = this.cppToolsAPI;
let cache: CMakeCache;
try {
cache = await CMakeCache.fromPath(await cmt.cachePath);
} catch (e: any) {
rollbar.exception(localize('filed.to.open.cache.file.on.code.model.update', 'Failed to open CMake cache file on code model update'), e);
return;
}
const drv: CMakeDriver | null = await cmt.getCMakeDriverInstance();
const configureEnv = await drv?.getConfigureEnvironment();
const isMultiConfig = !!cache.get('CMAKE_CONFIGURATION_TYPES');
if (drv) {
drv.isMultiConfig = isMultiConfig;
}
const actualBuildType = await (async () => {
if (cmt.useCMakePresets) {
if (isMultiConfig) {
return cmt.buildPreset?.configuration || null;
} else {
const buildType = cache.get('CMAKE_BUILD_TYPE');
return buildType ? buildType.as<string>() : null; // Single config generators set the build type during config, not build.
}
} else {
return cmt.currentBuildType();
}
})();
const clCompilerPath = await findCLCompilerPath(configureEnv);
this.configProvider.cpptoolsVersion = cpptools.getVersion();
let codeModelContent;
if (cmt.codeModelContent) {
codeModelContent = cmt.codeModelContent;
this.configProvider.updateConfigurationData({ cache, codeModelContent, clCompilerPath, activeTarget: cmt.defaultBuildTarget, activeBuildTypeVariant: actualBuildType, folder: cmt.folder.uri.fsPath });
} else if (drv && drv.codeModelContent) {
codeModelContent = drv.codeModelContent;
this.configProvider.updateConfigurationData({ cache, codeModelContent, clCompilerPath, activeTarget: cmt.defaultBuildTarget, activeBuildTypeVariant: actualBuildType, folder: cmt.folder.uri.fsPath });
this.projectOutlineProvider.updateCodeModel(
cmt.workspaceContext.folder,
codeModelContent,
{
defaultTarget: cmt.defaultBuildTarget || undefined,
launchTargetName: cmt.launchTargetName
}
);
}
this.ensureCppToolsProviderRegistered();
if (cpptools.notifyReady && this.cpptoolsNumFoldersReady < this.folders.size) {
++this.cpptoolsNumFoldersReady;
if (this.cpptoolsNumFoldersReady === this.folders.size) {
cpptools.notifyReady(this.configProvider);
this.configProvider.markAsReady();
}
} else {
cpptools.didChangeCustomBrowseConfiguration(this.configProvider);
cpptools.didChangeCustomConfiguration(this.configProvider);
this.configProvider.markAsReady();
}
}
});
}
private setupSubscriptions() {
this.disposeSubs();
const folder = this.folders.activeFolder;
const cmt = folder?.cmakeTools;
if (!cmt) {
this.statusBar.setVisible(false);
this.statusMessageSub = new DummyDisposable();
this.targetNameSub = new DummyDisposable();
this.buildTypeSub = new DummyDisposable();
this.launchTargetSub = new DummyDisposable();
this.ctestEnabledSub = new DummyDisposable();
this.testResultsSub = new DummyDisposable();
this.isBusySub = new DummyDisposable();
this.activeConfigurePresetSub = new DummyDisposable();
this.activeBuildPresetSub = new DummyDisposable();
this.activeTestPresetSub = new DummyDisposable();
this.statusBar.setActiveKitName('');
this.statusBar.setConfigurePresetName('');
this.statusBar.setBuildPresetName('');
this.statusBar.setTestPresetName('');
} else {
this.statusBar.setVisible(true);
this.statusMessageSub = cmt.onStatusMessageChanged(FireNow, s => this.statusBar.setStatusMessage(s));
this.targetNameSub = cmt.onTargetNameChanged(FireNow, t => {
this.statusBar.setBuildTargetName(t);
});
this.buildTypeSub = cmt.onActiveVariantNameChanged(FireNow, bt => this.statusBar.setVariantLabel(bt));
this.launchTargetSub = cmt.onLaunchTargetNameChanged(FireNow, t => {
this.statusBar.setLaunchTargetName(t || '');
});
this.ctestEnabledSub = cmt.onCTestEnabledChanged(FireNow, e => this.statusBar.setCTestEnabled(e));
this.testResultsSub = cmt.onTestResultsChanged(FireNow, r => this.statusBar.setTestResults(r));
this.isBusySub = cmt.onIsBusyChanged(FireNow, b => this.statusBar.setIsBusy(b));
this.statusBar.setActiveKitName(cmt.activeKit ? cmt.activeKit.name : '');
this.activeConfigurePresetSub = cmt.onActiveConfigurePresetChanged(FireNow, p => {
this.statusBar.setConfigurePresetName(p?.displayName || p?.name || '');
});
this.activeBuildPresetSub = cmt.onActiveBuildPresetChanged(FireNow, p => {
this.statusBar.setBuildPresetName(p?.displayName || p?.name || '');
});
this.activeTestPresetSub = cmt.onActiveTestPresetChanged(FireNow, p => {
this.statusBar.setTestPresetName(p?.displayName || p?.name || '');
});
}
}
/**
* Watches for changes to the kits file
*/
private readonly kitsWatcher = util.chokidarOnAnyChange(
chokidar.watch(USER_KITS_FILEPATH, { ignoreInitial: true }),
_ => rollbar.takePromise(localize('rereading.kits', 'Re-reading kits'), {}, KitsController.readUserKits(this.folders.activeFolder?.cmakeTools)));
/**
* Set the current kit for the specified workspace folder
* @param k The kit
*/
async setFolderKit(wsf: vscode.WorkspaceFolder, k: Kit | null) {
const cmtFolder = this.folders.get(wsf);
// Ignore if folder doesn't exist
if (cmtFolder) {
this.statusBar.setActiveKitName(await cmtFolder.kitsController.setFolderActiveKit(k));
}
}
/**
* Opens a text editor with the user-local `cmake-kits.json` file.
*/
async editKits(): Promise<vscode.TextEditor | null> {
log.debug(localize('opening.text.editor.for', 'Opening text editor for {0}', USER_KITS_FILEPATH));
if (!await fs.exists(USER_KITS_FILEPATH)) {
interface Item extends vscode.MessageItem {
action: 'scan' | 'cancel';
}
const chosen = await vscode.window.showInformationMessage<Item>(
localize('no.kits.file.what.to.do', 'No kits file is present. What would you like to do?'),
{ modal: true },
{
title: localize('scan.for.kits.button', 'Scan for kits'),
action: 'scan'
},
{
title: localize('cancel.button', 'Cancel'),
isCloseAffordance: true,
action: 'cancel'
}
);
if (!chosen || chosen.action === 'cancel') {
return null;
} else {
await this.scanForKits();
return this.editKits();
}
}
const doc = await vscode.workspace.openTextDocument(USER_KITS_FILEPATH);
return vscode.window.showTextDocument(doc);
}
async scanForCompilers() {
await this.scanForKits();
await this.folders.activeFolder?.presetsController.reapplyPresets();
}
async scanForKits() {
KitsController.minGWSearchDirs = await this.getMinGWDirs();
const cmakeTools = this.folders.activeFolder?.cmakeTools;
if (undefined === cmakeTools) {
return;
}
const duplicateRemoved = await KitsController.scanForKits(cmakeTools);
if (duplicateRemoved) {
// Check each folder. If there is an active kit set and if it is of the old definition,
// unset the kit
for (const cmtFolder of this.folders) {
const activeKit = cmtFolder.cmakeTools.activeKit;
if (activeKit) {
const definition = activeKit.visualStudio;
if (definition && (definition.startsWith("VisualStudio.15") || definition.startsWith("VisualStudio.16"))) {
await cmtFolder.kitsController.setFolderActiveKit(null);
}
}
}
}
}
/**
* Get the current MinGW search directories
*/
private async getMinGWDirs(): Promise<string[]> {
const optsVars: KitContextVars = {
userHome: paths.userHome,
// This is called during scanning for kits, which is an operation that happens
// outside the scope of a project folder, so it doesn't need the below variables.
buildKit: "",
buildType: "",
generator: "",
workspaceFolder: "",
workspaceFolderBasename: "",
workspaceHash: "",
workspaceRoot: "",
workspaceRootFolderName: "",
buildKitVendor: "",
buildKitTriple: "",
buildKitVersion: "",
buildKitHostOs: "",
buildKitTargetOs: "",
buildKitTargetArch: "",
buildKitVersionMajor: "",
buildKitVersionMinor: "",
projectName: ""
};
const result = new Set<string>();
for (const dir of this.workspaceConfig.mingwSearchDirs) {
const expandedDir: string = util.lightNormalizePath(await expandString(dir, { vars: optsVars }));
result.add(expandedDir);
}
return Array.from(result);
}
/**
* Show UI to allow the user to select an active kit
*/
async selectKit(folder?: vscode.WorkspaceFolder): Promise<boolean> {
if (util.isTestMode()) {
log.trace(localize('selecting.kit.in.test.mode', 'Running CMakeTools in test mode. selectKit is disabled.'));
return false;
}
const cmtFolder = this.checkFolderArgs(folder);
if (!cmtFolder) {
return false;
}
const kitSelected = await cmtFolder.kitsController.selectKit();
let kitSelectionType;
if (this.folders.activeFolder && this.folders.activeFolder.cmakeTools.activeKit) {
this.statusBar.setActiveKitName(this.folders.activeFolder.cmakeTools.activeKit.name);
if (this.folders.activeFolder.cmakeTools.activeKit.name === "__unspec__") {
kitSelectionType = "unspecified";
} else {
if (this.folders.activeFolder.cmakeTools.activeKit.visualStudio ||
this.folders.activeFolder.cmakeTools.activeKit.visualStudioArchitecture) {
kitSelectionType = "vsInstall";
} else {
kitSelectionType = "compilerSet";
}
}
}
if (kitSelectionType) {
const telemetryProperties: telemetry.Properties = {
type: kitSelectionType
};
telemetry.logEvent('kitSelection', telemetryProperties);
}
if (kitSelected) {
return true;
}
return false;
}
/**
* Set the current kit used in the specified folder by name of the kit
* For backward compatibility, apply kitName to all folders if folder is undefined
*/
async setKitByName(kitName: string, folder?: vscode.WorkspaceFolder) {
if (folder) {
await this.folders.get(folder)?.kitsController.setKitByName(kitName);
} else {
for (const cmtFolder of this.folders) {
await cmtFolder.kitsController.setKitByName(kitName);
}
}
if (this.folders.activeFolder && this.folders.activeFolder.cmakeTools.activeKit) {
this.statusBar.setActiveKitName(this.folders.activeFolder.cmakeTools.activeKit.name);
}
}
/**
* Set the current preset used in the specified folder by name of the preset
* For backward compatibility, apply preset to all folders if folder is undefined
*/
async setConfigurePreset(presetName: string, folder?: vscode.WorkspaceFolder) {
if (folder) {
await this.folders.get(folder)?.presetsController.setConfigurePreset(presetName);
} else {
for (const cmtFolder of this.folders) {
await cmtFolder.presetsController.setConfigurePreset(presetName);
}
}
}
async setBuildPreset(presetName: string, folder?: vscode.WorkspaceFolder) {
if (folder) {
await this.folders.get(folder)?.presetsController.setBuildPreset(presetName);
} else {
for (const cmtFolder of this.folders) {
await cmtFolder.presetsController.setBuildPreset(presetName);
}
}
}
async setTestPreset(presetName: string, folder?: vscode.WorkspaceFolder) {
if (folder) {
await this.folders.get(folder)?.presetsController.setTestPreset(presetName);
} else {
for (const cmtFolder of this.folders) {
await cmtFolder.presetsController.setTestPreset(presetName);
}
}
}
useCMakePresets(folder: vscode.WorkspaceFolder) {
return this.folders.get(folder)?.useCMakePresets;
}
ensureCppToolsProviderRegistered() {
if (!this.configProviderRegistered) {
this.doRegisterCppTools();
this.configProviderRegistered = true;
}
}
doRegisterCppTools() {
if (this.cppToolsAPI) {
this.cppToolsAPI.registerCustomConfigurationProvider(this.configProvider);
}
}
private cleanOutputChannel() {
if (this.workspaceConfig.clearOutputBeforeBuild) {
log.clearOutputChannel();
}
}
// The below functions are all wrappers around the backend.
async mapCMakeTools(fn: CMakeToolsMapFn,
cmt = this.folders.activeFolder ? this.folders.activeFolder.cmakeTools : undefined,
precheck?: (cmt: CMakeTools) => Promise<boolean>): Promise<any> {
if (!cmt) {
rollbar.error(localize('no.active.folder', 'No active folder.'));
return -2;
}
if (!await this.ensureActiveConfigurePresetOrKit(cmt)) {
return -1;
}
if (precheck && !await precheck(cmt)) {
return -100;
}
return fn(cmt);
}
async mapCMakeToolsAll(fn: CMakeToolsMapFn, precheck?: (cmt: CMakeTools) => Promise<boolean>, cleanOutputChannel?: boolean): Promise<any> {
if (cleanOutputChannel) {
this.cleanOutputChannel();
}
for (const folder of this.folders) {
if (!await this.ensureActiveConfigurePresetOrKit(folder.cmakeTools)) {
return -1;
}
if (precheck && !await precheck(folder.cmakeTools)) {
return -100;
}
const retc = await fn(folder.cmakeTools);
if (retc) {
return retc;
}
}
// Succeeded
return 0;
}
mapCMakeToolsFolder(fn: CMakeToolsMapFn,
folder?: vscode.WorkspaceFolder,
precheck?: (cmt: CMakeTools) => Promise<boolean>,
cleanOutputChannel?: boolean): Promise<any> {
if (cleanOutputChannel) {
this.cleanOutputChannel();
}
return this.mapCMakeTools(fn, this.folders.get(folder)?.cmakeTools, precheck);
}
mapQueryCMakeTools(fn: CMakeToolsQueryMapFn, folder?: vscode.WorkspaceFolder | string) {
const workspaceFolder = this.checkStringFolderArgs(folder);
if (workspaceFolder) {
const cmtFolder = this.folders.get(workspaceFolder);
if (cmtFolder) {
return fn(cmtFolder.cmakeTools);
}
} else {
rollbar.error(localize('invalid.folder', 'Invalid folder.'));
}
return Promise.resolve(null);
}
cleanConfigure(folder?: vscode.WorkspaceFolder) {
telemetry.logEvent("deleteCacheAndReconfigure");
return this.mapCMakeToolsFolder(cmt => cmt.cleanConfigure(ConfigureTrigger.commandCleanConfigure), folder, undefined, true);
}
cleanConfigureAll() {
telemetry.logEvent("deleteCacheAndReconfigure");
return this.mapCMakeToolsAll(cmt => cmt.cleanConfigure(ConfigureTrigger.commandCleanConfigureAll), undefined, true);
}
configure(folder?: vscode.WorkspaceFolder, showCommandOnly?: boolean) {
return this.mapCMakeToolsFolder(
cmt => cmt.configureInternal(ConfigureTrigger.commandConfigure, [], showCommandOnly ? ConfigureType.ShowCommandOnly : ConfigureType.Normal),
folder, undefined, true);
}
showConfigureCommand(folder?: vscode.WorkspaceFolder) {
return this.configure(folder, true);
}
configureAll() {
return this.mapCMakeToolsAll(cmt => cmt.configureInternal(ConfigureTrigger.commandCleanConfigureAll, [], ConfigureType.Normal), undefined, true);
}
editCacheUI() {
telemetry.logEvent("editCMakeCache", { command: "editCMakeCacheUI" });
return this.mapCMakeToolsFolder(cmt => cmt.editCacheUI());
}
build(folder?: vscode.WorkspaceFolder, name?: string, showCommandOnly?: boolean) {
return this.mapCMakeToolsFolder(cmt => cmt.build(name ? [name] : undefined, showCommandOnly), folder, this.ensureActiveBuildPreset, true);
}
showBuildCommand(folder?: vscode.WorkspaceFolder, name?: string) {
return this.build(folder, name, true);
}
buildAll(name?: string | string[]) {
return this.mapCMakeToolsAll(cmt => {
const targets = util.isArrayOfString(name) ? name : util.isString(name) ? [name] : undefined;
return cmt.build(targets);
},
this.ensureActiveBuildPreset,
true);
}
setDefaultTarget(folder?: vscode.WorkspaceFolder, name?: string) {
return this.mapCMakeToolsFolder(cmt => cmt.setDefaultTarget(name), folder);
}
setVariant(folder?: vscode.WorkspaceFolder, name?: string) {
return this.mapCMakeToolsFolder(cmt => cmt.setVariant(name), folder);
}
async setVariantAll() {
// Only supports default variants for now
const variantItems: vscode.QuickPickItem[] = [];
const choices = DEFAULT_VARIANTS.buildType!.choices;
for (const key in choices) {
variantItems.push({
label: choices[key]!.short,
description: choices[key]!.long
});
}
const choice = await vscode.window.showQuickPick(variantItems);
if (choice) {
return this.mapCMakeToolsAll(cmt => cmt.setVariant(choice.label));
}
return false;
}
install(folder?: vscode.WorkspaceFolder) {
telemetry.logEvent("install");
return this.mapCMakeToolsFolder(cmt => cmt.install(), folder, undefined, true);
}
installAll() {
telemetry.logEvent("install");
return this.mapCMakeToolsAll(cmt => cmt.install(), undefined, true);
}
editCache(folder: vscode.WorkspaceFolder) {
telemetry.logEvent("editCMakeCache", { command: "editCMakeCache" });
return this.mapCMakeToolsFolder(cmt => cmt.editCache(), folder);
}
clean(folder?: vscode.WorkspaceFolder) {
telemetry.logEvent("clean");
return this.build(folder, 'clean');
}
cleanAll() {
telemetry.logEvent("clean");
return this.buildAll(['clean']);
}
cleanRebuild(folder?: vscode.WorkspaceFolder) {
telemetry.logEvent("clean");
return this.mapCMakeToolsFolder(cmt => cmt.cleanRebuild(), folder, this.ensureActiveBuildPreset, true);
}
cleanRebuildAll() {
telemetry.logEvent("clean");
return this.mapCMakeToolsAll(cmt => cmt.cleanRebuild(), this.ensureActiveBuildPreset, true);
}
async buildWithTarget() {
this.cleanOutputChannel();
let cmtFolder: CMakeToolsFolder | undefined = this.folders.activeFolder;
if (!cmtFolder) {
cmtFolder = await this.pickFolder();
}
if (!cmtFolder) {
return; // Error or nothing is opened
}
return cmtFolder.cmakeTools.buildWithTarget();
}
/**
* Compile a single source file.
* @param file The file to compile. Either a file path or the URI to the file.
* If not provided, compiles the file in the active text editor.
*/
async compileFile(file?: string | vscode.Uri) {
this.cleanOutputChannel();
if (file instanceof vscode.Uri) {
file = file.fsPath;
}
if (!file) {
const editor = vscode.window.activeTextEditor;
if (!editor) {
return null;
}
file = editor.document.uri.fsPath;
}
for (const folder of this.folders) {
const term = await folder.cmakeTools.tryCompileFile(file);
if (term) {
return term;
}
}
void vscode.window.showErrorMessage(localize('compilation information.not.found', 'Unable to find compilation information for this file'));
}
async selectWorkspace(folder?: vscode.WorkspaceFolder) {
if (!folder) {
return;
}
await this.setActiveFolder(folder);
}
ctest(folder?: vscode.WorkspaceFolder) {
telemetry.logEvent("runTests");
return this.mapCMakeToolsFolder(cmt => cmt.ctest(), folder, this.ensureActiveTestPreset);
}
ctestAll() {
telemetry.logEvent("runTests");
return this.mapCMakeToolsAll(cmt => cmt.ctest(), this.ensureActiveTestPreset);
}
stop(folder?: vscode.WorkspaceFolder) {
return this.mapCMakeToolsFolder(cmt => cmt.stop(), folder);
}
stopAll() {
return this.mapCMakeToolsAll(cmt => cmt.stop());
}
quickStart(folder?: vscode.WorkspaceFolder) {
const cmtFolder = this.checkFolderArgs(folder);
telemetry.logEvent("quickStart");
return this.mapCMakeTools(cmt => cmt.quickStart(cmtFolder));
}
launchTargetPath(folder?: vscode.WorkspaceFolder | string) {
telemetry.logEvent("substitution", { command: "launchTargetPath" });
return this.mapQueryCMakeTools(cmt => cmt.launchTargetPath(), folder);
}
launchTargetDirectory(folder?: vscode.WorkspaceFolder | string) {
telemetry.logEvent("substitution", { command: "launchTargetDirectory" });
return this.mapQueryCMakeTools(cmt => cmt.launchTargetDirectory(), folder);
}
launchTargetFilename(folder?: vscode.WorkspaceFolder | string) {
telemetry.logEvent("substitution", { command: "launchTargetFilename" });
return this.mapQueryCMakeTools(cmt => cmt.launchTargetFilename(), folder);
}
getLaunchTargetPath(folder?: vscode.WorkspaceFolder | string) {
telemetry.logEvent("substitution", { command: "getLaunchTargetPath" });
return this.mapQueryCMakeTools(cmt => cmt.getLaunchTargetPath(), folder);
}
getLaunchTargetDirectory(folder?: vscode.WorkspaceFolder | string) {
telemetry.logEvent("substitution", { command: "getLaunchTargetDirectory" });
return this.mapQueryCMakeTools(cmt => cmt.getLaunchTargetDirectory(), folder);
}
getLaunchTargetFilename(folder?: vscode.WorkspaceFolder | string) {
telemetry.logEvent("substitution", { command: "getLaunchTargetFilename" });
return this.mapQueryCMakeTools(cmt => cmt.getLaunchTargetFilename(), folder);
}
buildTargetName(folder?: vscode.WorkspaceFolder | string) {
telemetry.logEvent("substitution", { command: "buildTargetName" });
return this.mapQueryCMakeTools(cmt => cmt.buildTargetName(), folder);
}
buildType(folder?: vscode.WorkspaceFolder | string) {
telemetry.logEvent("substitution", { command: "buildType" });
return this.mapQueryCMakeTools(cmt => cmt.currentBuildType(), folder);
}
buildDirectory(folder?: vscode.WorkspaceFolder | string) {
telemetry.logEvent("substitution", { command: "buildDirectory" });
return this.mapQueryCMakeTools(cmt => cmt.buildDirectory(), folder);
}
buildKit(folder?: vscode.WorkspaceFolder | string) {
telemetry.logEvent("substitution", { command: "buildKit" });
return this.mapQueryCMakeTools(cmt => cmt.buildKit(), folder);
}
executableTargets(folder?: vscode.WorkspaceFolder | string) {
telemetry.logEvent("substitution", { command: "executableTargets" });
return this.mapQueryCMakeTools(async cmt => (await cmt.executableTargets).map(target => target.name), folder);
}
tasksBuildCommand(folder?: vscode.WorkspaceFolder | string) {
telemetry.logEvent("substitution", { command: "tasksBuildCommand" });
return this.mapQueryCMakeTools(cmt => cmt.tasksBuildCommand(), folder);
}
debugTarget(folder?: vscode.WorkspaceFolder, name?: string): Promise<vscode.DebugSession | null> {
return this.mapCMakeToolsFolder(cmt => cmt.debugTarget(name), folder);
}
async debugTargetAll(): Promise<(vscode.DebugSession | null)[]> {
const debugSessions: (vscode.DebugSession | null)[] = [];
for (const cmtFolder of this.folders) {
if (cmtFolder) {
debugSessions.push(await this.mapCMakeTools(cmt => cmt.debugTarget(), cmtFolder.cmakeTools));
}
}
return debugSessions;
}
launchTarget(folder?: vscode.WorkspaceFolder, name?: string): Promise<vscode.Terminal | null> {
return this.mapCMakeToolsFolder(cmt => cmt.launchTarget(name), folder);
}
async launchTargetAll(): Promise<(vscode.Terminal | null)[]> {
const terminals: (vscode.Terminal | null)[] = [];
for (const cmtFolder of this.folders) {
if (cmtFolder) {
terminals.push(await this.mapCMakeTools(cmt => cmt.launchTarget(), cmtFolder.cmakeTools));
}
}
return terminals;
}
selectLaunchTarget(folder?: vscode.WorkspaceFolder, name?: string) {
return this.mapCMakeToolsFolder(cmt => cmt.selectLaunchTarget(name), folder);
}
async resetState(folder?: vscode.WorkspaceFolder) {
telemetry.logEvent("resetExtension");
if (folder) {
await this.mapCMakeToolsFolder(cmt => cmt.resetState(), folder);
} else {
await this.mapCMakeToolsAll(cmt => cmt.resetState());
}
void vscode.commands.executeCommand('workbench.action.reloadWindow');
}
async viewLog() {
telemetry.logEvent("openLogFile");
await logging.showLogFile();
}
async logDiagnostics() {
telemetry.logEvent("logDiagnostics");
const configurations: DiagnosticsConfiguration[] = [];
const settings: DiagnosticsSettings[] = [];
for (const folder of this.folders.getAll()) {
configurations.push(await folder.getDiagnostics());
settings.push(await folder.getSettingsDiagnostics());
}
const result: Diagnostics = {
os: platform(),
vscodeVersion: vscode.version,
cmtVersion: util.thisExtensionPackage().version,
configurations,
cpptoolsIntegration: this.configProvider.getDiagnostics(),
settings
};
const output = logging.channelManager.get("CMake Diagnostics");
output.clear();
output.appendLine(JSON.stringify(result, null, 2));
output.show();
}
activeFolderName(): string {
return this.folders.activeFolder?.folder.name || '';
}
activeFolderPath(): string {
return this.folders.activeFolder?.folder.uri.fsPath || '';
}
async hideLaunchCommand(shouldHide: boolean = true) {
// Don't hide command selectLaunchTarget here since the target can still be useful, one example is ${command:cmake.launchTargetPath} in launch.json
this.statusBar.hideLaunchButton(shouldHide);
await util.setContextValue(hideLaunchCommandKey, shouldHide);
}
async hideDebugCommand(shouldHide: boolean = true) {
// Don't hide command selectLaunchTarget here since the target can still be useful, one example is ${command:cmake.launchTargetPath} in launch.json
this.statusBar.hideDebugButton(shouldHide);
await util.setContextValue(hideDebugCommandKey, shouldHide);
}
async hideBuildCommand(shouldHide: boolean = true) {
this.statusBar.hideBuildButton(shouldHide);
await util.setContextValue(hideBuildCommandKey, shouldHide);
}
// Answers whether the workspace contains at least one project folder that is CMake based,
// without recalculating the valid states of CMakeLists.txt.
async workspaceHasCMakeProject(): Promise<boolean> {
for (const cmtFolder of this.folders) {
if (await this.folderIsCMakeProject(cmtFolder.cmakeTools)) {
return true;
}
}
return false;
}
activeConfigurePresetName(): string {
telemetry.logEvent("substitution", { command: "activeConfigurePresetName" });
return this.folders.activeFolder?.cmakeTools.configurePreset?.name || '';
}
activeBuildPresetName(): string {
telemetry.logEvent("substitution", { command: "activeBuildPresetName" });
return this.folders.activeFolder?.cmakeTools.buildPreset?.name || '';
}
activeTestPresetName(): string {
telemetry.logEvent("substitution", { command: "activeTestPresetName" });
return this.folders.activeFolder?.cmakeTools.testPreset?.name || '';
}
/**
* Opens CMakePresets.json at the root of the project. Creates one if it does not exist.
*/
async openCMakePresets(): Promise<void> {
await this.folders.activeFolder?.presetsController.openCMakePresets();
}
/**
* Show UI to allow the user to add an active configure preset
*/
async addConfigurePreset(folder: vscode.WorkspaceFolder): Promise<boolean> {
if (util.isTestMode()) {
log.trace(localize('add.config.preset.in.test.mode', 'Running CMakeTools in test mode. addConfigurePreset is disabled.'));
return false;
}
const cmtFolder = this.checkFolderArgs(folder);
if (!cmtFolder) {
return false;
}
return cmtFolder.presetsController.addConfigurePreset();
}
/**
* Show UI to allow the user to add an active build preset
*/
async addBuildPreset(folder: vscode.WorkspaceFolder): Promise<boolean> {
if (util.isTestMode()) {
log.trace(localize('add.build.preset.in.test.mode', 'Running CMakeTools in test mode. addBuildPreset is disabled.'));
return false;
}
const cmtFolder = this.checkFolderArgs(folder);
if (!cmtFolder) {
return false;
}
return cmtFolder.presetsController.addBuildPreset();
}
/**
* Show UI to allow the user to add an active test preset
*/
async addTestPreset(folder: vscode.WorkspaceFolder): Promise<boolean> {
if (util.isTestMode()) {
log.trace(localize('add.test.preset.in.test.mode', 'Running CMakeTools in test mode. addTestPreset is disabled.'));
return false;
}
const cmtFolder = this.checkFolderArgs(folder);
if (!cmtFolder) {
return false;
}
return cmtFolder.presetsController.addTestPreset();
}
// Referred in presetsController.ts
/**
* Show UI to allow the user to select an active configure preset
*/
async selectConfigurePreset(folder?: vscode.WorkspaceFolder): Promise<boolean> {
if (util.isTestMode()) {
log.trace(localize('selecting.config.preset.in.test.mode', 'Running CMakeTools in test mode. selectConfigurePreset is disabled.'));
return false;
}
const cmtFolder = this.checkFolderArgs(folder);
if (!cmtFolder) {
return false;
}
const presetSelected = await cmtFolder.presetsController.selectConfigurePreset();
const configurePreset = this.folders.activeFolder?.cmakeTools.configurePreset;
this.statusBar.setConfigurePresetName(configurePreset?.displayName || configurePreset?.name || '');
// Reset build and test presets since they might not be used with the selected configure preset
const buildPreset = this.folders.activeFolder?.cmakeTools.buildPreset;
this.statusBar.setBuildPresetName(buildPreset?.displayName || buildPreset?.name || '');
const testPreset = this.folders.activeFolder?.cmakeTools.testPreset;
this.statusBar.setTestPresetName(testPreset?.displayName || testPreset?.name || '');
return presetSelected;
}
/**
* Show UI to allow the user to select an active build preset
*/
async selectBuildPreset(folder?: vscode.WorkspaceFolder): Promise<boolean> {
if (util.isTestMode()) {
log.trace(localize('selecting.build.preset.in.test.mode', 'Running CMakeTools in test mode. selectBuildPreset is disabled.'));
return false;
}
const cmtFolder = this.checkFolderArgs(folder);
if (!cmtFolder) {
return false;
}
const presetSelected = await cmtFolder.presetsController.selectBuildPreset();
const buildPreset = this.folders.activeFolder?.cmakeTools.buildPreset;
this.statusBar.setBuildPresetName(buildPreset?.displayName || buildPreset?.name || '');
return presetSelected;
}
/**
* Show UI to allow the user to select an active test preset
*/
async selectTestPreset(folder?: vscode.WorkspaceFolder): Promise<boolean> {
if (util.isTestMode()) {
log.trace(localize('selecting.test.preset.in.test.mode', 'Running CMakeTools in test mode. selectTestPreset is disabled.'));
return false;
}
const cmtFolder = this.checkFolderArgs(folder);
if (!cmtFolder) {
return false;
}
const presetSelected = await cmtFolder.presetsController.selectTestPreset();
const testPreset = this.folders.activeFolder?.cmakeTools.testPreset;
this.statusBar.setTestPresetName(testPreset?.displayName || testPreset?.name || '');
return presetSelected;
}
}
async function setup(context: vscode.ExtensionContext, progress?: ProgressHandle) {
reportProgress(localize('initial.setup', 'Initial setup'), progress);
// Load a new extension manager
const ext = extensionManager = await ExtensionManager.create(context);
// A register function that helps us bind the commands to the extension
function register<K extends keyof ExtensionManager>(name: K) {
return vscode.commands.registerCommand(`cmake.${name}`, (...args: any[]) => {
// Generate a unqiue ID that can be correlated in the log file.
const id = util.randint(1000, 10000);
// Create a promise that resolves with the command.
const pr = (async () => {
// Debug when the commands start/stop
log.debug(`[${id}]`, `cmake.${name}`, localize('started', 'started'));
// Bind the method
const fn = (ext[name] as Function).bind(ext);
// Call the method
const ret = await fn(...args);
try {
// Log the result of the command.
log.debug(localize('cmake.finished.returned', '{0} finished (returned {1})', `[${id}] cmake.${name}`, JSON.stringify(ret)));
} catch (e) {
// Log, but don't try to serialize the return value.
log.debug(localize('cmake.finished.returned.unserializable', '{0} finished (returned an unserializable value)', `[${id}] cmake.${name}`));
}
// Return the result of the command.
return ret;
})();
// Hand the promise to rollbar.
rollbar.takePromise(name, {}, pr);
// Return the promise so that callers will get the result of the command.
return pr;
});
}
// List of functions that will be bound commands
const funs: (keyof ExtensionManager)[] = [
'activeFolderName',
'activeFolderPath',
'activeConfigurePresetName',
'activeBuildPresetName',
'activeTestPresetName',
"useCMakePresets",
"openCMakePresets",
'addConfigurePreset',
'addBuildPreset',
'addTestPreset',
'selectConfigurePreset',
'selectBuildPreset',
'selectTestPreset',
'selectActiveFolder',
'editKits',
'scanForKits',
'scanForCompilers',
'selectKit',
'setKitByName',
'setConfigurePreset',
'setBuildPreset',
'setTestPreset',
'build',
'showBuildCommand',
'buildAll',
'buildWithTarget',
'setVariant',
'setVariantAll',
'install',
'installAll',
'editCache',
'clean',
'cleanAll',
'cleanConfigure',
'cleanConfigureAll',
'cleanRebuild',
'cleanRebuildAll',
'configure',
'showConfigureCommand',
'configureAll',
'editCacheUI',
'ctest',
'ctestAll',
'stop',
'stopAll',
'quickStart',
'launchTargetPath',
'launchTargetDirectory',
'launchTargetFilename',
'getLaunchTargetPath',
'getLaunchTargetDirectory',
'getLaunchTargetFilename',
'buildTargetName',
'buildKit',
'buildType',
'buildDirectory',
'executableTargets',
'debugTarget',
'debugTargetAll',
'launchTarget',
'launchTargetAll',
'selectLaunchTarget',
'setDefaultTarget',
'resetState',
'viewLog',
'logDiagnostics',
'compileFile',
'selectWorkspace',
'tasksBuildCommand',
'hideLaunchCommand',
'hideDebugCommand',
'hideBuildCommand'
// 'toggleCoverageDecorations', // XXX: Should coverage decorations be revived?
];
// Register the functions before the extension is done loading so that fast
// fingers won't cause "unregistered command" errors while CMake Tools starts
// up. The command wrapper will await on the extension promise.
reportProgress(localize('loading.extension.commands', 'Loading extension commands'), progress);
for (const key of funs) {
log.trace(localize('register.command', 'Register CMakeTools extension command {0}', `cmake.${key}`));
context.subscriptions.push(register(key));
}
// Util for the special commands to forward to real commands
function runCommand(key: keyof ExtensionManager, ...args: any[]) {
return vscode.commands.executeCommand(`cmake.${key}`, ...args);
}
context.subscriptions.push(...[
// Special commands that don't require logging or separate error handling
vscode.commands.registerCommand('cmake.outline.configureAll', () => runCommand('configureAll')),
vscode.commands.registerCommand('cmake.outline.buildAll', () => runCommand('buildAll')),
vscode.commands.registerCommand('cmake.outline.stopAll', () => runCommand('stopAll')),
vscode.commands.registerCommand('cmake.outline.cleanAll', () => runCommand('cleanAll')),
vscode.commands.registerCommand('cmake.outline.cleanConfigureAll', () => runCommand('cleanConfigureAll')),
vscode.commands.registerCommand('cmake.outline.editCacheUI', () => runCommand('editCacheUI')),
vscode.commands.registerCommand('cmake.outline.cleanRebuildAll', () => runCommand('cleanRebuildAll')),
// Commands for outline items:
vscode.commands.registerCommand('cmake.outline.buildTarget',
(what: TargetNode) => runCommand('build', what.folder, what.name)),
vscode.commands.registerCommand('cmake.outline.runUtilityTarget',
(what: TargetNode) => runCommand('build', what.folder, what.name)),
vscode.commands.registerCommand('cmake.outline.debugTarget',
(what: TargetNode) => runCommand('debugTarget', what.folder, what.name)),
vscode.commands.registerCommand('cmake.outline.launchTarget',
(what: TargetNode) => runCommand('launchTarget', what.folder, what.name)),
vscode.commands.registerCommand('cmake.outline.setDefaultTarget',
(what: TargetNode) => runCommand('setDefaultTarget', what.folder, what.name)),
vscode.commands.registerCommand('cmake.outline.setLaunchTarget',
(what: TargetNode) => runCommand('selectLaunchTarget', what.folder, what.name)),
vscode.commands.registerCommand('cmake.outline.revealInCMakeLists',
(what: TargetNode) => what.openInCMakeLists()),
vscode.commands.registerCommand('cmake.outline.compileFile',
(what: SourceFileNode) => runCommand('compileFile', what.filePath)),
vscode.commands.registerCommand('cmake.outline.selectWorkspace',
(what: WorkspaceFolderNode) => runCommand('selectWorkspace', what.wsFolder))
]);
}
class SchemaProvider implements vscode.TextDocumentContentProvider {
public async provideTextDocumentContent(uri: vscode.Uri): Promise<string> {
console.assert(uri.path[0] === '/', "A preceeding slash is expected on schema uri path");
const fileName: string = uri.path.substr(1);
const locale: string = util.getLocaleId();
let localizedFilePath: string = path.join(util.thisExtensionPath(), "dist/schema/", locale, fileName);
const fileExists: boolean = await util.checkFileExists(localizedFilePath);
if (!fileExists) {
localizedFilePath = path.join(util.thisExtensionPath(), fileName);
}
return fs.readFile(localizedFilePath, "utf8");
}
}
/**
* Starts up the extension.
* @param context The extension context
* @returns A promise that will resolve when the extension is ready for use
*/
export async function activate(context: vscode.ExtensionContext) {
// CMakeTools versions newer or equal to #1.2 should not coexist with older versions
// because the publisher changed (from vector-of-bool into ms-vscode),
// causing many undesired behaviors (duplicate operations, registrations for UI elements, etc...)
const oldCMakeToolsExtension = vscode.extensions.getExtension('vector-of-bool.cmake-tools');
if (oldCMakeToolsExtension) {
await vscode.window.showWarningMessage(localize('uninstall.old.cmaketools', 'Please uninstall any older versions of the CMake Tools extension. It is now published by Microsoft starting with version 1.2.0.'));
}
// Start with a partial feature set view. The first valid CMake project will cause a switch to full feature set.
await enableFullFeatureSet(false);
// Register a protocol handler to serve localized schemas
vscode.workspace.registerTextDocumentContentProvider('cmake-tools-schema', new SchemaProvider());
await util.setContextValue("inCMakeProject", true);
taskProvider = vscode.tasks.registerTaskProvider(CMakeTaskProvider.CMakeScriptType, cmakeTaskProvider);
return setup(context);
// TODO: Return the extension API
// context.subscriptions.push(vscode.commands.registerCommand('cmake._extensionInstance', () => cmt));
}
// Enable all or part of the CMake Tools palette commands
// and show or hide the buttons in the status bar, according to the boolean.
// The scope of this is the whole workspace.
export async function enableFullFeatureSet(fullFeatureSet: boolean) {
await util.setContextValue("cmake:enableFullFeatureSet", fullFeatureSet);
extensionManager?.showStatusBar(fullFeatureSet);
}
export function isActiveFolder(folder: vscode.WorkspaceFolder): boolean | undefined {
const cmtFolder = extensionManager?.getCMTFolder(folder);
return cmtFolder && extensionManager?.isActiveFolder(cmtFolder);
}
// This method updates the full/partial view state of the given folder
// (by analyzing the valid state of its CMakeLists.txt)
// and also calculates the impact on the whole workspace.
// It is called whenever a project folder goes through a relevant event:
// sourceDirectory change, CMakeLists.txt creation/move/deletion.
export async function updateFullFeatureSetForFolder(folder: vscode.WorkspaceFolder) {
if (extensionManager) {
const cmt = extensionManager.getCMTFolder(folder)?.cmakeTools;
if (cmt) {
// Save the CMakeLists valid state in the map for later reference
// and evaluate its effects on the global full feature set view.
const folderFullFeatureSet: boolean = await extensionManager.folderIsCMakeProject(cmt);
// Reset ignoreCMakeListsMissing now that we have a valid CMakeLists.txt
// so that the next time we don't have one the user is notified.
if (folderFullFeatureSet) {
await cmt.workspaceContext.state.setIgnoreCMakeListsMissing(false);
}
// If the given folder is a CMake project, enable full feature set for the whole workspace,
// otherwise search for at least one more CMake project folder.
let workspaceFullFeatureSet = folderFullFeatureSet;
if (!workspaceFullFeatureSet && extensionManager) {
workspaceFullFeatureSet = await extensionManager.workspaceHasCMakeProject();
}
await enableFullFeatureSet(workspaceFullFeatureSet);
return;
}
}
// This shouldn't normally happen (not finding a CMT or not having a valid extension manager)
// but just in case, enable full feature set.
log.info(`Cannot find CMT for folder ${folder.name} or we don't have an extension manager created yet. ` +
`Setting feature set view to "full".`);
await enableFullFeatureSet(true);
}
// update CMakeDriver in taskProvider
export function updateCMakeDriverInTaskProvider(cmakeDriver: CMakeDriver) {
cmakeTaskProvider.updateCMakeDriver(cmakeDriver);
}
// update default target in taskProvider
export function updateDefaultTargetsInTaskProvider(defaultTargets?: string[]) {
cmakeTaskProvider.updateDefaultTargets(defaultTargets);
}
// Whether this CMake Tools extension instance will show the "Create/Locate/Ignore" toast popup
// for a non CMake project (as opposed to listing all existing CMakeLists.txt in the workspace
// in a quickPick.)
export function showCMakeListsExperiment(): Promise<boolean> {
return extensionManager?.showCMakeListsExperiment() || Promise.resolve(false);
}
// this method is called when your extension is deactivated.
export async function deactivate() {
log.debug(localize('deactivate.cmaketools', 'Deactivate CMakeTools'));
if (extensionManager) {
await extensionManager.asyncDispose();
}
if (taskProvider) {
taskProvider.dispose();
}
} | the_stack |
declare namespace commander {
interface CommanderError extends Error {
code: string;
exitCode: number;
message: string;
nestedError?: string;
}
type CommanderErrorConstructor = new (exitCode: number, code: string, message: string) => CommanderError;
interface Option {
flags: string;
required: boolean; // A value must be supplied when the option is specified.
optional: boolean; // A value is optional when the option is specified.
mandatory: boolean; // The option must have a value after parsing, which usually means it must be specified on command line.
bool: boolean;
short?: string;
long: string;
description: string;
}
type OptionConstructor = new (flags: string, description?: string) => Option;
interface ParseOptions {
from: 'node' | 'electron' | 'user';
}
interface Command {
[key: string]: any; // options as properties
args: string[];
commands: Command[];
/**
* Set the program version to `str`.
*
* This method auto-registers the "-V, --version" flag
* which will print the version number when passed.
*
* You can optionally supply the flags and description to override the defaults.
*/
version(str: string, flags?: string, description?: string): this;
/**
* Define a command, implemented using an action handler.
*
* @remarks
* The command description is supplied using `.description`, not as a parameter to `.command`.
*
* @example
* ```ts
* program
* .command('clone <source> [destination]')
* .description('clone a repository into a newly created directory')
* .action((source, destination) => {
* console.log('clone command called');
* });
* ```
*
* @param nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
* @param opts - configuration options
* @returns new command
*/
command(nameAndArgs: string, opts?: CommandOptions): ReturnType<this['createCommand']>;
/**
* Define a command, implemented in a separate executable file.
*
* @remarks
* The command description is supplied as the second parameter to `.command`.
*
* @example
* ```ts
* program
* .command('start <service>', 'start named service')
* .command('stop [service]', 'stop named service, or all if no name supplied');
* ```
*
* @param nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
* @param description - description of executable command
* @param opts - configuration options
* @returns `this` command for chaining
*/
command(nameAndArgs: string, description: string, opts?: commander.ExecutableCommandOptions): this;
/**
* Factory routine to create a new unattached command.
*
* See .command() for creating an attached subcommand, which uses this routine to
* create the command. You can override createCommand to customise subcommands.
*/
createCommand(name?: string): Command;
/**
* Add a prepared subcommand.
*
* See .command() for creating an attached subcommand which inherits settings from its parent.
*
* @returns `this` command for chaining
*/
addCommand(cmd: Command, opts?: CommandOptions): this;
/**
* Define argument syntax for command.
*
* @returns `this` command for chaining
*/
arguments(desc: string): this;
/**
* Override default decision whether to add implicit help command.
*
* addHelpCommand() // force on
* addHelpCommand(false); // force off
* addHelpCommand('help [cmd]', 'display help for [cmd]'); // force on with custom details
*
* @returns `this` command for chaining
*/
addHelpCommand(enableOrNameAndArgs?: string | boolean, description?: string): this;
/**
* Register callback to use as replacement for calling process.exit.
*/
exitOverride(callback?: (err: CommanderError) => never|void): this;
/**
* Register callback `fn` for the command.
*
* @example
* program
* .command('help')
* .description('display verbose help')
* .action(function() {
* // output help here
* });
*
* @returns `this` command for chaining
*/
action(fn: (...args: any[]) => void | Promise<void>): this;
/**
* Define option with `flags`, `description` and optional
* coercion `fn`.
*
* The `flags` string should contain both the short and long flags,
* separated by comma, a pipe or space. The following are all valid
* all will output this way when `--help` is used.
*
* "-p, --pepper"
* "-p|--pepper"
* "-p --pepper"
*
* @example
* // simple boolean defaulting to false
* program.option('-p, --pepper', 'add pepper');
*
* --pepper
* program.pepper
* // => Boolean
*
* // simple boolean defaulting to true
* program.option('-C, --no-cheese', 'remove cheese');
*
* program.cheese
* // => true
*
* --no-cheese
* program.cheese
* // => false
*
* // required argument
* program.option('-C, --chdir <path>', 'change the working directory');
*
* --chdir /tmp
* program.chdir
* // => "/tmp"
*
* // optional argument
* program.option('-c, --cheese [type]', 'add cheese [marble]');
*
* @returns `this` command for chaining
*/
option(flags: string, description?: string, defaultValue?: string | boolean): this;
option(flags: string, description: string, regexp: RegExp, defaultValue?: string | boolean): this;
option<T>(flags: string, description: string, fn: (value: string, previous: T) => T, defaultValue?: T): this;
/**
* Define a required option, which must have a value after parsing. This usually means
* the option must be specified on the command line. (Otherwise the same as .option().)
*
* The `flags` string should contain both the short and long flags, separated by comma, a pipe or space.
*/
requiredOption(flags: string, description?: string, defaultValue?: string | boolean): this;
requiredOption(flags: string, description: string, regexp: RegExp, defaultValue?: string | boolean): this;
requiredOption<T>(flags: string, description: string, fn: (value: string, previous: T) => T, defaultValue?: T): this;
/**
* Whether to store option values as properties on command object,
* or store separately (specify false). In both cases the option values can be accessed using .opts().
*
* @returns `this` command for chaining
*/
storeOptionsAsProperties(value?: boolean): this;
/**
* Whether to pass command to action handler,
* or just the options (specify false).
*
* @returns `this` command for chaining
*/
passCommandToAction(value?: boolean): this;
/**
* Alter parsing of short flags with optional values.
*
* @example
* // for `.option('-f,--flag [value]'):
* .combineFlagAndOptionalValue(true) // `-f80` is treated like `--flag=80`, this is the default behaviour
* .combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
*
* @returns `this` command for chaining
*/
combineFlagAndOptionalValue(arg?: boolean): this;
/**
* Allow unknown options on the command line.
*
* @param [arg] if `true` or omitted, no error will be thrown for unknown options.
* @returns `this` command for chaining
*/
allowUnknownOption(arg?: boolean): this;
/**
* Parse `argv`, setting options and invoking commands when defined.
*
* The default expectation is that the arguments are from node and have the application as argv[0]
* and the script being run in argv[1], with user parameters after that.
*
* Examples:
*
* program.parse(process.argv);
* program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions
* program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
*
* @returns `this` command for chaining
*/
parse(argv?: string[], options?: ParseOptions): this;
/**
* Parse `argv`, setting options and invoking commands when defined.
*
* Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise.
*
* The default expectation is that the arguments are from node and have the application as argv[0]
* and the script being run in argv[1], with user parameters after that.
*
* Examples:
*
* program.parseAsync(process.argv);
* program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions
* program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
*
* @returns Promise
*/
parseAsync(argv?: string[], options?: ParseOptions): Promise<this>;
/**
* Parse options from `argv` removing known options,
* and return argv split into operands and unknown arguments.
*
* @example
* argv => operands, unknown
* --known kkk op => [op], []
* op --known kkk => [op], []
* sub --unknown uuu op => [sub], [--unknown uuu op]
* sub -- --unknown uuu op => [sub --unknown uuu op], []
*/
parseOptions(argv: string[]): commander.ParseOptionsResult;
/**
* Return an object containing options as key-value pairs
*/
opts(): { [key: string]: any };
/**
* Set the description.
*
* @returns `this` command for chaining
*/
description(str: string, argsDescription?: {[argName: string]: string}): this;
/**
* Get the description.
*/
description(): string;
/**
* Set an alias for the command.
*
* You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
*
* @returns `this` command for chaining
*/
alias(alias: string): this;
/**
* Get alias for the command.
*/
alias(): string;
/**
* Set aliases for the command.
*
* Only the first alias is shown in the auto-generated help.
*
* @returns `this` command for chaining
*/
aliases(aliases: string[]): this;
/**
* Get aliases for the command.
*/
aliases(): string[];
/**
* Set the command usage.
*
* @returns `this` command for chaining
*/
usage(str: string): this;
/**
* Get the command usage.
*/
usage(): string;
/**
* Set the name of the command.
*
* @returns `this` command for chaining
*/
name(str: string): this;
/**
* Get the name of the command.
*/
name(): string;
/**
* Output help information for this command.
*
* When listener(s) are available for the helpLongFlag
* those callbacks are invoked.
*/
outputHelp(cb?: (str: string) => string): void;
/**
* Return command help documentation.
*/
helpInformation(): string;
/**
* You can pass in flags and a description to override the help
* flags and help description for your command. Pass in false
* to disable the built-in help option.
*/
helpOption(flags?: string | boolean, description?: string): this;
/**
* Output help information and exit.
*/
help(cb?: (str: string) => string): never;
/**
* Add a listener (callback) for when events occur. (Implemented using EventEmitter.)
*
* @example
* program
* .on('--help', () -> {
* console.log('See web site for more information.');
* });
*/
on(event: string | symbol, listener: (...args: any[]) => void): this;
}
type CommandConstructor = new (name?: string) => Command;
interface CommandOptions {
noHelp?: boolean; // old name for hidden
hidden?: boolean;
isDefault?: boolean;
}
interface ExecutableCommandOptions extends CommandOptions {
executableFile?: string;
}
interface ParseOptionsResult {
operands: string[];
unknown: string[];
}
interface CommanderStatic extends Command {
program: Command;
Command: CommandConstructor;
Option: OptionConstructor;
CommanderError: CommanderErrorConstructor;
}
}
// Declaring namespace AND global
// eslint-disable-next-line @typescript-eslint/no-redeclare
declare const commander: commander.CommanderStatic;
export = commander; | the_stack |
import { Observable } from "../../Misc/observable";
import { Nullable, int } from "../../types";
import { ICanvas, ICanvasRenderingContext } from "../../Engines/ICanvas";
import { HardwareTextureWrapper } from "./hardwareTextureWrapper";
import { TextureSampler } from "./textureSampler";
declare type ThinEngine = import("../../Engines/thinEngine").ThinEngine;
declare type BaseTexture = import("../../Materials/Textures/baseTexture").BaseTexture;
declare type SphericalPolynomial = import("../../Maths/sphericalPolynomial").SphericalPolynomial;
/**
* Defines the source of the internal texture
*/
export enum InternalTextureSource {
/**
* The source of the texture data is unknown
*/
Unknown,
/**
* Texture data comes from an URL
*/
Url,
/**
* Texture data is only used for temporary storage
*/
Temp,
/**
* Texture data comes from raw data (ArrayBuffer)
*/
Raw,
/**
* Texture content is dynamic (video or dynamic texture)
*/
Dynamic,
/**
* Texture content is generated by rendering to it
*/
RenderTarget,
/**
* Texture content is part of a multi render target process
*/
MultiRenderTarget,
/**
* Texture data comes from a cube data file
*/
Cube,
/**
* Texture data comes from a raw cube data
*/
CubeRaw,
/**
* Texture data come from a prefiltered cube data file
*/
CubePrefiltered,
/**
* Texture content is raw 3D data
*/
Raw3D,
/**
* Texture content is raw 2D array data
*/
Raw2DArray,
/**
* Texture content is a depth/stencil texture
*/
DepthStencil,
/**
* Texture data comes from a raw cube data encoded with RGBD
*/
CubeRawRGBD,
/**
* Texture content is a depth texture
*/
Depth,
}
/**
* Class used to store data associated with WebGL texture data for the engine
* This class should not be used directly
*/
export class InternalTexture extends TextureSampler {
/**
* Defines if the texture is ready
*/
public isReady: boolean = false;
/**
* Defines if the texture is a cube texture
*/
public isCube: boolean = false;
/**
* Defines if the texture contains 3D data
*/
public is3D: boolean = false;
/**
* Defines if the texture contains 2D array data
*/
public is2DArray: boolean = false;
/**
* Defines if the texture contains multiview data
*/
public isMultiview: boolean = false;
/**
* Gets the URL used to load this texture
*/
public url: string = "";
/** @hidden */
public _originalUrl: string; // not empty only if different from url
/**
* Gets a boolean indicating if the texture needs mipmaps generation
*/
public generateMipMaps: boolean = false;
/**
* Gets a boolean indicating if the texture uses mipmaps
* TODO implements useMipMaps as a separate setting from generateMipMaps
*/
public get useMipMaps() {
return this.generateMipMaps;
}
public set useMipMaps(value: boolean) {
this.generateMipMaps = value;
}
/**
* Gets the number of samples used by the texture (WebGL2+ only)
*/
public samples: number = 0;
/**
* Gets the type of the texture (int, float...)
*/
public type: number = -1;
/**
* Gets the format of the texture (RGB, RGBA...)
*/
public format: number = -1;
/**
* Observable called when the texture is loaded
*/
public onLoadedObservable = new Observable<InternalTexture>();
/**
* Observable called when the texture load is raising an error
*/
public onErrorObservable = new Observable<Partial<{ message: string, exception: any }>>();
/**
* If this callback is defined it will be called instead of the default _rebuild function
*/
public onRebuildCallback: Nullable<(internalTexture: InternalTexture) => {
proxy: Nullable<InternalTexture | Promise<InternalTexture>>;
isReady: boolean;
isAsync: boolean;
}> = null;
/**
* Gets the width of the texture
*/
public width: number = 0;
/**
* Gets the height of the texture
*/
public height: number = 0;
/**
* Gets the depth of the texture
*/
public depth: number = 0;
/**
* Gets the initial width of the texture (It could be rescaled if the current system does not support non power of two textures)
*/
public baseWidth: number = 0;
/**
* Gets the initial height of the texture (It could be rescaled if the current system does not support non power of two textures)
*/
public baseHeight: number = 0;
/**
* Gets the initial depth of the texture (It could be rescaled if the current system does not support non power of two textures)
*/
public baseDepth: number = 0;
/**
* Gets a boolean indicating if the texture is inverted on Y axis
*/
public invertY: boolean = false;
// Private
/** @hidden */
public _invertVScale = false;
/** @hidden */
public _associatedChannel = -1;
/** @hidden */
public _source = InternalTextureSource.Unknown;
/** @hidden */
public _buffer: Nullable<string | ArrayBuffer | ArrayBufferView | HTMLImageElement | Blob | ImageBitmap> = null;
/** @hidden */
public _bufferView: Nullable<ArrayBufferView> = null;
/** @hidden */
public _bufferViewArray: Nullable<ArrayBufferView[]> = null;
/** @hidden */
public _bufferViewArrayArray: Nullable<ArrayBufferView[][]> = null;
/** @hidden */
public _size: number = 0;
/** @hidden */
public _extension: string = "";
/** @hidden */
public _files: Nullable<string[]> = null;
/** @hidden */
public _workingCanvas: Nullable<ICanvas> = null;
/** @hidden */
public _workingContext: Nullable<ICanvasRenderingContext> = null;
/** @hidden */
public _cachedCoordinatesMode: Nullable<number> = null;
/** @hidden */
public _isDisabled: boolean = false;
/** @hidden */
public _compression: Nullable<string> = null;
/** @hidden */
public _sphericalPolynomial: Nullable<SphericalPolynomial> = null;
/** @hidden */
public _sphericalPolynomialPromise: Nullable<Promise<SphericalPolynomial>> = null;
/** @hidden */
public _sphericalPolynomialComputed = false;
/** @hidden */
public _lodGenerationScale: number = 0;
/** @hidden */
public _lodGenerationOffset: number = 0;
/** @hidden */
public _useSRGBBuffer: boolean = false;
// The following three fields helps sharing generated fixed LODs for texture filtering
// In environment not supporting the textureLOD extension like EDGE. They are for internal use only.
// They are at the level of the gl texture to benefit from the cache.
/** @hidden */
public _lodTextureHigh: Nullable<BaseTexture> = null;
/** @hidden */
public _lodTextureMid: Nullable<BaseTexture> = null;
/** @hidden */
public _lodTextureLow: Nullable<BaseTexture> = null;
/** @hidden */
public _isRGBD: boolean = false;
/** @hidden */
public _linearSpecularLOD: boolean = false;
/** @hidden */
public _irradianceTexture: Nullable<BaseTexture> = null;
/** @hidden */
public _hardwareTexture: Nullable<HardwareTextureWrapper> = null;
/** @hidden */
public _references: number = 1;
/** @hidden */
public _gammaSpace: Nullable<boolean> = null;
private _engine: ThinEngine;
private _uniqueId: number;
/** @hidden */
public static _Counter = 0;
/** Gets the unique id of the internal texture */
public get uniqueId() {
return this._uniqueId;
}
/**
* Gets the Engine the texture belongs to.
* @returns The babylon engine
*/
public getEngine(): ThinEngine {
return this._engine;
}
/**
* Gets the data source type of the texture
*/
public get source(): InternalTextureSource {
return this._source;
}
/**
* Creates a new InternalTexture
* @param engine defines the engine to use
* @param source defines the type of data that will be used
* @param delayAllocation if the texture allocation should be delayed (default: false)
*/
constructor(engine: ThinEngine, source: InternalTextureSource, delayAllocation = false) {
super();
this._engine = engine;
this._source = source;
this._uniqueId = InternalTexture._Counter++;
if (!delayAllocation) {
this._hardwareTexture = engine._createHardwareTexture();
}
}
/**
* Increments the number of references (ie. the number of Texture that point to it)
*/
public incrementReferences(): void {
this._references++;
}
/**
* Change the size of the texture (not the size of the content)
* @param width defines the new width
* @param height defines the new height
* @param depth defines the new depth (1 by default)
*/
public updateSize(width: int, height: int, depth: int = 1): void {
this._engine.updateTextureDimensions(this, width, height, depth);
this.width = width;
this.height = height;
this.depth = depth;
this.baseWidth = width;
this.baseHeight = height;
this.baseDepth = depth;
this._size = width * height * depth;
}
/** @hidden */
public _rebuild(): void {
this.isReady = false;
this._cachedCoordinatesMode = null;
this._cachedWrapU = null;
this._cachedWrapV = null;
this._cachedWrapR = null;
this._cachedAnisotropicFilteringLevel = null;
if (this.onRebuildCallback) {
const data = this.onRebuildCallback(this);
const swapAndSetIsReady = (proxyInternalTexture: InternalTexture) => {
proxyInternalTexture._swapAndDie(this, false);
this.isReady = data.isReady;
};
if (data.isAsync) {
(data.proxy as Promise<InternalTexture>).then(swapAndSetIsReady);
} else {
swapAndSetIsReady((data.proxy as InternalTexture));
}
return;
}
let proxy: InternalTexture;
switch (this.source) {
case InternalTextureSource.Temp:
break;
case InternalTextureSource.Url:
proxy = this._engine.createTexture(this._originalUrl ?? this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, () => {
proxy._swapAndDie(this, false);
this.isReady = true;
}, null, this._buffer, undefined, this.format, this._extension, undefined, undefined, undefined, this._useSRGBBuffer);
return;
case InternalTextureSource.Raw:
proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps,
this.invertY, this.samplingMode, this._compression, this.type);
proxy._swapAndDie(this, false);
this.isReady = true;
break;
case InternalTextureSource.Raw3D:
proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps,
this.invertY, this.samplingMode, this._compression, this.type);
proxy._swapAndDie(this, false);
this.isReady = true;
break;
case InternalTextureSource.Raw2DArray:
proxy = this._engine.createRawTexture2DArray(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps,
this.invertY, this.samplingMode, this._compression, this.type);
proxy._swapAndDie(this, false);
this.isReady = true;
break;
case InternalTextureSource.Dynamic:
proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
proxy._swapAndDie(this, false);
this._engine.updateDynamicTexture(this, this._engine.getRenderingCanvas()!, this.invertY, undefined, undefined, true);
// The engine will make sure to update content so no need to flag it as isReady = true
break;
case InternalTextureSource.Cube:
proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, () => {
proxy._swapAndDie(this, false);
this.isReady = true;
}, null, this.format, this._extension, false, 0, 0, null, undefined, this._useSRGBBuffer);
return;
case InternalTextureSource.CubeRaw:
proxy = this._engine.createRawCubeTexture(this._bufferViewArray!, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
proxy._swapAndDie(this, false);
this.isReady = true;
break;
case InternalTextureSource.CubeRawRGBD:
// This case is being handeled by the environment texture tools and is not a part of the rebuild process.
// To use CubeRawRGBD use updateRGBDAsync on the cube texture.
return;
case InternalTextureSource.CubePrefiltered:
proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, (proxy) => {
if (proxy) {
proxy._swapAndDie(this, false);
}
this.isReady = true;
}, null, this.format, this._extension);
proxy._sphericalPolynomial = this._sphericalPolynomial;
return;
}
}
/** @hidden */
public _swapAndDie(target: InternalTexture, swapAll = true): void {
// TODO what about refcount on target?
this._hardwareTexture?.setUsage(target._source, this.generateMipMaps, this.isCube, this.width, this.height);
target._hardwareTexture = this._hardwareTexture;
if (swapAll) {
target._isRGBD = this._isRGBD;
}
if (this._lodTextureHigh) {
if (target._lodTextureHigh) {
target._lodTextureHigh.dispose();
}
target._lodTextureHigh = this._lodTextureHigh;
}
if (this._lodTextureMid) {
if (target._lodTextureMid) {
target._lodTextureMid.dispose();
}
target._lodTextureMid = this._lodTextureMid;
}
if (this._lodTextureLow) {
if (target._lodTextureLow) {
target._lodTextureLow.dispose();
}
target._lodTextureLow = this._lodTextureLow;
}
if (this._irradianceTexture) {
if (target._irradianceTexture) {
target._irradianceTexture.dispose();
}
target._irradianceTexture = this._irradianceTexture;
}
let cache = this._engine.getLoadedTexturesCache();
var index = cache.indexOf(this);
if (index !== -1) {
cache.splice(index, 1);
}
var index = cache.indexOf(target);
if (index === -1) {
cache.push(target);
}
}
/**
* Dispose the current allocated resources
*/
public dispose(): void {
this._references--;
this.onLoadedObservable.clear();
this.onErrorObservable.clear();
if (this._references === 0) {
this._engine._releaseTexture(this);
this._hardwareTexture = null;
}
}
} | the_stack |
import { Color } from '../../math/Color'
import { Matrix4 } from '../../math/Matrix4'
import { Vector2 } from '../../math/Vector2'
import { Vector3 } from '../../math/Vector3'
import { Light } from '../../lights/Light'
import { Camera } from '../../cameras/Camera'
import { PointLight } from '../../lights/PointLight'
class LightUniforms {
static isLightUniforms: bool = true
}
class PointLightUniforms extends LightUniforms {
position: Vector3
color: Color
distance: f32
decay: f32
}
class UniformsCache {
lights: Map<i32, LightUniforms> = new Map()
get(light: Light): LightUniforms {
if (this.lights.has(light.id)) return this.lights.get(light.id)
let uniforms: LightUniforms | null = null
// TODO
// case 'DirectionalLight':
// uniforms = {
// direction: new Vector3(),
// color: new Color(),
// }
// break
// TODO
// case 'SpotLight':
// uniforms = {
// position: new Vector3(),
// direction: new Vector3(),
// color: new Color(),
// distance: 0,
// coneCos: 0,
// penumbraCos: 0,
// decay: 0,
// }
// break
if (light.type === 'PointLight') {
uniforms = {
position: new Vector3(),
color: new Color(),
distance: 0,
decay: 0,
} as PointLightUniforms
}
// TODO
// case 'HemisphereLight':
// uniforms = {
// direction: new Vector3(),
// skyColor: new Color(),
// groundColor: new Color(),
// }
// break
// TODO
// case 'RectAreaLight':
// uniforms = {
// color: new Color(),
// position: new Vector3(),
// halfWidth: new Vector3(),
// halfHeight: new Vector3(),
// }
// break
if (!uniforms) abort('Unknown light type.')
// This conditional check is not needed, but AS does not narrow the type with the previous abort() call.
if (uniforms) {
this.lights.set(light.id, uniforms)
return uniforms
}
// This never happens, but we need to trick AS/TS.
return new LightUniforms()
}
}
class ShadowUniforms {
static isShadowUniforms: bool = true
}
class PointLightShadowUniforms extends ShadowUniforms {
shadowBias: f32
shadowRadius: f32
shadowMapSize: Vector2
shadowCameraNear: f32
shadowCameraFar: f32
}
class ShadowUniformsCache {
lights: Map<i32, ShadowUniforms> = new Map()
get(light: Light): ShadowUniforms {
if (this.lights.has(light.id)) return this.lights.get(light.id)
let uniforms: ShadowUniforms | null = null
switch (light.type) {
// TODO
// case 'DirectionalLight':
// uniforms = {
// shadowBias: 0,
// shadowRadius: 1,
// shadowMapSize: new Vector2(),
// }
// break
// TODO
// case 'SpotLight':
// uniforms = {
// shadowBias: 0,
// shadowRadius: 1,
// shadowMapSize: new Vector2(),
// }
// break
case 'PointLight':
uniforms = {
shadowBias: 0,
shadowRadius: 1,
shadowMapSize: new Vector2(),
shadowCameraNear: 1,
shadowCameraFar: 1000,
} as PointLightShadowUniforms
break
// TODO (abelnation): set RectAreaLight shadow uniforms
}
if (!uniforms) abort('Unknown light type.')
// This conditional check is not needed, but AS does not narrow the type with the previous abort() call.
if (uniforms) {
this.lights.set(light.id, uniforms)
return uniforms
}
// This never happens, but we need to trick AS/TS.
return new ShadowUniforms()
}
}
let nextVersion: i32 = 0
class Hash {
// directionalLength: i32
pointLength: i32
// spotLength: i32
// rectAreaLength: i32
// hemiLength: i32
// numDirectionalShadows: i32
numPointShadows: i32
// numSpotShadows: i32
}
class State {
version: i32
hash: Hash
// ambient: Array<f32>
// probe: Array<Vector3>
// directional: Array<any>
// directionalShadow: Array<any>
// directionalShadowMap: Array<any>
// directionalShadowMatrix: Array<any>
// spot: Array<any>
// spotShadow: Array<any>
// spotShadowMap: Array<any>
// spotShadowMatrix: Array<any>
// rectArea: Array<any>
point: Array<PointLightUniforms>
// pointShadow: Array<any>
// pointShadowMap: Array<any>
// pointShadowMatrix: Array<any>
// hemi: Array<any>
}
export class WebGLLights {
constructor() {
// for (let i = 0; i < 9; i++) this.state.probe.push(new Vector3())
}
cache: UniformsCache = new UniformsCache()
shadowCache: ShadowUniformsCache = new ShadowUniformsCache()
state: State = {
version: 0,
hash: {
// directionalLength: -1,
pointLength: -1,
// spotLength: -1,
// rectAreaLength: -1,
// hemiLength: -1,
// numDirectionalShadows: -1,
numPointShadows: -1,
// numSpotShadows: -1,
},
// ambient: [0, 0, 0],
// probe: [],
// directional: [],
// directionalShadow: [],
// directionalShadowMap: [],
// directionalShadowMatrix: [],
// spot: [],
// spotShadow: [],
// spotShadowMap: [],
// spotShadowMatrix: [],
// rectArea: [],
point: [],
// pointShadow: [],
// pointShadowMap: [],
// pointShadowMatrix: [],
// hemi: [],
}
vector3: Vector3 = new Vector3()
matrix4: Matrix4 = new Matrix4()
matrix42: Matrix4 = new Matrix4()
setup(lights: Light[], shadows: Light[], camera: Camera): void {
let r = 0,
g = 0,
b = 0
// for (let i = 0; i < 9; i++) this.state.probe[i].set(0, 0, 0)
// let directionalLength = 0
let pointLength: i32 = 0
// let spotLength = 0
// let rectAreaLength = 0
// let hemiLength = 0
// let numDirectionalShadows = 0
let numPointShadows = 0
// let numSpotShadows = 0
const viewMatrix = camera.matrixWorldInverse
// lights.sort(shadowCastingLightsFirst)
for (let i = 0, l = lights.length; i < l; i++) {
const light = lights[i]
const color = light.color
const intensity = light.intensity
const distance = light.distance
// let shadowMap: LightShadow = null
// if (
// light instanceof PointLight
// // TODO
// // || light instanceof DirectionalLight
// // || light instanceof SpotLight
// ) {
// shadowMap = light.shadow && light.shadow.map ? light.shadow.map.texture : null
// }
// if (light.isAmbientLight) {
// r += color.r * intensity
// g += color.g * intensity
// b += color.b * intensity
// } else if (light.isLightProbe) {
// for (let j = 0; j < 9; j++) {
// this.state.probe[j].addScaledVector(light.sh.coefficients[j], intensity)
// }
// } else if (light.isDirectionalLight) {
// const uniforms = this.cache.get(light)
// uniforms.color.copy(light.color).multiplyScalar(light.intensity)
// uniforms.direction.setFromMatrixPosition(light.matrixWorld)
// vector3.setFromMatrixPosition(light.target.matrixWorld)
// uniforms.direction.sub(vector3)
// uniforms.direction.transformDirection(viewMatrix)
// if (light.castShadow) {
// const shadow = light.shadow
// const shadowUniforms = this.shadowCache.get(light)
// shadowUniforms.shadowBias = shadow.bias
// shadowUniforms.shadowRadius = shadow.radius
// shadowUniforms.shadowMapSize = shadow.mapSize
// this.state.directionalShadow[directionalLength] = shadowUniforms
// this.state.directionalShadowMap[directionalLength] = shadowMap
// this.state.directionalShadowMatrix[directionalLength] = light.shadow.matrix
// numDirectionalShadows++
// }
// this.state.directional[directionalLength] = uniforms
// directionalLength++
// } else if (light.isSpotLight) {
// const uniforms = this.cache.get(light)
// uniforms.position.setFromMatrixPosition(light.matrixWorld)
// uniforms.position.applyMatrix4(viewMatrix)
// uniforms.color.copy(color).multiplyScalar(intensity)
// uniforms.distance = distance
// uniforms.direction.setFromMatrixPosition(light.matrixWorld)
// vector3.setFromMatrixPosition(light.target.matrixWorld)
// uniforms.direction.sub(vector3)
// uniforms.direction.transformDirection(viewMatrix)
// uniforms.coneCos = Math.cos(light.angle)
// uniforms.penumbraCos = Math.cos(light.angle * (1 - light.penumbra))
// uniforms.decay = light.decay
// if (light.castShadow) {
// const shadow = light.shadow
// const shadowUniforms = this.shadowCache.get(light)
// shadowUniforms.shadowBias = shadow.bias
// shadowUniforms.shadowRadius = shadow.radius
// shadowUniforms.shadowMapSize = shadow.mapSize
// this.state.spotShadow[spotLength] = shadowUniforms
// this.state.spotShadowMap[spotLength] = shadowMap
// this.state.spotShadowMatrix[spotLength] = light.shadow.matrix
// numSpotShadows++
// }
// this.state.spot[spotLength] = uniforms
// spotLength++
// } else if (light.isRectAreaLight) {
// const uniforms = this.cache.get(light)
// // (a) intensity is the total visible light emitted
// //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
// // (b) intensity is the brightness of the light
// uniforms.color.copy(color).multiplyScalar(intensity)
// uniforms.position.setFromMatrixPosition(light.matrixWorld)
// uniforms.position.applyMatrix4(viewMatrix)
// // extract local rotation of light to derive width/height half vectors
// matrix42.identity()
// matrix4.copy(light.matrixWorld)
// matrix4.premultiply(viewMatrix)
// matrix42.extractRotation(matrix4)
// uniforms.halfWidth.set(light.width * 0.5, 0.0, 0.0)
// uniforms.halfHeight.set(0.0, light.height * 0.5, 0.0)
// uniforms.halfWidth.applyMatrix4(matrix42)
// uniforms.halfHeight.applyMatrix4(matrix42)
// // TODO (abelnation): RectAreaLight distance?
// // uniforms.distance = distance;
// this.state.rectArea[rectAreaLength] = uniforms
// rectAreaLength++
// } else
if (light instanceof PointLight) {
const _light = light as PointLight // casting needed for AS, AS does not (yet) have type narrowing
const uniforms = this.cache.get(_light) as PointLightUniforms
// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// log(' ----------------------------------------------------- ')
uniforms.position.setFromMatrixPosition(_light.matrixWorld)
uniforms.position.applyMatrix4(viewMatrix)
uniforms.color.copy(_light.color).multiplyScalar(_light.intensity)
uniforms.distance = _light.distance
uniforms.decay = _light.decay
// if (_light.castShadow) {
// const shadow = _light.shadow
// const shadowUniforms = this.shadowCache.get(_light)
// shadowUniforms.shadowBias = shadow.bias
// shadowUniforms.shadowRadius = shadow.radius
// shadowUniforms.shadowMapSize = shadow.mapSize
// shadowUniforms.shadowCameraNear = shadow.camera.near
// shadowUniforms.shadowCameraFar = shadow.camera.far
// this.state.pointShadow[pointLength] = shadowUniforms
// // this.state.pointShadowMap[pointLength] = shadowMap
// this.state.pointShadowMatrix[pointLength] = _light.shadow.matrix
// numPointShadows++
// }
this.state.point[pointLength] = uniforms
pointLength++
}
// else if (light.isHemisphereLight) {
// const uniforms = this.cache.get(light)
// uniforms.direction.setFromMatrixPosition(light.matrixWorld)
// uniforms.direction.transformDirection(viewMatrix)
// uniforms.direction.normalize()
// uniforms.skyColor.copy(light.color).multiplyScalar(intensity)
// uniforms.groundColor.copy(light.groundColor).multiplyScalar(intensity)
// this.state.hemi[hemiLength] = uniforms
// hemiLength++
// }
}
// this.state.ambient[0] = r
// this.state.ambient[1] = g
// this.state.ambient[2] = b
const hash = this.state.hash
if (
// hash.directionalLength !== directionalLength ||
// hash.pointLength !== pointLength ||
// hash.spotLength !== spotLength ||
// hash.rectAreaLength !== rectAreaLength ||
// hash.hemiLength !== hemiLength ||
// hash.numDirectionalShadows !== numDirectionalShadows ||
hash.numPointShadows !== numPointShadows
// || hash.numSpotShadows !== numSpotShadows
) {
// this.state.directional.length = directionalLength
// this.state.spot.length = spotLength
// this.state.rectArea.length = rectAreaLength
this.state.point.length = pointLength
// this.state.hemi.length = hemiLength
// this.state.directionalShadow.length = numDirectionalShadows
// this.state.directionalShadowMap.length = numDirectionalShadows
// this.state.pointShadow.length = numPointShadows
// this.state.pointShadowMap.length = numPointShadows
// this.state.spotShadow.length = numSpotShadows
// this.state.spotShadowMap.length = numSpotShadows
// this.state.directionalShadowMatrix.length = numDirectionalShadows
// this.state.pointShadowMatrix.length = numPointShadows
// this.state.spotShadowMatrix.length = numSpotShadows
// hash.directionalLength = directionalLength
hash.pointLength = pointLength
// hash.spotLength = spotLength
// hash.rectAreaLength = rectAreaLength
// hash.hemiLength = hemiLength
// hash.numDirectionalShadows = numDirectionalShadows
hash.numPointShadows = numPointShadows
// hash.numSpotShadows = numSpotShadows
this.state.version = nextVersion++
}
}
}
// function shadowCastingLightsFirst(lightA, lightB) {
// return (lightB.castShadow ? 1 : 0) - (lightA.castShadow ? 1 : 0)
// } | the_stack |
import { codec } from '@liskhq/lisk-codec';
import { getAddressFromPublicKey } from '@liskhq/lisk-cryptography';
import { BlockHeader, Chain, getValidators, StateStore } from '@liskhq/lisk-chain';
import * as assert from 'assert';
import * as createDebug from 'debug';
import { EventEmitter } from 'events';
import { dataStructures } from '@liskhq/lisk-utils';
import { BFT_ROUND_THRESHOLD } from './constant';
import { BFTInvalidAttributeError, BFTError } from './types';
import { areHeadersContradicting } from './header_contradicting';
const debug = createDebug('lisk:bft:consensus_manager');
export const EVENT_BFT_FINALIZED_HEIGHT_CHANGED = 'EVENT_BFT_FINALIZED_HEIGHT_CHANGED';
export const CONSENSUS_STATE_VALIDATOR_LEDGER_KEY = 'bft:votingLedger';
export const BFTVotingLedgerSchema = {
type: 'object',
$id: '/bft/validators',
title: 'Lisk BFT Validator ledger',
required: ['validators', 'ledger'],
properties: {
validators: {
type: 'array',
fieldNumber: 1,
items: {
type: 'object',
required: ['address', 'maxPreVoteHeight', 'maxPreCommitHeight'],
properties: {
address: {
dataType: 'bytes',
fieldNumber: 1,
},
maxPreVoteHeight: {
dataType: 'uint32',
fieldNumber: 2,
},
maxPreCommitHeight: {
dataType: 'uint32',
fieldNumber: 3,
},
},
},
},
ledger: {
type: 'array',
fieldNumber: 2,
items: {
type: 'object',
required: ['height', 'prevotes', 'precommits'],
properties: {
height: {
dataType: 'uint32',
fieldNumber: 1,
},
prevotes: {
dataType: 'uint32',
fieldNumber: 2,
},
precommits: {
dataType: 'uint32',
fieldNumber: 3,
},
},
},
},
},
};
codec.addSchema(BFTVotingLedgerSchema);
interface ValidatorsState {
address: Buffer;
maxPreVoteHeight: number;
maxPreCommitHeight: number;
}
interface LedgerState {
height: number;
prevotes: number;
precommits: number;
}
interface LedgerMap {
[key: string]: { prevotes: number; precommits: number };
}
interface ValidatorState {
maxPreVoteHeight: number;
maxPreCommitHeight: number;
}
interface VotingLedgerMap {
readonly validators: dataStructures.BufferMap<ValidatorState>;
readonly ledger: LedgerMap;
}
export interface VotingLedger {
readonly validators: ValidatorsState[];
readonly ledger: LedgerState[];
}
export class FinalityManager extends EventEmitter {
public readonly preVoteThreshold: number;
public readonly preCommitThreshold: number;
public readonly processingThreshold: number;
public readonly maxHeaders: number;
public finalizedHeight: number;
private readonly _chain: Chain;
private readonly _genesisHeight: number;
public constructor({
chain,
genesisHeight,
finalizedHeight,
threshold,
}: {
readonly chain: Chain;
readonly genesisHeight: number;
readonly finalizedHeight: number;
readonly threshold: number;
}) {
super();
assert(threshold > 0, 'Must provide a positive threshold');
this._chain = chain;
this._genesisHeight = genesisHeight;
// Threshold to consider a block pre-voted
this.preVoteThreshold = threshold;
// Threshold to consider a block pre-committed (or finalized)
this.preCommitThreshold = threshold;
if (this._chain.numberOfValidators <= 0) {
throw new Error('Invalid number of validators for BFT property');
}
// Limit for blocks to make perform verification or pre-vote/pre-commit (1 block less than 3 rounds)
this.processingThreshold = this._chain.numberOfValidators * BFT_ROUND_THRESHOLD - 1;
// Maximum headers to store (5 rounds)
this.maxHeaders = this._chain.numberOfValidators * 5;
// Height up to which blocks are finalized
this.finalizedHeight = finalizedHeight;
}
public async addBlockHeader(
blockHeader: BlockHeader,
stateStore: StateStore,
): Promise<FinalityManager> {
debug('addBlockHeader invoked');
debug('validateBlockHeader invoked');
const { lastBlockHeaders } = stateStore.chain;
// Verify the integrity of the header with chain
await this.verifyBlockHeaders(blockHeader, stateStore);
// Update the pre-votes and pre-commits
await this.updatePrevotesPrecommits(blockHeader, stateStore, lastBlockHeaders);
// Update the pre-voted confirmed and finalized height
await this.updateFinalizedHeight(stateStore);
debug('after adding block header', {
finalizedHeight: this.finalizedHeight,
});
return this;
}
public async updatePrevotesPrecommits(
header: BlockHeader,
stateStore: StateStore,
bftBlockHeaders: ReadonlyArray<BlockHeader>,
): Promise<boolean> {
debug('updatePrevotesPrecommits invoked');
// If validator forged a block with higher or same height previously
// That means he is forging on other chain and we don't count any
// Pre-votes and pre-commits from him
if (header.asset.maxHeightPreviouslyForged >= header.height) {
return false;
}
// Get validator public key
const { generatorPublicKey } = header;
const generatorAddress = getAddressFromPublicKey(generatorPublicKey);
const validators = await getValidators(stateStore);
const validator = validators.find(v => v.address.equals(generatorAddress));
if (!validator) {
throw new Error(`Generator ${generatorPublicKey.toString('hex')} is not in validators set`);
}
// If validator cannot vote, it cannot vote on the block
if (!validator.isConsensusParticipant) {
return false;
}
const votingLedger = await this._getVotingLedger(stateStore);
const { validators: validatorsMap, ledger: ledgerMap } = votingLedger;
// Load or initialize validator state in reference to current BlockHeaderManager block headers
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
const validatorState = validatorsMap.get(generatorAddress) ?? {
maxPreVoteHeight: 0,
maxPreCommitHeight: 0,
};
const minValidHeightToPreCommit = this._getMinValidHeightToPreCommit(header, bftBlockHeaders);
const validatorMinHeightActive = validator.minActiveHeight;
// If validator is new then first block of the round will be considered
// If it forged before then we probably have the last commit height
// Validator can't pre-commit a block before the above mentioned conditions
const minPreCommitHeight = Math.max(
header.height - this.processingThreshold,
validatorMinHeightActive,
minValidHeightToPreCommit,
validatorState.maxPreCommitHeight + 1,
);
// Validator can't pre-commit the blocks on tip of the chain
const maxPreCommitHeight = header.height - 1;
for (let j = minPreCommitHeight; j <= maxPreCommitHeight; j += 1) {
// Add pre-commit if threshold is reached
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
const ledgerState = ledgerMap[j] || {
prevotes: 0,
precommits: 0,
};
if (ledgerState.prevotes >= this.preVoteThreshold) {
// Increase the pre-commit for particular height
ledgerState.precommits += 1;
// Keep track of the last pre-commit point
validatorState.maxPreCommitHeight = j;
// Update ledger and validators map
ledgerMap[j] = ledgerState;
validatorsMap.set(generatorAddress, validatorState);
}
}
// Check between height of first block of the round when validator was active
// Or one step ahead where it forged the last block
// Or one step ahead where it left the last pre-vote
// Or maximum 3 rounds backward
const minPreVoteHeight = Math.max(
validatorMinHeightActive,
header.asset.maxHeightPreviouslyForged + 1,
// This is not written on LIP // validatorState.maxPreVoteHeight + 1,
header.height - this.processingThreshold,
);
// Pre-vote upto current block height
const maxPreVoteHeight = header.height;
for (let j = minPreVoteHeight; j <= maxPreVoteHeight; j += 1) {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
const ledgerState = ledgerMap[j] || {
prevotes: 0,
precommits: 0,
};
ledgerState.prevotes += 1;
// Update ledger map
ledgerMap[j] = ledgerState;
}
// Update validator state
validatorState.maxPreVoteHeight = maxPreVoteHeight;
validatorsMap.set(generatorAddress, validatorState);
// Remove ledger beyond maxHeaders size
Object.keys(ledgerMap)
.slice(0, this.maxHeaders * -1)
.forEach(key => {
delete ledgerMap[key];
});
// Update state to save the bft votes
await this._setVotingLedger(stateStore, {
validators: validatorsMap,
ledger: ledgerMap,
});
return true;
}
public async updateFinalizedHeight(stateStore: StateStore): Promise<boolean> {
debug('updatePreVotedAndFinalizedHeight invoked');
const { ledger } = await this._getVotingLedger(stateStore);
const highestHeightPreCommitted = Object.keys(ledger)
.reverse()
.find(key => ledger[key].precommits >= this.preCommitThreshold);
if (!highestHeightPreCommitted) {
return false;
}
// Store current finalizedHeight
const previouslyFinalizedHeight = this.finalizedHeight;
const nextFinalizedHeight = parseInt(highestHeightPreCommitted, 10);
// If finalized height is lower or equal, do not set
if (nextFinalizedHeight <= previouslyFinalizedHeight) {
return false;
}
this.finalizedHeight = nextFinalizedHeight;
this.emit(EVENT_BFT_FINALIZED_HEIGHT_CHANGED, this.finalizedHeight);
return true;
}
public async verifyBlockHeaders(
blockHeader: BlockHeader,
stateStore: StateStore,
): Promise<boolean> {
debug('verifyBlockHeaders invoked');
debug(blockHeader);
const bftBlockHeaders = stateStore.chain.lastBlockHeaders;
const { ledger } = await this._getVotingLedger(stateStore);
// lastBlockHeaders are sorted by height desc
const lastMaxHeightPrevoted =
bftBlockHeaders.length > 0 && bftBlockHeaders[0].asset.maxHeightPrevoted
? bftBlockHeaders[0].asset.maxHeightPrevoted
: this._genesisHeight;
const chainMaxHeightPrevoted = this._calculateMaxHeightPrevoted(ledger, lastMaxHeightPrevoted);
// We need minimum processingThreshold to decide
// If maxHeightPrevoted is correct
if (
bftBlockHeaders.length >= this.processingThreshold &&
blockHeader.asset.maxHeightPrevoted !== chainMaxHeightPrevoted
) {
throw new BFTInvalidAttributeError(
`Wrong maxHeightPrevoted in blockHeader. maxHeightPrevoted: ${blockHeader.asset.maxHeightPrevoted}, : ${chainMaxHeightPrevoted}`,
);
}
// Find top most block forged by same validator
const validatorLastBlock = bftBlockHeaders.find(header =>
header.generatorPublicKey.equals(blockHeader.generatorPublicKey),
);
if (!validatorLastBlock) {
return true;
}
if (areHeadersContradicting(validatorLastBlock, blockHeader)) {
throw new BFTError();
}
return true;
}
public async getMaxHeightPrevoted(lastMaxHeightPrevoted?: number): Promise<number> {
const bftState = await this._chain.dataAccess.getConsensusState(
CONSENSUS_STATE_VALIDATOR_LEDGER_KEY,
);
const { ledger } = this._decodeVotingLedger(bftState);
return this._calculateMaxHeightPrevoted(ledger, lastMaxHeightPrevoted ?? this._genesisHeight);
}
private _calculateMaxHeightPrevoted(ledger: LedgerMap, lastMaxHeightPrevoted: number): number {
debug('updatePreVotedAndFinalizedHeight invoked');
const maxHeightPreVoted = Object.keys(ledger)
.reverse()
.find(key => ledger[key].prevotes >= this.preVoteThreshold);
return maxHeightPreVoted ? parseInt(maxHeightPreVoted, 10) : lastMaxHeightPrevoted;
}
/**
* Get the min height from which a validator can make pre-commits
*
* The flow is as following:
* - We search backward from top block to bottom block in the chain
* - We can search down to current block height - processingThreshold(302)
* -
*/
private _getMinValidHeightToPreCommit(
header: BlockHeader,
bftApplicableBlocks: ReadonlyArray<BlockHeader>,
): number {
let needleHeight = Math.max(
header.asset.maxHeightPreviouslyForged,
header.height - this.processingThreshold,
);
/* We should search down to the height we have in our headers list
and within the processing threshold which is three rounds */
const searchTillHeight = Math.max(1, header.height - this.processingThreshold);
// Hold reference for the previously forged height
let previousBlockHeight = header.asset.maxHeightPreviouslyForged;
const blocksIncludingCurrent = [header, ...bftApplicableBlocks];
while (needleHeight >= searchTillHeight) {
// We need to ensure that the validator forging header did not forge on any other chain, i.e.,
// MaxHeightPreviouslyForged always refers to a height with a block forged by the same validator.
if (needleHeight === previousBlockHeight) {
const previousBlockHeader = blocksIncludingCurrent.find(
// eslint-disable-next-line no-loop-func
bftHeader => bftHeader.height === needleHeight,
);
if (!previousBlockHeader) {
// If the height is not in the cache, it should not be considered
debug('Fail to get cached block header');
return 0;
}
if (
!previousBlockHeader.generatorPublicKey.equals(header.generatorPublicKey) ||
previousBlockHeader.asset.maxHeightPreviouslyForged >= needleHeight
) {
return needleHeight + 1;
}
previousBlockHeight = previousBlockHeader.asset.maxHeightPreviouslyForged;
needleHeight = previousBlockHeader.asset.maxHeightPreviouslyForged;
} else {
needleHeight -= 1;
}
}
return Math.max(needleHeight + 1, searchTillHeight);
}
private async _getVotingLedger(stateStore: StateStore): Promise<VotingLedgerMap> {
const votingLedgerBuffer = await stateStore.consensus.get(CONSENSUS_STATE_VALIDATOR_LEDGER_KEY);
return this._decodeVotingLedger(votingLedgerBuffer);
}
private _decodeVotingLedger(bftVotingLedgerBuffer: Buffer | undefined): VotingLedgerMap {
const votingLedger =
bftVotingLedgerBuffer === undefined
? {
ledger: [],
validators: [],
}
: codec.decode<VotingLedger>(BFTVotingLedgerSchema, bftVotingLedgerBuffer);
const ledger = votingLedger.ledger.reduce((prev: LedgerMap, curr) => {
// eslint-disable-next-line no-param-reassign
prev[curr.height] = {
prevotes: curr.prevotes,
precommits: curr.precommits,
};
return prev;
}, {});
const validators = votingLedger.validators.reduce(
(prev: dataStructures.BufferMap<ValidatorState>, curr) => {
prev.set(curr.address, {
maxPreVoteHeight: curr.maxPreVoteHeight,
maxPreCommitHeight: curr.maxPreCommitHeight,
});
return prev;
},
new dataStructures.BufferMap<ValidatorsState>(),
);
return { ledger, validators };
}
private async _setVotingLedger(
stateStore: StateStore,
votingLedgerMap: VotingLedgerMap,
): Promise<void> {
const ledgerState = [];
for (const height of Object.keys(votingLedgerMap.ledger)) {
const intHeight = parseInt(height, 10);
ledgerState.push({
height: intHeight,
...votingLedgerMap.ledger[intHeight],
});
}
const validatorsState = [];
for (const [key, value] of votingLedgerMap.validators.entries()) {
validatorsState.push({
address: key,
...value,
});
}
await stateStore.consensus.set(
CONSENSUS_STATE_VALIDATOR_LEDGER_KEY,
codec.encode(BFTVotingLedgerSchema, {
validators: validatorsState,
ledger: ledgerState,
}),
);
}
} | the_stack |
import { AccessLevelList } from "../shared/access-level";
import { PolicyStatement } from "../shared";
/**
* Statement provider for service [logs](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazoncloudwatchlogs.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
export class Logs extends PolicyStatement {
public servicePrefix = 'logs';
/**
* Statement provider for service [logs](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazoncloudwatchlogs.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 permissions to associate the specified AWS Key Management Service (AWS KMS) customer master key (CMK) with the specified log group
*
* Access Level: Write
*
* https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_AssociateKmsKey.html
*/
public toAssociateKmsKey() {
return this.to('AssociateKmsKey');
}
/**
* Grants permissions to cancel an export task if it is in PENDING or RUNNING state
*
* Access Level: Write
*
* https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_CancelExportTask.html
*/
public toCancelExportTask() {
return this.to('CancelExportTask');
}
/**
* Grants permissions to create an ExportTask which allows you to efficiently export data from a Log Group to your Amazon S3 bucket
*
* Access Level: Write
*
* https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_CreateExportTask.html
*/
public toCreateExportTask() {
return this.to('CreateExportTask');
}
/**
* Grants permissions to create the log delivery
*
* Access Level: Write
*
* https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/AWS-logs-and-resource-policy.html
*/
public toCreateLogDelivery() {
return this.to('CreateLogDelivery');
}
/**
* Grants permissions to create a new log group with the specified name
*
* Access Level: Write
*
* https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_CreateLogGroup.html
*/
public toCreateLogGroup() {
return this.to('CreateLogGroup');
}
/**
* Grants permissions to create a new log stream with the specified name
*
* Access Level: Write
*
* https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_CreateLogStream.html
*/
public toCreateLogStream() {
return this.to('CreateLogStream');
}
/**
* Grants permissions to delete the destination with the specified name
*
* Access Level: Write
*
* https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_DeleteDestination.html
*/
public toDeleteDestination() {
return this.to('DeleteDestination');
}
/**
* Grants permissions to delete the log delivery information for specified log delivery
*
* Access Level: Write
*
* https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/AWS-logs-and-resource-policy.html
*/
public toDeleteLogDelivery() {
return this.to('DeleteLogDelivery');
}
/**
* Grants permissions to delete the log group with the specified name
*
* Access Level: Write
*
* https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_DeleteLogGroup.html
*/
public toDeleteLogGroup() {
return this.to('DeleteLogGroup');
}
/**
* Grants permissions to delete a log stream
*
* Access Level: Write
*
* https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_DeleteLogStream.html
*/
public toDeleteLogStream() {
return this.to('DeleteLogStream');
}
/**
* Grants permissions to delete a metric filter associated with the specified log group
*
* Access Level: Write
*
* https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_DeleteMetricFilter.html
*/
public toDeleteMetricFilter() {
return this.to('DeleteMetricFilter');
}
/**
* Grants permissions to delete a saved CloudWatch Logs Insights query definition
*
* Access Level: Write
*
* https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_DeleteQueryDefinition.html
*/
public toDeleteQueryDefinition() {
return this.to('DeleteQueryDefinition');
}
/**
* Grants permissions to delete a resource policy from this account
*
* Access Level: Permissions management
*
* https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_DeleteResourcePolicy.html
*/
public toDeleteResourcePolicy() {
return this.to('DeleteResourcePolicy');
}
/**
* Grants permissions to delete the retention policy of the specified log group
*
* Access Level: Write
*
* https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_DeleteRetentionPolicy.html
*/
public toDeleteRetentionPolicy() {
return this.to('DeleteRetentionPolicy');
}
/**
* Grants permissions to delete a subscription filter associated with the specified log group
*
* Access Level: Write
*
* https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_DeleteSubscriptionFilter.html
*/
public toDeleteSubscriptionFilter() {
return this.to('DeleteSubscriptionFilter');
}
/**
* Grants permissions to return all the destinations that are associated with the AWS account making the request
*
* Access Level: List
*
* https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_DescribeDestinations.html
*/
public toDescribeDestinations() {
return this.to('DescribeDestinations');
}
/**
* Grants permissions to return all the export tasks that are associated with the AWS account making the request
*
* Access Level: List
*
* https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_DescribeExportTasks.html
*/
public toDescribeExportTasks() {
return this.to('DescribeExportTasks');
}
/**
* Grants permissions to return all the log groups that are associated with the AWS account making the request
*
* Access Level: List
*
* https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_DescribeLogGroups.html
*/
public toDescribeLogGroups() {
return this.to('DescribeLogGroups');
}
/**
* Grants permissions to return all the log streams that are associated with the specified log group
*
* Access Level: List
*
* https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_DescribeLogStreams.html
*/
public toDescribeLogStreams() {
return this.to('DescribeLogStreams');
}
/**
* Grants permissions to return all the metrics filters associated with the specified log group
*
* Access Level: List
*
* https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_DescribeMetricFilters.html
*/
public toDescribeMetricFilters() {
return this.to('DescribeMetricFilters');
}
/**
* Grants permissions to return a list of CloudWatch Logs Insights queries that are scheduled, executing, or have been executed recently in this account
*
* Access Level: List
*
* https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_DescribeQueries.html
*/
public toDescribeQueries() {
return this.to('DescribeQueries');
}
/**
* Grants permissions to return a paginated list of your saved CloudWatch Logs Insights query definitions
*
* Access Level: List
*
* https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_DescribeQueryDefinitions.html
*/
public toDescribeQueryDefinitions() {
return this.to('DescribeQueryDefinitions');
}
/**
* Grants permissions to return all the resource policies in this account
*
* Access Level: List
*
* https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_DescribeResourcePolicies.html
*/
public toDescribeResourcePolicies() {
return this.to('DescribeResourcePolicies');
}
/**
* Grants permissions to return all the subscription filters associated with the specified log group
*
* Access Level: List
*
* https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_DescribeSubscriptionFilters.html
*/
public toDescribeSubscriptionFilters() {
return this.to('DescribeSubscriptionFilters');
}
/**
* Grants permissions to disassociate the associated AWS Key Management Service (AWS KMS) customer master key (CMK) from the specified log group
*
* Access Level: Write
*
* https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_DisassociateKmsKey.html
*/
public toDisassociateKmsKey() {
return this.to('DisassociateKmsKey');
}
/**
* Grants permissions to retrieve log events, optionally filtered by a filter pattern from the specified log group
*
* Access Level: Read
*
* https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_FilterLogEvents.html
*/
public toFilterLogEvents() {
return this.to('FilterLogEvents');
}
/**
* Grants permissions to get the log delivery information for specified log delivery
*
* Access Level: Read
*
* https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/AWS-logs-and-resource-policy.html
*/
public toGetLogDelivery() {
return this.to('GetLogDelivery');
}
/**
* Grants permissions to retrieve log events from the specified log stream
*
* Access Level: Read
*
* https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_GetLogEvents.html
*/
public toGetLogEvents() {
return this.to('GetLogEvents');
}
/**
* Grants permissions to return a list of the fields that are included in log events in the specified log group, along with the percentage of log events that contain each field
*
* Access Level: Read
*
* https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_GetLogGroupFields.html
*/
public toGetLogGroupFields() {
return this.to('GetLogGroupFields');
}
/**
* Grants permissions to retrieve all the fields and values of a single log event
*
* Access Level: Read
*
* https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_GetLogRecord.html
*/
public toGetLogRecord() {
return this.to('GetLogRecord');
}
/**
* Grants permissions to return the results from the specified query
*
* Access Level: Read
*
* https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_GetQueryResults.html
*/
public toGetQueryResults() {
return this.to('GetQueryResults');
}
/**
* Grants permissions to list all the log deliveries for specified account and/or log source
*
* Access Level: List
*
* https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/AWS-logs-and-resource-policy.html
*/
public toListLogDeliveries() {
return this.to('ListLogDeliveries');
}
/**
* Grants permissions to list the tags for the specified log group
*
* Access Level: List
*
* https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_ListTagsLogGroup.html
*/
public toListTagsLogGroup() {
return this.to('ListTagsLogGroup');
}
/**
* Grants permissions to create or update a Destination
*
* Access Level: Write
*
* Dependent actions:
* - iam:PassRole
*
* https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_PutDestination.html
*/
public toPutDestination() {
return this.to('PutDestination');
}
/**
* Grants permissions to create or update an access policy associated with an existing Destination
*
* Access Level: Write
*
* https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_PutDestinationPolicy.html
*/
public toPutDestinationPolicy() {
return this.to('PutDestinationPolicy');
}
/**
* Grants permissions to upload a batch of log events to the specified log stream
*
* Access Level: Write
*
* https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_PutLogEvents.html
*/
public toPutLogEvents() {
return this.to('PutLogEvents');
}
/**
* Grants permissions to create or update a metric filter and associates it with the specified log group
*
* Access Level: Write
*
* https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_PutMetricFilter.html
*/
public toPutMetricFilter() {
return this.to('PutMetricFilter');
}
/**
* Grants permissions to create or update a query definition
*
* Access Level: Write
*
* https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_PutQueryDefinition.html
*/
public toPutQueryDefinition() {
return this.to('PutQueryDefinition');
}
/**
* Grants permissions to create or update a resource policy allowing other AWS services to put log events to this account
*
* Access Level: Permissions management
*
* https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_PutResourcePolicy.html
*/
public toPutResourcePolicy() {
return this.to('PutResourcePolicy');
}
/**
* Grants permissions to set the retention of the specified log group
*
* Access Level: Write
*
* https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_PutRetentionPolicy.html
*/
public toPutRetentionPolicy() {
return this.to('PutRetentionPolicy');
}
/**
* Grants permissions to create or update a subscription filter and associates it with the specified log group
*
* Access Level: Write
*
* Dependent actions:
* - iam:PassRole
*
* https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_PutSubscriptionFilter.html
*/
public toPutSubscriptionFilter() {
return this.to('PutSubscriptionFilter');
}
/**
* Grants permissions to schedules a query of a log group using CloudWatch Logs Insights
*
* Access Level: Read
*
* https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_StartQuery.html
*/
public toStartQuery() {
return this.to('StartQuery');
}
/**
* Grants permissions to stop a CloudWatch Logs Insights query that is in progress
*
* Access Level: Read
*
* https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_StopQuery.html
*/
public toStopQuery() {
return this.to('StopQuery');
}
/**
* Grants permissions to add or update the specified tags for the specified log group
*
* Access Level: Tagging
*
* https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_TagLogGroup.html
*/
public toTagLogGroup() {
return this.to('TagLogGroup');
}
/**
* Grants permissions to test the filter pattern of a metric filter against a sample of log event messages
*
* Access Level: Read
*
* https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_TestMetricFilter.html
*/
public toTestMetricFilter() {
return this.to('TestMetricFilter');
}
/**
* Grants permissions to remove the specified tags from the specified log group
*
* Access Level: Tagging
*
* https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_UntagLogGroup.html
*/
public toUntagLogGroup() {
return this.to('UntagLogGroup');
}
/**
* Grants permissions to update the log delivery information for specified log delivery
*
* Access Level: Write
*
* https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/AWS-logs-and-resource-policy.html
*/
public toUpdateLogDelivery() {
return this.to('UpdateLogDelivery');
}
protected accessLevelList: AccessLevelList = {
"Write": [
"AssociateKmsKey",
"CancelExportTask",
"CreateExportTask",
"CreateLogDelivery",
"CreateLogGroup",
"CreateLogStream",
"DeleteDestination",
"DeleteLogDelivery",
"DeleteLogGroup",
"DeleteLogStream",
"DeleteMetricFilter",
"DeleteQueryDefinition",
"DeleteRetentionPolicy",
"DeleteSubscriptionFilter",
"DisassociateKmsKey",
"PutDestination",
"PutDestinationPolicy",
"PutLogEvents",
"PutMetricFilter",
"PutQueryDefinition",
"PutRetentionPolicy",
"PutSubscriptionFilter",
"UpdateLogDelivery"
],
"Permissions management": [
"DeleteResourcePolicy",
"PutResourcePolicy"
],
"List": [
"DescribeDestinations",
"DescribeExportTasks",
"DescribeLogGroups",
"DescribeLogStreams",
"DescribeMetricFilters",
"DescribeQueries",
"DescribeQueryDefinitions",
"DescribeResourcePolicies",
"DescribeSubscriptionFilters",
"ListLogDeliveries",
"ListTagsLogGroup"
],
"Read": [
"FilterLogEvents",
"GetLogDelivery",
"GetLogEvents",
"GetLogGroupFields",
"GetLogRecord",
"GetQueryResults",
"StartQuery",
"StopQuery",
"TestMetricFilter"
],
"Tagging": [
"TagLogGroup",
"UntagLogGroup"
]
};
/**
* Adds a resource of type log-group to the statement
*
* https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_LogGroup.html
*
* @param logGroupName - Identifier for the logGroupName.
* @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 onLogGroup(logGroupName: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:logs:${Region}:${Account}:log-group:${LogGroupName}';
arn = arn.replace('${LogGroupName}', logGroupName);
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 log-stream to the statement
*
* https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_LogStream.html
*
* @param logGroupName - Identifier for the logGroupName.
* @param logStreamName - Identifier for the logStreamName.
* @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 onLogStream(logGroupName: string, logStreamName: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:logs:${Region}:${Account}:log-group:${LogGroupName}:log-stream:${LogStreamName}';
arn = arn.replace('${LogGroupName}', logGroupName);
arn = arn.replace('${LogStreamName}', logStreamName);
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/AmazonCloudWatchLogs/latest/APIReference/API_Destination.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`.
*/
public onDestination(destinationName: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:logs:${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);
}
} | the_stack |
import { Data } from "./data";
import { Type } from "./enum";
import * as type from "./type";
import { DataType } from "./type";
import * as vecs from "./vector/index";
import * as builders from "./builder/index";
import { BuilderOptions } from "./builder/index";
/** @ignore */ declare type FloatArray = Float32Array | Float64Array;
/** @ignore */ declare type IntArray = Int8Array | Int16Array | Int32Array;
/** @ignore */ declare type UintArray =
| Uint8Array
| Uint16Array
| Uint32Array
| Uint8ClampedArray;
/** @ignore */
export declare type TypedArray = FloatArray | IntArray | UintArray;
/** @ignore */
export declare type BigIntArray = BigInt64Array | BigUint64Array;
/** @ignore */
export interface TypedArrayConstructor<T extends TypedArray> {
readonly prototype: T;
new (length?: number): T;
new (array: Iterable<number>): T;
new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): T;
/**
* The size in bytes of each element in the array.
*/
readonly BYTES_PER_ELEMENT: number;
/**
* Returns a new array from a set of elements.
* @param items A set of elements to include in the new array object.
*/
of(...items: number[]): T;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(
arrayLike: ArrayLike<number>,
mapfn?: (v: number, k: number) => number,
thisArg?: any
): T;
from<U>(
arrayLike: ArrayLike<U>,
mapfn: (v: U, k: number) => number,
thisArg?: any
): T;
}
/** @ignore */
export interface BigIntArrayConstructor<T extends BigIntArray> {
readonly prototype: T;
new (length?: number): T;
new (array: Iterable<bigint>): T;
new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): T;
/**
* The size in bytes of each element in the array.
*/
readonly BYTES_PER_ELEMENT: number;
/**
* Returns a new array from a set of elements.
* @param items A set of elements to include in the new array object.
*/
of(...items: bigint[]): T;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(
arrayLike: ArrayLike<bigint>,
mapfn?: (v: bigint, k: number) => bigint,
thisArg?: any
): T;
from<U>(
arrayLike: ArrayLike<U>,
mapfn: (v: U, k: number) => bigint,
thisArg?: any
): T;
}
/** @ignore */
export declare type VectorCtorArgs<
T extends VectorType<R>,
R extends DataType = any,
TArgs extends any[] = any[],
TCtor extends new (data: Data<R>, ...args: TArgs) => T = new (
data: Data<R>,
...args: TArgs
) => T
> = TCtor extends new (data: Data<R>, ...args: infer TArgs) => T
? TArgs
: never;
/** @ignore */
export declare type BuilderCtorArgs<
T extends BuilderType<R, any>,
R extends DataType = any,
TArgs extends any[] = any[],
TCtor extends new (type: R, ...args: TArgs) => T = new (
type: R,
...args: TArgs
) => T
> = TCtor extends new (type: R, ...args: infer TArgs) => T ? TArgs : never;
/**
* Obtain the constructor function of an instance type
* @ignore
*/
export declare type ConstructorType<
T,
TCtor extends new (...args: any[]) => T = new (...args: any[]) => T
> = TCtor extends new (...args: any[]) => T ? TCtor : never;
/** @ignore */
export declare type VectorCtorType<
T extends VectorType<R>,
R extends DataType = any,
TCtor extends new (data: Data<R>, ...args: VectorCtorArgs<T, R>) => T = new (
data: Data<R>,
...args: VectorCtorArgs<T, R>
) => T
> = TCtor extends new (data: Data<R>, ...args: VectorCtorArgs<T, R>) => T
? TCtor
: never;
/** @ignore */
export declare type BuilderCtorType<
T extends BuilderType<R, any>,
R extends DataType = any,
TCtor extends new (options: BuilderOptions<R, any>) => T = new (
options: BuilderOptions<R, any>
) => T
> = TCtor extends new (options: BuilderOptions<R, any>) => T ? TCtor : never;
/** @ignore */
export declare type VectorType<
T extends Type | DataType = any
> = T extends Type
? TypeToVector<T>
: T extends DataType
? DataTypeToVector<T>
: vecs.BaseVector<any>;
/** @ignore */
export declare type BuilderType<
T extends Type | DataType = any,
TNull = any
> = T extends Type
? TypeToBuilder<T, TNull>
: T extends DataType
? DataTypeToBuilder<T, TNull>
: builders.Builder<any, TNull>;
/** @ignore */
export declare type VectorCtor<
T extends Type | DataType | VectorType
> = T extends VectorType
? VectorCtorType<T>
: T extends Type
? VectorCtorType<VectorType<T>>
: T extends DataType
? VectorCtorType<VectorType<T["TType"]>>
: VectorCtorType<vecs.BaseVector>;
/** @ignore */
export declare type BuilderCtor<
T extends Type | DataType = any
> = T extends Type
? BuilderCtorType<BuilderType<T>>
: T extends DataType
? BuilderCtorType<BuilderType<T>>
: BuilderCtorType<builders.Builder>;
/** @ignore */
export declare type DataTypeCtor<
T extends Type | DataType | VectorType = any
> = T extends DataType
? ConstructorType<T>
: T extends VectorType
? ConstructorType<T["type"]>
: T extends Type
? ConstructorType<TypeToDataType<T>>
: never;
/** @ignore */
declare type TypeToVector<T extends Type> = {
[key: number]: any;
[Type.Null]: vecs.NullVector;
[Type.Bool]: vecs.BoolVector;
[Type.Int8]: vecs.Int8Vector;
[Type.Int16]: vecs.Int16Vector;
[Type.Int32]: vecs.Int32Vector;
[Type.Int64]: vecs.Int64Vector;
[Type.Uint8]: vecs.Uint8Vector;
[Type.Uint16]: vecs.Uint16Vector;
[Type.Uint32]: vecs.Uint32Vector;
[Type.Uint64]: vecs.Uint64Vector;
[Type.Int]: vecs.IntVector;
[Type.Float16]: vecs.Float16Vector;
[Type.Float32]: vecs.Float32Vector;
[Type.Float64]: vecs.Float64Vector;
[Type.Float]: vecs.FloatVector;
[Type.Utf8]: vecs.Utf8Vector;
[Type.Binary]: vecs.BinaryVector;
[Type.FixedSizeBinary]: vecs.FixedSizeBinaryVector;
[Type.Date]: vecs.DateVector;
[Type.DateDay]: vecs.DateDayVector;
[Type.DateMillisecond]: vecs.DateMillisecondVector;
[Type.Timestamp]: vecs.TimestampVector;
[Type.TimestampSecond]: vecs.TimestampSecondVector;
[Type.TimestampMillisecond]: vecs.TimestampMillisecondVector;
[Type.TimestampMicrosecond]: vecs.TimestampMicrosecondVector;
[Type.TimestampNanosecond]: vecs.TimestampNanosecondVector;
[Type.Time]: vecs.TimeVector;
[Type.TimeSecond]: vecs.TimeSecondVector;
[Type.TimeMillisecond]: vecs.TimeMillisecondVector;
[Type.TimeMicrosecond]: vecs.TimeMicrosecondVector;
[Type.TimeNanosecond]: vecs.TimeNanosecondVector;
[Type.Decimal]: vecs.DecimalVector;
[Type.Union]: vecs.UnionVector;
[Type.DenseUnion]: vecs.DenseUnionVector;
[Type.SparseUnion]: vecs.SparseUnionVector;
[Type.Interval]: vecs.IntervalVector;
[Type.IntervalDayTime]: vecs.IntervalDayTimeVector;
[Type.IntervalYearMonth]: vecs.IntervalYearMonthVector;
[Type.Map]: vecs.MapVector;
[Type.List]: vecs.ListVector;
[Type.Struct]: vecs.StructVector;
[Type.Dictionary]: vecs.DictionaryVector;
[Type.FixedSizeList]: vecs.FixedSizeListVector;
}[T];
/** @ignore */
declare type DataTypeToVector<T extends DataType = any> = {
[key: number]: any;
[Type.Null]: T extends type.Null ? vecs.NullVector : vecs.BaseVector<T>;
[Type.Bool]: T extends type.Bool ? vecs.BoolVector : vecs.BaseVector<T>;
[Type.Int8]: T extends type.Int8 ? vecs.Int8Vector : vecs.BaseVector<T>;
[Type.Int16]: T extends type.Int16 ? vecs.Int16Vector : vecs.BaseVector<T>;
[Type.Int32]: T extends type.Int32 ? vecs.Int32Vector : vecs.BaseVector<T>;
[Type.Int64]: T extends type.Int64 ? vecs.Int64Vector : vecs.BaseVector<T>;
[Type.Uint8]: T extends type.Uint8 ? vecs.Uint8Vector : vecs.BaseVector<T>;
[Type.Uint16]: T extends type.Uint16
? vecs.Uint16Vector
: vecs.BaseVector<T>;
[Type.Uint32]: T extends type.Uint32
? vecs.Uint32Vector
: vecs.BaseVector<T>;
[Type.Uint64]: T extends type.Uint64
? vecs.Uint64Vector
: vecs.BaseVector<T>;
[Type.Int]: T extends type.Int ? vecs.IntVector : vecs.BaseVector<T>;
[Type.Float16]: T extends type.Float16
? vecs.Float16Vector
: vecs.BaseVector<T>;
[Type.Float32]: T extends type.Float32
? vecs.Float32Vector
: vecs.BaseVector<T>;
[Type.Float64]: T extends type.Float64
? vecs.Float64Vector
: vecs.BaseVector<T>;
[Type.Float]: T extends type.Float ? vecs.FloatVector : vecs.BaseVector<T>;
[Type.Utf8]: T extends type.Utf8 ? vecs.Utf8Vector : vecs.BaseVector<T>;
[Type.Binary]: T extends type.Binary
? vecs.BinaryVector
: vecs.BaseVector<T>;
[Type.FixedSizeBinary]: T extends type.FixedSizeBinary
? vecs.FixedSizeBinaryVector
: vecs.BaseVector<T>;
[Type.Date]: T extends type.Date_ ? vecs.DateVector : vecs.BaseVector<T>;
[Type.DateDay]: T extends type.DateDay
? vecs.DateDayVector
: vecs.BaseVector<T>;
[Type.DateMillisecond]: T extends type.DateMillisecond
? vecs.DateMillisecondVector
: vecs.BaseVector<T>;
[Type.Timestamp]: T extends type.Timestamp
? vecs.TimestampVector
: vecs.BaseVector<T>;
[Type.TimestampSecond]: T extends type.TimestampSecond
? vecs.TimestampSecondVector
: vecs.BaseVector<T>;
[Type.TimestampMillisecond]: T extends type.TimestampMillisecond
? vecs.TimestampMillisecondVector
: vecs.BaseVector<T>;
[Type.TimestampMicrosecond]: T extends type.TimestampMicrosecond
? vecs.TimestampMicrosecondVector
: vecs.BaseVector<T>;
[Type.TimestampNanosecond]: T extends type.TimestampNanosecond
? vecs.TimestampNanosecondVector
: vecs.BaseVector<T>;
[Type.Time]: T extends type.Time ? vecs.TimeVector : vecs.BaseVector<T>;
[Type.TimeSecond]: T extends type.TimeSecond
? vecs.TimeSecondVector
: vecs.BaseVector<T>;
[Type.TimeMillisecond]: T extends type.TimeMillisecond
? vecs.TimeMillisecondVector
: vecs.BaseVector<T>;
[Type.TimeMicrosecond]: T extends type.TimeMicrosecond
? vecs.TimeMicrosecondVector
: vecs.BaseVector<T>;
[Type.TimeNanosecond]: T extends type.TimeNanosecond
? vecs.TimeNanosecondVector
: vecs.BaseVector<T>;
[Type.Decimal]: T extends type.Decimal
? vecs.DecimalVector
: vecs.BaseVector<T>;
[Type.Union]: T extends type.Union ? vecs.UnionVector : vecs.BaseVector<T>;
[Type.DenseUnion]: T extends type.DenseUnion
? vecs.DenseUnionVector
: vecs.BaseVector<T>;
[Type.SparseUnion]: T extends type.SparseUnion
? vecs.SparseUnionVector
: vecs.BaseVector<T>;
[Type.Interval]: T extends type.Interval
? vecs.IntervalVector
: vecs.BaseVector<T>;
[Type.IntervalDayTime]: T extends type.IntervalDayTime
? vecs.IntervalDayTimeVector
: vecs.BaseVector<T>;
[Type.IntervalYearMonth]: T extends type.IntervalYearMonth
? vecs.IntervalYearMonthVector
: vecs.BaseVector<T>;
[Type.Map]: T extends type.Map_
? vecs.MapVector<T["keyType"], T["valueType"]>
: vecs.BaseVector<T>;
[Type.List]: T extends type.List
? vecs.ListVector<T["valueType"]>
: vecs.BaseVector<T>;
[Type.Struct]: T extends type.Struct
? vecs.StructVector<T["dataTypes"]>
: vecs.BaseVector<T>;
[Type.Dictionary]: T extends type.Dictionary
? vecs.DictionaryVector<T["valueType"], T["indices"]>
: vecs.BaseVector<T>;
[Type.FixedSizeList]: T extends type.FixedSizeList
? vecs.FixedSizeListVector<T["valueType"]>
: vecs.BaseVector<T>;
}[T["TType"]];
/** @ignore */
export declare type TypeToDataType<T extends Type> = {
[key: number]: type.DataType;
[Type.Null]: type.Null;
[Type.Bool]: type.Bool;
[Type.Int]: type.Int;
[Type.Int16]: type.Int16;
[Type.Int32]: type.Int32;
[Type.Int64]: type.Int64;
[Type.Uint8]: type.Uint8;
[Type.Uint16]: type.Uint16;
[Type.Uint32]: type.Uint32;
[Type.Uint64]: type.Uint64;
[Type.Int8]: type.Int8;
[Type.Float16]: type.Float16;
[Type.Float32]: type.Float32;
[Type.Float64]: type.Float64;
[Type.Float]: type.Float;
[Type.Utf8]: type.Utf8;
[Type.Binary]: type.Binary;
[Type.FixedSizeBinary]: type.FixedSizeBinary;
[Type.Date]: type.Date_;
[Type.DateDay]: type.DateDay;
[Type.DateMillisecond]: type.DateMillisecond;
[Type.Timestamp]: type.Timestamp;
[Type.TimestampSecond]: type.TimestampSecond;
[Type.TimestampMillisecond]: type.TimestampMillisecond;
[Type.TimestampMicrosecond]: type.TimestampMicrosecond;
[Type.TimestampNanosecond]: type.TimestampNanosecond;
[Type.Time]: type.Time;
[Type.TimeSecond]: type.TimeSecond;
[Type.TimeMillisecond]: type.TimeMillisecond;
[Type.TimeMicrosecond]: type.TimeMicrosecond;
[Type.TimeNanosecond]: type.TimeNanosecond;
[Type.Decimal]: type.Decimal;
[Type.Union]: type.Union;
[Type.DenseUnion]: type.DenseUnion;
[Type.SparseUnion]: type.SparseUnion;
[Type.Interval]: type.Interval;
[Type.IntervalDayTime]: type.IntervalDayTime;
[Type.IntervalYearMonth]: type.IntervalYearMonth;
[Type.Map]: type.Map_;
[Type.List]: type.List;
[Type.Struct]: type.Struct;
[Type.Dictionary]: type.Dictionary;
[Type.FixedSizeList]: type.FixedSizeList;
}[T];
/** @ignore */
declare type TypeToBuilder<T extends Type = any, TNull = any> = {
[key: number]: builders.Builder;
[Type.Null]: builders.NullBuilder<TNull>;
[Type.Bool]: builders.BoolBuilder<TNull>;
[Type.Int8]: builders.Int8Builder<TNull>;
[Type.Int16]: builders.Int16Builder<TNull>;
[Type.Int32]: builders.Int32Builder<TNull>;
[Type.Int64]: builders.Int64Builder<TNull>;
[Type.Uint8]: builders.Uint8Builder<TNull>;
[Type.Uint16]: builders.Uint16Builder<TNull>;
[Type.Uint32]: builders.Uint32Builder<TNull>;
[Type.Uint64]: builders.Uint64Builder<TNull>;
[Type.Int]: builders.IntBuilder<any, TNull>;
[Type.Float16]: builders.Float16Builder<TNull>;
[Type.Float32]: builders.Float32Builder<TNull>;
[Type.Float64]: builders.Float64Builder<TNull>;
[Type.Float]: builders.FloatBuilder<any, TNull>;
[Type.Utf8]: builders.Utf8Builder<TNull>;
[Type.Binary]: builders.BinaryBuilder<TNull>;
[Type.FixedSizeBinary]: builders.FixedSizeBinaryBuilder<TNull>;
[Type.Date]: builders.DateBuilder<any, TNull>;
[Type.DateDay]: builders.DateDayBuilder<TNull>;
[Type.DateMillisecond]: builders.DateMillisecondBuilder<TNull>;
[Type.Timestamp]: builders.TimestampBuilder<any, TNull>;
[Type.TimestampSecond]: builders.TimestampSecondBuilder<TNull>;
[Type.TimestampMillisecond]: builders.TimestampMillisecondBuilder<TNull>;
[Type.TimestampMicrosecond]: builders.TimestampMicrosecondBuilder<TNull>;
[Type.TimestampNanosecond]: builders.TimestampNanosecondBuilder<TNull>;
[Type.Time]: builders.TimeBuilder<any, TNull>;
[Type.TimeSecond]: builders.TimeSecondBuilder<TNull>;
[Type.TimeMillisecond]: builders.TimeMillisecondBuilder<TNull>;
[Type.TimeMicrosecond]: builders.TimeMicrosecondBuilder<TNull>;
[Type.TimeNanosecond]: builders.TimeNanosecondBuilder<TNull>;
[Type.Decimal]: builders.DecimalBuilder<TNull>;
[Type.Union]: builders.UnionBuilder<any, TNull>;
[Type.DenseUnion]: builders.DenseUnionBuilder<any, TNull>;
[Type.SparseUnion]: builders.SparseUnionBuilder<any, TNull>;
[Type.Interval]: builders.IntervalBuilder<any, TNull>;
[Type.IntervalDayTime]: builders.IntervalDayTimeBuilder<TNull>;
[Type.IntervalYearMonth]: builders.IntervalYearMonthBuilder<TNull>;
[Type.Map]: builders.MapBuilder<any, any, TNull>;
[Type.List]: builders.ListBuilder<any, TNull>;
[Type.Struct]: builders.StructBuilder<any, TNull>;
[Type.Dictionary]: builders.DictionaryBuilder<any, TNull>;
[Type.FixedSizeList]: builders.FixedSizeListBuilder<any, TNull>;
}[T];
/** @ignore */
declare type DataTypeToBuilder<T extends DataType = any, TNull = any> = {
[key: number]: builders.Builder<any, TNull>;
[Type.Null]: T extends type.Null
? builders.NullBuilder<TNull>
: builders.Builder<any, TNull>;
[Type.Bool]: T extends type.Bool
? builders.BoolBuilder<TNull>
: builders.Builder<any, TNull>;
[Type.Int8]: T extends type.Int8
? builders.Int8Builder<TNull>
: builders.Builder<any, TNull>;
[Type.Int16]: T extends type.Int16
? builders.Int16Builder<TNull>
: builders.Builder<any, TNull>;
[Type.Int32]: T extends type.Int32
? builders.Int32Builder<TNull>
: builders.Builder<any, TNull>;
[Type.Int64]: T extends type.Int64
? builders.Int64Builder<TNull>
: builders.Builder<any, TNull>;
[Type.Uint8]: T extends type.Uint8
? builders.Uint8Builder<TNull>
: builders.Builder<any, TNull>;
[Type.Uint16]: T extends type.Uint16
? builders.Uint16Builder<TNull>
: builders.Builder<any, TNull>;
[Type.Uint32]: T extends type.Uint32
? builders.Uint32Builder<TNull>
: builders.Builder<any, TNull>;
[Type.Uint64]: T extends type.Uint64
? builders.Uint64Builder<TNull>
: builders.Builder<any, TNull>;
[Type.Int]: T extends type.Int
? builders.IntBuilder<T, TNull>
: builders.Builder<any, TNull>;
[Type.Float16]: T extends type.Float16
? builders.Float16Builder<TNull>
: builders.Builder<any, TNull>;
[Type.Float32]: T extends type.Float32
? builders.Float32Builder<TNull>
: builders.Builder<any, TNull>;
[Type.Float64]: T extends type.Float64
? builders.Float64Builder<TNull>
: builders.Builder<any, TNull>;
[Type.Float]: T extends type.Float
? builders.FloatBuilder<T, TNull>
: builders.Builder<any, TNull>;
[Type.Utf8]: T extends type.Utf8
? builders.Utf8Builder<TNull>
: builders.Builder<any, TNull>;
[Type.Binary]: T extends type.Binary
? builders.BinaryBuilder<TNull>
: builders.Builder<any, TNull>;
[Type.FixedSizeBinary]: T extends type.FixedSizeBinary
? builders.FixedSizeBinaryBuilder<TNull>
: builders.Builder<any, TNull>;
[Type.Date]: T extends type.Date_
? builders.DateBuilder<T, TNull>
: builders.Builder<any, TNull>;
[Type.DateDay]: T extends type.DateDay
? builders.DateDayBuilder<TNull>
: builders.Builder<any, TNull>;
[Type.DateMillisecond]: T extends type.DateMillisecond
? builders.DateMillisecondBuilder<TNull>
: builders.Builder<any, TNull>;
[Type.Timestamp]: T extends type.Timestamp
? builders.TimestampBuilder<T, TNull>
: builders.Builder<any, TNull>;
[Type.TimestampSecond]: T extends type.TimestampSecond
? builders.TimestampSecondBuilder<TNull>
: builders.Builder<any, TNull>;
[Type.TimestampMillisecond]: T extends type.TimestampMillisecond
? builders.TimestampMillisecondBuilder<TNull>
: builders.Builder<any, TNull>;
[Type.TimestampMicrosecond]: T extends type.TimestampMicrosecond
? builders.TimestampMicrosecondBuilder<TNull>
: builders.Builder<any, TNull>;
[Type.TimestampNanosecond]: T extends type.TimestampNanosecond
? builders.TimestampNanosecondBuilder<TNull>
: builders.Builder<any, TNull>;
[Type.Time]: T extends type.Time
? builders.TimeBuilder<T, TNull>
: builders.Builder<any, TNull>;
[Type.TimeSecond]: T extends type.TimeSecond
? builders.TimeSecondBuilder<TNull>
: builders.Builder<any, TNull>;
[Type.TimeMillisecond]: T extends type.TimeMillisecond
? builders.TimeMillisecondBuilder<TNull>
: builders.Builder<any, TNull>;
[Type.TimeMicrosecond]: T extends type.TimeMicrosecond
? builders.TimeMicrosecondBuilder<TNull>
: builders.Builder<any, TNull>;
[Type.TimeNanosecond]: T extends type.TimeNanosecond
? builders.TimeNanosecondBuilder<TNull>
: builders.Builder<any, TNull>;
[Type.Decimal]: T extends type.Decimal
? builders.DecimalBuilder<TNull>
: builders.Builder<any, TNull>;
[Type.Union]: T extends type.Union
? builders.UnionBuilder<T, TNull>
: builders.Builder<any, TNull>;
[Type.DenseUnion]: T extends type.DenseUnion
? builders.DenseUnionBuilder<T, TNull>
: builders.Builder<any, TNull>;
[Type.SparseUnion]: T extends type.SparseUnion
? builders.SparseUnionBuilder<T, TNull>
: builders.Builder<any, TNull>;
[Type.Interval]: T extends type.Interval
? builders.IntervalBuilder<T, TNull>
: builders.Builder<any, TNull>;
[Type.IntervalDayTime]: T extends type.IntervalDayTime
? builders.IntervalDayTimeBuilder<TNull>
: builders.Builder<any, TNull>;
[Type.IntervalYearMonth]: T extends type.IntervalYearMonth
? builders.IntervalYearMonthBuilder<TNull>
: builders.Builder<any, TNull>;
[Type.Map]: T extends type.Map_
? builders.MapBuilder<T["keyType"], T["valueType"], TNull>
: builders.Builder<any, TNull>;
[Type.List]: T extends type.List
? builders.ListBuilder<T["valueType"], TNull>
: builders.Builder<any, TNull>;
[Type.Struct]: T extends type.Struct
? builders.StructBuilder<T["dataTypes"], TNull>
: builders.Builder<any, TNull>;
[Type.Dictionary]: T extends type.Dictionary
? builders.DictionaryBuilder<T, TNull>
: builders.Builder<any, TNull>;
[Type.FixedSizeList]: T extends type.FixedSizeList
? builders.FixedSizeListBuilder<T["valueType"], TNull>
: builders.Builder<any, TNull>;
}[T["TType"]];
export {}; | the_stack |
import { NameToken, ValueToken, Repeater, AllTokens, BracketType, Bracket, Operator, OperatorType, Quote, WhiteSpace, Literal } from '../tokenizer';
import tokenScanner, { TokenScanner, peek, consume, readable, next, error, slice } from './TokenScanner';
import { ParserOptions } from '../types';
export type TokenStatement = TokenElement | TokenGroup;
export interface TokenAttribute {
name?: ValueToken[];
value?: ValueToken[];
expression?: boolean;
}
export interface TokenElement {
type: 'TokenElement';
name?: NameToken[];
attributes?: TokenAttribute[];
value?: ValueToken[];
repeat?: Repeater;
selfClose: boolean;
elements: TokenStatement[];
}
export interface TokenGroup {
type: 'TokenGroup';
elements: TokenStatement[];
repeat?: Repeater;
}
export default function abbreviation(abbr: AllTokens[], options: ParserOptions = {}): TokenGroup {
const scanner = tokenScanner(abbr);
const result = statements(scanner, options);
if (readable(scanner)) {
throw error(scanner, 'Unexpected character');
}
return result;
}
function statements(scanner: TokenScanner, options: ParserOptions): TokenGroup {
const result: TokenGroup = {
type: 'TokenGroup',
elements: []
};
let ctx: TokenStatement = result;
let node: TokenStatement | undefined;
const stack: TokenStatement[] = [];
while (readable(scanner)) {
if (node = element(scanner, options) || group(scanner, options)) {
ctx.elements.push(node);
if (consume(scanner, isChildOperator)) {
stack.push(ctx);
ctx = node;
} else if (consume(scanner, isSiblingOperator)) {
continue;
} else if (consume(scanner, isClimbOperator)) {
do {
if (stack.length) {
ctx = stack.pop()!;
}
} while (consume(scanner, isClimbOperator));
}
} else {
break;
}
}
return result;
}
/**
* Consumes group from given scanner
*/
function group(scanner: TokenScanner, options: ParserOptions): TokenGroup | undefined {
if (consume(scanner, isGroupStart)) {
const result = statements(scanner, options);
const token = next(scanner);
if (isBracket(token, 'group', false)) {
result.repeat = repeater(scanner);
}
return result;
}
}
/**
* Consumes single element from given scanner
*/
function element(scanner: TokenScanner, options: ParserOptions): TokenElement | undefined {
let attr: TokenAttribute | TokenAttribute[] | undefined;
const elem: TokenElement = {
type: 'TokenElement',
name: void 0,
attributes: void 0,
value: void 0,
repeat: void 0,
selfClose: false,
elements: []
};
if (elementName(scanner, options)) {
elem.name = slice(scanner) as NameToken[];
}
while (readable(scanner)) {
scanner.start = scanner.pos;
if (!elem.repeat && !isEmpty(elem) && consume(scanner, isRepeater)) {
elem.repeat = scanner.tokens[scanner.pos - 1] as Repeater;
} else if (!elem.value && text(scanner)) {
elem.value = getText(scanner);
} else if (attr = shortAttribute(scanner, 'id', options) || shortAttribute(scanner, 'class', options) || attributeSet(scanner)) {
if (!elem.attributes) {
elem.attributes = Array.isArray(attr) ? attr.slice() : [attr];
} else {
elem.attributes = elem.attributes.concat(attr);
}
} else {
if (!isEmpty(elem) && consume(scanner, isCloseOperator)) {
elem.selfClose = true;
if (!elem.repeat && consume(scanner, isRepeater)) {
elem.repeat = scanner.tokens[scanner.pos - 1] as Repeater;
}
}
break;
}
}
return !isEmpty(elem) ? elem : void 0;
}
/**
* Consumes attribute set from given scanner
*/
function attributeSet(scanner: TokenScanner): TokenAttribute[] | undefined {
if (consume(scanner, isAttributeSetStart)) {
const attributes: TokenAttribute[] = [];
let attr: TokenAttribute | undefined;
while (readable(scanner)) {
if (attr = attribute(scanner)) {
attributes.push(attr);
} else if (consume(scanner, isAttributeSetEnd)) {
break;
} else if (!consume(scanner, isWhiteSpace)) {
throw error(scanner, `Unexpected "${peek(scanner)!.type}" token`);
}
}
return attributes;
}
}
/**
* Consumes attribute shorthand (class or id) from given scanner
*/
function shortAttribute(scanner: TokenScanner, type: 'class' | 'id', options: ParserOptions): TokenAttribute | undefined {
if (isOperator(peek(scanner), type)) {
scanner.pos++;
const attr: TokenAttribute = {
name: [createLiteral(type)]
};
// Consume expression after shorthand start for React-like components
if (options.jsx && text(scanner)) {
attr.value = getText(scanner);
attr.expression = true;
} else {
attr.value = literal(scanner) ? slice(scanner) as ValueToken[] : void 0;
}
return attr;
}
}
/**
* Consumes single attribute from given scanner
*/
function attribute(scanner: TokenScanner): TokenAttribute | undefined {
if (quoted(scanner)) {
// Consumed quoted value: it’s a value for default attribute
return {
value: slice(scanner) as ValueToken[]
};
}
if (literal(scanner, true)) {
return {
name: slice(scanner) as NameToken[],
value: consume(scanner, isEquals) && (quoted(scanner) || literal(scanner, true))
? slice(scanner) as ValueToken[]
: void 0
};
}
}
function repeater(scanner: TokenScanner): Repeater | undefined {
return isRepeater(peek(scanner))
? scanner.tokens[scanner.pos++] as Repeater
: void 0;
}
/**
* Consumes quoted value from given scanner, if possible
*/
function quoted(scanner: TokenScanner): boolean {
const start = scanner.pos;
const quote = peek(scanner);
if (isQuote(quote)) {
scanner.pos++;
while (readable(scanner)) {
if (isQuote(next(scanner), quote.single)) {
scanner.start = start;
return true;
}
}
throw error(scanner, 'Unclosed quote', quote);
}
return false;
}
/**
* Consumes literal (unquoted value) from given scanner
*/
function literal(scanner: TokenScanner, allowBrackets?: boolean): boolean {
const start = scanner.pos;
const brackets: { [type in BracketType]: number } = {
attribute: 0,
expression: 0,
group: 0
};
while (readable(scanner)) {
const token = peek(scanner);
if (brackets.expression) {
// If we’re inside expression, we should consume all content in it
if (isBracket(token, 'expression')) {
brackets[token.context] += token.open ? 1 : -1;
}
} else if (isQuote(token) || isOperator(token) || isWhiteSpace(token) || isRepeater(token)) {
break;
} else if (isBracket(token)) {
if (!allowBrackets) {
break;
}
if (token.open) {
brackets[token.context]++;
} else if (!brackets[token.context]) {
// Stop if found unmatched closing brace: it must be handled
// by parent consumer
break;
} else {
brackets[token.context]--;
}
}
scanner.pos++;
}
if (start !== scanner.pos) {
scanner.start = start;
return true;
}
return false;
}
/**
* Consumes element name from given scanner
*/
function elementName(scanner: TokenScanner, options: ParserOptions): boolean {
const start = scanner.pos;
if (options.jsx && consume(scanner, isCapitalizedLiteral)) {
// Check for edge case: consume immediate capitalized class names
// for React-like components, e.g. `Foo.Bar.Baz`
while (readable(scanner)) {
const { pos } = scanner;
if (!consume(scanner, isClassNameOperator) || !consume(scanner, isCapitalizedLiteral)) {
scanner.pos = pos;
break;
}
}
}
while (readable(scanner) && consume(scanner, isElementName)) {
// empty
}
if (scanner.pos !== start) {
scanner.start = start;
return true;
}
return false;
}
/**
* Consumes text value from given scanner
*/
function text(scanner: TokenScanner): boolean {
const start = scanner.pos;
if (consume(scanner, isTextStart)) {
let brackets = 0;
while (readable(scanner)) {
const token = next(scanner);
if (isBracket(token, 'expression')) {
if (token.open) {
brackets++;
} else if (!brackets) {
break;
} else {
brackets--;
}
}
}
scanner.start = start;
return true;
}
return false;
}
function getText(scanner: TokenScanner): ValueToken[] {
let from = scanner.start;
let to = scanner.pos;
if (isBracket(scanner.tokens[from], 'expression', true)) {
from++;
}
if (isBracket(scanner.tokens[to - 1], 'expression', false)) {
to--;
}
return slice(scanner, from, to) as ValueToken[];
}
export function isBracket(token: AllTokens | undefined, context?: BracketType, isOpen?: boolean): token is Bracket {
return Boolean(token && token.type === 'Bracket'
&& (!context || token.context === context)
&& (isOpen == null || token.open === isOpen));
}
export function isOperator(token: AllTokens | undefined, type?: OperatorType): token is Operator {
return Boolean(token && token.type === 'Operator' && (!type || token.operator === type));
}
export function isQuote(token: AllTokens | undefined, isSingle?: boolean): token is Quote {
return Boolean(token && token.type === 'Quote' && (isSingle == null || token.single === isSingle));
}
function isWhiteSpace(token?: AllTokens): token is WhiteSpace {
return Boolean(token && token.type === 'WhiteSpace');
}
function isEquals(token: AllTokens) {
return isOperator(token, 'equal');
}
function isRepeater(token?: AllTokens): token is Repeater {
return Boolean(token && token.type === 'Repeater');
}
function isLiteral(token: AllTokens): token is Literal {
return token.type === 'Literal';
}
function isCapitalizedLiteral(token: AllTokens) {
if (isLiteral(token)) {
const ch = token.value.charCodeAt(0);
return ch >= 65 && ch <= 90;
}
return false;
}
function isElementName(token: AllTokens): boolean {
return token.type === 'Literal' || token.type === 'RepeaterNumber' || token.type === 'RepeaterPlaceholder';
}
function isClassNameOperator(token: AllTokens) {
return isOperator(token, 'class');
}
function isAttributeSetStart(token?: AllTokens) {
return isBracket(token, 'attribute', true);
}
function isAttributeSetEnd(token?: AllTokens) {
return isBracket(token, 'attribute', false);
}
function isTextStart(token: AllTokens) {
return isBracket(token, 'expression', true);
}
function isGroupStart(token: AllTokens) {
return isBracket(token, 'group', true);
}
function createLiteral(value: string): Literal {
return { type: 'Literal', value };
}
function isEmpty(elem: TokenElement): boolean {
return !elem.name && !elem.value && !elem.attributes;
}
function isChildOperator(token: AllTokens) {
return isOperator(token, 'child');
}
function isSiblingOperator(token: AllTokens) {
return isOperator(token, 'sibling');
}
function isClimbOperator(token: AllTokens) {
return isOperator(token, 'climb');
}
function isCloseOperator(token: AllTokens) {
return isOperator(token, 'close');
} | the_stack |
import { call, put, all, takeLatest, takeEvery } from 'redux-saga/effects'
import { ActionTypes } from './constants'
import { ViewActions, ViewActionType } from './actions'
import omit from 'lodash/omit'
import { AxiosRequestConfig, AxiosResponse, AxiosError } from 'axios'
import request, { IDavinciResponse } from 'utils/request'
import api from 'utils/api'
import { errorHandler, getErrorMessage } from 'utils/util'
import { IViewBase, IView, IExecuteSqlResponse, IExecuteSqlParams, IViewVariable } from './types'
import { IDistinctValueReqeustParams } from 'app/components/Filters/types'
export function* getViews (action: ViewActionType) {
if (action.type !== ActionTypes.LOAD_VIEWS) { return }
const { payload } = action
const { viewsLoaded, loadViewsFail } = ViewActions
let views: IViewBase[]
try {
const asyncData = yield call(request, `${api.view}?projectId=${payload.projectId}`)
views = asyncData.payload
yield put(viewsLoaded(views))
} catch (err) {
yield put(loadViewsFail())
errorHandler(err)
} finally {
if (payload.resolve) {
payload.resolve(views)
}
}
}
export function* getViewsDetail (action: ViewActionType) {
if (action.type !== ActionTypes.LOAD_VIEWS_DETAIL) { return }
const { payload } = action
const { viewsDetailLoaded, loadViewsDetailFail } = ViewActions
const { viewIds, resolve, isEditing } = payload
try {
// @FIXME make it be a single request
const asyncData = yield all(viewIds.map((viewId) => (call(request, `${api.view}/${viewId}`))))
const views: IView[] = asyncData.map((item) => item.payload)
yield put(viewsDetailLoaded(views, isEditing))
if (resolve) { resolve() }
} catch (err) {
yield put(loadViewsDetailFail())
errorHandler(err)
}
}
export function* addView (action: ViewActionType) {
if (action.type !== ActionTypes.ADD_VIEW) { return }
const { payload } = action
const { view, resolve } = payload
const { viewAdded, addViewFail } = ViewActions
try {
const asyncData = yield call<AxiosRequestConfig>(request, {
method: 'post',
url: api.view,
data: view
})
yield put(viewAdded(asyncData.payload))
resolve()
} catch (err) {
yield put(addViewFail())
errorHandler(err)
}
}
export function* editView (action: ViewActionType) {
if (action.type !== ActionTypes.EDIT_VIEW) { return }
const { payload } = action
const { view, resolve } = payload
const { viewEdited, editViewFail } = ViewActions
try {
yield call<AxiosRequestConfig>(request, {
method: 'put',
url: `${api.view}/${view.id}`,
data: view
})
yield put(viewEdited(view))
resolve()
} catch (err) {
yield put(editViewFail())
errorHandler(err)
}
}
export function* deleteView (action: ViewActionType) {
if (action.type !== ActionTypes.DELETE_VIEW) { return }
const { payload } = action
const { viewDeleted, deleteViewFail } = ViewActions
try {
yield call<AxiosRequestConfig>(request, {
method: 'delete',
url: `${api.view}/${payload.id}`
})
yield put(viewDeleted(payload.id))
payload.resolve(payload.id)
} catch (err) {
yield put(deleteViewFail())
errorHandler(err)
}
}
export function* copyView (action: ViewActionType) {
if (action.type !== ActionTypes.COPY_VIEW) { return }
const { view, resolve } = action.payload
const { viewCopied, copyViewFail } = ViewActions
try {
const fromViewResponse = yield call(request, `${api.view}/${view.id}`)
const fromView = fromViewResponse.payload
const copyView: IView = { ...fromView, name: view.name, description: view.description }
const asyncData = yield call<AxiosRequestConfig>(request, {
method: 'post',
url: api.view,
data: copyView
})
yield put(viewCopied(fromView.id, asyncData.payload))
resolve()
} catch (err) {
yield put(copyViewFail())
errorHandler(err)
}
}
export function* executeSql (action: ViewActionType) {
if (action.type !== ActionTypes.EXECUTE_SQL) { return }
const { params } = action.payload
const { variables, ...rest } = params
const omitKeys: Array<keyof IViewVariable> = ['key', 'alias', 'fromService']
const variableParam = variables.map((v) => omit(v, omitKeys))
const { sqlExecuted, executeSqlFail } = ViewActions
try {
const asyncData: IDavinciResponse<IExecuteSqlResponse> = yield call<AxiosRequestConfig>(request, {
method: 'post',
url: `${api.view}/executesql`,
data: {
...rest,
variables: variableParam
}
})
yield put(sqlExecuted(asyncData))
} catch (err) {
const { response } = err as AxiosError
const { data } = response as AxiosResponse<IDavinciResponse<any>>
yield put(executeSqlFail(data.header))
}
}
/** View sagas for external usages */
export function* getViewData (action: ViewActionType) {
if (action.type !== ActionTypes.LOAD_VIEW_DATA) { return }
const { id, requestParams, resolve, reject } = action.payload
const { viewDataLoaded, loadViewDataFail } = ViewActions
try {
const asyncData = yield call(request, {
method: 'post',
url: `${api.view}/${id}/getdata`,
data: requestParams
})
yield put(viewDataLoaded())
const { resultList } = asyncData.payload
asyncData.payload.resultList = (resultList && resultList.slice(0, 600)) || []
resolve(asyncData.payload)
} catch (err) {
const { response } = err as AxiosError
const { data } = response as AxiosResponse<IDavinciResponse<any>>
yield put(loadViewDataFail(err))
reject(data.header)
}
}
export function* getSelectOptions (action: ViewActionType) {
if (action.type !== ActionTypes.LOAD_SELECT_OPTIONS) { return }
const { payload } = action
const { selectOptionsLoaded, loadSelectOptionsFail } = ViewActions
try {
const { controlKey, requestParams, itemId, cancelTokenSource } = payload
const requestParamsMap: Array<[string, IDistinctValueReqeustParams]> = Object.entries(requestParams)
const requests = requestParamsMap.map(([viewId, params]: [string, IDistinctValueReqeustParams]) => {
const { columns, filters, variables, cache, expired } = params
return call(request, {
method: 'post',
url: `${api.bizlogic}/${viewId}/getdistinctvalue`,
data: {
columns,
filters,
params: variables,
cache,
expired
},
cancelToken: cancelTokenSource.token
})
})
const results = yield all(requests)
const values = results.reduce((payloads, r, index) => {
const { columns } = requestParamsMap[index][1]
if (columns.length === 1) {
return payloads.concat(r.payload.map((obj) => obj[columns[0]]))
}
return payloads
}, [])
yield put(selectOptionsLoaded(controlKey, Array.from(new Set(values)), itemId))
} catch (err) {
yield put(loadSelectOptionsFail(err))
// errorHandler(err)
}
}
export function* getViewDistinctValue (action: ViewActionType) {
if (action.type !== ActionTypes.LOAD_VIEW_DISTINCT_VALUE) { return }
const { viewId, params, resolve } = action.payload
const { viewDistinctValueLoaded, loadViewDistinctValueFail } = ViewActions
try {
const result = yield call(request, {
method: 'post',
url: `${api.view}/${viewId}/getdistinctvalue`,
data: {
cache: false,
expired: 0,
...params
}
})
const list = params.columns.reduce((arr, col) => {
return arr.concat(result.payload.map((item) => item[col]))
}, [])
yield put(viewDistinctValueLoaded(Array.from(new Set(list))))
if (resolve) {
resolve(result.payload)
}
} catch (err) {
yield put(loadViewDistinctValueFail(err))
errorHandler(err)
}
}
export function* getViewDataFromVizItem (action: ViewActionType) {
if (action.type !== ActionTypes.LOAD_VIEW_DATA_FROM_VIZ_ITEM) { return }
const { renderType, itemId, viewId, requestParams, vizType, cancelTokenSource } = action.payload
const { viewDataFromVizItemLoaded, loadViewDataFromVizItemFail } = ViewActions
const {
filters,
tempFilters,
linkageFilters,
globalFilters,
variables,
linkageVariables,
globalVariables,
pagination,
...rest
} = requestParams
const { pageSize, pageNo } = pagination || { pageSize: 0, pageNo: 0 }
try {
const asyncData = yield call(request, {
method: 'post',
url: `${api.view}/${viewId}/getdata`,
data: {
...omit(rest, 'customOrders'),
filters: filters.concat(tempFilters).concat(linkageFilters).concat(globalFilters),
params: variables.concat(linkageVariables).concat(globalVariables),
pageSize,
pageNo
},
cancelToken: cancelTokenSource.token
})
const { resultList } = asyncData.payload
asyncData.payload.resultList = (resultList && resultList.slice(0, 600)) || []
yield put(viewDataFromVizItemLoaded(renderType, itemId, requestParams, asyncData.payload, vizType, action.statistic))
} catch (err) {
yield put(loadViewDataFromVizItemFail(itemId, vizType, getErrorMessage(err)))
}
}
/** */
/** View sagas for fetch external authorization variables values */
export function* getDacChannels (action: ViewActionType) {
if (action.type !== ActionTypes.LOAD_DAC_CHANNELS) { return }
const { dacChannelsLoaded, loadDacChannelsFail } = ViewActions
try {
const asyncData = yield call(request, `${api.view}/dac/channels`)
const channels = asyncData.payload
yield put(dacChannelsLoaded(channels))
} catch (err) {
yield put(loadDacChannelsFail())
errorHandler(err)
}
}
export function* getDacTenants (action: ViewActionType) {
if (action.type !== ActionTypes.LOAD_DAC_TENANTS) { return }
const { dacTenantsLoaded, loadDacTenantsFail } = ViewActions
const { channelName } = action.payload
try {
const asyncData = yield call(request, `${api.view}/dac/${channelName}/tenants`)
const tenants = asyncData.payload
yield put(dacTenantsLoaded(tenants))
} catch (err) {
yield put(loadDacTenantsFail())
errorHandler(err)
}
}
export function* getDacBizs (action: ViewActionType) {
if (action.type !== ActionTypes.LOAD_DAC_BIZS) { return }
const { dacBizsLoaded, loadDacBizsFail } = ViewActions
const { channelName, tenantId } = action.payload
try {
const asyncData = yield call(request, `${api.view}/dac/${channelName}/tenants/${tenantId}/bizs`)
const bizs = asyncData.payload
yield put(dacBizsLoaded(bizs))
} catch (err) {
yield put(loadDacBizsFail())
errorHandler(err)
}
}
/** */
export default function* rootViewSaga () {
yield all([
takeLatest(ActionTypes.LOAD_VIEWS, getViews),
takeEvery(ActionTypes.LOAD_VIEWS_DETAIL, getViewsDetail),
takeLatest(ActionTypes.ADD_VIEW, addView),
takeEvery(ActionTypes.EDIT_VIEW, editView),
takeEvery(ActionTypes.DELETE_VIEW, deleteView),
takeEvery(ActionTypes.COPY_VIEW, copyView),
takeLatest(ActionTypes.EXECUTE_SQL, executeSql),
takeEvery(ActionTypes.LOAD_VIEW_DATA, getViewData),
takeEvery(ActionTypes.LOAD_SELECT_OPTIONS, getSelectOptions),
takeEvery(ActionTypes.LOAD_VIEW_DISTINCT_VALUE, getViewDistinctValue),
takeEvery(ActionTypes.LOAD_VIEW_DATA_FROM_VIZ_ITEM, getViewDataFromVizItem),
takeEvery(ActionTypes.LOAD_DAC_CHANNELS, getDacChannels),
takeEvery(ActionTypes.LOAD_DAC_TENANTS, getDacTenants),
takeEvery(ActionTypes.LOAD_DAC_BIZS, getDacBizs)
])
} | the_stack |
import { assert } from 'chai';
import * as fs from 'fs-extra';
import * as path from 'path';
import { FileChangeType } from '../../../../../client/common/platform/fileSystemWatcher';
import { createDeferred, Deferred, sleep } from '../../../../../client/common/utils/async';
import { getOSType, OSType } from '../../../../../client/common/utils/platform';
import { IDisposable } from '../../../../../client/common/utils/resourceLifecycle';
import { traceWarn } from '../../../../../client/logging';
import { PythonEnvKind } from '../../../../../client/pythonEnvironments/base/info';
import { BasicEnvInfo, ILocator } from '../../../../../client/pythonEnvironments/base/locator';
import { getEnvs } from '../../../../../client/pythonEnvironments/base/locatorUtils';
import { PythonEnvsChangedEvent } from '../../../../../client/pythonEnvironments/base/watcher';
import { getInterpreterPathFromDir } from '../../../../../client/pythonEnvironments/common/commonUtils';
import * as externalDeps from '../../../../../client/pythonEnvironments/common/externalDependencies';
import { deleteFiles, PYTHON_PATH } from '../../../../common';
import { TEST_TIMEOUT } from '../../../../constants';
import { run } from '../envTestUtils';
/**
* A utility class used to create, delete, or modify environments. Primarily used for watcher
* tests, where we need to create environments.
*/
class Venvs {
constructor(private readonly root: string, private readonly prefix = '.virtualenv-') {}
public async create(name: string): Promise<{ executable: string; envDir: string }> {
const envName = this.resolve(name);
const argv = [PYTHON_PATH.fileToCommandArgumentForPythonExt(), '-m', 'virtualenv', envName];
try {
await run(argv, { cwd: this.root });
} catch (err) {
throw new Error(`Failed to create Env ${path.basename(envName)} Error: ${err}`);
}
const dirToLookInto = path.join(this.root, envName);
const filename = await getInterpreterPathFromDir(dirToLookInto);
if (!filename) {
throw new Error(`No environment to update exists in ${dirToLookInto}`);
}
return { executable: filename, envDir: path.dirname(path.dirname(filename)) };
}
/**
* Creates a dummy environment by creating a fake executable.
* @param name environment suffix name to create
*/
public async createDummyEnv(
name: string,
kind: PythonEnvKind | undefined,
): Promise<{ executable: string; envDir: string }> {
const envName = this.resolve(name);
const interpreterPath = path.join(this.root, envName, getOSType() === OSType.Windows ? 'python.exe' : 'python');
const configPath = path.join(this.root, envName, 'pyvenv.cfg');
try {
await fs.createFile(interpreterPath);
if (kind === PythonEnvKind.Venv) {
await fs.createFile(configPath);
await fs.writeFile(configPath, 'version = 3.9.2');
}
} catch (err) {
throw new Error(`Failed to create python executable ${interpreterPath}, Error: ${err}`);
}
return { executable: interpreterPath, envDir: path.dirname(interpreterPath) };
}
// eslint-disable-next-line class-methods-use-this
public async update(filename: string): Promise<void> {
try {
await fs.writeFile(filename, 'Environment has been updated');
} catch (err) {
throw new Error(`Failed to update Workspace virtualenv executable ${filename}, Error: ${err}`);
}
}
// eslint-disable-next-line class-methods-use-this
public async delete(filename: string): Promise<void> {
try {
await fs.remove(filename);
} catch (err) {
traceWarn(`Failed to clean up ${filename}`);
}
}
public async cleanUp(): Promise<void> {
const globPattern = path.join(this.root, `${this.prefix}*`);
await deleteFiles(globPattern);
}
private resolve(name: string): string {
// Ensure env is random to avoid conflicts in tests (corrupting test data)
const now = new Date().getTime().toString().substr(-8);
return `${this.prefix}${name}${now}`;
}
}
type locatorFactoryFuncType1 = () => Promise<ILocator<BasicEnvInfo> & IDisposable>;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type locatorFactoryFuncType2 = (_: any) => Promise<ILocator<BasicEnvInfo> & IDisposable>;
export type locatorFactoryFuncType = locatorFactoryFuncType1 & locatorFactoryFuncType2;
/**
* Test if we're able to:
* * Detect a new environment
* * Detect when an environment has been deleted
* * Detect when an environment has been updated
* @param root The root folder where we create, delete, or modify environments.
* @param createLocatorFactoryFunc The factory function used to create the locator.
*/
export function testLocatorWatcher(
root: string,
createLocatorFactoryFunc: locatorFactoryFuncType,
options?: {
/**
* Argument to the locator factory function if any.
*/
arg?: string;
/**
* Environment kind to check for in watcher events.
* If not specified the check is skipped is default. This is because detecting kind of virtual env
* often depends on the file structure around the executable, so we need to wait before attempting
* to verify it. Omitting that check in those cases as we can never deterministically say when it's
* ready to check.
*/
kind?: PythonEnvKind;
/**
* For search based locators it is possible to verify if the environment is now being located, as it
* can be searched for. But for non-search based locators, for eg. which rely on running commands to
* get environments, it's not possible to verify it without executing actual commands, installing tools
* etc, so this option is useful for those locators.
*/
doNotVerifyIfLocated?: boolean;
},
): void {
let locator: ILocator<BasicEnvInfo> & IDisposable;
const venvs = new Venvs(root);
async function waitForChangeToBeDetected(deferred: Deferred<void>) {
const timeout = setTimeout(() => {
clearTimeout(timeout);
deferred.reject(new Error('Environment not detected'));
}, TEST_TIMEOUT);
await deferred.promise;
}
async function isLocated(executable: string): Promise<boolean> {
const items = await getEnvs(locator.iterEnvs());
return items.some((item) => externalDeps.arePathsSame(item.executablePath, executable));
}
suiteSetup(async function () {
if (getOSType() === OSType.Linux) {
this.skip();
}
await venvs.cleanUp();
});
async function setupLocator(onChanged: (e: PythonEnvsChangedEvent) => Promise<void>) {
locator = options?.arg ? await createLocatorFactoryFunc(options.arg) : await createLocatorFactoryFunc();
locator.onChanged(onChanged);
await getEnvs(locator.iterEnvs()); // Force the FS watcher to start.
// Wait for watchers to get ready
await sleep(2000);
}
teardown(async () => {
if (locator) {
await locator.dispose();
}
await venvs.cleanUp();
});
test('Detect a new environment', async () => {
let actualEvent: PythonEnvsChangedEvent;
const deferred = createDeferred<void>();
await setupLocator(async (e) => {
actualEvent = e;
deferred.resolve();
});
const { executable, envDir } = await venvs.create('one');
await waitForChangeToBeDetected(deferred);
if (!options?.doNotVerifyIfLocated) {
const isFound = await isLocated(executable);
assert.ok(isFound);
}
assert.strictEqual(actualEvent!.type, FileChangeType.Created, 'Wrong event emitted');
if (options?.kind) {
assert.strictEqual(actualEvent!.kind, options.kind, 'Wrong event emitted');
}
assert.notStrictEqual(actualEvent!.searchLocation, undefined, 'Wrong event emitted');
assert.ok(
externalDeps.arePathsSame(actualEvent!.searchLocation!.fsPath, path.dirname(envDir)),
'Wrong event emitted',
);
}).timeout(TEST_TIMEOUT * 2);
test('Detect when an environment has been deleted', async () => {
let actualEvent: PythonEnvsChangedEvent;
const deferred = createDeferred<void>();
const { executable, envDir } = await venvs.create('one');
await setupLocator(async (e) => {
if (e.type === FileChangeType.Deleted) {
actualEvent = e;
deferred.resolve();
}
});
// VSCode API has a limitation where it fails to fire event when environment folder is deleted directly:
// https://github.com/microsoft/vscode/issues/110923
// Using chokidar directly in tests work, but it has permission issues on Windows that you cannot delete a
// folder if it has a subfolder that is being watched inside: https://github.com/paulmillr/chokidar/issues/422
// Hence we test directly deleting the executable, and not the whole folder using `workspaceVenvs.cleanUp()`.
await venvs.delete(executable);
await waitForChangeToBeDetected(deferred);
if (!options?.doNotVerifyIfLocated) {
const isFound = await isLocated(executable);
assert.notOk(isFound);
}
assert.notStrictEqual(actualEvent!, undefined, 'Wrong event emitted');
if (options?.kind) {
assert.strictEqual(actualEvent!.kind, options.kind, 'Wrong event emitted');
}
assert.notStrictEqual(actualEvent!.searchLocation, undefined, 'Wrong event emitted');
assert.ok(
externalDeps.arePathsSame(actualEvent!.searchLocation!.fsPath, path.dirname(envDir)),
'Wrong event emitted',
);
}).timeout(TEST_TIMEOUT * 2);
test('Detect when an environment has been updated', async () => {
let actualEvent: PythonEnvsChangedEvent;
const deferred = createDeferred<void>();
// Create a dummy environment so we can update its executable later. We can't choose a real environment here.
// Executables inside real environments can be symlinks, so writing on them can result in the real executable
// being updated instead of the symlink.
const { executable, envDir } = await venvs.createDummyEnv('one', options?.kind);
await setupLocator(async (e) => {
if (e.type === FileChangeType.Changed) {
actualEvent = e;
deferred.resolve();
}
});
await venvs.update(executable);
await waitForChangeToBeDetected(deferred);
assert.notStrictEqual(actualEvent!, undefined, 'Event was not emitted');
if (options?.kind) {
assert.strictEqual(actualEvent!.kind, options.kind, 'Kind is not as expected');
}
assert.notStrictEqual(actualEvent!.searchLocation, undefined, 'Search location is not set');
assert.ok(
externalDeps.arePathsSame(actualEvent!.searchLocation!.fsPath, path.dirname(envDir)),
`Paths don't match ${actualEvent!.searchLocation!.fsPath} != ${path.dirname(envDir)}`,
);
}).timeout(TEST_TIMEOUT * 2);
} | the_stack |
import {ChangeType, CRDTChange, CRDTError, CRDTModel, CRDTTypeRecord, VersionMap, Referenceable, createEmptyChange} from './crdt.js';
import {Dictionary} from '../../utils/lib-utils.js';
import {assert} from '../../platform/assert-web.js';
type RawCollection<T> = Set<T>;
export type CollectionData<T extends Referenceable> = {
values: Dictionary<{value: T, version: VersionMap}>,
version: VersionMap
};
export enum CollectionOpTypes {
Add,
Remove,
FastForward,
}
export type CollectionFastForwardOp<T> = {type: CollectionOpTypes.FastForward, added: [T, VersionMap][], removed: T[], oldVersionMap: VersionMap, newVersionMap: VersionMap};
export type CollectionOperationAdd<T> = {type: CollectionOpTypes.Add, added: T, actor: string, versionMap: VersionMap};
export type CollectionOperationRemove<T> = {type: CollectionOpTypes.Remove, removed: T, actor: string, versionMap: VersionMap};
export type CollectionOperation<T> = CollectionOperationAdd<T> | CollectionOperationRemove<T> | CollectionFastForwardOp<T>;
export interface CRDTCollectionTypeRecord<T extends Referenceable> extends CRDTTypeRecord {
data: CollectionData<T>;
operation: CollectionOperation<T>;
consumerType: RawCollection<T>;
}
type CollectionChange<T extends Referenceable> = CRDTChange<CRDTCollectionTypeRecord<T>>;
type CollectionModel<T extends Referenceable> = CRDTModel<CRDTCollectionTypeRecord<T>>;
export class CRDTCollection<T extends Referenceable> implements CollectionModel<T> {
private model: CollectionData<T> = {values: {}, version: {}};
merge(other: CollectionData<T>): {modelChange: CollectionChange<T>, otherChange: CollectionChange<T>} {
// Ensure we never send an update if the two versions are already the same.
// TODO(shans): Remove this once fast-forwarding is two-sided, and replace with
// a check for an effect-free fast-forward op in each direction instead.
if (sameVersions(this.model.version, other.version)) {
let entriesMatch = true;
const theseKeys = Object.keys(this.model.values);
const otherKeys = Object.keys(other.values);
if (theseKeys.length === otherKeys.length) {
for (const key of Object.keys(this.model.values)) {
if (!other.values[key]) {
entriesMatch = false;
break;
}
}
if (entriesMatch) {
// tslint:disable-next-line: no-any
return {modelChange: createEmptyChange() as any, otherChange: createEmptyChange() as any};
}
}
}
const newVersionMap = mergeVersions(this.model.version, other.version);
const merged: Dictionary<{value: T, version: VersionMap}> = {};
// Fast-forward op to send to other model. Elements added and removed will
// be filled in below.
const fastForwardOp: CollectionFastForwardOp<T> = {
type: CollectionOpTypes.FastForward,
added: [],
removed: [],
oldVersionMap: other.version,
newVersionMap,
};
for (const otherEntry of Object.values(other.values)) {
const value = otherEntry.value;
const id = value.id;
const thisEntry = this.model.values[id];
if (thisEntry) {
if (sameVersions(thisEntry.version, otherEntry.version)) {
// Both models have the same value at the same version. Add it to the
// merge.
merged[id] = thisEntry;
} else {
// Models have different versions for the same value. Merge the
// versions, and update other.
const mergedVersion = mergeVersions(thisEntry.version, otherEntry.version);
merged[id] = {value, version: mergedVersion};
fastForwardOp.added.push([value, mergedVersion]);
}
} else if (dominates(this.model.version, otherEntry.version)) {
// Value was deleted by this model.
fastForwardOp.removed.push(value);
} else {
// Value was added by other model.
merged[id] = otherEntry;
}
}
for (const [id, thisEntry] of Object.entries(this.model.values)) {
if (!other.values[id] && !dominates(other.version, thisEntry.version)) {
// Value was added by this model.
merged[id] = thisEntry;
fastForwardOp.added.push([thisEntry.value, thisEntry.version]);
}
}
const operations = simplifyFastForwardOp(fastForwardOp) || [fastForwardOp];
this.model.values = merged;
this.model.version = newVersionMap;
const modelChange: CollectionChange<T> = {
changeType: ChangeType.Model,
modelPostChange: this.model
};
const otherChange: CollectionChange<T> = {
changeType: ChangeType.Operations,
operations,
};
return {modelChange, otherChange};
}
applyOperation(op: CollectionOperation<T>): boolean {
switch (op.type) {
case CollectionOpTypes.Add:
return this.add(op.added, op.actor, op.versionMap);
case CollectionOpTypes.Remove:
return this.remove(op.removed, op.actor, op.versionMap);
case CollectionOpTypes.FastForward:
return this.fastForward(op);
default:
throw new CRDTError(`Op ${op} not supported`);
}
}
getData(): CollectionData<T> {
return this.model;
}
getParticleView(): RawCollection<T> {
return new Set(Object.values(this.model.values).map(entry => entry.value));
}
private add(value: T, key: string, version: VersionMap): boolean {
this.checkValue(value);
// Only accept an add if it is immediately consecutive to the versionMap for that actor.
const expectedVersionMapValue = (this.model.version[key] || 0) + 1;
if (!(expectedVersionMapValue === version[key] || 0)) {
return false;
}
this.model.version[key] = version[key];
const previousVersion = this.model.values[value.id] ? this.model.values[value.id].version : {};
const newValue = this.model.values[value.id] ? this.model.values[value.id].value : value;
this.model.values[value.id] = {value: newValue, version: mergeVersions(version, previousVersion)};
return true;
}
private remove(value: T, key: string, version: VersionMap): boolean {
this.checkValue(value);
if (!this.model.values[value.id]) {
return false;
}
const versionMapValue = (version[key] || 0);
// Removes do not increment the VersionMap.
const expectedVersionMapValue = (this.model.version[key] || 0);
if (!(expectedVersionMapValue === versionMapValue)) {
return false;
}
// Cannot remove an element unless version is higher for all other actors as
// well.
if (!dominates(version, this.model.values[value.id].version)) {
return false;
}
this.model.version[key] = versionMapValue;
delete this.model.values[value.id];
return true;
}
private fastForward(op: CollectionFastForwardOp<T>): boolean {
const currentVersionMap = this.model.version;
if (!dominates(currentVersionMap, op.oldVersionMap)) {
// Can't apply fast-forward op. Current model's VersionMap is behind oldVersionMap.
return false;
}
if (dominates(currentVersionMap, op.newVersionMap)) {
// Current model already knows about everything in this fast-forward op.
// Nothing to do, but not an error.
return true;
}
for (const [value, version] of op.added) {
this.checkValue(value);
const existingValue = this.model.values[value.id];
if (existingValue) {
existingValue.version = mergeVersions(existingValue.version, version);
} else if (!dominates(currentVersionMap, version)) {
this.model.values[value.id] = {value, version};
}
}
for (const value of op.removed) {
this.checkValue(value);
const existingValue = this.model.values[value.id];
if (existingValue && dominates(op.newVersionMap, existingValue.version)) {
delete this.model.values[value.id];
}
}
this.model.version = mergeVersions(currentVersionMap, op.newVersionMap);
return true;
}
private checkValue(value: T) {
assert(value.id && value.id.length, `CRDT value must have an ID.`);
}
}
function mergeVersions(version1: VersionMap, version2: VersionMap): VersionMap {
const merged = {};
for (const [k, v] of Object.entries(version1)) {
merged[k] = v;
}
for (const [k, v] of Object.entries(version2)) {
merged[k] = Math.max(v, version1[k] || 0);
}
return merged;
}
function sameVersions(version1: VersionMap, version2: VersionMap): boolean {
if (Object.keys(version1).length !== Object.keys(version2).length) {
return false;
}
for (const [k, v] of Object.entries(version1)) {
if (v !== version2[k]) {
return false;
}
}
return true;
}
/** Returns true if map1 dominates map2. */
function dominates(map1: VersionMap, map2: VersionMap): boolean {
for (const [k, v] of Object.entries(map2)) {
if ((map1[k] || 0) < v) {
return false;
}
}
return true;
}
/**
* Converts a simple fast-forward operation into a sequence of regular ops.
* Currently only supports converting add ops made by a single actor. Returns
* null if it could not simplify the fast-forward operation.
*/
export function simplifyFastForwardOp<T>(fastForwardOp: CollectionFastForwardOp<T>): CollectionOperation<T>[] {
if (fastForwardOp.removed.length > 0) {
// Remove ops can't be replayed in order.
return null;
}
if (fastForwardOp.added.length === 0) {
if (sameVersions(fastForwardOp.oldVersionMap, fastForwardOp.newVersionMap)) {
// No added, no removed, and no versionMap changes: op should be empty.
return [];
}
// Just a version bump, no add ops to replay.
return null;
}
const actor = getSingleActorIncrement(fastForwardOp.oldVersionMap, fastForwardOp.newVersionMap);
if (actor === null) {
return null;
}
// Sort the add ops in increasing order by the actor's version.
const addOps = [...fastForwardOp.added].sort(([elem1, v1], [elem2, v2]) => (v1[actor] || 0) - (v2[actor] || 0));
let expectedVersion = fastForwardOp.oldVersionMap[actor] || 0;
for (const [elem, version] of addOps) {
if (++expectedVersion !== version[actor]) {
// The add op didn't match the expected increment-by-one pattern. Can't
// replay it properly.
return null;
}
}
// If we reach here then all added versions are incremented by one.
// Check the final versionMap.
const expectedVersionMap = {...fastForwardOp.oldVersionMap};
expectedVersionMap[actor] = expectedVersion;
if (!sameVersions(expectedVersionMap, fastForwardOp.newVersionMap)) {
return null;
}
return addOps.map(([elem, version]) => ({
type: CollectionOpTypes.Add,
added: elem,
actor,
versionMap: version,
}));
}
/**
* Given two version maps, returns the actor who incremented their version. If
* there's more than one such actor, returns null.
*/
function getSingleActorIncrement(oldVersion: VersionMap, newVersion: VersionMap): string | null {
const incrementedActors = Object.entries(newVersion).filter(([k, v]) => v > (oldVersion[k] || 0));
return incrementedActors.length === 1 ? incrementedActors[0][0] : null;
} | the_stack |
import {
BspSet,
empty,
dense,
Empty,
Dense,
combineCmp,
SetOperations,
intersectUntyped,
compareUntyped,
Cachable,
UntypedBspSet,
unionUntyped,
exceptUntyped,
lazy,
UntypedSparse,
fromUntyped,
meetsUntyped,
Pair,
} from "./bspSet";
type Restrict<T, Props extends (keyof T)[]> = { [Prop in Props[number]]: T[Prop] };
export type Product<T> = { readonly [dim in keyof T]: T[dim] extends BspSet<infer _TKey, infer _TId> ? T[dim] : never };
type UntypedProduct<T> = {
readonly [dim in keyof T]?: T[dim] extends BspSet<infer TKey, infer _TId> ? UntypedSparse<TKey> : never;
};
type Probabilities<T> = { readonly [dim in keyof T]?: number };
type ProductOperations<T> = {
readonly [dim in keyof T]: T[dim] extends BspSet<infer TKey, infer TId> ? SetOperations<TKey, TId> : never;
};
/** Given a cartesian product, a subspace is a subset of said space, such that it is also a cartesian product
* and all the dimensions form subsets of the original cartesian product.
*
* This is a generalized notion of something like hyper-rectangles. Examples include:
* - Rectangles
* - Individual cells in a grid
* - Rectangular ranges with missing rows and/or columns
*
* For the actual definition and properties, please read the document about *Operations on Cartesian Products*.
*/
interface Subspace<T> {
readonly isSubspace: true;
// isCoSubspace: boolean;
readonly bounds: UntypedProduct<T>;
}
// type CoSubspace<T> = {
// isSubspace: boolean;
// isCoSubspace: true;
// subspace: Product<T>;
// };
interface Union<T> {
readonly isSubspace: false;
// readonly isCoSubspace: false;
readonly left: UntypedSparseProduct<T>;
readonly right: UntypedSparseProduct<T>;
readonly bounds: UntypedProduct<T>;
readonly subspaceCount: number;
}
type UntypedSparseProduct<T> = Subspace<T> | Union<T>; // | CoSubspace<T>;
interface SparseProduct<T> {
readonly productOperations: ProductOperations<T>;
readonly root: UntypedSparseProduct<T>;
}
interface Box<T> {
box: UntypedProduct<T>;
probabilities: Probabilities<T>;
children?: Pair<Box<T>>;
depth: number;
}
const tops: { [poKey in string]?: Box<unknown> } = {};
const top = <T>(productOperations: ProductOperations<T>): Box<T> => {
const dims: [keyof T, ProductOperations<T>[keyof T]["id"]][] = [];
for (const dimStr of Object.keys(productOperations)) {
const dim = dimStr as keyof T;
dims.push([dim, productOperations[dim].id]);
}
const poKey = JSON.stringify(dims.sort());
let currTop = tops[poKey];
if (currTop === undefined) {
currTop = { box: {}, probabilities: {}, depth: 1 };
tops[poKey] = currTop;
}
return currTop;
};
function subspace<T>(bounds: UntypedProduct<T>): Subspace<T> | Dense {
let isDense = true;
for (const dim of Object.keys(bounds)) {
if (Object.prototype.hasOwnProperty.call(bounds, dim)) {
isDense = false;
break;
}
}
if (isDense) {
return dense;
}
return { isSubspace: true as const, bounds };
}
function getUntypedSubspaceCount<T>(set: UntypedSparseProduct<T>) {
if (set.isSubspace) {
return 1;
}
return set.subspaceCount;
}
const union = <T>(
left: UntypedSparseProduct<T>,
right: UntypedSparseProduct<T>,
bounds: UntypedProduct<T>,
): Union<T> => ({
isSubspace: false as const,
left,
right,
bounds,
subspaceCount: getUntypedSubspaceCount(left) + getUntypedSubspaceCount(right),
});
function sparseProduct<T>(
productOperations: ProductOperations<T>,
root: UntypedSparseProduct<T> | Dense,
): SparseProduct<T> | Dense {
if (root === dense) {
return root;
}
if (root.isSubspace) {
let hasSparseDimensions = false;
for (const dim of Object.keys(root.bounds)) {
if (Object.prototype.hasOwnProperty.call(productOperations, dim)) {
hasSparseDimensions = true;
break;
}
}
if (!hasSparseDimensions) {
return dense;
}
}
return { productOperations, root };
}
type UntypedProductSet<T> = Empty | Dense | UntypedSparseProduct<T>;
export type ProductSet<T> = Empty | Dense | SparseProduct<T>;
function toBspSet<T>(set: UntypedBspSet<T> | undefined) {
if (set === undefined) {
return dense;
}
return set;
}
/** An object that contains all downcasts. The operations in here are generally of the kind that need dynamic
* features, i.e. iterate over the object properties somehow. Their *usage* can be considered safe, but they warrant
* more careful review whenever a change occurs, because we get less support from the type system and we are
* downcasting. */
const unsafe = {
unzip<T>(product: Product<T>): ProductSet<T> {
const productOperations: { [dim in keyof T]?: SetOperations<unknown, unknown> } = {};
const root: { [dim in keyof T]?: UntypedSparse<unknown> } = {};
for (const dimStr of Object.keys(product)) {
const dim = dimStr as keyof T;
if (Object.prototype.hasOwnProperty.call(product, dim)) {
const set: BspSet<unknown, unknown> = product[dim];
if (set === empty) {
return empty;
}
if (set === dense) {
continue;
}
productOperations[dim] = set.setOperations;
root[dim] = set.root;
}
}
return sparseProduct(productOperations as ProductOperations<T>, subspace(root as UntypedProduct<T>));
},
combineProduct<T>(
productOperations: ProductOperations<T>,
left: UntypedProduct<T>,
right: UntypedProduct<T>,
combineFunc: <Key extends Cachable<Key>, Id>(
setOperations: SetOperations<Key, Id>,
left: UntypedBspSet<Key>,
right: UntypedBspSet<Key>
) => UntypedBspSet<Key>,
) {
const res: { [dim in keyof T]?: UntypedSparse<unknown> } = {};
for (const dimStr of Object.keys(productOperations)) {
const dim = dimStr as keyof T;
if (Object.prototype.hasOwnProperty.call(productOperations, dim)) {
const combined = combineFunc<unknown, unknown>(
productOperations[dim],
toBspSet(left[dim]),
toBspSet(right[dim]),
);
if (combined === empty) {
return combined;
}
if (combined === dense) {
continue;
}
res[dim] = combined;
}
}
return res as UntypedProduct<T>;
},
// eslint-disable-next-line @typescript-eslint/ban-types
restrict<T extends object, Props extends (keyof T)[]>(object: T, ...props: Props) {
const res: Partial<Restrict<T, Props>> = {};
for (const key of props) {
if (Object.prototype.hasOwnProperty.call(object, key)) {
const prop = object[key];
res[key] = prop;
}
}
return res as Restrict<T, Props>;
},
fromUntypedProduct<T, Props extends (keyof T)[]>(
productOperations: ProductOperations<Restrict<T, Props>>,
bounds: UntypedProduct<Restrict<T, Props>>,
dims: Props,
) {
const product: { [dim in Props[number]]?: BspSet<unknown, unknown> } = {};
for (const dim of dims) {
const bound: UntypedSparse<unknown> | undefined = bounds[dim];
product[dim] = fromUntyped(productOperations[dim], bound !== undefined ? bound : dense);
}
return product as Product<Restrict<T, Props>>;
},
denseProduct<T, Props extends (keyof T)[]>(dims: Props): Product<Restrict<T, Props>> {
const top_inner: { [dim in Props[number]]?: Dense } = {};
for (const dim of dims) {
top_inner[dim] = dense;
}
return top_inner as Product<Restrict<T, Props>>;
},
};
export const createFromProduct = unsafe.unzip.bind(unsafe);
type Compatible<T, U> = { [dim in keyof T & keyof U]: T[dim] };
function joinBounds<T>(productOperations: ProductOperations<T>, left: UntypedProduct<T>, right: UntypedProduct<T>) {
const join = unsafe.combineProduct(productOperations, left, right, unionUntyped);
if (join === empty) {
throw new Error("broken invariant: the union of two non-empty products cannot be empty");
}
return join;
}
function compareSubspace<T>(
productOperations: ProductOperations<T>,
left: UntypedProduct<T>,
right: UntypedProduct<T>,
) {
let cmp: ReturnType<typeof combineCmp> = 0;
for (const dimStr of Object.keys(productOperations)) {
const dim = dimStr as keyof T;
if (Object.prototype.hasOwnProperty.call(productOperations, dim)) {
const lProj = toBspSet(left[dim]);
const rProj = toBspSet(right[dim]);
const setOperations = productOperations[dim];
cmp = combineCmp(cmp, compareUntyped<unknown, unknown>(setOperations, lProj, rProj));
if (cmp === undefined) {
return undefined;
}
}
}
return cmp;
}
const tryUnionSubspaces = (() => {
const cache: { left?: unknown; right?: unknown; res?: unknown } = {};
return <T>(
productOperations: ProductOperations<T>,
left: Subspace<T>,
right: Subspace<T>,
): Subspace<T> | Dense | Empty | undefined => {
if (left === cache.left && right === cache.right) {
return cache.res as ReturnType<typeof tryUnionSubspaces>;
}
cache.left = left;
cache.right = right;
const cmp = compareSubspace(productOperations, left.bounds, right.bounds);
if (cmp !== undefined) {
return (cache.res = cmp <= 0 ? right : left);
}
let differentDimension: keyof T | undefined;
// because Object.keys only returns string[], we need to downcast
const po_keys = Object.keys(productOperations) as (keyof T)[];
for (const dim of po_keys) {
if (Object.prototype.hasOwnProperty.call(productOperations, dim)) {
const cmp_inner = compareUntyped<unknown, unknown>(
productOperations[dim],
toBspSet(left.bounds[dim]),
toBspSet(right.bounds[dim]),
);
if (cmp_inner !== 0) {
if (differentDimension !== undefined) {
return (cache.res = undefined);
}
differentDimension = dim;
}
}
}
if (differentDimension !== undefined) {
const newDim = unionUntyped<unknown, unknown>(
productOperations[differentDimension],
toBspSet(left.bounds[differentDimension]),
toBspSet(right.bounds[differentDimension]),
);
if (newDim === empty) {
return (cache.res = empty);
}
if (newDim === dense) {
// we are actually deleting the `differentDimension`, so the variable
// `deleted` must be there. Hence disabling the rule here.
const { [differentDimension]: deleted, ...leftBoundsWithoutDifferentDimension } = left.bounds;
return (cache.res = subspace<unknown>(leftBoundsWithoutDifferentDimension));
}
const newBounds: UntypedProduct<T> = {
...left.bounds,
[differentDimension]: newDim,
};
return (cache.res = subspace(newBounds));
}
return (cache.res = undefined);
};
})();
function combineChildren<T>(
productOperations: ProductOperations<T>,
left: UntypedProductSet<T>,
right: UntypedProductSet<T>,
): UntypedProductSet<T> {
if (right === empty) {
return left;
}
if (right === dense) {
return right;
}
if (left === empty) {
return right;
}
if (left === dense) {
return left;
}
if (!left.isSubspace || !right.isSubspace) {
return union<T>(left, right, joinBounds(productOperations, left.bounds, right.bounds));
}
const combinedSubspace = tryUnionSubspaces<T>(productOperations, left, right);
if (combinedSubspace !== undefined) {
return combinedSubspace;
}
return union(left, right, joinBounds(productOperations, left.bounds, right.bounds));
}
function projectUntyped<T, Props extends (keyof T)[]>(
productOperations: ProductOperations<T>,
set: UntypedSparseProduct<T>,
...dims: Props
): UntypedProductSet<Restrict<T, Props>> {
const bounds = unsafe.restrict(set.bounds, ...dims);
if (set.isSubspace) {
return subspace(bounds);
}
const lChild = projectUntyped(productOperations, set.left, ...dims);
if (lChild === dense) {
return dense;
}
const rChild = projectUntyped(productOperations, set.right, ...dims);
return combineChildren(productOperations, lChild, rChild);
}
export function project<T, Props extends (keyof T)[]>(
set: ProductSet<T>,
...dims: Props
): ProductSet<Restrict<T, Props>> {
if (set === dense || set === empty) {
return set;
}
const productOperations = unsafe.restrict(set.productOperations, ...dims);
const root = projectUntyped(productOperations, set.root, ...dims);
if (root === empty) {
return root;
}
return sparseProduct(productOperations, root);
}
function splitBox<T>(productOperations: ProductOperations<T>, currentBox: Box<T>): Pair<Box<T>> {
if (currentBox.children !== undefined) { return currentBox.children; }
const { box, probabilities } = currentBox;
let biggestDim: keyof T | undefined;
let biggestDimKey;
let currentProb = 0;
// because Object.keys only returns string[], we need to downcast
const po_keys = Object.keys(productOperations) as (keyof T)[];
for (const dim of po_keys) {
if (Object.prototype.hasOwnProperty.call(productOperations, dim)) {
const prob: number | undefined = probabilities[dim];
const setOperations_inner = productOperations[dim];
if (prob === undefined) {
biggestDim = dim;
biggestDimKey = setOperations_inner.top;
break;
}
if (prob > currentProb) {
const dimensionSet = toBspSet(box[dim]);
if (dimensionSet === empty) {
throw new Error("the key split can never return empty");
}
let key = setOperations_inner.top;
if (dimensionSet !== dense) {
if (!dimensionSet.isExact) {
throw new Error("the key can always be represented exactly");
}
key = dimensionSet.key;
}
if (!setOperations_inner.canSplit(key)) {
continue;
}
biggestDim = dim;
currentProb = prob;
biggestDimKey = key;
}
}
}
if (biggestDim === undefined || biggestDimKey === undefined) {
throw new Error("there has to be at least one dimension");
}
const setOperations = productOperations[biggestDim];
const [[leftDim, leftProb], [rightDim, rightProb]] = setOperations.split(biggestDimKey);
const res: ReturnType<typeof splitBox> = [
{
box: { ...box, [biggestDim]: lazy<unknown, unknown>(setOperations, setOperations.top, leftDim) },
probabilities: { ...probabilities, [biggestDim]: leftProb },
depth: currentBox.depth + 1,
},
{
box: { ...box, [biggestDim]: lazy<unknown, unknown>(setOperations, setOperations.top, rightDim) },
probabilities: { ...probabilities, [biggestDim]: rightProb },
depth: currentBox.depth + 1,
},
];
if (currentBox.depth < 10) {
currentBox.children = res;
}
return res;
}
function restrictByBounds<T>(
productOperations: ProductOperations<T>,
set: UntypedProductSet<T>,
leftBounds: UntypedProduct<T>,
rightBounds: UntypedProduct<T>,
): Pair<UntypedProductSet<T>> {
if (set === empty) {
return [empty, empty];
}
if (set === dense) {
return [subspace(leftBounds), subspace(rightBounds)];
}
const cmp = compareSubspace(productOperations, set.bounds, leftBounds);
// the set is fully contained in the left half, i.e. we know the pair.
if (cmp !== undefined && cmp <= 0) {
return [set, empty];
}
const newLeftBounds = unsafe.combineProduct(productOperations, set.bounds, leftBounds, intersectUntyped);
// if we know, that the left set is completely empty, then the whole set is in the right bounds.
if (newLeftBounds === empty) {
return [empty, set];
}
const newRightBounds = unsafe.combineProduct(productOperations, set.bounds, rightBounds, intersectUntyped);
if (set.isSubspace) {
return [subspace(newLeftBounds), newRightBounds === empty ? empty : subspace(newRightBounds)];
}
const [ll, lr] = restrictByBounds(productOperations, set.left, leftBounds, rightBounds);
const [rl, rr] = restrictByBounds(productOperations, set.right, leftBounds, rightBounds);
return [combineChildren(productOperations, ll, rl), combineChildren(productOperations, lr, rr)];
}
const splitByBox = <T>(
productOperations: ProductOperations<T>,
set: UntypedProductSet<T>,
{ box: leftBounds }: Box<T>,
{ box: rightBounds }: Box<T>,
): Pair<UntypedProductSet<T>, UntypedProductSet<T>> => {
return restrictByBounds(productOperations, set, leftBounds, rightBounds);
};
function recurse<T>(
productOperations: ProductOperations<T>,
left: UntypedProductSet<T>,
right: UntypedProductSet<T>,
currentBox: Box<T>,
visitFunc: (
productOperations: ProductOperations<T>,
left: UntypedProductSet<T>,
right: UntypedProductSet<T>,
box: Box<T>
) => UntypedProductSet<T>,
) {
const [leftBox, rightBox] = splitBox(productOperations, currentBox);
const [ll, lr] = splitByBox(productOperations, left, leftBox, rightBox);
const [rl, rr] = splitByBox(productOperations, right, leftBox, rightBox);
const lChild = visitFunc(productOperations, ll, rl, leftBox);
if (lChild === dense) {
return dense;
}
const rChild = visitFunc(productOperations, lr, rr, rightBox);
return combineChildren(productOperations, lChild, rChild);
}
function unionUntypedProduct<T>(
productOperations: ProductOperations<T>,
left: UntypedProductSet<T>,
right: UntypedProductSet<T>,
currentBox: Box<T>,
): UntypedProductSet<T> {
if (right === empty) {
return left;
}
if (left === empty) {
return right;
}
if (left === dense) {
return left;
}
if (right === dense) {
return right;
}
if (left.isSubspace && right.isSubspace) {
const combinedSubspace = tryUnionSubspaces(productOperations, left, right);
if (combinedSubspace !== undefined) {
return combinedSubspace;
}
}
return recurse(productOperations, left, right, currentBox, unionUntypedProduct);
}
export function unionProduct<T extends Compatible<U, T>, U extends Compatible<T, U>>(
left: ProductSet<T>,
right: ProductSet<U>,
): ProductSet<T & U> {
if (right === empty) {
return left;
}
if (right === dense) {
return right;
}
if (left === empty) {
return right;
}
if (left === dense) {
return left;
}
const productOperations = { ...left.productOperations, ...right.productOperations };
const res = unionUntypedProduct(productOperations, left.root, right.root, top(productOperations));
if (res === empty) {
return res;
}
return sparseProduct(productOperations, res);
}
function intersectUntypedProduct<T>(
productOperations: ProductOperations<T>,
left: UntypedProductSet<T>,
right: UntypedProductSet<T>,
currentBox: Box<T>,
): UntypedProductSet<T> {
if (left === empty || right === empty) {
return empty;
}
if (left === dense) {
return right;
}
if (right === dense) {
return left;
}
if (left.isSubspace && right.isSubspace) {
const res = unsafe.combineProduct(productOperations, left.bounds, right.bounds, intersectUntyped);
if (res === empty) {
return empty;
}
return subspace(res);
}
return recurse(productOperations, left, right, currentBox, intersectUntypedProduct);
}
export function intersectProduct<T extends Compatible<U, T>, U extends Compatible<T, U>>(
left: ProductSet<T>,
right: ProductSet<U>,
): ProductSet<T & U> {
if (left === empty) {
return left;
}
if (right === empty) {
return right;
}
if (left === dense) {
return right;
}
if (right === dense) {
return left;
}
const productOperations = { ...left.productOperations, ...right.productOperations };
const res = intersectUntypedProduct(productOperations, left.root, right.root, top(productOperations));
if (res === empty) {
return res;
}
return sparseProduct(productOperations, res);
}
function tryExceptSubspaces<T>(
productOperations: ProductOperations<T>,
left: Subspace<T>,
right: Subspace<T>,
): Subspace<T> | Dense | Empty | undefined {
const cmp = compareSubspace(productOperations, left.bounds, right.bounds);
if (cmp === 0 || cmp === -1) {
return empty;
}
let notContainedDimension: keyof T | undefined;
// because Object.keys only returns string[], we need to downcast
const po_keys = Object.keys(productOperations) as (keyof T)[];
for (const dim of po_keys) {
if (Object.prototype.hasOwnProperty.call(productOperations, dim)) {
const cmp_inner = compareUntyped<unknown, unknown>(
productOperations[dim],
toBspSet(left.bounds[dim]),
toBspSet(right.bounds[dim]),
);
if (cmp_inner === undefined || cmp_inner > 0) {
if (notContainedDimension !== undefined) {
return undefined;
}
notContainedDimension = dim;
}
}
}
if (notContainedDimension !== undefined) {
const newDim = exceptUntyped<unknown, unknown>(
productOperations[notContainedDimension],
toBspSet(left.bounds[notContainedDimension]),
toBspSet(right.bounds[notContainedDimension]),
);
if (newDim === empty) {
return empty;
}
if (newDim === dense) {
// we are actually deleting the `differentDimension`, so the variable
// `deleted` must be there. Hence disabling the rule here.
const { [notContainedDimension]: deleted, ...leftBoundsWithoutDifferentDimension } = left.bounds;
return subspace<unknown>(leftBoundsWithoutDifferentDimension);
}
const newBounds: UntypedProduct<T> = {
...left.bounds,
[notContainedDimension]: newDim,
};
return subspace(newBounds);
}
return undefined;
}
function exceptUntypedProduct<T>(
productOperations: ProductOperations<T>,
left: UntypedProductSet<T>,
right: UntypedProductSet<T>,
currentBox: Box<T>,
): UntypedProductSet<T> {
if (left === empty) {
return left;
}
if (right === dense) {
return empty;
}
if (right === empty) {
return left;
}
if (left === dense) {
return recurse(productOperations, left, right, currentBox, exceptUntypedProduct);
}
if (left.isSubspace && right.isSubspace) {
const combinedSubspace = tryExceptSubspaces(productOperations, left, right);
if (combinedSubspace !== undefined) {
return combinedSubspace;
}
}
return recurse(productOperations, left, right, currentBox, exceptUntypedProduct);
}
export function exceptProduct<T extends Compatible<U, T>, U extends Compatible<T, U>>(
left: ProductSet<T>,
right: ProductSet<U>,
): ProductSet<T & U> {
if (left === empty) {
return left;
}
if (right === empty) {
return left;
}
if (right === dense) {
return empty;
}
if (left === dense) {
const res_inner =
exceptUntypedProduct(right.productOperations, dense, right.root, top(right.productOperations));
if (res_inner === empty) {
return res_inner;
}
return sparseProduct(right.productOperations, res_inner);
}
const productOperations = { ...left.productOperations, ...right.productOperations };
const res = exceptUntypedProduct(productOperations, left.root, right.root, top(productOperations));
if (res === empty) {
return res;
}
return sparseProduct(productOperations, res);
}
function compareUntypedProduct<T>(
productOperations: ProductOperations<T>,
left: UntypedProductSet<T>,
right: UntypedProductSet<T>,
boundingBox: Box<T>,
): -1 | 0 | 1 | undefined {
if (left === right) {
return 0;
}
if (left === empty) {
return -1;
}
if (right === empty) {
return 1;
}
if (left === dense) {
if (right === dense) {
return 0;
}
return 1;
}
if (right === dense) {
return -1;
}
if (left.isSubspace) {
if (right.isSubspace) {
return compareSubspace(productOperations, left.bounds, right.bounds);
}
}
const [leftBox, rightBox] = splitBox(productOperations, boundingBox);
const [ll, lr] = splitByBox(productOperations, left, leftBox, rightBox);
const [rl, rr] = splitByBox(productOperations, right, leftBox, rightBox);
const leftCmp = compareUntypedProduct(productOperations, ll, rl, leftBox);
if (leftCmp === undefined) {
return undefined;
}
return combineCmp(leftCmp, compareUntypedProduct(productOperations, lr, rr, rightBox));
}
export function compareProduct<T extends Compatible<U, T>, U extends Compatible<T, U>>(
left: ProductSet<T>,
right: ProductSet<U>,
) {
if (left === right) {
return 0;
}
if (left === empty) {
return -1;
}
if (right === empty) {
return 1;
}
if (left === dense) {
if (right === dense) {
return 0;
}
return 1;
}
if (right === dense) {
return -1;
}
const productOperations = { ...left.productOperations, ...right.productOperations };
return compareUntypedProduct(productOperations, left.root, right.root, top(productOperations));
}
function meetsSubspace<T>(productOperations: ProductOperations<T>, left: UntypedProduct<T>, right: UntypedProduct<T>) {
for (const dimStr of Object.keys(productOperations)) {
const dim = dimStr as keyof T;
if (Object.prototype.hasOwnProperty.call(productOperations, dim)) {
const lProj = toBspSet(left[dim]);
const rProj = toBspSet(right[dim]);
const setOperations = productOperations[dim];
if (!meetsUntyped<unknown, unknown>(setOperations, lProj, rProj)) {
return false;
}
}
}
return true;
}
function meetsUntypedProduct<T>(
productOperations: ProductOperations<T>,
left: UntypedProductSet<T>,
right: UntypedProductSet<T>,
boundingBox: Box<T>,
): boolean {
if (left === empty || right === empty) {
return false;
}
if (left === dense || right === dense) {
return true;
}
if (!meetsSubspace(productOperations, left.bounds, right.bounds)) {
return false;
}
if (left.isSubspace && right.isSubspace) {
return true;
}
const [leftBox, rightBox] = splitBox(productOperations, boundingBox);
const [ll, lr] = splitByBox(productOperations, left, leftBox, rightBox);
const [rl, rr] = splitByBox(productOperations, right, leftBox, rightBox);
return (
meetsUntypedProduct(productOperations, ll, rl, leftBox)
|| meetsUntypedProduct(productOperations, lr, rr, rightBox)
);
}
export function meetsProduct<T extends Compatible<U, T>, U extends Compatible<T, U>>(
left: ProductSet<T>,
right: ProductSet<U>,
) {
if (left === empty || right === empty) {
return false;
}
if (left === dense || right === dense) {
return true;
}
const productOperations = { ...left.productOperations, ...right.productOperations };
return meetsUntypedProduct(productOperations, left.root, right.root, top(productOperations));
}
export const complementProduct = <T>(set: ProductSet<T>) => exceptProduct(dense, set);
export const symmetricDiffProduct = <T>(left: ProductSet<T>, right: ProductSet<T>) =>
unionProduct(exceptProduct(left, right), exceptProduct(right, left));
export function getSubspaces<T>(set: ProductSet<T>) {
if (set === empty || set === dense) {
return [];
}
const res: UntypedProduct<T>[] = [];
function loop(root: UntypedSparseProduct<T>) {
if (root.isSubspace) {
res.push(root.bounds);
return;
}
loop(root.left);
loop(root.right);
}
loop(set.root);
return res;
}
export function forEachProduct<T, Props extends (keyof T)[]>(
set: ProductSet<T>,
f: (product: Product<Restrict<T, Props>>) => boolean,
...dims: Props
): boolean {
const newSet = project(set, ...dims);
if (newSet === empty) {
return true;
}
if (newSet === dense) {
return f(unsafe.denseProduct(dims));
}
const { productOperations, root } = newSet;
function loop(root_inner: UntypedSparseProduct<T>): boolean {
if (root_inner.isSubspace) {
return f(unsafe.fromUntypedProduct(productOperations, root_inner.bounds, dims));
}
return loop(root_inner.left) && loop(root_inner.right);
}
return loop(root);
}
export function getSubspaceCount<T>(set: ProductSet<T>) {
if (set === empty || set === dense) {
return 0;
}
return getUntypedSubspaceCount(set.root);
} | the_stack |
import {
AfterViewInit,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ContentChild,
ElementRef,
EventEmitter,
HostBinding,
HostListener,
Input,
NgZone,
OnChanges,
OnDestroy,
OnInit,
Output,
Renderer2,
SimpleChanges,
ViewChild,
} from "@angular/core";
import { autobind } from "@batch-flask/core";
import * as elementResizeDetectorMaker from "element-resize-detector";
import { VirtualScrollRowDirective } from "./virtual-scroll-row.directive";
import { VirtualScrollTailComponent } from "./virtual-scroll-tail";
import "./virtual-scroll.scss";
export interface ChangeEvent {
start?: number;
end?: number;
}
interface VirtualScrollDimensions {
itemCount: number;
viewWidth: number;
viewHeight: number;
childWidth: number;
childHeight: number;
itemsPerRow: number;
itemsPerCol: number;
scrollHeight: number;
tail: number;
}
@Component({
selector: "bl-virtual-scroll",
templateUrl: "virtual-scroll.html",
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class VirtualScrollComponent implements OnInit, AfterViewInit, OnChanges, OnDestroy {
@Input() public items: any[] = [];
@Input() public scrollbarWidth: number;
@Input() public scrollbarHeight: number;
@Input() public childWidth: number;
/**
* Heigth of the rows. This is required to compute which row to show
*/
@Input() public childHeight: number;
@Input() public bufferAmount: number = 0;
@Input() public set parentScroll(element: Element | Window) {
if (this._parentScroll === element) {
return;
}
this._removeParentEventHandlers(this._parentScroll);
this._parentScroll = element;
this._addParentEventHandlers(this._parentScroll);
}
public get parentScroll(): Element | Window {
return this._parentScroll;
}
@Output() public update = new EventEmitter<any[]>();
@Output() public change = new EventEmitter<ChangeEvent>();
@Output() public start = new EventEmitter<ChangeEvent>();
@Output() public end = new EventEmitter<ChangeEvent>();
@Output() public scroll = new EventEmitter<Event>();
public viewportItems: any[] = [];
@ViewChild("content", { read: ElementRef, static: false })
public contentElementRef: ElementRef;
@ContentChild(VirtualScrollTailComponent, { static: false })
public set tail(tail: VirtualScrollTailComponent) {
this._tail = tail;
this.refresh();
}
public get tail() { return this._tail; }
@ContentChild(VirtualScrollRowDirective, { static: false })
public rowDef: VirtualScrollRowDirective<any>;
public topPadding: number;
public previousStart: number;
public previousEnd: number;
public startupLoop: boolean = true;
public currentTween: any;
private _parentScroll: Element | Window;
/** Cache of the last scroll height to prevent setting CSS when not needed. */
private _lastScrollHeight = -1;
private _lastTopPadding = -1;
private _tail: VirtualScrollTailComponent;
private _erd: any;
@ViewChild("padding", { read: ElementRef, static: false })
private _paddingElementRef: ElementRef;
constructor(
private readonly element: ElementRef,
private readonly zone: NgZone,
private readonly renderer: Renderer2,
private changeDetector: ChangeDetectorRef,
) { }
@HostBinding("style.overflow-y")
public get overflow() {
return this.parentScroll ? "hidden" : "auto";
}
@HostListener("scroll")
public onScroll() {
this.refresh();
}
public ngOnInit() {
this.scrollbarWidth = 0;
this.scrollbarHeight = 0;
}
public ngAfterViewInit() {
this._erd = elementResizeDetectorMaker({
strategy: "scroll",
});
this._erd.listenTo(this.element.nativeElement, (element) => {
this.refresh();
});
}
public ngOnDestroy() {
if (this._erd) {
this._erd.uninstall(this.element.nativeElement);
}
this._removeParentEventHandlers(this.parentScroll);
}
public ngOnChanges(changes: SimpleChanges) {
this.previousStart = undefined;
this.previousEnd = undefined;
if (changes.items) {
const { previousValue } = changes.items;
if (previousValue === undefined || previousValue.length === 0) {
this.startupLoop = true;
}
}
this.refresh();
}
@autobind()
public refresh() {
requestAnimationFrame(() => this._calculateItems());
}
public scrollToBottom() {
this.scrollToItemAt((this.items || []).length - 1);
}
public scrollToItem(item: any) {
const index: number = (this.items || []).indexOf(item);
if (index < 0 || index >= (this.items || []).length) { return; }
this.scrollToItemAt(index);
}
public scrollToItemAt(index: number, behavior: ScrollBehavior = "auto") {
const el = this._getScrollElement();
if (index < 0 || index >= (this.items || []).length) { return; }
const d = this._calculateDimensions();
const scrollTop = (Math.floor(index / d.itemsPerRow) * d.childHeight)
- (d.childHeight * Math.min(index, this.bufferAmount));
if (this.currentTween) {
this.currentTween.stop();
}
el.scrollTo({
top: scrollTop,
behavior,
});
}
/**
* This will make sure the item is visible.
* Difference with scroll to item is it will try to scroll the least possible.
*/
public ensureItemVisible(item: any, behavior: ScrollBehavior = "auto") {
const index: number = (this.items || []).indexOf(item);
if (index < 0 || index >= (this.items || []).length) { return; }
this.ensureItemAtVisible(index, behavior);
}
/**
* This will make sure the item is visible.
* Difference with scroll to item is it will try to scroll the least possible.
*/
public ensureItemAtVisible(index: number, behavior: ScrollBehavior = "auto") {
const el = this._getScrollElement();
if (index < 0 || index >= (this.items || []).length) { return; }
const d = this._calculateDimensions();
const top = (Math.floor(index / d.itemsPerRow) * d.childHeight);
const buffer = (d.childHeight * Math.min(index, this.bufferAmount));
const maxScrollTop = top - buffer - d.childHeight;
const minScrollTop = top - d.viewHeight + d.childHeight + buffer;
if (this.currentTween) {
this.currentTween.stop();
}
if (el.scrollTop > maxScrollTop) {
el.scrollTo({
top: maxScrollTop,
behavior,
});
} else if (el.scrollTop < minScrollTop) {
el.scrollTo({
top: minScrollTop,
behavior,
});
}
}
private _getScrollElement(): Element {
return this.parentScroll instanceof Window ? document.body : this.parentScroll || this.element.nativeElement;
}
private _addParentEventHandlers(parentScroll: Element | Window) {
if (!parentScroll) { return; }
parentScroll.addEventListener("scroll", this.refresh);
if (parentScroll instanceof Window) {
parentScroll.addEventListener("resize", this.refresh);
}
}
private _removeParentEventHandlers(parentScroll: Element | Window) {
if (!parentScroll) { return; }
parentScroll.removeEventListener("scroll", this.refresh);
if (parentScroll instanceof Window) {
parentScroll.removeEventListener("resize", this.refresh);
}
}
private _getElementsOffset(): number {
let offsetTop = 0;
if (this.parentScroll) {
offsetTop += this.element.nativeElement.offsetTop;
}
return offsetTop;
}
private _calculateDimensions(): VirtualScrollDimensions {
const el = this._getScrollElement();
const items = this.items || [];
const itemCount = items.length;
const viewWidth = el.clientWidth - this.scrollbarWidth;
const viewHeight = el.clientHeight - this.scrollbarHeight;
const containerDimensions = this.element.nativeElement.getBoundingClientRect();
const childWidth = this.childWidth || containerDimensions.width;
const childHeight = this.childHeight || containerDimensions.height;
const itemsPerRow = Math.max(1, Math.floor(viewWidth / childWidth));
const itemsPerCol = Math.max(1, Math.floor(viewHeight / childHeight));
const tail = this.tail && this.tail.height || 0;
const scrollHeight = childHeight * Math.ceil(itemCount / itemsPerRow) + tail;
if (scrollHeight !== this._lastScrollHeight) {
this.renderer.setStyle(this._paddingElementRef.nativeElement, "height", `${scrollHeight}px`);
this._lastScrollHeight = scrollHeight;
}
return {
itemCount: itemCount,
viewWidth: viewWidth,
viewHeight: viewHeight,
childWidth: childWidth,
childHeight: childHeight,
itemsPerRow: itemsPerRow,
itemsPerCol: itemsPerCol,
tail,
scrollHeight,
};
}
private _calculateItems(forceViewportUpdate: boolean = false) {
const d = this._calculateDimensions();
const items = this.items || [];
let { start, end } = this._computeRange(d);
this._applyTopPadding(items, start, d);
start = !isNaN(start) ? start : -1;
end = !isNaN(end) ? end : -1;
start -= this.bufferAmount;
start = Math.max(0, start);
end += this.bufferAmount;
end = Math.min(items.length, end);
this._detectViewportChanges(items, start, end, forceViewportUpdate);
}
private _computeRange(d: VirtualScrollDimensions) {
const scrollTop = this._computeScrollTop(d);
const indexByScrollTop = scrollTop / d.scrollHeight * d.itemCount / d.itemsPerRow;
const end = Math.min(d.itemCount, d.itemsPerRow * (Math.ceil(indexByScrollTop) + d.itemsPerCol + 1));
let maxStartEnd = end;
const modEnd = end % d.itemsPerRow;
if (modEnd) {
maxStartEnd = end + d.itemsPerRow - modEnd;
}
const maxStart = Math.max(0, maxStartEnd - d.itemsPerCol * d.itemsPerRow - d.itemsPerRow);
const start = Math.min(maxStart, Math.floor(indexByScrollTop) * d.itemsPerRow);
return { start, end };
}
private _computeScrollTop(d): number {
const el = this._getScrollElement();
const offsetTop = this._getElementsOffset();
let elScrollTop = this.parentScroll instanceof Window
? (window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0)
: el.scrollTop;
if (elScrollTop > d.scrollHeight) {
elScrollTop = d.scrollHeight + offsetTop;
}
return Math.max(0, elScrollTop - offsetTop);
}
private _applyTopPadding(items, start, d: VirtualScrollDimensions) {
let topPadding = 0;
if (items) {
topPadding = d.childHeight * (Math.ceil(start / d.itemsPerRow) - Math.min(start, this.bufferAmount));
}
if (topPadding !== this._lastTopPadding) {
this.renderer.setStyle(this.contentElementRef.nativeElement, "transform", `translateY(${topPadding}px)`);
this._lastTopPadding = topPadding;
}
}
private _detectViewportChanges(items: any, start: number, end: number, forceViewportUpdate: boolean) {
if (start !== this.previousStart || end !== this.previousEnd || forceViewportUpdate === true) {
this.zone.run(() => {
this._applyViewportChanges(items, start, end, forceViewportUpdate);
});
} else if (this.startupLoop === true) {
this.startupLoop = false;
this.refresh();
}
}
private _applyViewportChanges(items: any, start: number, end: number, forceViewportUpdate: boolean) {
// To prevent from accidentally selecting the entire array with a negative 1 (-1) in the end position.
const _end = end >= 0 ? end : 0;
// update the scroll list
this.viewportItems = items.slice(start, _end);
this.update.emit(this.viewportItems);
// emit 'start' event
if (start !== this.previousStart && this.startupLoop === false) {
this.start.emit({ start, end });
}
// emit 'end' event
if (end !== this.previousEnd && this.startupLoop === false) {
this.end.emit({ start, end });
}
this.previousStart = start;
this.previousEnd = end;
if (this.startupLoop === true) {
this.refresh();
} else {
this.change.emit({ start, end });
}
this.changeDetector.markForCheck();
}
} | the_stack |
import { existsSync, readFileSync } from 'fs-extra';
import { join, resolve } from 'path';
import chalk from 'chalk';
import { Sequelize, Options, Dialect, QueryTypes } from 'sequelize';
import { IDatabaseConfig, ISQLDatabase, ISQLiteDatabase } from '@materia/interfaces';
import { App, AppMode } from './app';
import { ConfigType } from './config';
import { DatabaseInterface } from './database/interface';
import { MateriaError } from './error';
const dialect = {
postgres: 'PostgreSQL',
mysql: 'MySQL',
sqlite: 'SQLite'
};
const DEFAULT_DATABASE_MYSQL = 'mysql';
const DEFAULT_DATABASE_POSTGRES = 'postgres';
const defaultDatabase = {
mysql: DEFAULT_DATABASE_MYSQL,
postgres: DEFAULT_DATABASE_POSTGRES
};
/**
* @class Database
* @classdesc
* Represent the connection to database
*/
export class Database {
interface: DatabaseInterface;
disabled: boolean;
locked = false;
host: string;
port: number;
username: string;
password: string;
database: string;
storage: string;
type: Dialect;
started: boolean;
opts: Options;
sequelize: Sequelize;
constructor(private app: App) {
this.interface = new DatabaseInterface(this);
}
static isSQL(settings: IDatabaseConfig): settings is ISQLDatabase {
return settings.type !== 'sqlite';
}
static isSQLite(settings: IDatabaseConfig): settings is ISQLiteDatabase {
return settings.type === 'sqlite';
}
/**
Load the database configuration
@param {object} - *optional* The settings of the database
@returns {object}
*/
load(settings?: IDatabaseConfig): boolean {
this.disabled = false;
if ( ! settings && this.app.path) {
this.app.config.reloadConfig();
if (this.app.live) {
settings = this.app.config.get<IDatabaseConfig>(this.app.mode, ConfigType.DATABASE, {live: true});
}
settings = settings || this.app.config.get<IDatabaseConfig>(this.app.mode, ConfigType.DATABASE);
}
if ( ! settings || ! settings.type ) {
this.disabled = true;
this.app.logger.log(` └── Database: ${chalk.yellow.bold('No database configured!')}`);
return false;
}
if (Database.isSQL(settings)) {
this.host = this.app.options['database-host'] || settings.host || 'localhost';
this.port = Number(this.app.options['database-port'] || settings.port);
this.username = this.app.options['database-username'] || settings.username;
this.password = this.app.options['database-password'] || settings.password;
this.database = this.app.options['database-db'] || settings.database;
} else if (Database.isSQLite(settings)) {
this.storage = this.app.options['storage'] || settings.storage;
}
this.type = (settings.type as Dialect);
this.started = false;
let logging: any;
if (this.app.options.logSql == true) {
logging = (...args) => { this.app.logger.log.apply(this.app.logger, args); };
} else if (this.app.options.logSql !== undefined) {
logging = this.app.options.logSql;
} else {
logging = false;
}
this.opts = {
dialect: this.type,
host: this.host,
port: this.port,
logging: logging,
dialectOptions: {}
};
if (this.type !== 'sqlite') {
if ((settings as ISQLDatabase).ssl) {
this.opts.dialectOptions['ssl'] = true;
}
}
if (Database.isSQLite(settings)) {
this.opts.storage = resolve(this.app.path, this.storage || 'database.sqlite');
}
if (this.app.mode == AppMode.PRODUCTION && process.env.GCLOUD_PROJECT && this.type == 'mysql') {
try {
const gcloudJsonPath = join(this.app.path, '.materia', 'gcloud.json');
if (existsSync(gcloudJsonPath)) {
const gcloudSettings = JSON.parse(readFileSync(gcloudJsonPath, 'utf-8'));
this.opts.dialectOptions = { socketPath: `/cloudsql/${gcloudSettings.project}:${gcloudSettings.region}:${gcloudSettings.instance}` };
delete this.opts.host;
delete this.opts.port;
} else {
throw new MateriaError('gcloud.json not found');
}
} catch (e) {
this.app.logger.log(chalk.yellow(` └── Warning: Impossible to load GCloud database settings - ${chalk.bold(e)}`));
}
}
this.app.logger.log(` └─┬ Database: ${chalk.green.bold('OK')}`);
this.app.logger.log(` │ └── Dialect: ${chalk.bold(dialect[this.type])}`);
if (this.type == 'sqlite') {
this.app.logger.log(` │ └── File: ${chalk.bold(this.storage || 'database.sqlite')}`);
} else {
this.app.logger.log(` │ └── Host: ${chalk.bold(this.host)}`);
this.app.logger.log(` │ └── Port: ${chalk.bold(this.port.toString())}`);
}
return true;
}
/**
Try to connect with a custom configuration
@param {object} - The configuration object
@returns {Promise}
*/
static tryDatabase(settings: IDatabaseConfig, app?: App): Promise<void> {
// TODO: check settings.storage to be a real path
if (this.isSQLite(settings) && settings.storage) {
return Promise.resolve();
}
const optsDialect = {
dialect: settings.type,
logging: false
};
let opts: Options;
if (Database.isSQL(settings)) {
opts = Object.assign({}, optsDialect, {
host: settings.host,
port: settings.port
});
} else if (Database.isSQLite(settings) && app) {
opts.storage = resolve(app.path, settings.storage || 'database.sqlite');
}
let tmp;
return new Promise((accept, reject) => {
try {
if (Database.isSQL(settings)) {
tmp = new Sequelize(settings.database, settings.username, settings.password, opts);
} else if (Database.isSQLite(settings)) {
tmp = new Sequelize(null, null, null, opts);
}
tmp.authenticate().then(() => {
tmp.close();
accept();
}).catch((e) => { reject(e); });
} catch (e) {
return reject(e);
}
});
}
/**
Try to connect database server default database with username password
MySQL or PostgreSQL only
@param {object} - The configuration object
@returns {Promise}
*/
static tryServer(settings: IDatabaseConfig, app?: App) {
if (!Database.isSQL(settings)) {
return Promise.reject(new Error("You can't try to connect to SQLite with username/password"));
}
const opts: Options = {
dialect: (settings.type as Dialect),
host: settings.host,
port: settings.port,
logging: false
};
return new Promise((accept, reject) => {
try {
const tmpConnect = new Sequelize(defaultDatabase[settings.type], settings.username, settings.password, opts);
tmpConnect.authenticate().then(() =>
tmpConnect.close()
).then(accept).catch(reject);
} catch (e) {
reject(e);
}
});
}
/**
List databases in mysql or postgres instances
MySQL and PostgreSQL only
@param settings - The configuration object
@returns {Promise}
*/
static listDatabases(settings: IDatabaseConfig): Promise<any> {
if (!Database.isSQL(settings)) {
return Promise.reject(new Error(`You can't list database on a SQLite database`));
}
const opts: Options = {
dialect: (settings.type as Dialect),
host: settings.host,
port: settings.port,
logging: false
};
return new Promise((accept, reject) => {
try {
const tmp = new Sequelize(defaultDatabase[settings.type], settings.username, settings.password, opts);
let query: string;
let field: string;
if (settings.type == 'mysql') {
query = `SHOW DATABASES`;
field = 'Database';
} else if (settings.type == 'postgres') {
query = `SELECT datname FROM pg_database`;
field = 'datname';
}
tmp.query(query).spread((results: any, metadata) => {
const formatedResult = [];
for (const i in results) {
if (results[i]) {
const result = results[i];
formatedResult.push(result[field]);
}
}
return accept(formatedResult);
});
} catch (e) {
return reject(e);
}
});
}
/**
Create new database in mysql or postgresql instances
@param settings - The configuration object
@param name - Name for the new database
*/
static createDatabase(settings, name) {
const opts: Options = {
dialect: settings.type,
host: settings.host,
port: settings.port,
logging: false
};
let tmp;
return new Promise((accept, reject) => {
const dbName = defaultDatabase[settings.type] === DEFAULT_DATABASE_MYSQL ? '`' + name + '`' : `"${name}"`;
try {
tmp = new Sequelize(defaultDatabase[settings.type], settings.username, settings.password, opts);
} catch (e) {
return reject(e);
}
return tmp.query(`CREATE DATABASE ${dbName}`).spread((results, metadata) => {
return accept();
}).catch(err => reject(err.message));
});
}
tryDatabase(settings) {
return Database.tryDatabase(settings, this.app);
}
tryServer(settings) {
return Database.tryServer(settings, this.app);
}
listDatabases(settings) {
return Database.listDatabases(settings);
}
createDatabase(settings, name) {
return Database.createDatabase(settings, name);
}
runSql(query: string): Promise<any> {
return this.sequelize.query(
query,
{
type: QueryTypes[query.split(' ')[0]] ?? 'sql'
}
);
}
/**
Connect to the database
@returns {Promise}
*/
start(): Promise<any> {
if (this.sequelize) {
this.stop();
}
if ( this.disabled ) {
return Promise.resolve();
}
if ( ! this.interface.hasDialect(this.type)) {
return Promise.reject(new MateriaError('The database\'s dialect is not supported'));
}
this.app.emit('db:start');
try {
this.sequelize = new Sequelize(this.database, this.username, this.password, this.opts);
} catch (e) {
this.disabled = true;
return Promise.reject(e);
}
this.interface.setDialect(this.type);
return this.interface.authenticate().then(() => {
this.app.logger.log(`│ └── Connection: ${chalk.green.bold('Authenticated')}`);
this.started = true;
}).catch((e) => {
this.app.logger.error(`│ └── Connection: ${chalk.red.bold('Failed')}`);
this.app.logger.error(chalk.red(' (Warning) Impossible to connect the database: ') + chalk.red.bold(e && e.message));
this.app.logger.error(chalk.red(' The database has been disabled'));
this.disabled = true;
return Promise.resolve(e);
});
}
/**
Stop the database connection
*/
stop() {
this.started = false;
if (this.sequelize) {
this.sequelize.close();
this.sequelize = null;
}
return Promise.resolve();
}
/**
Synchronize the database with the state of the application
@returns {Promise}
*/
sync() {
return this.app.entities.sync().then(() => {
return this.sequelize.sync();
});
}
} | the_stack |
namespace ts.pxtc {
const vmSpecOpcodes: pxt.Map<string> = {
"pxtrt::mapSetGeneric": "mapset",
"pxtrt::mapGetGeneric": "mapget",
}
const vmCallMap: pxt.Map<string> = {
}
function shimToVM(shimName: string) {
return shimName
}
function qs(s: string) {
return JSON.stringify(s)
}
function vtableToVM(info: ClassInfo, opts: CompileOptions, bin: Binary) {
/*
uint16_t numbytes;
ValType objectType;
uint8_t magic;
uint32_t padding;
PVoid *ifaceTable;
BuiltInType classNo;
uint16_t reserved;
uint32_t ifaceHashMult;
uint32_t padding;
PVoid methods[2 or 4];
*/
const ifaceInfo = computeHashMultiplier(info.itable.map(e => e.idx))
//if (info.itable.length == 0)
// ifaceInfo.mult = 0
const mapping = U.toArray(ifaceInfo.mapping)
while (mapping.length & 3)
mapping.push(0)
let s = `
${vtName(info)}_start:
.short ${info.allfields.length * 8 + 8} ; size in bytes
.byte ${pxt.ValTypeObject}, ${pxt.VTABLE_MAGIC} ; magic
.short ${mapping.length} ; entries in iface hashmap
.short ${info.lastSubtypeNo || info.classNo} ; last sub class-id
.short ${info.classNo} ; class-id
.short 0 ; reserved
.word ${ifaceInfo.mult} ; hash-mult
`;
if (embedVTs()) {
s += `
.word pxt::RefRecord_destroy
.word pxt::RefRecord_print
.word pxt::RefRecord_scan
.word pxt::RefRecord_gcsize
.word 0,0,0,0 ; keep in sync with VM_NUM_CPP_METHODS
`
} else {
s += `
.word 0,0, 0,0, 0,0, 0,0 ; space for 4 (VM_NUM_CPP_METHODS) native methods
`
}
s += `
.balign 4
${info.id}_IfaceVT:
`
const descSize = 1
const zeroOffset = mapping.length >> 2
let descs = ""
let offset = zeroOffset
let offsets: pxt.Map<number> = {}
for (let e of info.itable) {
offsets[e.idx + ""] = offset
const desc = !e.proc ? 0 : e.proc.isGetter() ? 1 : 2
descs += ` .short ${e.idx}, ${desc} ; ${e.name}\n`
descs += ` .word ${e.proc ? e.proc.vtLabel() + "@fn" : e.info}\n`
offset += descSize
if (e.setProc) {
descs += ` .short ${e.idx}, 2 ; set ${e.name}\n`
descs += ` .word ${e.setProc.vtLabel()}@fn\n`
offset += descSize
}
}
descs += " .word 0, 0, 0, 0 ; the end\n"
offset += descSize
for (let i = 0; i < mapping.length; ++i) {
bin.itEntries++
if (mapping[i])
bin.itFullEntries++
}
s += " .short " + U.toArray(mapping).map((e, i) => offsets[e + ""] || zeroOffset).join(", ") + "\n"
s += descs
s += "\n"
return s
}
// keep in sync with vm.h
enum SectionType {
Invalid = 0x00,
// singular sections
InfoHeader = 0x01, // VMImageHeader
OpCodeMap = 0x02, // \0-terminated names of opcodes and APIs (shims)
NumberLiterals = 0x03, // array of boxed doubles and ints
ConfigData = 0x04, // sorted array of pairs of int32s; zero-terminated
IfaceMemberNames = 0x05, // array of 32 bit offsets, that point to string literals
NumberBoxes = 0x06, // numbers from NumberLiteral that need to be boxed on 32 bit hosts
// repetitive sections
Function = 0x20,
Literal = 0x21, // aux field contains literal type (string, hex, image, ...)
VTable = 0x22,
}
// this also handles dates after 2106-02-07 (larger than 2^32 seconds since the beginning of time)
function encodeTime(d: Date) {
const t = d.getTime() / 1000
return `${t >>> 0}, ${(t / 0x100000000) | 0}`
}
let additionalClassInfos: pxt.Map<ClassInfo> = {}
function vtName(info: ClassInfo) {
if (!info.classNo)
additionalClassInfos[info.id] = info
return info.id + "_VT"
}
function embedVTs() {
return target.useESP
}
function vtRef(vt: string) {
if (embedVTs())
return `0xffffffff, ${vt}`
else
return `0xffffffff, 0xffffffff ; -> ${vt}`
}
function encodeSourceMap(srcmap: pxt.Map<number[]>) {
// magic: 0x4d435253 0x2d4e1588 0x719986aa ('SRCM' ... )
const res: number[] = [0x53, 0x52, 0x43, 0x4d, 0x88, 0x15, 0x4e, 0x2d, 0xaa, 0x86, 0x99, 0x71, 0x00, 0x00, 0x00, 0x00]
for (const fn of Object.keys(srcmap)) {
for (const c of U.stringToUint8Array(fn))
res.push(c)
res.push(0)
const arr = srcmap[fn]
let prevLn = 0
let prevOff = 0
for (let i = 0; i < arr.length; i += 3) {
encodeNumber(arr[i] - prevLn)
encodeNumber((arr[i + 1] - prevOff) >> 1)
encodeNumber(arr[i + 2] >> 1)
prevLn = arr[i]
prevOff = arr[i + 1]
}
res.push(0xff) // end-marker
}
res.push(0)
if (res.length & 1) res.push(0)
const res2: number[] = []
for (let i = 0; i < res.length; i += 2)
res2.push(res[i] | (res[i + 1] << 8))
return res2
function encodeNumber(k: number) {
if (0 <= k && k < 0xf0)
res.push(k)
else {
let mark = 0xf0
if (k < 0) {
k = -k
mark |= 0x08
}
const idx = res.length
res.push(null) // placeholder
let len = 0
while (k != 0) {
res.push(k & 0xff)
k >>>= 8
len++
}
res[idx] = mark | len
}
}
}
/* eslint-disable no-trailing-spaces */
export function vmEmit(bin: Binary, opts: CompileOptions) {
let vmsource = `; VM start
_img_start:
${hexfile.hexPrelude()}
`
additionalClassInfos = {}
const ctx: EmitCtx = {
dblText: [],
dblBoxText: [],
dbls: {},
opcodeMap: {},
opcodes: vm.opcodes.map(o => "pxt::op_" + o.replace(/ .*/, "")),
}
ctx.opcodes.unshift(null)
while (ctx.opcodes.length < 128)
ctx.opcodes.push(null)
let address = 0
function section(name: string, tp: SectionType, body: () => string, aliases?: string[], aux = 0) {
vmsource += `
; --- ${name}
.section code
.set ${name} = ${address}
`
if (aliases) {
for (let alias of aliases)
vmsource += ` .set ${alias} = ${address}\n`
}
vmsource += `
_start_${name}:
.byte ${tp}, 0x00
.short ${aux}
.word _end_${name}-_start_${name}\n`
vmsource += body()
vmsource += `\n.balign 8\n_end_${name}:\n`
address++
}
const now = new Date(0) // new Date()
let encodedName = U.toUTF8(opts.name, true)
if (encodedName.length > 100) encodedName = encodedName.slice(0, 100)
let encodedLength = encodedName.length + 1
if (encodedLength & 1) encodedLength++
const paddingSize = 128 - encodedLength
section("_info", SectionType.InfoHeader, () => `
; magic - \\0 added by assembler
.string "\\nPXT64\\n"
.hex 5471fe2b5e213768 ; magic
.hex ${hexfile.hexTemplateHash()} ; hex template hash
.hex 0000000000000000 ; @SRCHASH@
.word ${bin.globalsWords} ; num. globals
.word ${bin.nonPtrGlobals} ; non-ptr globals
.word 0, 0 ; last usage time
.word ${encodeTime(now)} ; installation time
.word ${encodeTime(now)} ; publication time - TODO
.word _img_end-_img_start ; total image size
.space 60 ; reserved
.string ${JSON.stringify(encodedName)}
.space ${paddingSize} ; pad to 128 bytes
`
)
bin.procs.forEach(p => {
section(p.label(), SectionType.Function, () => irToVM(ctx, bin, p),
[p.label() + "_Lit"])
})
vmsource += "_code_end:\n\n"
vmsource += "_helpers_end:\n\n"
bin.usedClassInfos.forEach(info => {
section(vtName(info), SectionType.VTable, () => vtableToVM(info, opts, bin))
})
U.values(additionalClassInfos).forEach(info => {
info.itable = []
info.classNo = 0xfff0
section(vtName(info), SectionType.VTable, () => vtableToVM(info, opts, bin))
})
additionalClassInfos = {}
let idx = 0
section("ifaceMemberNames", SectionType.IfaceMemberNames, () =>
` .word ${bin.ifaceMembers.length} ; num. entries\n` + bin.ifaceMembers.map(d =>
` .word ${bin.emitString(d)} ; ${idx++} .${d}`
).join("\n"))
vmsource += "_vtables_end:\n\n"
U.iterMap(bin.hexlits, (k, v) => {
section(v, SectionType.Literal, () =>
`.word ${vtRef("pxt::buffer_vt")}\n` +
hexLiteralAsm(k), [], pxt.BuiltInType.BoxedBuffer)
})
// ifaceMembers are already sorted alphabetically
// here we make sure that the pointers to them are also sorted alphabetically
// by emitting them in order and before everything else
const keys = U.unique(bin.ifaceMembers.concat(Object.keys(bin.strings)), s => s)
keys.forEach(k => {
const info = utf8AsmStringLiteral(k)
let tp = pxt.BuiltInType.BoxedString
if (info.vt == "pxt::string_inline_ascii_vt")
tp = pxt.BuiltInType.BoxedString_ASCII
else if (info.vt == "pxt::string_skiplist16_packed_vt")
tp = pxt.BuiltInType.BoxedString_SkipList
else if (info.vt == "pxt::string_inline_utf8_vt")
tp = pxt.BuiltInType.BoxedString
else oops("invalid vt")
const text =
`.word ${vtRef(info.vt)}\n` +
info.asm
section(bin.strings[k], SectionType.Literal, () => text, [], tp)
})
section("numberBoxes", SectionType.NumberBoxes, () => ctx.dblBoxText.join("\n")
+ "\n.word 0, 0, 0 ; dummy entry to make sure not empty")
section("numberLiterals", SectionType.NumberLiterals, () => ctx.dblText.join("\n")
+ "\n.word 0, 0 ; dummy entry to make sure not empty")
const cfg = bin.res.configData || []
section("configData", SectionType.ConfigData, () => cfg.map(d =>
` .word ${d.key}, ${d.value} ; ${d.name}=${d.value}`).join("\n")
+ "\n .word 0, 0")
let s = ctx.opcodes.map(s => s == null ? "" : s).join("\x00") + "\x00"
let opcm = ""
while (s) {
let pref = s.slice(0, 64)
s = s.slice(64)
if (pref.length & 1)
pref += "\x00"
opcm += ".hex " + U.toHex(U.stringToUint8Array(pref)) + "\n"
}
section("opcodeMap", SectionType.OpCodeMap, () => opcm)
vmsource += "_literals_end:\n"
vmsource += "_img_end:\n"
vmsource += "\n; The end.\n"
bin.writeFile(BINARY_ASM, vmsource)
let res = assemble(opts.target, bin, vmsource)
const srcmap = res.thumbFile.getSourceMap()
const encodedSrcMap = encodeSourceMap(srcmap)
if (res.src)
bin.writeFile(pxtc.BINARY_ASM, `; srcmap size: ${encodedSrcMap.length << 1} bytes\n` + res.src)
{
let binstring = ""
for (let v of res.buf)
binstring += String.fromCharCode(v & 0xff, v >> 8)
const hash = U.sha256(binstring)
for (let i = 0; i < 4; ++i) {
res.buf[16 + i] = parseInt(hash.slice(i * 4, i * 4 + 4), 16)
}
srcmap["__meta"] = {
name: opts.name,
programHash: res.buf[16] | (res.buf[16 + 1] << 16),
// TODO would be nice to include version number of editor...
} as any
}
bin.writeFile(pxtc.BINARY_SRCMAP, JSON.stringify(srcmap))
if (pxt.options.debug) {
let pc = res.thumbFile.peepCounts
let keys = Object.keys(pc)
keys.sort((a, b) => pc[b] - pc[a])
for (let k of keys.slice(0, 50)) {
console.log(`${k} ${pc[k]}`)
}
}
if (res.buf) {
let binstring = ""
const buf = res.buf
while (buf.length & 0xf) buf.push(0)
U.pushRange(buf, encodedSrcMap)
for (let v of buf)
binstring += String.fromCharCode(v & 0xff, v >> 8)
binstring = ts.pxtc.encodeBase64(binstring)
if (embedVTs()) {
bin.writeFile(pxtc.BINARY_PXT64, binstring)
const patched = hexfile.patchHex(bin, buf, false, !!target.useUF2)[0]
bin.writeFile(pxt.outputName(target), ts.pxtc.encodeBase64(patched))
} else {
bin.writeFile(pxt.outputName(target), binstring)
}
}
}
/* eslint-enable */
interface EmitCtx {
dblText: string[]
dblBoxText: string[]
dbls: pxt.Map<number>
opcodeMap: pxt.Map<number>;
opcodes: string[];
}
function irToVM(ctx: EmitCtx, bin: Binary, proc: ir.Procedure): string {
let resText = ""
const writeRaw = (s: string) => { resText += s + "\n"; }
const write = (s: string) => { resText += " " + s + "\n"; }
const EK = ir.EK;
let alltmps: ir.Expr[] = []
let currTmps: ir.Expr[] = []
let final = false
let numLoc = 0
let argDepth = 0
const immMax = (1 << 23) - 1
if (pxt.options.debug)
console.log("EMIT", proc.toString())
emitAll()
resText = ""
for (let t of alltmps) t.reset()
final = true
U.assert(argDepth == 0)
emitAll()
return resText
function emitAll() {
writeRaw(`;\n; ${proc.getFullName()}\n;`)
write(".section code")
if (bin.procs[0] == proc) {
writeRaw(`; main`)
}
write(`.word ${vtRef("pxt::RefAction_vtable")}`)
write(`.short 0, ${proc.args.length} ; #args`)
write(`.short ${proc.captured.length}, 0 ; #cap`)
write(`.word .fnstart-_img_start, 0 ; func+possible padding`)
numLoc = proc.locals.length + currTmps.length
write(`.fnstart:`)
write(`pushmany ${numLoc} ; incl. ${currTmps.length} tmps`)
for (let s of proc.body) {
switch (s.stmtKind) {
case ir.SK.Expr:
emitExpr(s.expr)
break;
case ir.SK.StackEmpty:
clearStack()
for (let e of currTmps) {
if (e) {
oops(`uses: ${e.currUses}/${e.totalUses} ${e.toString()}`);
}
}
break;
case ir.SK.Jmp:
emitJmp(s);
break;
case ir.SK.Label:
writeRaw(`${s.lblName}:`)
break;
case ir.SK.Comment:
writeRaw(`; ${s.expr.data}`)
break
case ir.SK.Breakpoint:
break;
default: oops();
}
}
write(`ret ${proc.args.length}, ${numLoc}`)
}
function emitJmp(jmp: ir.Stmt) {
let trg = jmp.lbl.lblName
if (jmp.jmpMode == ir.JmpMode.Always) {
if (jmp.expr)
emitExpr(jmp.expr)
write(`jmp ${trg}`)
} else {
emitExpr(jmp.expr)
if (jmp.jmpMode == ir.JmpMode.IfNotZero) {
write(`jmpnz ${trg}`)
} else if (jmp.jmpMode == ir.JmpMode.IfZero) {
write(`jmpz ${trg}`)
} else {
oops()
}
}
}
function cellref(cell: ir.Cell) {
if (cell.isGlobal()) {
U.assert((cell.index & 3) == 0)
return (`glb ` + (cell.index >> 2) + ` ; ${cell.getName()}`)
} else if (cell.iscap)
return (`cap ` + cell.index + ` ; ${cell.getName()}`)
else if (cell.isarg) {
let idx = proc.args.length - cell.index - 1
assert(idx >= 0, "arg#" + idx)
return (`loc ${argDepth + numLoc + 2 + idx} ; ${cell.getName()}`)
}
else {
let idx = cell.index + currTmps.length
//console.log(proc.locals.length, currTmps.length, cell.index)
assert(!final || idx < numLoc, "cell#" + idx)
assert(idx >= 0, "cell#" + idx)
return (`loc ${argDepth + idx}`)
}
}
function callRT(name: string) {
const inf = hexfile.lookupFunc(name)
if (!inf) U.oops("missing function: " + name)
let id = ctx.opcodeMap[inf.name]
if (id == null) {
id = ctx.opcodes.length
ctx.opcodes.push(inf.name)
ctx.opcodeMap[inf.name] = id
inf.value = id
}
write(`callrt ${name}`)
}
function emitInstanceOf(info: ClassInfo, tp: string) {
if (tp == "bool") {
write(`checkinst ${vtName(info)}`)
} else if (tp == "validate") {
U.oops()
} else {
U.oops()
}
}
function emitExprInto(e: ir.Expr) {
switch (e.exprKind) {
case EK.NumberLiteral:
const tagged = taggedSpecial(e.data)
if (tagged != null)
write(`ldspecial ${tagged} ; ${e.data}`)
else {
let n = e.data as number
let n0 = 0, n1 = 0
const needsBox = ((n << 1) >> 1) != n // boxing needed on PXT32?
if ((n | 0) == n) {
if (Math.abs(n) <= immMax) {
if (n < 0)
write(`ldintneg ${-n}`)
else
write(`ldint ${n}`)
return
} else {
n0 = ((n << 1) | 1) >>> 0
n1 = n < 0 ? 1 : 0
}
} else {
let a = new Float64Array(1)
a[0] = n
let u = new Uint32Array(a.buffer)
u[1] += 0x10000
n0 = u[0]
n1 = u[1]
}
let key = n0 + "," + n1
let id = U.lookup(ctx.dbls, key)
if (id == null) {
id = ctx.dblText.length
ctx.dblText.push(`.word ${n0}, ${n1} ; ${id}: ${e.data}`)
if (needsBox) {
const vt = "pxt::number_vt"
ctx.dblBoxText.push(`.word ${embedVTs() ? vt : `0xffffffff ; ${vt}`}\n`)
let a = new Float64Array(1)
a[0] = n
let u = new Uint32Array(a.buffer)
ctx.dblBoxText.push(`.word ${u[0]}, ${u[1]} ; ${n}\n`)
}
ctx.dbls[key] = id
}
write(`ldnumber ${id} ; ${e.data}`)
}
return
case EK.PointerLiteral:
write(`ldlit ${e.data}`)
return
case EK.SharedRef:
let arg = e.args[0]
if (!arg.currUses || arg.currUses >= arg.totalUses) {
console.log(arg.sharingInfo())
U.assert(false)
}
arg.currUses++
let idx = currTmps.indexOf(arg)
if (idx < 0) {
console.log(currTmps, arg)
assert(false)
}
write(`ldloc ${idx + argDepth}` + (arg.currUses == arg.totalUses ? " ; LAST" : ""))
clearStack()
return
case EK.CellRef:
write("ld" + cellref(e.data))
return
case EK.InstanceOf:
emitExpr(e.args[0])
emitInstanceOf(e.data, e.jsInfo as string)
break
default: throw oops("kind: " + e.exprKind);
}
}
// result in R0
function emitExpr(e: ir.Expr): void {
//console.log(`EMITEXPR ${e.sharingInfo()} E: ${e.toString()}`)
switch (e.exprKind) {
case EK.JmpValue:
write("; jmp value (already in r0)")
break;
case EK.Nop:
write("; nop")
break
case EK.FieldAccess:
let info = e.data as FieldAccessInfo
emitExpr(e.args[0])
write(`ldfld ${info.idx}, ${vtName(info.classInfo)}`)
break
case EK.Store:
return emitStore(e.args[0], e.args[1])
case EK.RuntimeCall:
return emitRtCall(e);
case EK.ProcCall:
return emitProcCall(e)
case EK.SharedDef:
return emitSharedDef(e)
case EK.Sequence:
return e.args.forEach(emitExpr)
default:
return emitExprInto(e)
}
}
function emitSharedDef(e: ir.Expr) {
let arg = e.args[0]
U.assert(arg.totalUses >= 1)
U.assert(arg.currUses === 0)
arg.currUses = 1
alltmps.push(arg)
if (arg.totalUses == 1)
return emitExpr(arg)
else {
emitExpr(arg)
let idx = -1
for (let i = 0; i < currTmps.length; ++i)
if (currTmps[i] == null) {
idx = i
break
}
if (idx < 0) {
if (final) {
console.log(arg, currTmps)
assert(false, "missed tmp")
}
idx = currTmps.length
currTmps.push(arg)
} else {
currTmps[idx] = arg
}
write(`stloc ${idx + argDepth}`)
}
}
function push() {
write(`push`)
argDepth++
}
function emitRtCall(topExpr: ir.Expr) {
let name: string = topExpr.data
if (name == "pxt::beginTry") {
write(`try ${topExpr.args[0].data}`)
return
}
name = U.lookup(vmCallMap, name) || name
clearStack()
let spec = U.lookup(vmSpecOpcodes, name)
let args = topExpr.args
let numPush = 0
if (name == "pxt::mkClassInstance") {
write(`newobj ${args[0].data}`)
return
}
for (let i = 0; i < args.length; ++i) {
emitExpr(args[i])
if (i < args.length - 1) {
push()
numPush++
}
}
//let inf = hex.lookupFunc(name)
if (name == "langsupp::ignore") {
if (numPush)
write(`popmany ${numPush} ; ignore`)
} else if (spec) {
write(spec)
} else {
callRT(name)
}
argDepth -= numPush
}
function clearStack() {
for (let i = 0; i < currTmps.length; ++i) {
let e = currTmps[i]
if (e && e.currUses == e.totalUses) {
if (!final)
alltmps.push(e)
currTmps[i] = null
}
}
}
function emitProcCall(topExpr: ir.Expr) {
let calledProcId = topExpr.data as ir.ProcId
let calledProc = calledProcId.proc
if (calledProc && calledProc.inlineBody) {
const inlined = calledProc.inlineSelf(topExpr.args)
if (pxt.options.debug) {
console.log("INLINE", topExpr.toString(), "->", inlined.toString())
}
return emitExpr(inlined)
}
let numPush = 0
const args = topExpr.args.slice()
const lambdaArg = calledProcId.virtualIndex == -1 ? args.shift() : null
for (let e of args) {
emitExpr(e)
push()
numPush++
}
let nargs = args.length
if (lambdaArg) {
emitExpr(lambdaArg)
write(`callind ${nargs}`)
} else if (calledProcId.ifaceIndex != null) {
let idx = calledProcId.ifaceIndex + " ; ." + bin.ifaceMembers[calledProcId.ifaceIndex]
if (calledProcId.isSet) {
write(`callset ${idx}`)
U.assert(nargs == 2)
} else if (calledProcId.noArgs) {
// TODO implementation of op_callget needs to auto-bind if needed
write(`callget ${idx}`)
U.assert(nargs == 1)
} else {
// TODO impl of op_calliface needs to call getter and then the lambda if needed
write(`calliface ${nargs}, ${idx}`)
}
} else if (calledProcId.virtualIndex != null) {
U.oops()
} else {
write(`callproc ${calledProc.label()}`)
}
argDepth -= numPush
}
function emitStore(trg: ir.Expr, src: ir.Expr) {
switch (trg.exprKind) {
case EK.CellRef:
emitExpr(src)
let cell = trg.data as ir.Cell
let instr = "st" + cellref(cell)
if (cell.isGlobal() && (cell.bitSize != BitSize.None)) {
const enc = sizeOfBitSize(cell.bitSize) |
(isBitSizeSigned(cell.bitSize) ? 0x10 : 0x00)
write("bitconv " + enc)
}
write(instr)
break;
case EK.FieldAccess:
let info = trg.data as FieldAccessInfo
emitExpr(trg.args[0])
push()
emitExpr(src)
write(`stfld ${info.idx}, ${vtName(info.classInfo)}`)
argDepth--
break;
default: oops();
}
}
}
} | the_stack |
import path from 'path';
import defaults, {
ruleName,
SecondaryOptions,
IgnoreValue,
IgnoreValueList,
IgnoreValueHash,
IgnoreVariableOrFunctionConfig,
IgnoreVariableOrFunctionHash,
IgnoreValueConfig,
AutoFixFunc,
AutoFixFuncConfig,
isIIgnoreValueHash,
} from '../defaults';
/**
* Check if type is either `number` or `string`.
*
* @internal
* @param value - Any value.
*
* @returns Returns `true` if `value`'s type is either `number` or `string`, else `false`.
*/
function isNumberOrString(value: unknown): value is IgnoreValue {
const type = typeof value;
return type === 'string' || type === 'number';
}
/**
* Validate primary options of stylelint plugin config.
*
* @internal
* @param actual - The actual config to validate.
*
* @returns Returns `true` if primary options are valid, else `false`.
*/
export function validProperties(
actual: unknown
): actual is IgnoreValue | IgnoreValueList {
return (
isNumberOrString(actual) ||
(Array.isArray(actual) && actual.every((item) => isNumberOrString(item)))
);
}
/**
* Validate optional hash keyword config.
*
* @internal
* @param actual - A keyword config.
*
* @returns Returns `true` if hash keyword config is valid, else `false`.
*/
function validHash(actual: unknown): actual is IgnoreValueHash {
if (typeof actual !== 'object' || !actual) return false;
return Object.keys(actual).every((key) =>
validProperties((actual as IgnoreValueHash)[key as keyof IgnoreValueHash])
);
}
/**
* Validate optional boolean hash variable/function config.
*
* @internal
* @param actual - A variable/function config.
*
* @returns Returns `true` if hash variable/function config is valid, else `false`.
*/
function validBooleanHash(
actual: unknown
): actual is IgnoreVariableOrFunctionHash {
if (typeof actual !== 'object' || !actual) return false;
return Object.keys(actual).every(
(key) =>
typeof (actual as IgnoreVariableOrFunctionHash)[
key as keyof IgnoreVariableOrFunctionHash
] === 'boolean'
);
}
/**
* Validate optional secondary options of stylelint plugin config.
*
* @internal
* @param actual - The actual config to validate.
*
* @returns Returns `true` if secondary options are valid, else `false`.
*/
export function validOptions(actual: SecondaryOptions): boolean {
if (typeof actual !== 'object') return false;
const allowedKeys = Object.keys(defaults);
if (!Object.keys(actual).every((key) => allowedKeys.indexOf(key) > -1))
return false;
if (
'ignoreVariables' in actual &&
typeof actual.ignoreVariables !== 'boolean' &&
!validBooleanHash(actual.ignoreVariables) &&
actual.ignoreVariables !== null
)
return false;
if (
'ignoreFunctions' in actual &&
typeof actual.ignoreFunctions !== 'boolean' &&
!validBooleanHash(actual.ignoreFunctions) &&
actual.ignoreFunctions !== null
)
return false;
if (
'severity' in actual &&
typeof actual.severity !== 'string' &&
actual.severity !== null
)
return false;
if (
'ignoreKeywords' in actual &&
!validProperties(actual.ignoreKeywords) &&
!validHash(actual.ignoreKeywords)
)
return false;
if (
'ignoreValues' in actual &&
!validProperties(actual.ignoreValues) &&
!validHash(actual.ignoreValues)
)
return false;
if (
'expandShorthand' in actual &&
typeof actual.expandShorthand !== 'boolean' &&
actual.expandShorthand !== null
)
return false;
if (
'recurseLonghand' in actual &&
typeof actual.recurseLonghand !== 'boolean' &&
actual.recurseLonghand !== null
)
return false;
if (
'message' in actual &&
typeof actual.message !== 'string' &&
actual.message !== null
)
return false;
if (
'disableFix' in actual &&
typeof actual.disableFix !== 'boolean' &&
actual.disableFix !== null
)
return false;
if (
'autoFixFunc' in actual &&
typeof actual.autoFixFunc !== 'function' &&
typeof actual.autoFixFunc !== 'string' &&
actual.autoFixFunc !== null
)
return false;
return true;
}
/**
* Expected type of CSS value, available by configuration.
* @internal
*/
type ExpectedType = 'variable' | 'function' | 'keyword';
/**
* Expected types of CSS value, as configured.
* @internal
*/
type ExpectedTypes = Array<ExpectedType>;
/**
* Build expected message for stylelint report.
*
* @internal
* @param types - Either `variable`, `function` and/or `keyword`.
* @param value - The CSS declaration's value.
* @param property - The CSS declaration's property.
* @param customMessage - A custom message to be delivered upon error interpolated with `${types}`, `${value}` and `${property}`.
*
* @returns Returns an expected message for stylelint report.
*/
export function expected(
types: ExpectedType | ExpectedTypes,
value: string,
property: string,
customMessage = ''
): string {
let typesMessage: string;
if (Array.isArray(types)) {
const typesLast = types.pop();
// eslint-disable-next-line no-param-reassign
typesMessage = types.length
? `${types.join(', ')} or ${typesLast}`
: (typesLast as string);
} else {
typesMessage = types;
}
if (typeof customMessage === 'string' && customMessage.length) {
/* eslint-disable no-template-curly-in-string */
return customMessage
.replace('${types}', typesMessage)
.replace('${value}', value)
.replace('${property}', property);
/* eslint-enable no-template-curly-in-string */
}
return `Expected ${typesMessage} for "${value}" of "${property}"`;
}
/**
* Get configured types for stylelint report message.
*
* @internal
* @param config - The secondary stylelint-plugin config.
* @param property - The specific CSS declaration's property of the current iteration.
*
* @returns Returns a list of configured types.
*/
export function getTypes(
config: SecondaryOptions,
property: string
): ExpectedTypes {
const {
ignoreVariables,
ignoreFunctions,
ignoreKeywords,
ignoreValues,
} = config;
const types: ExpectedTypes = [];
if (ignoreVariables) {
types.push('variable');
}
if (ignoreFunctions) {
types.push('function');
}
if (ignoreKeywords && getIgnoredKeywords(ignoreKeywords, property)) {
types.push('keyword');
}
if (
types.indexOf('keyword') === -1 &&
ignoreValues &&
getIgnoredValues(ignoreValues, property)
) {
types.push('keyword');
}
return types;
}
/**
* Get the correct ignored variable or function for a specific CSS declaration's property
* out of a complex `ignoreVariablesOrFunctions` config hash or boolean.
*
* @internal
* @param ignoreVariablesOrFunctions - The variables or functions to ignore.
* @param property - The specific CSS declaration's property of the current iteration.
*
* @returns Returns ignored variable or function for a specific CSS property.
*/
export function getIgnoredVariablesOrFunctions(
ignoreVariablesOrFunctions: IgnoreVariableOrFunctionConfig,
property: string
): boolean {
// @see: https://github.com/microsoft/TypeScript/issues/41627
// const type = typeof ignoreVariablesOrFunctions
if (typeof ignoreVariablesOrFunctions === 'boolean') {
return ignoreVariablesOrFunctions;
}
if (
typeof ignoreVariablesOrFunctions === 'object' &&
ignoreVariablesOrFunctions &&
{}.hasOwnProperty.call(ignoreVariablesOrFunctions, property)
) {
return ignoreVariablesOrFunctions[property];
}
return !!ignoreVariablesOrFunctions;
}
/**
* Get the correct ignored keywords for a specific CSS declaration's property
* out of a complex `ignoreKeywords` config hash or array.
*
* @internal
* @param ignoreKeywords - The keyword/-s to ignore.
* @param property - The specific CSS declaration's property of the current iteration.
*
* @returns Returns ignored keywords for a specific CSS property, or `null`.
*/
export function getIgnoredKeywords(
ignoreKeywords: IgnoreValueConfig,
property: string
): null | IgnoreValueList {
if (!ignoreKeywords) return null;
let keywords = ignoreKeywords;
if (isIIgnoreValueHash(keywords, property)) {
keywords = keywords[property];
} else if (isIIgnoreValueHash(keywords, '')) {
keywords = keywords[''];
}
return Array.isArray(keywords) ? keywords : [keywords];
}
/**
* Get the correct ignored values for a specific CSS declaration's property
* out of a complex `ignoreValues` config hash or array.
*
* @internal
* @param ignoreValues - The values/-s to ignore.
* @param property - The specific CSS declaration's property of the current iteration.
* @returns Returns ignored values for a specific CSS property, or `null`.
*/
export function getIgnoredValues(
ignoreValues: IgnoreValueConfig,
property: string
): null | IgnoreValueList {
if (!ignoreValues) return null;
let values = ignoreValues;
if (isIIgnoreValueHash(values, property)) {
values = values[property];
} else if (isIIgnoreValueHash(values, '')) {
values = values[''];
}
return Array.isArray(values) ? values : [values];
}
/**
* Get the auto-fix function either by a function directly or from a source file.
*
* @internal
* @param autoFixFunc - A JavaScript function or a module path to resolve it, also from `cwd`.
*
* @returns Returns the auto-fix function if found, else `null`.
*/
export function getAutoFixFunc(
autoFixFunc: AutoFixFuncConfig,
disableFix?: boolean,
contextFix?: boolean
): null | AutoFixFunc {
// @see: https://github.com/microsoft/TypeScript/issues/41627
// const type = typeof autoFixFunc
if (typeof autoFixFunc === 'function') {
return autoFixFunc;
}
if (typeof autoFixFunc === 'string') {
let resolveAutoFixfunc;
try {
resolveAutoFixfunc = require.resolve(autoFixFunc);
} catch (error) {
resolveAutoFixfunc = require.resolve(
path.join(process.cwd(), autoFixFunc)
);
}
// eslint-disable-next-line import/no-dynamic-require, global-require
return require(resolveAutoFixfunc);
}
if (!disableFix && contextFix) {
// eslint-disable-next-line no-console
console.warn(
`No \`autoFix\` function provided, consider using \`disableFix\` for "${ruleName}"`
);
}
return null;
} | the_stack |
import { IndexFormat, TypedArray, VertexElement, VertexElementFormat } from "@oasis-engine/core";
import { Color, Vector2, Vector3, Vector4 } from "@oasis-engine/math";
import { AccessorComponentType, AccessorType, IAccessor, IBufferView, IGLTF } from "./Schema";
/**
* @internal
*/
export class GLTFUtil {
public static floatBufferToVector2Array(buffer: Float32Array): Vector2[] {
const bufferLen = buffer.length;
const array = new Array<Vector2>(bufferLen / 2);
for (let i = 0; i < bufferLen; i += 2) {
array[i / 2] = new Vector2(buffer[i], buffer[i + 1]);
}
return array;
}
public static floatBufferToVector3Array(buffer: Float32Array): Vector3[] {
const bufferLen = buffer.length;
const array = new Array<Vector3>(bufferLen / 3);
for (let i = 0; i < bufferLen; i += 3) {
array[i / 3] = new Vector3(buffer[i], buffer[i + 1], buffer[i + 2]);
}
return array;
}
public static floatBufferToVector4Array(buffer: Float32Array): Vector4[] {
const bufferLen = buffer.length;
const array = new Array<Vector4>(bufferLen / 4);
for (let i = 0; i < bufferLen; i += 4) {
array[i / 4] = new Vector4(buffer[i], buffer[i + 1], buffer[i + 2], buffer[i + 3]);
}
return array;
}
public static floatBufferToColorArray(buffer: Float32Array, isColor3: boolean): Color[] {
const bufferLen = buffer.length;
const colors = new Array<Color>(bufferLen / (isColor3 ? 3 : 4));
if (isColor3) {
for (let i = 0; i < bufferLen; i += 3) {
colors[i / 3] = new Color(buffer[i], buffer[i + 1], buffer[i + 2], 1.0);
}
} else {
for (let i = 0; i < bufferLen; i += 4) {
colors[i / 4] = new Color(buffer[i], buffer[i + 1], buffer[i + 2], buffer[i + 3]);
}
}
return colors;
}
/**
* Parse binary text for glb loader.
*/
static decodeText(array: Uint8Array): string {
if (typeof TextDecoder !== "undefined") {
return new TextDecoder().decode(array);
}
// TextDecoder polyfill
let s = "";
for (let i = 0, il = array.length; i < il; i++) {
s += String.fromCharCode(array[i]);
}
return decodeURIComponent(encodeURIComponent(s));
}
/**
* Get the number of bytes occupied by accessor type.
*/
static getAccessorTypeSize(accessorType: AccessorType): number {
switch (accessorType) {
case AccessorType.SCALAR:
return 1;
case AccessorType.VEC2:
return 2;
case AccessorType.VEC3:
return 3;
case AccessorType.VEC4:
return 4;
case AccessorType.MAT2:
return 4;
case AccessorType.MAT3:
return 9;
case AccessorType.MAT4:
return 16;
}
}
/**
* Get the TypedArray corresponding to the component type.
*/
static getComponentType(componentType: AccessorComponentType) {
switch (componentType) {
case AccessorComponentType.BYTE:
return Int8Array;
case AccessorComponentType.UNSIGNED_BYTE:
return Uint8Array;
case AccessorComponentType.SHORT:
return Int16Array;
case AccessorComponentType.UNSIGNED_SHORT:
return Uint16Array;
case AccessorComponentType.UNSIGNED_INT:
return Uint32Array;
case AccessorComponentType.FLOAT:
return Float32Array;
}
}
/**
* Get accessor data.
*/
static getAccessorData(gltf: IGLTF, accessor: IAccessor, buffers: ArrayBuffer[]): TypedArray {
const bufferViews = gltf.bufferViews;
const bufferView = bufferViews[accessor.bufferView];
const arrayBuffer = buffers[bufferView.buffer];
const accessorByteOffset = accessor.hasOwnProperty("byteOffset") ? accessor.byteOffset : 0;
const bufferViewByteOffset = bufferView.hasOwnProperty("byteOffset") ? bufferView.byteOffset : 0;
const byteOffset = accessorByteOffset + bufferViewByteOffset;
const accessorTypeSize = GLTFUtil.getAccessorTypeSize(accessor.type);
const length = accessorTypeSize * accessor.count;
const byteStride = bufferView.byteStride ?? 0;
const arrayType = GLTFUtil.getComponentType(accessor.componentType);
let uint8Array;
if (byteStride) {
const accessorByteSize = accessorTypeSize * arrayType.BYTES_PER_ELEMENT;
uint8Array = new Uint8Array(accessor.count * accessorByteSize);
const originalBufferView = new Uint8Array(arrayBuffer, bufferViewByteOffset, bufferView.byteLength);
for (let i = 0; i < accessor.count; i++) {
for (let j = 0; j < accessorByteSize; j++) {
uint8Array[i * accessorByteSize + j] = originalBufferView[i * byteStride + accessorByteOffset + j];
}
}
} else {
uint8Array = new Uint8Array(arrayBuffer.slice(byteOffset, byteOffset + length * arrayType.BYTES_PER_ELEMENT));
}
const typedArray = new arrayType(uint8Array.buffer);
if (accessor.sparse) {
const { count, indices, values } = accessor.sparse;
const indicesBufferView = bufferViews[indices.bufferView];
const valuesBufferView = bufferViews[values.bufferView];
const indicesArrayBuffer = buffers[indicesBufferView.buffer];
const valuesArrayBuffer = buffers[valuesBufferView.buffer];
const indicesByteOffset = (indices.byteOffset ?? 0) + (indicesBufferView.byteOffset ?? 0);
const indicesByteLength = indicesBufferView.byteLength;
const valuesByteOffset = (values.byteOffset ?? 0) + (valuesBufferView.byteOffset ?? 0);
const valuesByteLength = valuesBufferView.byteLength;
const indicesType = GLTFUtil.getComponentType(indices.componentType);
const indicesArray = new indicesType(
indicesArrayBuffer,
indicesByteOffset,
indicesByteLength / indicesType.BYTES_PER_ELEMENT
);
const valuesArray = new arrayType(
valuesArrayBuffer,
valuesByteOffset,
valuesByteLength / arrayType.BYTES_PER_ELEMENT
);
for (let i = 0; i < count; i++) {
const replaceIndex = indicesArray[i];
for (let j = 0; j < accessorTypeSize; j++) {
typedArray[replaceIndex * accessorTypeSize + j] = valuesArray[i * accessorTypeSize + j];
}
}
}
return typedArray;
}
static getBufferViewData(bufferView: IBufferView, buffers: ArrayBuffer[]): ArrayBuffer {
const { buffer, byteOffset = 0, byteLength } = bufferView;
const arrayBuffer = buffers[buffer];
return arrayBuffer.slice(byteOffset, byteOffset + byteLength);
}
static getVertexStride(gltf: IGLTF, accessor: IAccessor): number {
const stride = gltf.bufferViews[accessor.bufferView ?? 0].byteStride;
if (stride) {
return stride;
}
const size = GLTFUtil.getAccessorTypeSize(accessor.type);
const componentType = GLTFUtil.getComponentType(accessor.componentType);
return size * componentType.BYTES_PER_ELEMENT;
}
static createVertexElement(semantic: string, accessor: IAccessor, index: number): VertexElement {
const size = GLTFUtil.getAccessorTypeSize(accessor.type);
return new VertexElement(
semantic,
0,
GLTFUtil.getElementFormat(accessor.componentType, size, accessor.normalized),
index
);
}
static getIndexFormat(type: AccessorComponentType): IndexFormat {
switch (type) {
case AccessorComponentType.UNSIGNED_BYTE:
return IndexFormat.UInt8;
case AccessorComponentType.UNSIGNED_SHORT:
return IndexFormat.UInt16;
case AccessorComponentType.UNSIGNED_INT:
return IndexFormat.UInt32;
}
}
static getElementFormat(type: AccessorComponentType, size: number, normalized: boolean = false): VertexElementFormat {
if (type == AccessorComponentType.FLOAT) {
switch (size) {
case 1:
return VertexElementFormat.Float;
case 2:
return VertexElementFormat.Vector2;
case 3:
return VertexElementFormat.Vector3;
case 4:
return VertexElementFormat.Vector4;
}
}
if (type == AccessorComponentType.SHORT) {
switch (size) {
case 2:
return normalized ? VertexElementFormat.NormalizedShort2 : VertexElementFormat.Short2;
case 3:
case 4:
return normalized ? VertexElementFormat.NormalizedShort4 : VertexElementFormat.Short4;
}
}
if (type == AccessorComponentType.UNSIGNED_SHORT) {
switch (size) {
case 2:
return normalized ? VertexElementFormat.NormalizedUShort2 : VertexElementFormat.UShort2;
case 3:
case 4:
return normalized ? VertexElementFormat.NormalizedUShort4 : VertexElementFormat.UShort4;
}
}
if (type == AccessorComponentType.BYTE) {
switch (size) {
case 2:
case 3:
case 4:
return normalized ? VertexElementFormat.NormalizedByte4 : VertexElementFormat.Byte4;
}
}
if (type == AccessorComponentType.UNSIGNED_BYTE) {
switch (size) {
case 2:
case 3:
case 4:
return normalized ? VertexElementFormat.NormalizedUByte4 : VertexElementFormat.UByte4;
}
}
}
/**
* Load image buffer
*/
static loadImageBuffer(imageBuffer: ArrayBuffer, type: string): Promise<HTMLImageElement> {
return new Promise((resolve, reject) => {
const blob = new window.Blob([imageBuffer], { type });
const img = new Image();
img.src = URL.createObjectURL(blob);
img.crossOrigin = "anonymous";
img.onerror = function () {
reject(new Error("Failed to load image buffer"));
};
img.onload = function () {
// Call requestAnimationFrame to avoid iOS's bug.
requestAnimationFrame(() => {
resolve(img);
img.onload = null;
img.onerror = null;
img.onabort = null;
});
};
});
}
static isAbsoluteUrl(url: string): boolean {
return /^(?:http|blob|data:|\/)/.test(url);
}
static parseRelativeUrl(baseUrl: string, relativeUrl: string): string {
if (GLTFUtil.isAbsoluteUrl(relativeUrl)) {
return relativeUrl;
}
const char0 = relativeUrl.charAt(0);
if (char0 === ".") {
return GLTFUtil._formatRelativePath(relativeUrl + relativeUrl);
}
return baseUrl.substring(0, baseUrl.lastIndexOf("/") + 1) + relativeUrl;
}
/**
* Parse the glb format.
*/
static parseGLB(glb: ArrayBuffer): {
gltf: IGLTF;
buffers: ArrayBuffer[];
} {
const UINT32_LENGTH = 4;
const GLB_HEADER_MAGIC = 0x46546c67; // 'glTF'
const GLB_HEADER_LENGTH = 12;
const GLB_CHUNK_TYPES = { JSON: 0x4e4f534a, BIN: 0x004e4942 };
const dataView = new DataView(glb);
// read header
const header = {
magic: dataView.getUint32(0, true),
version: dataView.getUint32(UINT32_LENGTH, true),
length: dataView.getUint32(2 * UINT32_LENGTH, true)
};
if (header.magic !== GLB_HEADER_MAGIC) {
console.error("Invalid glb magic number. Expected 0x46546C67, found 0x" + header.magic.toString(16));
return null;
}
// read main data
let chunkLength = dataView.getUint32(GLB_HEADER_LENGTH, true);
let chunkType = dataView.getUint32(GLB_HEADER_LENGTH + UINT32_LENGTH, true);
// read glTF json
if (chunkType !== GLB_CHUNK_TYPES.JSON) {
console.error("Invalid glb chunk type. Expected 0x4E4F534A, found 0x" + chunkType.toString(16));
return null;
}
const glTFData = new Uint8Array(glb, GLB_HEADER_LENGTH + 2 * UINT32_LENGTH, chunkLength);
const gltf: IGLTF = JSON.parse(GLTFUtil.decodeText(glTFData));
// read all buffers
const buffers: ArrayBuffer[] = [];
let byteOffset = GLB_HEADER_LENGTH + 2 * UINT32_LENGTH + chunkLength;
while (byteOffset < header.length) {
chunkLength = dataView.getUint32(byteOffset, true);
chunkType = dataView.getUint32(byteOffset + UINT32_LENGTH, true);
if (chunkType !== GLB_CHUNK_TYPES.BIN) {
console.error("Invalid glb chunk type. Expected 0x004E4942, found 0x" + chunkType.toString(16));
return null;
}
const currentOffset = byteOffset + 2 * UINT32_LENGTH;
const buffer = glb.slice(currentOffset, currentOffset + chunkLength);
buffers.push(buffer);
byteOffset += chunkLength + 2 * UINT32_LENGTH;
}
return {
gltf,
buffers
};
}
private static _formatRelativePath(value: string): string {
const parts = value.split("/");
for (let i = 0, n = parts.length; i < n; i++) {
if (parts[i] == "..") {
parts.splice(i - 1, 2);
i -= 2;
}
}
return parts.join("/");
}
} | the_stack |
import Users from "../users/collection";
import { ensureIndex } from '../../collectionUtils';
import { spamRiskScoreThreshold } from "../../../components/common/RecaptchaWarning";
import pick from 'lodash/pick';
import isNumber from 'lodash/isNumber';
import mapValues from 'lodash/mapValues';
declare global {
interface UsersViewTerms extends ViewTermsBase {
view?: UsersViewName
sort?: {
createdAt?: number,
karma?: number,
postCount?: number,
commentCount?: number,
afKarma?: number,
afPostCount?: number,
afCommentCount?: number,
},
userId?: string,
slug?: string,
lng?: number
lat?: number
}
}
// Auto-generated indexes from production
ensureIndex(Users, {username:1}, {unique:true,sparse:1});
ensureIndex(Users, {"emails.address":1}, {unique:true,sparse:1});
ensureIndex(Users, {"services.resume.loginTokens.hashedToken":1}, {unique:true,sparse:1});
ensureIndex(Users, {"services.resume.loginTokens.token":1}, {unique:true,sparse:1});
ensureIndex(Users, {"services.resume.haveLoginTokensToDelete":1}, {sparse:1});
ensureIndex(Users, {"services.resume.loginTokens.when":1}, {sparse:1});
ensureIndex(Users, {"services.email.verificationTokens.token":1}, {unique:true,sparse:1});
ensureIndex(Users, {"services.password.reset.token":1}, {unique:true,sparse:1});
ensureIndex(Users, {"services.password.reset.when":1}, {sparse:1});
ensureIndex(Users, {"services.twitter.id":1}, {unique:true,sparse:1});
ensureIndex(Users, {"services.facebook.id":1}, {unique:true,sparse:1});
ensureIndex(Users, {"services.google.id":1}, {unique:true,sparse:1});
ensureIndex(Users, {karma:-1,_id:-1});
ensureIndex(Users, {slug:1});
ensureIndex(Users, {isAdmin:1});
ensureIndex(Users, {"services.github.id":1}, {unique:true,sparse:1});
ensureIndex(Users, {createdAt:-1,_id:-1});
// Case-insensitive email index
ensureIndex(Users, {'emails.address': 1}, {sparse: 1, unique: true, collation: { locale: 'en', strength: 2 }})
ensureIndex(Users, {email: 1})
const termsToMongoSort = (terms: UsersViewTerms) => {
if (!terms.sort)
return undefined;
const filteredSort = pick(terms.sort, [
"createdAt", "karma", "postCount", "commentCount",
"afKarma", "afPostCount", "afCommentCount",
]);
return mapValues(filteredSort,
v => isNumber(v) ? v : 1
);
}
Users.addView('usersProfile', function(terms: UsersViewTerms) {
if (terms.userId) {
return {
selector: {_id:terms.userId}
}
}
return {
selector: {$or: [{slug: terms.slug}, {oldSlugs: terms.slug}]},
}
});
ensureIndex(Users, {oldSlugs:1});
Users.addView('LWSunshinesList', function(terms: UsersViewTerms) {
return {
selector: {groups:'sunshineRegiment'},
options: {
sort: termsToMongoSort(terms),
}
}
});
Users.addView('LWTrustLevel1List', function(terms: UsersViewTerms) {
return {
selector: {groups:'trustLevel1'},
options: {
sort: termsToMongoSort(terms),
}
}
});
Users.addView('LWUsersAdmin', (terms: UsersViewTerms) => ({
options: {
sort: termsToMongoSort(terms),
}
}));
Users.addView("usersWithBannedUsers", function () {
return {
selector: {
bannedUserIds: {$exists: true}
},
}
})
Users.addView("sunshineNewUsers", function (terms: UsersViewTerms) {
return {
selector: {
needsReview: true,
reviewedByUserId: null,
$or: [{signUpReCaptchaRating: {$gt: spamRiskScoreThreshold*1.25}}, {signUpReCaptchaRating: {$exists: false}}, {signUpReCaptchaRating:null}]
},
options: {
sort: {
sunshineFlagged: -1,
reviewedByUserId: 1,
postCount: -1,
signUpReCaptchaRating: -1,
createdAt: -1
}
}
}
})
ensureIndex(Users, {needsReview: 1, signUpReCaptchaRating: 1, createdAt: -1})
Users.addView("allUsers", function (terms: UsersViewTerms) {
return {
options: {
sort: {
...termsToMongoSort(terms),
reviewedAt: -1,
createdAt: -1
}
}
}
})
ensureIndex(Users, {reviewedAt: -1, createdAt: -1})
Users.addView("usersMapLocations", function () {
return {
selector: {
mapLocationSet: true
},
}
})
ensureIndex(Users, {mapLocationSet: 1})
Users.addView("reviewAdminUsers", function (terms: UsersViewTerms) {
return {
selector: {
karma: {$gte: 1000},
},
options: {
sort: {
karma: -1
}
}
}
})
Users.addView("usersWithPaymentInfo", function (terms: UsersViewTerms) {
return {
selector: {
$or: [{ paymentEmail: {$exists: true}}, {paymentInfo: {$exists: true}}],
},
options: {
sort: {
displayName: 1
}
}
}
})
export const hashedPetrovLaunchCodes = [
"KEDzA2lmOdFDFweWi6jWe9kerEYXGn4qvXjrI41S4bc=",
"iEe7eacQU9TLDrB+bkEDW5/Ti6EkZzNfsHvE/0rlRE8=",
"jQLUwGlfOYo2+uczUN6bBBnOuzyek18dcoYaCWmtACA=",
"U7IzacSbqJA27Xpm8YU5MExdf0JNH20GTYd0fIKEbag=",
"UpIrSpxnf7U2AXPhkXAFQmK3hBvVyIIFisgMdhqQ0vU=",
"weXBk/Qe8ghzGCFhOJ07pSiLyRo/NQxq2zEWuEGx/Kk=",
"9M7XPkLgxURmC2TJYTi9SbsZkgg3eWqYiaa8TpROuSA=",
"H8WnoWoTP0y0IHwKxigJrGYEWNwqHu4c64LfmMsRNng=",
"MP8tXSZYg4O4O9XzlRpTOYVm30tXcM9x6mObSMoe5Jo=",
"I8d8mWBeVO2vhSJbg/FzNSiOL/5XbA+xhsXLnHn1jwY=",
"hgZXRwTmS92d7wOwpaJq2rQRrsjcRhFbetytSfYYNOg=",
"jwZCimOX03f8WIDCBqjKClCpRlB/BTMdYzyJg/Ny224=",
"dFY3IfBBAJFypw8KtEX8yuSkm99kNfSskuTsR49zTow=",
"mdyX6Y/qYs+wsKyZxv/7mHWS5Vvym4coh8KjBBsb+L4=",
"SNUKPUsFtgr5y1BWxXtAkZE73pFHdFnYUJapVWVVJy8=",
"usmj8eXdbghMD+/0Fn04Bw0MLPzTpEPqn9Pj1JTsAVk=",
"v2kpY58U7kVyOiUscaztgOi4s9OiCVXv6S9QKq+ZHe4=",
"63F4EbuLc8opRINm/sGqQsmy53oz+wC9AYGVddhk5qM=",
"C9pHTHQ+w5d+a0N+nXxO2nX4WhBUsNobOfK6Fvms7Q4=",
"wxGJxbk1WK7+RijxqFXx6DIwZzQORkZOv0JW6FaKFCQ=",
"wB1Ns819Sx+UdB3PglJhHpZTcyrcs9HqfD2m7o3KRk8=",
"Ad3OEzt/EQJPDKO63wYmKnOxNO6iJi2wwV3MbaxB+LE=",
"TtER2oLUDlmX7AZjh4cKAj5axS5K0M4/w2Kq0dMI+v4=",
"fAwMckf5AiJyklIQDSSkHMX+0NLHsugm+9kBe1rUs6A=",
"M5gFYJuEiRVJe5ZjNyo576lycQVS13eKZTHAxto9dhk=",
"oy8YNQE7CRur7Q/2fTEcY2SU5hNXz6zuJWC+tvo9sbY=",
"749MNm9/pF6AMPfpWzfZipdh+nPqEEgS2jCMh4zeG4w=",
"6BEpoFIaPOf85NExYFSHxbLiweU5JyigkrUX3tvB2w4=",
"q7wlG1O0dWIsiHVsmDyBYZs5rkshYaGtOZHjExVk2I8=",
"+U51njudAG0PTdO+vVD6KinYJIlh6A6orxoP6vrel9Q=",
"kdXOpISGbI6yWG4ibJ1fwt5mD0xOPYVnqfFKA6M5MQk=",
"ZE3tPHl70KCYVJb3FaqTYjrVQaaW4asWSKcRwICBXJ0=",
"ZlU5XpgiujrMLY7fyFLyOaZxP+bbl0ySMeLTIVaBXsU=",
"q6F4vL8FKbYxsZIuAlwVF2op4KtlW49O0ci2KBNoy5Y=",
"pNV95cWaUurlo8luq5mZ5LWWjsA1A0g4nExzmDh+1u0=",
"bSK/0yP6q/u7ALtRDxMmyse8eO86LQgBZjiBWcWIuR4=",
"urktlQLd8UpJNLUtBHVvpCgFRggwuEkxfWdBR102s+w=",
"LLRdTTRlj6coFcng6+fB8fl+kLvF5amyyjQEg1iq6p0=",
"sdYeVWy/H/8M2zw2YJ8PmccawkHqFRO4DBt5PIeUqoM=",
"a4rW/BM7oZsI3TNQmkLFOOcA2qczsPw80DSkbuWnlX0=",
"H+VpdDA/FHbnW0a2aQdnIFLGwkPJt3t5phsc+YURgmg=",
"oIsrAj26cN9twnNZu5AdJDwRqMROf5KySh+c2I9sqTg=",
"zrz5sa/c0cnDeVuaW+Q8ki3BYAkj7GAyG2ZtAtx4GXo=",
"s6hW8rNKgXdzlCYlrQeeSLmayN5XMnuuucmaIEifbaY=",
"colHZ5szaH3jvbvngOp7D9ZiWcIvffL/q48g3QHvKYk=",
"69xvlvMdRNAP0dZob0iCuPsrEJu+XwQDLrqLXCAFth4=",
"ueVYg5bhxSq13eRLDUQGRzXRWOhuJIb9OV6As/FVeko=",
"HkbCq9CVPyfwgMDi0h1FPk2ASuOfhgqMNlKDwqcQM9c=",
"ty3nOq2l+ZJgHrb/9a202EpAR979tVlii/a6fpiWIX8=",
"JHYUgzK18LkXNahrtGzhLcv7wBry7RbknsvffHJOYzk=",
"hfts6tDL0zX23iVhD8TqD0gLJrc0+4bU1tp3SjW1i9Q=",
"y4htIeFNJWf/yneLfexeGOBuaQuNIo0/Pb5/FyHQizk=",
"yTZVHfo2D2Y9ZLIE6+dXFL00qbCVTrisOQsbZKMA9dE=",
"yY+64+vCptZa+j2fZGyq4e/xNDJ/UPmA5bIolnVPtPg=",
"EzM0QfHRmR7kIUz9RCrjdfzdahM8Mx9x9Jm/9ObHerg=",
"Sf69cYFwXoDKk8zlvTHzwyqrDbJq0Q7EbJuClPioSms=",
"p1HI+dfGaMd3MM89DdWSgXgrMfOsTDeoBwYj1jSytm4=",
"2TPDZhqGSLqe7BaqSuES367ZKbk5o35J9f6TK/YzhHc=",
"DvDNrXDaQRmhaxAPysdOu3An5nShE8w3IKh4epPzS6I=",
"p9aVipMb4qGyVfeBCN6MeN0Ic+yPtAZyTJPaheXhg88=",
"SNdEliT61auaD6aqF/SkFqe0dcKZfUrBckUr917AAY4=",
"pcZ5APLDi9YvyoHFKbjX2Kune8sKvisxt9aNuenqoSc=",
"MvO3eTkz4jA0EIQCBP5+T3xkqEDG15SwiI7QMzHcrHc=",
"YwWEy24HBBP+yMXdSxAnT8aBWbj8wOD1YDghLpsmUSI=",
"Bly+OSKiNMVuGqBO5OtqyiozAeke3f9+jB92lBUZ1CY=",
"IdKf2EOovFFQV1ODvm1lo9sSHZXwe2UGInoFrwNy67Y=",
"ciC6n6LX5BO1Kkn0kFeejtWicm9v9rjQU/vggcUlpi0=",
"u22MCQMC/n2yNIFZQf4Hu+qicXkwekU4vUYC4vSXVVY=",
"vnqxxZ3Q/eiPUuTfKqxYhfeFRKHj0na16kLuL+z49ZQ=",
"j6XfAgoPRmJwvL21QE9rdmGZlUTsbGy1TT9UHWtWD6Y=",
"6qqIHD0qzlvD4EqH2CGlvjWNZLXDX1n6mnEqq8Kfd4k=",
"wsVQy2TQCrz1zToSjp78TIcX0WbZD3Fl8ScWJTtAg8g=",
"UZOr9qoqQRz2LQ/RzpqDgXUQuf8+ph300qe1hlDy8II=",
"162bDMXB3+M27vDt2S5wbeHOhGKYVYjAko7CcDYcg9g=",
"KTWkCzhIBWXBIgfxy5ghi6ak7dQKFtdG8/8evKuBukg=",
"z6L/Y4+ZPW23uoNf2ylXLBAFumf5Qgx6Oy/JoTA6FNg=",
"VN8+V8csaWQxjHL83Bu5px04DFuH+atHPx5apGBq1p4=",
"cC5VoQyVrBofGi7eSo+iR29fJL9jKk9QN4AfaVFXPck=",
"DZcYGgxd0Kwy792fevETIyXwhzRmfYFZpJw99UyWnjk=",
"qUc1B4wlpSotVKfV48N0mJ9Ib1fi1WnRMOZcuYnJ6bo=",
"a417H7hUk1USOwhI8le3Ev9gLOD1Zr5krLwRFt80AQc=",
"0weG9mBi6BRsacNOPoYXrwXzbgZEi6PGM2qrsg/P/ZI=",
"HgsbBaE30vzGFTOaH8GftAT5wYjXBShCe693y8qM/YQ=",
"E8w3y4JepGkDp4Elb+d3Wx3g3bwT4AOfSEKH68+OP90=",
"dmTU1q0MnwYli1HIA207vLHg2WSPKfdgTnTGxP+O+Oc=",
"dmGEcvqbtgZGZOBd99QVR+0X4LbsbMLrvCrES9tVPig=",
"GTYVESGYH/g1F/EI5tVSg8+GhcVnFLxy77lF6ehMJJM=",
"2WPQJQa82nv971nPq4gsiDIff6YbTukzyjSVDqhCz7o=",
"aZS29NfRjmKXdERQQhiZDCgJ11NrgiHXHwiXjhX+OG8=",
"ggGQnh4pgs2zDKc5NT2ojLBuY8gDrhXbqLxWC4xkxhw=",
"uJnwZcC+Vqv/hdy6/U4wAfdc9f7Wtgaml9xvG8GgIas=",
"NxRjSeRxB9Lo56JPfqsdKW+XMlW03T3hMRIOZmGcCQo=",
"5MJ2aSou6bm3N7f/CL1rYT43f09VE2He8fe0Z38SjIQ=",
"d7Ej1ZSauBrV1OLoHp0izLGNl9pW9Zc3hj2v6wrktOk=",
"3JFgac3VSn8ujp5fdOXa+vwRCj1UFruPiaIu6ei/iTs=",
"8lQF9DeHQefnD6XsKFttruq8pfVdW6ZPzEhNHSqwC5A=",
"8lf/H3LTt0XZziUMo2l5HyBbT/s08TFjEuPRmFOM+kk=",
"p42m8A0htGV8pvJMMiw8mIVcK6ZW1cN1CbDx/mCaZxU=",
"7Jwr9OlkcsbyAMP9vVLZXY5svzGXmftW/lrf/aPjWdA=",
"aYBfg2CStuWNM9p+oFDwEh4PJu9AYTrSdwLLQ/TgHqA=",
"rmjwWxP6svFadVrd5SaM08rmFxblFdkBb+dBucMTQ/c=",
"VicOuzS4dKhwymw1yEv6v8m6HfHVfyVkZON4cCzk/r0=",
"6fgFP280humyeTOsTHhx9JNDli5O0O2/6wH+PJJHVmY=",
"D6WWevz/uKmjSGEL3uFzasx0DjfpaEsblhVG0e12YnI=",
"it8Ee4CFv1UbdlT7X1hjGggqUyZe0DYw8voVBw4CQic=",
"74w+0FzxE2SavJIl6ztovV++ySmXIas5MZ9H02kCN5I=",
"qlVSfuS4TDekrs9lPZQUhwfDpYHYUZZB6zeNFsVdg0E=",
"75OwKyHYlwkMD0Z0KN5ChMqxdAzM0yQ8R7+FucMKB7k=",
"n1P2WRP+BDapx7ByeLZDZjm0L5IPBL9I+tD34AObEs8=",
"LHlDk7HUwWvbchqysHOhdGX2Wk27vq7P9UUTgnNafsA=",
"6ZaxhBGoKCqz7pwU+H03SuTUGNZOzhXFYUi477wf6SI=",
"1HoB51FQZnP3S7OhRfnIShLUJjTk0o/hfQws3uDoAUQ=",
"UypL5pLirxaM+LfKgQVVPwl2e8hKSauP4tYoAti7GDk=",
"nH8rAYbInnGBhsmENTPznC0OuuZQqbePbwJCBtavne8=",
"GeZJ/b2Hm0szD9Bpw+EdVohj4oQAG6IvUd/7QmIMQo4=",
"Pu31feTY/rHVcNJtuWCjVwTP4vj1gj8vLmr9ejwIOT0=",
"SNjx0Tkj3tBQ6Ks64SRi1eqMMr90RlUmz/8+Dnz08dQ=",
"6mMlLEESPgtEriaQp7VhQVQDkCEtSKh4XqLNlEsx26M=",
"liBi7ekLtFVTSzwPhpT/ezo1MLZtSyJ6cdESJSSXyhs=",
"Wu3JRA9+kwvFrx2f1iMf4qyuLBUowUD+sKyzTLqBJ2c=",
"atqJuRMwPV9x5IEVCyFchgqOoU08cUHFrJX4GmDFfbY=",
"sd/18blKhizdQhi8wsQmVANhlrVCgU3+u7HEx1AZZ1Y=",
"i0aGZSzXaWw/cOp1VcLt3l15EDq/8C2RON5DivNn//M=",
"fvUPurGTw5u3Ck15vs4VS7Hqmup3jX0MLBAoQ2GxVIY=",
"UveV+2yRoot3XGyR+wg/qDZVgFoS1kTTrJG/2/ZY4J4=",
"3BYq5SjblLCiziGAy2n6yhHD+vrFDtRN3YnWVaWudK4=",
"nY4xwoOWur7N1hdUkpdA8bIZmVQuyHNshwpWuKX1L4I=",
"fedX5HyV+kV7Z2tFfuxxEL4iURCQAToL+aDBYlIBqqY=",
"6FKe+GFNukrQF4Wl1UVsckInjAUweowXLT92Ogfbg18=",
"DxwtI7f4PdxOwXfoOdoxOzh9HprUpoja+AUWSy4HZt0=",
"DszY8xKG2llkONa+vSNeRhIRoB098ZdJzUVymT8JwNg=",
"c2KsC8Zk+gJICT18aDoHnfjPDhwsLHaD7JttHpJY0Ik=",
"mrBU2+0cLlkkAvTLp0rlNu7K0BI0USnbjAI7U7jW1u8=",
"Z5GKJCKhvgkpctTuXzsnk+BrFrxIXMSowIYyrWeuRAY=",
"DhypIMxYKpZflv6WZVFJWs+xSouFRs1PwgdOeTao7Iw=",
"mSt9HqzbjLFZICE/PGQU4oK6KTK0Dc3ZFNPU683eQLo=",
"ot8rflPG8k3PAb47N5+W7elG1YHhfazlcSAkZWl2bpk=",
"BA5XpC/oCRc52udZ9fTGqh8gmJOAFzJ2vun9I04u5EE=",
"DlRQhz7OMWwISrMssoHb6Cz55LtpFZ4N3jJdVj7ovZI=",
"scV7XKJrM6mN0aRWmN926TmCiZNk1IEz+tjRsvg3ZUc=",
"5PNqoIYrYCRGMi7p6hLHeP2K9M0H8v99BrJ3KIfCcgI=",
"vBcMhPo6vWpbOOjmsEu1NDa7ie34AW7ocO0fiuRc4ok=",
"VLcvrkeU88eLLIed2BvJqfVmsf/8tRCLP0LsMDSnLf0=",
"qPHxpwnPYUGi/fVpvuJ0y4/tYNpGzrMvCM1G4pqZobg=",
"FiVDoXPKWkG6yNUblPbIyn1KUrJ7znjEIzk6BnYSTaw=",
"xJ/+zoHXE6pQUTOQLIAAlJGfO3VKAOGg8m3qSSvGCgU=",
"OwqoREygdoVLrNGia5sbgjzVT1kiT0kiqY2ixVAeCfw=",
"dBr1tqtqaCDamTafSHoWtOsG4rah8J8gkpGXIjDoOW0=",
"LGDZ4lOTjBh05vFyZ0uzkPAqqCGpt6vmFL6PwcHAJFE=",
"e8MeSpVel0bfJCC+MQSD7vLgFVDrTbVOeMzREeCEb0c=",
]
/*Users.addView("areWeNuked", function () {
return {
selector: {
petrovCodesEnteredHashed: {$in: hashedPetrovLaunchCodes}
},
}
})
ensureIndex(Users, {petrovCodesEnteredHashed: 1})*/
Users.addView("walledGardenInvitees", function () {
return {
selector: {
walledGardenInvite: true
},
options: {
sort: {
displayName: 1
}
}
}
})
ensureIndex(Users, {walledGardenInvite: 1}) | the_stack |
import { TreeIterator, ENTRIES, KEYS, VALUES, LEAF } from './TreeIterator'
import fuzzySearch, { FuzzyResults } from './fuzzySearch'
import { RadixTree, Entry, Path } from './types'
/**
* A class implementing the same interface as a standard JavaScript
* [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map)
* with string keys, but adding support for efficiently searching entries with
* prefix or fuzzy search. This class is used internally by [[MiniSearch]] as
* the inverted index data structure. The implementation is a radix tree
* (compressed prefix tree).
*
* Since this class can be of general utility beyond _MiniSearch_, it is
* exported by the `minisearch` package and can be imported (or required) as
* `minisearch/SearchableMap`.
*
* @typeParam T The type of the values stored in the map.
*/
export default class SearchableMap<T = any> {
/**
* @internal
*/
_tree: RadixTree<T>
/**
* @internal
*/
_prefix: string
private _size?: number
/**
* The constructor is normally called without arguments, creating an empty
* map. In order to create a [[SearchableMap]] from an iterable or from an
* object, check [[SearchableMap.from]] and [[SearchableMap.fromObject]].
*
* The constructor arguments are for internal use, when creating derived
* mutable views of a map at a prefix.
*/
constructor (tree = {}, prefix = '') {
this._tree = tree
this._prefix = prefix
}
/**
* Creates and returns a mutable view of this [[SearchableMap]], containing only
* entries that share the given prefix.
*
* ### Usage:
*
* ```javascript
* let map = new SearchableMap()
* map.set("unicorn", 1)
* map.set("universe", 2)
* map.set("university", 3)
* map.set("unique", 4)
* map.set("hello", 5)
*
* let uni = map.atPrefix("uni")
* uni.get("unique") // => 4
* uni.get("unicorn") // => 1
* uni.get("hello") // => undefined
*
* let univer = map.atPrefix("univer")
* univer.get("unique") // => undefined
* univer.get("universe") // => 2
* univer.get("university") // => 3
* ```
*
* @param prefix The prefix
* @return A [[SearchableMap]] representing a mutable view of the original Map at the given prefix
*/
atPrefix (prefix: string): SearchableMap<T> {
if (!prefix.startsWith(this._prefix)) { throw new Error('Mismatched prefix') }
const [node, path] = trackDown(this._tree, prefix.slice(this._prefix.length))
if (node === undefined) {
const [parentNode, key] = last(path)
const nodeKey = Object.keys(parentNode!).find(k => k !== LEAF && k.startsWith(key))
if (nodeKey !== undefined) {
return new SearchableMap({ [nodeKey.slice(key.length)]: parentNode![nodeKey] }, prefix)
}
}
return new SearchableMap<T>(node || {}, prefix)
}
/**
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/clear
*/
clear (): void {
delete this._size
this._tree = {}
}
/**
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/delete
* @param key Key to delete
*/
delete (key: string): void {
delete this._size
return remove(this._tree, key)
}
/**
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/entries
* @return An iterator iterating through `[key, value]` entries.
*/
entries () {
return new TreeIterator<T, Entry<T>>(this, ENTRIES)
}
/**
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/forEach
* @param fn Iteration function
*/
forEach (fn: (key: string, value: T, map: SearchableMap) => void): void {
for (const [key, value] of this) {
fn(key, value, this)
}
}
/**
* Returns a key-value object of all the entries that have a key within the
* given edit distance from the search key. The keys of the returned object are
* the matching keys, while the values are two-elements arrays where the first
* element is the value associated to the key, and the second is the edit
* distance of the key to the search key.
*
* ### Usage:
*
* ```javascript
* let map = new SearchableMap()
* map.set('hello', 'world')
* map.set('hell', 'yeah')
* map.set('ciao', 'mondo')
*
* // Get all entries that match the key 'hallo' with a maximum edit distance of 2
* map.fuzzyGet('hallo', 2)
* // => { "hello": ["world", 1], "hell": ["yeah", 2] }
*
* // In the example, the "hello" key has value "world" and edit distance of 1
* // (change "e" to "a"), the key "hell" has value "yeah" and edit distance of 2
* // (change "e" to "a", delete "o")
* ```
*
* @param key The search key
* @param maxEditDistance The maximum edit distance (Levenshtein)
* @return A key-value object of the matching keys to their value and edit distance
*/
fuzzyGet (key: string, maxEditDistance: number): FuzzyResults<T> {
return fuzzySearch<T>(this._tree, key, maxEditDistance)
}
/**
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/get
* @param key Key to get
* @return Value associated to the key, or `undefined` if the key is not
* found.
*/
get (key: string): T | undefined {
const node = lookup<T>(this._tree, key)
return node !== undefined ? (node[LEAF] as T) : undefined
}
/**
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/has
* @param key Key
* @return True if the key is in the map, false otherwise
*/
has (key: string): boolean {
const node = lookup(this._tree, key)
return node !== undefined && node.hasOwnProperty(LEAF)
}
/**
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/keys
* @return An `Iterable` iterating through keys
*/
keys () {
return new TreeIterator<T, string>(this, KEYS)
}
/**
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/set
* @param key Key to set
* @param value Value to associate to the key
* @return The [[SearchableMap]] itself, to allow chaining
*/
set (key: string, value: T): SearchableMap<T> {
if (typeof key !== 'string') { throw new Error('key must be a string') }
delete this._size
const node = createPath(this._tree, key)
node[LEAF] = value
return this
}
/**
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/size
*/
get size (): number {
if (this._size) { return this._size }
/** @ignore */
this._size = 0
this.forEach(() => { this._size! += 1 })
return this._size
}
/**
* Updates the value at the given key using the provided function. The function
* is called with the current value at the key, and its return value is used as
* the new value to be set.
*
* ### Example:
*
* ```javascript
* // Increment the current value by one
* searchableMap.update('somekey', (currentValue) => currentValue == null ? 0 : currentValue + 1)
* ```
*
* @param key The key to update
* @param fn The function used to compute the new value from the current one
* @return The [[SearchableMap]] itself, to allow chaining
*/
update (key: string, fn: (value: T) => T): SearchableMap<T> {
if (typeof key !== 'string') { throw new Error('key must be a string') }
delete this._size
const node = createPath(this._tree, key)
node[LEAF] = fn(node[LEAF] as T)
return this
}
/**
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/values
* @return An `Iterable` iterating through values.
*/
values () {
return new TreeIterator<T, T>(this, VALUES)
}
/**
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/@@iterator
*/
[Symbol.iterator] () {
return this.entries()
}
/**
* Creates a [[SearchableMap]] from an `Iterable` of entries
*
* @param entries Entries to be inserted in the [[SearchableMap]]
* @return A new [[SearchableMap]] with the given entries
*/
static from<T = any> (entries: Iterable<Entry<T>> | Entry<T>[]) {
const tree = new SearchableMap()
for (const [key, value] of entries) {
tree.set(key, value)
}
return tree
}
/**
* Creates a [[SearchableMap]] from the iterable properties of a JavaScript object
*
* @param object Object of entries for the [[SearchableMap]]
* @return A new [[SearchableMap]] with the given entries
*/
static fromObject<T = any> (object: { [key: string]: T }) {
return SearchableMap.from<T>(Object.entries(object))
}
}
const trackDown = <T = any>(tree: RadixTree<T> | undefined, key: string, path: Path<T> = []): [RadixTree<T> | undefined, Path<T>] => {
if (key.length === 0 || tree == null) { return [tree, path] }
const nodeKey = Object.keys(tree).find(k => k !== LEAF && key.startsWith(k))
if (nodeKey === undefined) {
path.push([tree, key]) // performance: update in place
return trackDown(undefined, '', path)
}
path.push([tree, nodeKey]) // performance: update in place
return trackDown(tree[nodeKey] as RadixTree<T>, key.slice(nodeKey.length), path)
}
const lookup = <T = any>(tree: RadixTree<T>, key: string): RadixTree<T> | undefined => {
if (key.length === 0 || tree == null) { return tree }
const nodeKey = Object.keys(tree).find(k => k !== LEAF && key.startsWith(k))
if (nodeKey === undefined) { return undefined }
return lookup(tree[nodeKey] as RadixTree<T>, key.slice(nodeKey.length))
}
const createPath = <T = any>(tree: RadixTree<T>, key: string): RadixTree<T> => {
if (key.length === 0 || tree == null) { return tree }
const nodeKey = Object.keys(tree).find(k => k !== LEAF && key.startsWith(k))
if (nodeKey === undefined) {
const toSplit = Object.keys(tree).find(k => k !== LEAF && k.startsWith(key[0]))
if (toSplit === undefined) {
tree[key] = {}
} else {
const prefix = commonPrefix(key, toSplit)
tree[prefix] = { [toSplit.slice(prefix.length)]: tree[toSplit] }
delete tree[toSplit]
return createPath(tree[prefix] as RadixTree<T>, key.slice(prefix.length))
}
return tree[key] as RadixTree<T>
}
return createPath(tree[nodeKey] as RadixTree<T>, key.slice(nodeKey.length))
}
const commonPrefix = (a: string, b: string, i: number = 0, length: number = Math.min(a.length, b.length), prefix: string = ''): string => {
if (i >= length) { return prefix }
if (a[i] !== b[i]) { return prefix }
return commonPrefix(a, b, i + 1, length, prefix + a[i])
}
const remove = <T = any>(tree: RadixTree<T>, key: string): void => {
const [node, path] = trackDown(tree, key)
if (node === undefined) { return }
delete node[LEAF]
const keys = Object.keys(node)
if (keys.length === 0) { cleanup(path) }
if (keys.length === 1) { merge(path, keys[0], node[keys[0]]) }
}
const cleanup = <T = any>(path: Path<T>): void => {
if (path.length === 0) { return }
const [node, key] = last(path)
delete node![key]
const keys = Object.keys(node!)
if (keys.length === 0) { cleanup(path.slice(0, -1)) }
if (keys.length === 1 && keys[0] !== LEAF) { merge(path.slice(0, -1), keys[0], node![keys[0]]) }
}
const merge = <T = any>(path: Path<T>, key: string, value: T): void => {
if (path.length === 0) { return }
const [node, nodeKey] = last(path)
node![nodeKey + key] = value
delete node![nodeKey]
}
const last = <T = any>(array: T[]): T => {
return array[array.length - 1]
} | the_stack |
import { appState, dispatch } from "./AppRedux";
import { AppState } from "./AppState";
import { Constants as C } from "./Constants";
import { LoginDlg } from "./dlg/LoginDlg";
import { MainMenuDlg } from "./dlg/MainMenuDlg";
import { MessageDlg } from "./dlg/MessageDlg";
import { PrefsDlg } from "./dlg/PrefsDlg";
import { SearchContentDlg } from "./dlg/SearchContentDlg";
import { NavIntf } from "./intf/NavIntf";
import { TabDataIntf } from "./intf/TabDataIntf";
import * as J from "./JavaIntf";
import { PubSub } from "./PubSub";
import { Singletons } from "./Singletons";
import { Button } from "./widget/Button";
import { ButtonBar } from "./widget/ButtonBar";
import { Heading } from "./widget/Heading";
import { VerticalLayout } from "./widget/VerticalLayout";
let S: Singletons;
PubSub.sub(C.PUBSUB_SingletonsReady, (s: Singletons) => {
S = s;
});
export class Nav implements NavIntf {
_UID_ROWID_PREFIX: string = "row_";
login = (state: AppState): void => {
new LoginDlg(null, state).open();
}
logout = (state: AppState = null): void => {
state = appState(state);
S.user.logout(true, state);
}
signup = (state: AppState): void => {
state = appState(state);
S.user.openSignupPg(state);
}
preferences = (state: AppState): void => {
new PrefsDlg(state).open();
}
displayingRepositoryRoot = (state: AppState): boolean => {
if (!state.node) return false;
// one way to detect repository root (without path, since we don't send paths back to client) is as the only node that owns itself.
// console.log(S.util.prettyPrint(S.quanta.currentNodeData.node));
return state.node.id === state.node.ownerId;
}
displayingHome = (state: AppState): boolean => {
if (!state.node) return false;
if (state.isAnonUser) {
return state.node.id === state.anonUserLandingPageNode;
} else {
return state.node.id === state.homeNodeId;
}
}
parentVisibleToUser = (state: AppState): boolean => {
return !this.displayingHome(state);
}
upLevelResponse = (res: J.RenderNodeResponse, id: string, scrollToTop: boolean, state: AppState): void => {
if (!res || !res.node || res.errorType === J.ErrorType.AUTH) {
dispatch("Action_ShowPageMessage", (s: AppState): AppState => {
s.pageMessage = "The node above is not shared.";
return s;
});
this.delayedClearPageMessage();
} else {
S.render.renderPageFromData(res, scrollToTop, id, true, true);
}
}
delayedClearPageMessage = (): void => {
setTimeout(() => {
dispatch("Action_ClearPageMessage", (s: AppState): AppState => {
s.pageMessage = null;
return s;
});
}, 5000);
}
navOpenSelectedNode = (state: AppState): void => {
const currentSelNode: J.NodeInfo = S.quanta.getHighlightedNode(state);
if (!currentSelNode) return;
S.nav.openNodeById(null, currentSelNode.id, state);
}
navToPrev = () => {
S.nav.navToSibling(-1);
}
navToNext = () => {
S.nav.navToSibling(1);
}
navToSibling = (siblingOffset: number, state?: AppState): void => {
state = appState(state);
if (!state.node) return null;
S.util.ajax<J.RenderNodeRequest, J.RenderNodeResponse>("renderNode", {
nodeId: state.node.id,
upLevel: false,
siblingOffset: siblingOffset,
renderParentIfLeaf: true,
offset: 0,
goToLastPage: false,
forceIPFSRefresh: false,
singleNode: false
},
// success callback
(res: J.RenderNodeResponse) => {
this.upLevelResponse(res, null, true, state);
},
// fail callback
(res: string) => {
S.quanta.clearLastNodeIds();
this.navHome(state);
});
}
navUpLevelClick = async (evt: Event = null, id: string = null): Promise<void> => {
// for state management, especially for scrolling, we need to run the node click on the node
// before upLeveling from it.
await this.clickNodeRow(evt, id);
this.navUpLevel(false);
}
navUpLevel = (processingDelete: boolean): void => {
const state = appState();
if (!state.node) return null;
if (!this.parentVisibleToUser(state)) {
S.util.showMessage("The parent of this node isn't shared to you.", "Warning");
// Already at root. Can't go up.
return;
}
S.util.ajax<J.RenderNodeRequest, J.RenderNodeResponse>("renderNode", {
nodeId: state.node.id,
upLevel: true,
siblingOffset: 0,
renderParentIfLeaf: false,
offset: 0,
goToLastPage: false,
forceIPFSRefresh: false,
singleNode: false
},
// success callback
(res: J.RenderNodeResponse) => {
if (processingDelete) {
S.quanta.refresh(state);
}
else {
this.upLevelResponse(res, state.node.id, false, state);
}
},
// fail callback
(res: string) => {
S.quanta.clearLastNodeIds();
this.navHome(state);
}
);
}
/*
* turn of row selection DOM element of whatever row is currently selected
*/
getSelectedDomElement = (state: AppState): HTMLElement => {
var currentSelNode = S.quanta.getHighlightedNode(state);
if (currentSelNode) {
/* get node by node identifier */
const node: J.NodeInfo = state.idToNodeMap.get(currentSelNode.id);
if (node) {
// console.log("found highlighted node.id=" + node.id);
/* now make CSS id from node */
const nodeId: string = this._UID_ROWID_PREFIX + node.id;
// console.log("looking up using element id: "+nodeId);
return S.util.domElm(nodeId);
}
}
return null;
}
/* NOTE: Elements that have this as an onClick method must have the nodeId
on an attribute of the element */
clickNodeRow = async (evt: Event, id: string, state?: AppState): Promise<void> => {
return new Promise<void>(async (resolve, reject) => {
id = S.util.allowIdFromEvent(evt, id);
state = appState(state);
/* First check if this node is already highlighted and if so just return */
const hltNode = S.quanta.getHighlightedNode();
if (hltNode && hltNode.id === id) {
resolve();
return;
}
const node: J.NodeInfo = state.idToNodeMap.get(id);
if (!node) {
reject();
// console.log("idToNodeMap: "+S.util.prettyPrint(state.idToNodeMap));
throw new Error("node not found in idToNodeMap: " + id);
}
/*
* sets which node is selected on this page (i.e. parent node of this page being the 'key')
*/
S.quanta.highlightNode(node, false, state);
// todo-1: without this timeout checkboxes on main tab don't work reliably. Need their state stored in global state to fix it
// in a good way.
setTimeout(() => {
S.quanta.tempDisableAutoScroll();
dispatch("Action_FastRefresh", (s: AppState): AppState => {
return s;
});
// console.log("nodeClickRow. Focusing Main tab");
S.util.focusId(C.TAB_MAIN);
resolve();
}, 100);
});
}
openContentNode = (nodePathOrId: string, state: AppState = null): void => {
state = appState(state);
// console.log("openContentNode(): " + nodePathOrId);
S.util.ajax<J.RenderNodeRequest, J.RenderNodeResponse>("renderNode", {
nodeId: nodePathOrId,
upLevel: false,
siblingOffset: 0,
renderParentIfLeaf: null,
offset: 0,
goToLastPage: false,
forceIPFSRefresh: false,
singleNode: false
}, (res) => {
this.navPageNodeResponse(res, state);
},
// fail callback
(res: string) => {
S.quanta.clearLastNodeIds();
this.navHome(state);
});
}
openNodeById = (evt: Event, id: string, state: AppState): void => {
id = S.util.allowIdFromEvent(evt, id);
state = appState(state);
const node: J.NodeInfo = state.idToNodeMap.get(id);
S.quanta.highlightNode(node, false, state);
if (!node) {
S.util.showMessage("Unknown nodeId in openNodeByUid: " + id, "Warning");
} else {
S.view.refreshTree(node.id, true, true, null, false, true, true, state);
}
}
setNodeSel = (selected: boolean, id: string, state: AppState): void => {
if (!id) return;
state = appState(state);
if (selected) {
state.selectedNodes.add(id);
} else {
state.selectedNodes.delete(id);
}
}
navPageNodeResponse = (res: J.RenderNodeResponse, state: AppState): void => {
S.render.renderPageFromData(res, true, null, true, true);
S.quanta.selectTab(C.TAB_MAIN);
}
geoLocation = (state: AppState): void => {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((location) => {
// todo-1: make this string a configurable property template
let googleUrl = "https://www.google.com/maps/search/?api=1&query=" + location.coords.latitude + "," + location.coords.longitude;
new MessageDlg("Your current location...", "GEO Location", null,
new VerticalLayout([
new Heading(3, "Lat/Lon: " + location.coords.latitude + "," + location.coords.longitude),
new Heading(5, "Accuracy: +/- " + location.coords.accuracy + " meters (" + (location.coords.accuracy * 0.000621371).toFixed(1) + " miles)"),
new ButtonBar([
new Button("Show on Google Maps", () => {
window.open(googleUrl, "_blank");
}),
new Button("Copy Google Link to Clipboard", () => {
S.util.copyToClipboard(googleUrl);
S.util.flashMessage("Copied to Clipboard: " + googleUrl, "Clipboard", true);
})])
]), false, 0, state
).open();
});
}
else {
new MessageDlg("GeoLocation is not available on this device.", "Message", null, null, false, 0, state).open();
}
}
showMainMenu = (state: AppState): void => {
S.quanta.mainMenu = new MainMenuDlg();
S.quanta.mainMenu.open();
}
navHome = (state: AppState = null): void => {
state = appState(state);
S.view.scrollAllTop(state);
// console.log("navHome()");
if (state.isAnonUser) {
S.quanta.loadAnonPageHome(null);
} else {
// console.log("renderNode (navHome): " + state.homeNodeId);
S.util.ajax<J.RenderNodeRequest, J.RenderNodeResponse>("renderNode", {
nodeId: state.homeNodeId,
upLevel: false,
siblingOffset: 0,
renderParentIfLeaf: null,
offset: 0,
goToLastPage: false,
forceIPFSRefresh: false,
singleNode: false
}, (res) => { this.navPageNodeResponse(res, state); },
// fail callback
(res: string) => {
S.quanta.clearLastNodeIds();
// NOPE! This would be recursive!
// this.navHome(state);
});
}
}
navPublicHome = (state: AppState): void => {
S.quanta.loadAnonPageHome(null);
}
runSearch = (evt: Event): void => {
let id = S.util.allowIdFromEvent(evt, null);
const state = appState();
this.clickNodeRow(null, id);
setTimeout(() => {
new SearchContentDlg(state).open();
}, 500);
}
runTimeline = (evt: Event): void => {
let id = S.util.allowIdFromEvent(evt, null);
const state = appState();
this.clickNodeRow(null, id);
setTimeout(() => {
const node: J.NodeInfo = state.idToNodeMap.get(id);
if (!node) {
return;
}
S.srch.timeline(node, "mtm", state, null, "Rev-chron by Modify Time", 0, true);
}, 500);
}
openNodeFeed = (evt: Event, id: string): void => {
id = S.util.allowIdFromEvent(evt, id);
const state = appState();
let node: J.NodeInfo = state.idToNodeMap.get(id);
// Try to get node from local memory...
if (node) {
setTimeout(() => {
let feedData = S.quanta.getTabDataById(state, C.TAB_FEED);
if (feedData) {
feedData.props.searchTextState.setValue("");
}
this.messages({
feedFilterFriends: false,
feedFilterToMe: false,
feedFilterFromMe: false,
feedFilterToPublic: true,
feedFilterLocalServer: true,
feedFilterRootNode: node,
feedResults: null
});
}, 500);
}
// if node not in local memory, then we have to get it from the server first...
else {
S.util.ajax<J.RenderNodeRequest, J.RenderNodeResponse>("renderNode", {
nodeId: id,
upLevel: false,
siblingOffset: 0,
renderParentIfLeaf: false,
offset: 0,
goToLastPage: false,
forceIPFSRefresh: false,
singleNode: true
},
(res: J.RenderNodeResponse) => {
if (!res.node) return;
S.quanta.updateNodeMap(res.node, state);
let feedData = S.quanta.getTabDataById(state, C.TAB_FEED);
if (feedData) {
feedData.props.searchTextState.setValue("");
}
this.messages({
feedFilterFriends: false,
feedFilterToMe: false,
feedFilterFromMe: false,
feedFilterToPublic: true,
feedFilterLocalServer: true,
feedFilterRootNode: res.node,
feedResults: null
});
}, // fail callback
(res: string) => {
console.log("failed to refresh node: " + res);
});
}
}
closeFullScreenViewer = (appState: AppState): void => {
dispatch("Action_CloseFullScreenViewer", (s: AppState): AppState => {
s.fullScreenViewId = null;
s.fullScreenGraphId = null;
s.fullScreenCalendarId = null;
s.fullScreenCalendarAllNodes = false;
return s;
});
}
prevFullScreenImgViewer = (appState: AppState): void => {
const prevNode: J.NodeInfo = this.getAdjacentNode("prev", appState);
if (prevNode) {
dispatch("Action_PrevFullScreenImgViewer", (s: AppState): AppState => {
s.fullScreenViewId = prevNode.id;
return s;
});
}
}
nextFullScreenImgViewer = (appState: AppState): void => {
const nextNode: J.NodeInfo = this.getAdjacentNode("next", appState);
if (nextNode) {
dispatch("Action_NextFullScreenImgViewer", (s: AppState): AppState => {
s.fullScreenViewId = nextNode.id;
return s;
});
}
}
// todo-2: need to make view.scrollRelativeToNode use this function instead of embedding all the same logic.
getAdjacentNode = (dir: string, state: AppState): J.NodeInfo => {
let newNode: J.NodeInfo = null;
// First detect if page root node is selected, before doing a child search
if (state.fullScreenViewId === state.node.id) {
return null;
}
else if (state.node.children && state.node.children.length > 0) {
let prevChild = null;
let nodeFound = false;
state.node.children.some((child: J.NodeInfo) => {
let ret = false;
const isAnAccountNode = child.ownerId && child.id === child.ownerId;
if (S.props.hasBinary(child) && !isAnAccountNode) {
if (nodeFound && dir === "next") {
ret = true;
newNode = child;
}
if (child.id === state.fullScreenViewId) {
if (dir === "prev") {
if (prevChild) {
ret = true;
newNode = prevChild;
}
}
nodeFound = true;
}
prevChild = child;
}
// NOTE: returning true stops the iteration.
return ret;
});
}
return newNode;
}
messages = (props: Object): void => {
let feedData: TabDataIntf = S.quanta.getTabDataById(null, C.TAB_FEED);
if (!feedData) {
return;
}
dispatch("Action_SelectTab", (s: AppState): AppState => {
s.guiReady = true;
S.quanta.tabChanging(s.activeTab, C.TAB_FEED, s);
s.activeTab = S.quanta.activeTab = C.TAB_FEED;
// merge props prarmeter into the feed data props.
feedData.props = { ...feedData.props, ...props };
return s;
});
setTimeout(S.srch.refreshFeed, 10);
}
} | the_stack |
describe('datepicker: <uif-datepicker />', () => {
beforeEach(() => {
angular.mock.module('officeuifabric.core');
angular.mock.module('officeuifabric.components.datepicker');
});
it('should be able to configure months', inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
let $scope: any = $rootScope.$new();
let datepicker: JQuery = $compile('<uif-datepicker ng-model="value"></uif-datepicker>')($scope);
$scope.$digest();
datepicker = jQuery(datepicker[0]);
// verify default months
let monthsContainer: JQuery = datepicker.find('.ms-DatePicker-optionGrid .ms-DatePicker-monthOption');
expect(monthsContainer.length).toBe(12, 'Default month configuration');
// verify valid set of months
$scope = $rootScope.$new();
datepicker = $compile('<uif-datepicker ng-model="value" ' +
'uif-months="Jan,Feb,Maa,Apr,Mei,Jun,Jul,Aug,Sep,Okt,Nov,Dec"></uif-datepicker>')($scope);
$scope.$digest();
datepicker = jQuery(datepicker[0]);
monthsContainer = datepicker.find('.ms-DatePicker-optionGrid .ms-DatePicker-monthOption');
expect(monthsContainer.length).toBe(12, 'Custom months configuration');
expect(monthsContainer.get(2).innerHTML).toBe('Maa');
// verify valid set of months
$scope = $rootScope.$new();
let exception: boolean = false;
try {
$compile('<uif-datepicker ng-model="value" uif-months="Jan,Feb,Maa,Apr,Mei,Jun,Jul,Aug,Sep,Okt,Nov"></uif-datepicker>')($scope);
$scope.$digest();
} catch (e) {
exception = true;
}
expect(exception).toBe(true, 'Invalid list of months should have failed.');
}));
it('should be able to use the custom year selector', inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
let $scope: any = $rootScope.$new();
$scope.value = new Date(2015, 2, 1);
let datepicker: JQuery = $compile('<uif-datepicker ng-model="value"></uif-datepicker>')($scope);
$scope.$digest();
datepicker = jQuery(datepicker[0]);
datepicker.appendTo(document.body);
let prevYear: JQuery = datepicker.find('.js-prevYear');
let nextYear: JQuery = datepicker.find('.js-nextYear');
let yearPickerSwitcher: JQuery = datepicker.find('.js-showYearPicker');
expect(yearPickerSwitcher.length).toBe(1);
yearPickerSwitcher.click();
expect(datepicker).toHaveClass('is-pickingYears');
let yearOptions: JQuery = datepicker.find('.ms-DatePicker-yearOption');
expect(yearOptions.length).toBe(11, 'There should be 11 year options');
let highlightedYear: JQuery = datepicker.find('.ms-DatePicker-yearOption.is-highlighted');
expect(highlightedYear.length).toBe(1, 'There should be one active year');
expect(highlightedYear.html()).toBe('2015', 'Highlighted year should be 2015');
prevYear.click();
prevYear.click();
highlightedYear = datepicker.find('.ms-DatePicker-yearOption.is-highlighted');
expect(highlightedYear.html()).toBe('2013', 'Highlighted year should be 2015');
nextYear.click();
highlightedYear = datepicker.find('.ms-DatePicker-yearOption.is-highlighted');
expect(highlightedYear.html()).toBe('2014', 'Highlighted year should be 2015');
let year2010: JQuery = datepicker.find('.js-changeDate.ms-DatePicker-yearOption[data-year=2010]');
year2010.click();
expect(year2010).toHaveClass('is-highlighted');
}));
it('should be able to use the custom month selector', inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
let $scope: any = $rootScope.$new();
// important to take the first of the month, as previously this test failed due to time zone issues
$scope.value = new Date(2015, 2, 1);
let datepicker: JQuery = $compile('<uif-datepicker ng-model="value"></uif-datepicker>')($scope);
$scope.$digest();
datepicker = jQuery(datepicker[0]);
// add the element to the DOM, otherwise click event is not registered
datepicker.appendTo(document.body);
let prevMonth: JQuery = datepicker.find('.js-prevMonth');
let nextMonth: JQuery = datepicker.find('.js-nextMonth');
let monthPickerSwitcher: JQuery = datepicker.find('.js-showMonthPicker');
expect(monthPickerSwitcher.length).toBe(1);
monthPickerSwitcher.click();
expect(datepicker).toHaveClass('is-pickingMonths');
let highlightedMonth: JQuery = datepicker.find('.ms-DatePicker-monthOption.is-highlighted');
// months are zero based => 02 is March
expect(highlightedMonth.html().trim()).toBe('Mar', 'Selected month in month picker should be Mar');
let juneMonth: JQuery = datepicker.find('.js-changeDate.ms-DatePicker-monthOption[data-month=5]');
let julyMonth: JQuery = datepicker.find('.js-changeDate.ms-DatePicker-monthOption[data-month=6]');
let mayMonth: JQuery = datepicker.find('.js-changeDate.ms-DatePicker-monthOption[data-month=4]');
juneMonth.click();
expect(mayMonth).not.toHaveClass('is-highlighted');
expect(julyMonth).not.toHaveClass('is-highlighted');
expect(juneMonth).toHaveClass('is-highlighted');
nextMonth.click();
expect(juneMonth).not.toHaveClass('is-highlighted');
expect(julyMonth).toHaveClass('is-highlighted');
prevMonth.click();
prevMonth.click();
expect(juneMonth).not.toHaveClass('is-highlighted');
expect(mayMonth).toHaveClass('is-highlighted');
expect(julyMonth).not.toHaveClass('is-highlighted');
}));
it('should be able to specify custom date format', inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
let $scope: any = $rootScope.$new();
$scope.value = '';
let datepicker: JQuery = $compile('<uif-datepicker ng-model="value" placeholder="TEST"></uif-datepicker>')($scope);
$scope.$digest();
datepicker = jQuery(datepicker[0]);
let date: Date = new Date('2015-01-02');
$scope.value = date;
$scope.$digest();
let textboxValue: string = jQuery(datepicker[0]).find('.ms-TextField-field').val();
let monthNames: string[] =
['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
let formattedValue: string = `${date.getDate()} ${monthNames[date.getMonth()]}, ${date.getFullYear()}`;
expect(textboxValue).toBe(formattedValue, 'Default date format');
$scope = $rootScope.$new();
datepicker = $compile('<uif-datepicker ng-model="value" placeholder="TEST" uif-date-format="mmmm d, yyyy"></uif-datepicker>')
($scope);
$scope.$digest();
datepicker = jQuery(datepicker[0]);
$scope.value = date;
$scope.$digest();
textboxValue = jQuery(datepicker[0]).find('.ms-TextField-field').val();
let newFormattedValue: string = `${monthNames[date.getMonth()]} ${date.getDate()}, ${date.getFullYear()}`;
expect(textboxValue).toBe(newFormattedValue, 'Custom date format');
}));
it('should be able to click next and prev decade', inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
let $scope: any = $rootScope.$new();
$scope.value = new Date(2015, 1, 1);
let datepicker: JQuery = $compile('<uif-datepicker ng-model="value" placeholder="TEST"></uif-datepicker>')($scope);
$scope.$digest();
datepicker = jQuery(datepicker[0]);
datepicker.appendTo(document.body);
let yearPickerSwitcher: JQuery = datepicker.find('.js-showYearPicker');
let prevDecade: JQuery = datepicker.find('.js-prevDecade');
expect(prevDecade.length).toBe(1);
let nextDecade: JQuery = datepicker.find('.js-nextDecade');
expect(nextDecade.length).toBe(1);
let currentDecade: JQuery = datepicker.find('.ms-DatePicker-currentDecade');
yearPickerSwitcher.click();
expect(currentDecade.html()).toBe('2005 - 2015');
nextDecade.click();
expect(currentDecade.html()).toBe('2015 - 2025');
prevDecade.click();
prevDecade.click();
expect(currentDecade.html()).toBe('1995 - 2005');
}));
it('should be able to set and retrieve a value', inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
let $scope: any = $rootScope.$new();
$scope.value = '';
let datepicker: JQuery = $compile('<uif-datepicker ng-model="value" placeholder="TEST"></uif-datepicker>')($scope);
$scope.$digest();
datepicker = jQuery(datepicker[0]);
expect($scope.value).toBe('');
let goToday: JQuery = datepicker.find('.ms-DatePicker-goToday');
expect(goToday.length).toBe(1, 'Go to today should be present');
goToday.triggerHandler('click');
$scope.$digest();
// we are using UTC Dates here, as otherwise this test will fail in certain timezones.
// $scope.value is e.g. "2015-02-01", which is February 1st. However, left of UTC new Date("2015-02-01").getDate() == 31 (January).
// that's why we take the UTC Date of $scope.value
// with new Date() this is not necessary as that is always the local date.
expect(new Date($scope.value).getUTCDate()).toBe(new Date().getDate(), 'Day Today');
expect(new Date($scope.value).getUTCMonth()).toBe(new Date().getMonth(), 'Month Today');
expect(new Date($scope.value).getUTCFullYear()).toBe(new Date().getFullYear(), 'Year Today');
let date: Date = new Date('2015-01-02');
$scope.value = date;
$scope.$digest();
let textboxValue: string = jQuery(datepicker[0]).find('.ms-TextField-field').val();
let monthNames: string[] =
['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
let formattedValue: string = `${date.getDate()} ${monthNames[date.getMonth()]}, ${date.getFullYear()}`;
expect(textboxValue).toBe(formattedValue);
}));
it('should be able to set placeholder', inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
let $scope: any = $rootScope.$new();
let datepicker: JQuery = $compile('<uif-datepicker ng-model="value"></uif-datepicker>')($scope);
$scope.$digest();
// verify default value
let input: JQuery = jQuery(datepicker[0]).find('.ms-TextField-field');
expect(input.attr('Placeholder')).toBe('Select a date');
datepicker = $compile('<uif-datepicker ng-model="value" placeholder="Please, find a date"></uif-datepicker>')($scope);
$scope.$digest();
// verify custom value
input = jQuery(datepicker[0]).find('.ms-TextField-field');
expect(input.attr('Placeholder')).toBe('Please, find a date');
}));
it('should be able to disable & enable as needed', inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
let $scope: any = $rootScope.$new();
$scope.disabled = false;
let datepicker: JQuery = $compile('<uif-datepicker ng-model="value" ng-disabled="disabled"></uif-datepicker>')($scope);
$scope.$digest();
// initially should not be disabled
let input: JQuery = jQuery(datepicker[0]).find('.ms-TextField-field');
expect(input.attr('disabled')).toBe(undefined, 'Input should not be disabled');
$scope.disabled = true;
$scope.$digest();
expect(input.attr('disabled')).toBe('disabled', 'Input should be disabled');
}));
it('should be initially be disabled', inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
let $scope: any = $rootScope.$new();
let datepicker: JQuery = $compile('<uif-datepicker ng-model="value" disabled="disabled"></uif-datepicker>')($scope);
$scope.$digest();
// initially should be disabled
let input: JQuery = jQuery(datepicker[0]).find('.ms-TextField-field');
expect(input.attr('disabled')).toBe('disabled', 'Input should be disabled');
}));
it('should not set $dirty on ngModel initially', inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
let $scope: any = $rootScope.$new();
$scope.value = new Date(2016, 3, 2);
let datepicker: JQuery = $compile('<uif-datepicker ng-model="value"></uif-datepicker>')($scope);
$scope.$digest();
// initially should not be disabled
let ngModel: angular.INgModelController = angular.element(datepicker).controller('ngModel');
expect(ngModel.$dirty).toBeFalsy();
}));
it('should not set $touched on ngModel initially', inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
let $scope: any = $rootScope.$new();
$scope.value = new Date(2016, 3, 2);
let datepicker: JQuery = $compile('<uif-datepicker ng-model="value"></uif-datepicker>')($scope);
$scope.$digest();
// initially should not be disabled
let ngModel: angular.INgModelController = angular.element(datepicker).controller('ngModel');
expect(ngModel.$touched).toBeFalsy();
}));
it('should set $dirty on ngModel when date changed', inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
let $scope: any = $rootScope.$new();
$scope.value = new Date(2016, 3, 2);
let datepicker: JQuery = $compile('<uif-datepicker ng-model="value"></uif-datepicker>')($scope);
$scope.$digest();
datepicker = jQuery(datepicker[0]);
let goToday: JQuery = datepicker.find('.ms-DatePicker-goToday');
expect(goToday.length).toBe(1, 'Go to today should be present');
goToday.triggerHandler('click');
$scope.$digest();
expect(new Date($scope.value).getUTCDate()).toBe(new Date().getDate(), 'Day Today');
expect(new Date($scope.value).getUTCMonth()).toBe(new Date().getMonth(), 'Month Today');
expect(new Date($scope.value).getUTCFullYear()).toBe(new Date().getFullYear(), 'Year Today');
let ngModel: angular.INgModelController = angular.element(datepicker).controller('ngModel');
expect(ngModel.$dirty).toBeTruthy();
}));
it('should set $touched on ngModel when datepicker opened', inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
let $scope: any = $rootScope.$new();
$scope.value = new Date(2016, 3, 2);
let datepicker: JQuery = $compile('<uif-datepicker ng-model="value"></uif-datepicker>')($scope);
$scope.$digest();
datepicker = jQuery(datepicker[0]);
let textField: JQuery = datepicker.find('.ms-TextField-field');
expect(textField.length).toBe(1, 'Input should be present');
textField.triggerHandler('click');
$scope.$digest();
let ngModel: angular.INgModelController = angular.element(datepicker).controller('ngModel');
expect(ngModel.$touched).toBeTruthy();
}));
it('should handle setting null for value', inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
let $scope: any = $rootScope.$new();
$scope.value = null;
let datepicker: JQuery = $compile('<uif-datepicker ng-model="value" placeholder="TEST"></uif-datepicker>')($scope);
$scope.$digest();
datepicker = jQuery(datepicker[0]);
expect($scope.value).toBeNull();
}));
it('should handle setting undefined for value', inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
let $scope: any = $rootScope.$new();
$scope.value = undefined;
let datepicker: JQuery = $compile('<uif-datepicker ng-model="value" placeholder="TEST"></uif-datepicker>')($scope);
$scope.$digest();
datepicker = jQuery(datepicker[0]);
expect($scope.value).toBeUndefined();
}));
it('should handle setting empty string for value', inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
let $scope: any = $rootScope.$new();
$scope.value = '';
let datepicker: JQuery = $compile('<uif-datepicker ng-model="value" placeholder="TEST"></uif-datepicker>')($scope);
$scope.$digest();
datepicker = jQuery(datepicker[0]);
expect($scope.value).toBe('');
}));
}); | the_stack |
import { Events } from 'vue-iclient/src/common/_types/event/Events';
import municipalCenterData from './config/MunicipalCenter.json';
import provincialCenterData from './config/ProvinceCenter.json';
import 'vue-iclient/static/libs/geostats/geostats';
import 'vue-iclient/static/libs/json-sql/jsonsql';
import isNumber from 'lodash.isnumber';
import canvg from 'canvg';
import WebMapService from '../_utils/WebMapService';
import { getColorWithOpacity } from '../_utils/util';
import { getProjection, registerProjection } from '../../common/_utils/epsg-define';
import { coordEach } from '@turf/meta';
// 迁徙图最大支持要素数量
const MAX_MIGRATION_ANIMATION_COUNT = 1000;
export default abstract class WebMapBase extends Events {
map: any;
mapId: string | number | Object;
webMapInfo: any;
mapOptions: any;
serverUrl: string;
accessToken: string;
accessKey: string;
tiandituKey: string;
withCredentials: boolean;
proxy: string | boolean;
target: string;
excludePortalProxyUrl: boolean;
isSuperMapOnline: boolean;
zoom: number;
mapParams: { title?: string; description?: string };
baseProjection: string;
ignoreBaseProjection: boolean;
on: any;
echartslayer: any = [];
eventTypes: any;
triggerEvent: any;
protected webMapService: WebMapService;
protected _layers: any = [];
protected _svgDiv: HTMLElement;
protected _taskID: Date;
protected layerAdded: number;
protected expectLayerLen: number;
constructor(id, options?, mapOptions?) {
super();
this.serverUrl = options.serverUrl || 'https://www.supermapol.com';
this.accessToken = options.accessToken;
this.accessKey = options.accessKey;
this.tiandituKey = options.tiandituKey || '';
this.withCredentials = options.withCredentials || false;
this.proxy = options.proxy;
this.target = options.target || 'map';
this.excludePortalProxyUrl = options.excludePortalProxyUrl;
this.isSuperMapOnline = options.isSuperMapOnline;
this.ignoreBaseProjection = options.ignoreBaseProjection;
this.echartslayer = [];
this.webMapService = new WebMapService(id, options);
this.mapOptions = mapOptions;
this.eventTypes = [
'getmapinfofailed',
'crsnotsupport',
'getlayerdatasourcefailed',
'addlayerssucceeded',
'notsupportmvt',
'notsupportbaidumap',
'projectionIsNotMatch',
'beforeremovemap'
];
this.mapId = id;
}
abstract _initWebMap(): void;
abstract _getMapInfo(data, _taskID?);
abstract _createMap();
// TODO 重构子类 webmap layer 添加逻辑,只重写具体添加某个layer的方法,基类实现 initxxxx
abstract _initBaseLayer(mapInfo);
abstract _initOverlayLayer(layer, features?);
abstract _addLayerSucceeded();
abstract _unproject(point: [number, number]): [number, number];
abstract cleanWebMap();
public echartsLayerResize(): void {
this.echartslayer.forEach(echartslayer => {
echartslayer.chart.resize();
});
}
public setMapId(mapId: string | number): void {
if (typeof mapId === 'string' || typeof mapId === 'number') {
this.mapId = mapId;
this.webMapInfo = null;
} else if (mapId !== null && typeof mapId === 'object') {
this.webMapInfo = mapId;
}
this.webMapService.setMapId(mapId);
setTimeout(() => {
this._initWebMap();
}, 0);
}
public setServerUrl(serverUrl: string): void {
this.serverUrl = serverUrl;
this.webMapService.setServerUrl(serverUrl);
}
public setWithCredentials(withCredentials) {
this.withCredentials = withCredentials;
this.webMapService.setWithCredentials(withCredentials);
}
public setProxy(proxy) {
this.proxy = proxy;
this.webMapService.setProxy(proxy);
}
public setZoom(zoom) {
if (this.map) {
this.mapOptions.zoom = zoom;
if (zoom !== +this.map.getZoom().toFixed(2)) {
(zoom || zoom === 0) && this.map.setZoom(zoom, { from: 'setZoom' });
}
}
}
public setMaxBounds(maxBounds): void {
if (this.map) {
this.mapOptions.maxBounds = maxBounds;
maxBounds && this.map.setMaxBounds(maxBounds);
}
}
public setMinZoom(minZoom): void {
if (this.map) {
this.mapOptions.minZoom = minZoom;
(minZoom || minZoom === 0) && this.map.setMinZoom(minZoom);
}
}
public setMaxZoom(maxZoom): void {
if (this.map) {
this.mapOptions.maxZoom = maxZoom;
(maxZoom || maxZoom === 0) && this.map.setMaxZoom(maxZoom);
}
}
protected initWebMap() {
this.cleanWebMap();
this.serverUrl = this.serverUrl && this.webMapService.handleServerUrl(this.serverUrl);
if (this.webMapInfo) {
// 传入是webmap对象
const mapInfo = this.webMapInfo;
mapInfo.mapParams = {
title: this.webMapInfo.title,
description: this.webMapInfo.description
};
this.mapParams = mapInfo.mapParams;
this._getMapInfo(mapInfo);
return;
} else if (!this.mapId || !this.serverUrl) {
this._createMap();
return;
}
this._taskID = new Date();
this.getMapInfo(this._taskID);
}
protected getMapInfo(_taskID) {
this.serverUrl = this.serverUrl && this.webMapService.handleServerUrl(this.serverUrl);
this.webMapService
.getMapInfo()
.then(
(mapInfo: any) => {
if (this._taskID !== _taskID) {
return;
}
// 存储地图的名称以及描述等信息,返回给用户
this.mapParams = mapInfo.mapParams;
this._getMapInfo(mapInfo, _taskID);
},
error => {
throw error;
}
)
.catch(error => {
this.triggerEvent('getmapinfofailed', { error });
console.log(error);
});
}
protected getBaseLayerType(layerInfo) {
let layerType = layerInfo.layerType; // 底图和rest地图兼容
if (
layerType.indexOf('TIANDITU_VEC') > -1 ||
layerType.indexOf('TIANDITU_IMG') > -1 ||
layerType.indexOf('TIANDITU_TER') > -1
) {
layerType = 'TIANDITU';
}
switch (layerType) {
case 'TILE':
case 'SUPERMAP_REST':
return 'TILE';
case 'CLOUD':
case 'CLOUD_BLACK':
return 'CLOUD';
case 'OSM':
case 'JAPAN_ORT':
case 'JAPAN_RELIEF':
case 'JAPAN_PALE':
case 'JAPAN_STD':
case 'GOOGLE_CN':
case 'GOOGLE':
return 'XYZ';
default:
return layerType;
}
}
protected getMapurls(mapurl: { CLOUD?: string; CLOUD_BLACK?: string; OSM?: string } = {}) {
const mapUrls = {
CLOUD: mapurl.CLOUD || 'http://t2.dituhui.com/FileService/image?map=quanguo&type=web&x={x}&y={y}&z={z}',
CLOUD_BLACK: mapurl.CLOUD_BLACK || 'http://t3.dituhui.com/MapService/getGdp?x={x}&y={y}&z={z}',
OSM: mapurl.OSM || 'https://{a-c}.tile.openstreetmap.org/{z}/{x}/{y}.png',
GOOGLE:
'https://www.google.cn/maps/vt/pb=!1m4!1m3!1i{z}!2i{x}!3i{y}!2m3!1e0!2sm!3i380072576!3m8!2szh-CN!3scn!5e1105!12m4!1e68!2m2!1sset!2sRoadmap!4e0!5m1!1e0',
GOOGLE_CN: 'https://mt{0-3}.google.cn/vt/lyrs=m&hl=zh-CN&gl=cn&x={x}&y={y}&z={z}',
JAPAN_STD: 'https://cyberjapandata.gsi.go.jp/xyz/std/{z}/{x}/{y}.png',
JAPAN_PALE: 'https://cyberjapandata.gsi.go.jp/xyz/pale/{z}/{x}/{y}.png',
JAPAN_RELIEF: 'https://cyberjapandata.gsi.go.jp/xyz/relief/{z}/{x}/{y}.png',
JAPAN_ORT: 'https://cyberjapandata.gsi.go.jp/xyz/ort/{z}/{x}/{y}.jpg'
};
return mapUrls;
}
protected getLayerFeatures(layer, _taskID, type) {
const getLayerFunc = this.webMapService.getLayerFeatures(type, layer, this.baseProjection);
getLayerFunc &&
getLayerFunc
.then(
async result => {
if (this.mapId && this._taskID !== _taskID) {
return;
}
if (result && layer.projection) {
if (!getProjection(layer.projection)) {
const epsgWKT = await this.webMapService.getEpsgCodeInfo(
layer.projection.split(':')[1],
this.serverUrl
);
if (epsgWKT) {
registerProjection(layer.projection, epsgWKT);
}
}
}
this._getLayerFeaturesSucceeded(result, layer);
},
error => {
throw new Error(error);
}
)
.catch(error => {
this._addLayerSucceeded();
this.triggerEvent('getlayerdatasourcefailed', { error, layer, map: this.map });
console.log(error);
});
}
protected setFeatureInfo(feature: any): any {
let featureInfo;
const info = feature.dv_v5_markerInfo;
if (info && info.dataViz_title) {
// 有featureInfo信息就不需要再添加
featureInfo = info;
} else {
// featureInfo = this.getDefaultAttribute();
return info;
}
const properties = feature.properties;
for (const key in featureInfo) {
if (properties[key]) {
featureInfo[key] = properties[key];
delete properties[key];
}
}
return featureInfo;
}
protected getRankStyleGroup(themeField, features, parameters) {
// 找出所有的单值
const values = [];
let segements = [];
const style = parameters.style;
const themeSetting = parameters.themeSetting;
const segmentMethod = themeSetting.segmentMethod;
const segmentCount = themeSetting.segmentCount;
const customSettings = themeSetting.customSettings;
const minR = parameters.themeSetting.minRadius;
const maxR = parameters.themeSetting.maxRadius;
const colors = themeSetting.colors;
const fillColor = style.fillColor;
features.forEach(feature => {
const properties = feature.properties;
const value = properties[themeField];
// 过滤掉空值和非数值
if (value == null || value === '' || !isNumber(+value)) {
return;
}
values.push(Number(value));
});
try {
segements = SuperMap.ArrayStatistic.getArraySegments(values, segmentMethod, segmentCount);
} catch (error) {
console.log(error);
}
// 处理自定义 分段
for (let i = 0; i < segmentCount; i++) {
if (i in customSettings) {
const startValue = customSettings[i].segment.start;
const endValue = customSettings[i].segment.end;
startValue != null && (segements[i] = startValue);
endValue != null && (segements[i + 1] = endValue);
}
}
// 生成styleGroup
const styleGroup = [];
if (segements && segements.length) {
const len = segements.length;
const incrementR = (maxR - minR) / (len - 1); // 半径增量
let start;
let end;
let radius = Number(((maxR + minR) / 2).toFixed(2));
let color = '';
const rangeColors = colors ? SuperMap.ColorsPickerUtil.getGradientColors(colors, len, 'RANGE') : [];
for (let i = 0; i < len - 1; i++) {
// 处理radius
start = Number(segements[i].toFixed(2));
end = Number(segements[i + 1].toFixed(2));
// 这里特殊处理以下分段值相同的情况(即所有字段值相同)
radius = start === end ? radius : minR + Math.round(incrementR * i);
// 最后一个分段时将end+0.01,避免取不到最大值
end = i === len - 2 ? end + 0.01 : end;
// 处理自定义 半径
radius = customSettings[i] && customSettings[i].radius ? customSettings[i].radius : radius;
style.radius = radius;
// 处理颜色
if (colors && colors.length > 0) {
color = customSettings[i] && customSettings[i].color ? customSettings[i].color : rangeColors[i] || fillColor;
style.fillColor = color;
}
styleGroup.push({ radius, color, start, end, style });
}
return styleGroup;
} else {
return false;
}
}
protected createRankStyleSource(parameters, features) {
const themeSetting = parameters.themeSetting;
const themeField = themeSetting.themeField;
const styleGroups = this.getRankStyleGroup(themeField, features, parameters);
// @ts-ignore
return styleGroups ? { parameters, styleGroups } : false;
}
protected isMatchAdministrativeName(featureName, fieldName) {
const isString = typeof fieldName === 'string' && fieldName.constructor === String;
if (isString) {
let shortName = featureName.substr(0, 2);
// 张家口市和张家界市 特殊处理
if (shortName === '张家') {
shortName = featureName.substr(0, 3);
}
return !!fieldName.match(new RegExp(shortName));
}
return false;
}
protected getRestMapLayerInfo(restMapInfo, layer) {
const { bounds, coordUnit, visibleScales, url } = restMapInfo;
layer.layerType = 'TILE';
layer.orginEpsgCode = this.baseProjection;
layer.units = coordUnit && coordUnit.toLowerCase();
layer.extent = [bounds.left, bounds.bottom, bounds.right, bounds.top];
layer.visibleScales = visibleScales;
layer.url = url;
layer.sourceType = 'TILE';
return layer;
}
protected handleLayerFeatures(features, layerInfo) {
const { layerType, style, themeSetting, filterCondition } = layerInfo;
if ((style || themeSetting) && filterCondition) {
// 将 feature 根据过滤条件进行过滤, 分段专题图和单值专题图因为要计算 styleGroup 所以暂时不过滤
if (layerType !== 'RANGE' && layerType !== 'UNIQUE' && layerType !== 'RANK_SYMBOL') {
features = this.getFilterFeatures(filterCondition, features);
}
}
return features;
}
protected mergeFeatures(layerId: string, features: any, mergeByField?: string): any {
if (!(features instanceof Array)) {
return features;
}
features = features.map((feature: any, index: any) => {
if (!Object.prototype.hasOwnProperty.call(feature.properties, 'index')) {
feature.properties.index = index;
}
return feature;
});
if (!features.length || !mergeByField && features[0].geometry) {
return features;
}
const source = this.map.getSource(layerId);
if ((!source || !source._data.features) && features[0].geometry) {
return features;
}
const prevFeatures = source && source._data && source._data.features;
const nextFeatures = [];
if (!mergeByField && prevFeatures) {
return prevFeatures;
}
features.forEach((feature: any) => {
const prevFeature = prevFeatures.find((item: any) => {
if (isNaN(+item.properties[mergeByField]) && isNaN(+feature.properties[mergeByField])) {
return (
JSON.stringify(item.properties[mergeByField] || '') ===
JSON.stringify(feature.properties[mergeByField] || '')
);
} else {
return +item.properties[mergeByField] === +feature.properties[mergeByField];
}
});
if (prevFeature) {
nextFeatures.push({
...prevFeature,
...feature
});
} else if (feature.geometry) {
nextFeatures.push(feature);
}
});
return nextFeatures;
}
protected getFilterFeatures(filterCondition: string, allFeatures): any {
if (!filterCondition) {
return allFeatures;
}
const condition = this.replaceFilterCharacter(filterCondition);
const sql = 'select * from json where (' + condition + ')';
const filterFeatures = [];
for (let i = 0; i < allFeatures.length; i++) {
const feature = allFeatures[i];
let filterResult: any;
try {
filterResult = window.jsonsql.query(sql, {
properties: feature.properties
});
} catch (err) {
// 必须把要过滤得内容封装成一个对象,主要是处理jsonsql(line : 62)中由于with语句遍历对象造成的问题
continue;
}
if (filterResult && filterResult.length > 0) {
// afterFilterFeatureIdx.push(i);
filterFeatures.push(feature);
}
}
return filterFeatures;
}
protected replaceFilterCharacter(filterString: string): string {
filterString = filterString
.replace(/=/g, '==')
.replace(/AND|and/g, '&&')
.replace(/or|OR/g, '||')
.replace(/<==/g, '<=')
.replace(/>==/g, '>=');
return filterString;
}
protected getEchartsLayerOptions(layerInfo, features, coordinateSystem) {
const properties = this.webMapService.getFeatureProperties(features);
const lineData = this._createLinesData(layerInfo, properties);
const pointData = this._createPointsData(lineData, layerInfo, properties);
const options = this._createOptions(layerInfo, lineData, pointData, coordinateSystem);
return options;
}
protected getDashStyle(str, strokeWidth = 1, type = 'array') {
if (!str) {
return type === 'array' ? [] : '';
}
const w = strokeWidth;
let dashArr;
switch (str) {
case 'solid':
dashArr = [];
break;
case 'dot':
dashArr = [1, 4 * w];
break;
case 'dash':
dashArr = [4 * w, 4 * w];
break;
case 'dashrailway':
dashArr = [8 * w, 12 * w];
break;
case 'dashdot':
dashArr = [4 * w, 4 * w, 1 * w, 4 * w];
break;
case 'longdash':
dashArr = [8 * w, 4 * w];
break;
case 'longdashdot':
dashArr = [8 * w, 4 * w, 1, 4 * w];
break;
default:
if (SuperMap.Util.isArray(str)) {
dashArr = str;
}
str = SuperMap.String.trim(str).replace(/\s+/g, ',');
dashArr = str.replace(/\[|\]/gi, '').split(',');
break;
}
dashArr = type === 'array' ? dashArr : dashArr.join(',');
return dashArr;
}
protected getCanvasFromSVG(svgUrl: string, divDom: HTMLElement, callBack: Function): void {
const canvas = document.createElement('canvas');
canvas.id = `dataviz-canvas-${new Date().getTime()}`;
canvas.style.display = 'none';
divDom.appendChild(canvas);
if (svgUrl) {
const canvgs = window.canvg ? window.canvg : canvg;
canvgs(canvas.id, svgUrl, {
ignoreMouse: true,
ignoreAnimation: true,
renderCallback: () => {
if (canvas.width > 300 || canvas.height > 300) {
return;
}
callBack(canvas);
},
forceRedraw: () => {
return false;
}
});
} else {
callBack(canvas);
}
}
protected getRangeStyleGroup(layerInfo: any, features: any): Array<any> | void {
const { featureType, style, themeSetting } = layerInfo;
const { customSettings, themeField, segmentCount, segmentMethod, colors } = themeSetting;
// 找出分段值
const values = [];
let attributes;
features.forEach(feature => {
attributes = feature.properties;
if (attributes) {
// 过滤掉非数值的数据
const val = attributes[themeField];
(val || val === 0) && isNumber(+val) && values.push(parseFloat(val));
}
}, this);
let segements =
values && values.length && SuperMap.ArrayStatistic.getArraySegments(values, segmentMethod, segmentCount);
if (segements) {
let itemNum = segmentCount;
if (attributes && segements[0] === segements[attributes.length - 1]) {
itemNum = 1;
segements.length = 2;
}
// 保留两位有效数
for (let i = 0; i < segements.length; i++) {
let value = segements[i];
value = i === 0 ? Math.floor(value * 100) / 100 : Math.ceil(value * 100) / 100 + 0.1; // 加0.1 解决最大值没有样式问题
segements[i] = Number(value.toFixed(2));
}
// 获取一定量的颜色
let curentColors = colors;
curentColors = SuperMap.ColorsPickerUtil.getGradientColors(curentColors, itemNum, 'RANGE');
for (let index = 0; index < itemNum; index++) {
if (index in customSettings) {
if (customSettings[index].segment.start) {
segements[index] = customSettings[index].segment.start;
}
if (customSettings[index].segment.end) {
segements[index + 1] = customSettings[index].segment.end;
}
}
}
// 生成styleGroup
const styleGroups = [];
for (let i = 0; i < itemNum; i++) {
let color = curentColors[i];
if (i in customSettings) {
if (customSettings[i].color) {
color = customSettings[i].color;
}
}
if (featureType === 'LINE') {
style.strokeColor = color;
} else {
style.fillColor = color;
}
const start = segements[i];
const end = segements[i + 1];
const styleObj = JSON.parse(JSON.stringify(style));
styleGroups.push({
style: styleObj,
color: color,
start: start,
end: end
});
}
return styleGroups;
}
}
protected getUniqueStyleGroup(parameters: any, features: any) {
const { featureType, style, themeSetting } = parameters;
const { colors, customSettings } = themeSetting;
let themeField = themeSetting.themeField;
// 找出所有的单值
const featurePropertie = (features && features[0] && features[0].properties) || {};
Object.keys(featurePropertie).forEach(key => {
key.toLocaleUpperCase() === themeField.toLocaleUpperCase() && (themeField = key);
});
const names = [];
for (const i in features) {
const properties = features[i].properties;
const name = properties[themeField];
let isSaved = false;
for (const j in names) {
if (names[j] === name) {
isSaved = true;
break;
}
}
if (!isSaved) {
names.push(name || '0');
}
}
// 获取一定量的颜色
let curentColors = colors;
curentColors = SuperMap.ColorsPickerUtil.getGradientColors(curentColors, names.length);
const styleGroup = [];
names.forEach((name, index) => {
let color = curentColors[index];
let itemStyle = { ...style };
if (name in customSettings) {
const customStyle = customSettings[name];
if (typeof customStyle === 'object') {
itemStyle = Object.assign(itemStyle, customStyle);
} else {
if (typeof customStyle === 'string') {
color = customSettings[name];
}
if (featureType === 'LINE') {
itemStyle.strokeColor = color;
} else {
itemStyle.fillColor = color;
}
}
}
styleGroup.push({
color: color,
style: itemStyle,
value: name,
themeField: themeField
});
}, this);
return styleGroup;
}
protected transformFeatures(features) {
features &&
features.forEach((feature, index) => {
let coordinates = feature.geometry && feature.geometry.coordinates;
if (!coordinates || coordinates.length === 0) {
return;
}
coordEach(feature, (coordinates) => {
// @ts-ignore
let transCoordinates = this._unproject(coordinates);
coordinates[0] = transCoordinates[0];
coordinates[1] = transCoordinates[1];
});
features[index] = feature;
});
return features;
}
private _drawTextRectAndGetSize({ context, style, textArray, lineHeight, doublePadding, canvas }) {
let backgroundFill = style.backgroundFill;
const maxWidth = style.maxWidth - doublePadding;
let width = 0;
let height = 0;
let lineCount = 0;
let lineWidths = [];
// 100的宽度,去掉左右两边3padding
textArray.forEach((arrText: string) => {
let line = '';
let isOverMax = false;
lineCount++;
for (let n = 0; n < arrText.length; n++) {
let textLine = line + arrText[n];
let metrics = context.measureText(textLine);
let textWidth = metrics.width;
if ((textWidth > maxWidth && n > 0) || arrText[n] === '\n') {
line = arrText[n];
lineCount++;
// 有换行,记录当前换行的width
isOverMax = true;
} else {
line = textLine;
width = textWidth;
}
}
if(isOverMax) {
lineWidths.push(maxWidth);
} else {
lineWidths.push(width);
}
}, this);
for (let i = 0; i < lineWidths.length; i++) {
let lineW = lineWidths[i];
if(lineW >= maxWidth) {
// 有任何一行超过最大高度,就用最大高度
width = maxWidth;
break;
} else if(lineW > width) {
// 自己换行,就要比较每行的最大宽度
width = lineW;
}
}
width += doublePadding;
// -6 是为了去掉canvas下方多余空白,让文本垂直居中
height = lineCount * lineHeight + doublePadding - 6;
canvas.width = width;
canvas.height = height;
context.fillStyle = backgroundFill;
context.fillRect(0, 0, width, height);
context.lineWidth = style.borderWidth;
context.strokeStyle = style.borderColor;
context.strokeRect(0, 0, width, height);
return {
width: width,
height: height
};
}
private _drawTextWithCanvas({ context, canvas, style }) {
const padding = 8;
const doublePadding = padding * 2;
const lineHeight = Number(style.font.replace(/[^0-9]/ig, '')) + 3;
const textArray = style.text.split('\r\n');
context.font = style.font;
const size = this._drawTextRectAndGetSize({ context, style, textArray, lineHeight, doublePadding, canvas });
let positionY = padding;
textArray.forEach((text: string, i: number) => {
if(i !== 0) {
positionY = positionY + lineHeight;
}
context.font = style.font;
let textAlign = style.textAlign;
let x: number;
const width = size.width - doublePadding; // 减去padding
switch (textAlign) {
case 'center':
x = width / 2;
break;
case 'right':
x = width;
break;
default:
x = 8;
break;
}
// 字符分隔为数组
const arrText = text.split('');
let line = '';
const fillColor = style.fillColor;
// 每一行限制的高度
let maxWidth = style.maxWidth - doublePadding;
for (let n = 0; n < arrText.length; n++) {
let testLine = line + arrText[n];
let metrics = context.measureText(testLine);
let testWidth = metrics.width;
if ((testWidth > maxWidth && n > 0) || arrText[n] === '\n') {
context.fillStyle = fillColor;
context.textAlign = textAlign;
context.textBaseline = 'top';
context.fillText(line, x, positionY);
line = arrText[n];
positionY += lineHeight;
} else {
line = testLine;
}
}
context.fillStyle = fillColor;
context.textAlign = textAlign;
context.textBaseline = 'top';
context.fillText(line, x, positionY);
}, this);
}
protected handleSvgColor(style, canvas) {
const { fillColor, fillOpacity, strokeColor, strokeOpacity, strokeWidth } = style;
const context = canvas.getContext('2d');
if (style.text) {
this._drawTextWithCanvas({ context, canvas, style });
return;
}
if (fillColor) {
context.fillStyle = getColorWithOpacity(fillColor, fillOpacity);
context.fill();
}
if (strokeColor || strokeWidth) {
context.strokeStyle = getColorWithOpacity(strokeColor, strokeOpacity);
context.lineWidth = strokeWidth;
context.stroke();
}
}
private _createLinesData(layerInfo, properties) {
const data = [];
if (properties && properties.length) {
// 重新获取数据
const from = layerInfo.from;
const to = layerInfo.to;
let fromCoord;
let toCoord;
if (from.type === 'XY_FIELD' && from.xField && from.yField && to.xField && to.yField) {
properties.forEach(property => {
const fromX = property[from.xField];
const fromY = property[from.yField];
const toX = property[to.xField];
const toY = property[to.yField];
if (!fromX || !fromY || !toX || !toY) {
return;
}
fromCoord = [property[from.xField], property[from.yField]];
toCoord = [property[to.xField], property[to.yField]];
data.push({
coords: [fromCoord, toCoord]
});
});
} else if (from.type === 'PLACE_FIELD' && from.field && to.field) {
const centerDatas = provincialCenterData.concat(municipalCenterData);
properties.forEach(property => {
const fromField = property[from.field];
const toField = property[to.field];
fromCoord = centerDatas.find(item => {
return this.isMatchAdministrativeName(item.name, fromField);
});
toCoord = centerDatas.find(item => {
return this.isMatchAdministrativeName(item.name, toField);
});
if (!fromCoord || !toCoord) {
return;
}
data.push({
coords: [fromCoord.coord, toCoord.coord]
});
});
}
}
return data;
}
private _createPointsData(lineData, layerInfo, properties) {
let data = [];
const labelSetting = layerInfo.labelSetting;
// 标签隐藏则直接返回
if (!labelSetting.show || !lineData.length) {
return data;
}
const fromData = [];
const toData = [];
lineData.forEach((item, idx) => {
const coords = item.coords;
const fromCoord = coords[0];
const toCoord = coords[1];
const fromProperty = properties[idx][labelSetting.from];
const toProperty = properties[idx][labelSetting.to];
// 起始字段去重
const f = fromData.find(d => {
return d.value[0] === fromCoord[0] && d.value[1] === fromCoord[1];
});
!f &&
fromData.push({
name: fromProperty,
value: fromCoord
});
// 终点字段去重
const t = toData.find(d => {
return d.value[0] === toCoord[0] && d.value[1] === toCoord[1];
});
!t &&
toData.push({
name: toProperty,
value: toCoord
});
});
data = fromData.concat(toData);
return data;
}
private _createOptions(layerInfo, lineData, pointData, coordinateSystem) {
let series;
const lineSeries = this._createLineSeries(layerInfo, lineData, coordinateSystem);
if (pointData && pointData.length) {
const pointSeries: any = this._createPointSeries(layerInfo, pointData, coordinateSystem);
series = lineSeries.concat(pointSeries);
} else {
series = lineSeries.slice();
}
return { series };
}
private _createPointSeries(layerInfo, pointData, coordinateSystem) {
const lineSetting = layerInfo.lineSetting;
const animationSetting = layerInfo.animationSetting;
const labelSetting = layerInfo.labelSetting;
const pointSeries = [
{
name: 'point-series',
coordinateSystem: coordinateSystem,
zlevel: 2,
label: {
normal: {
show: labelSetting.show,
position: 'right',
formatter: '{b}',
color: labelSetting.color,
fontFamily: labelSetting.fontFamily
}
},
itemStyle: {
normal: {
color: lineSetting.color || labelSetting.color
}
},
data: pointData
}
];
if (animationSetting.show) {
// 开启动画
// @ts-ignore
pointSeries[0].type = 'effectScatter';
// @ts-ignore
pointSeries[0].rippleEffect = {
brushType: 'stroke'
};
} else {
// 关闭动画
// @ts-ignore
pointSeries[0].type = 'scatter';
}
return pointSeries;
}
private _createLineSeries(layerInfo, lineData, coordinateSystem) {
const lineSetting = layerInfo.lineSetting;
const animationSetting = layerInfo.animationSetting;
const linesSeries = [
// 轨迹线样式
{
name: 'line-series',
coordinateSystem: coordinateSystem,
type: 'lines',
zlevel: 1,
effect: {
show: animationSetting.show,
constantSpeed: animationSetting.constantSpeed,
trailLength: 0,
symbol: animationSetting.symbol,
symbolSize: animationSetting.symbolSize
},
lineStyle: {
normal: {
color: lineSetting.color,
type: lineSetting.type,
width: lineSetting.width,
opacity: lineSetting.opacity,
curveness: lineSetting.curveness
}
},
data: lineData
}
];
if (lineData.length >= MAX_MIGRATION_ANIMATION_COUNT) {
// @ts-ignore
linesSeries[0].large = true;
// @ts-ignore
linesSeries[0].largeThreshold = 100;
// @ts-ignore
linesSeries[0].blendMode = 'lighter';
}
return linesSeries;
}
private _getLayerFeaturesSucceeded(result, layer) {
switch (result.type) {
case 'feature':
this._initOverlayLayer(layer, result.features);
break;
case 'restMap':
layer.layerType = 'restMap';
this._initOverlayLayer(layer, result.restMaps);
break;
case 'mvt':
layer.layerType = 'mvt';
this._initOverlayLayer(layer, result);
break;
case 'dataflow':
case 'noServerId':
this._initOverlayLayer(layer);
break;
}
}
} | the_stack |
declare function JitsiConference(options: any): void;
declare class JitsiConference {
/**
* Creates a JitsiConference object with the given name and properties.
* Note: this constructor is not a part of the public API (objects should be
* created using JitsiConnection.createConference).
* @param options.config properties / settings related to the conference that
* will be created.
* @param options.name the name of the conference
* @param options.connection the JitsiConnection object for this
* JitsiConference.
* @param {number} [options.config.avgRtpStatsN=15] how many samples are to be
* collected by {@link AvgRTPStatsReporter}, before arithmetic mean is
* calculated and submitted to the analytics module.
* @param {boolean} [options.config.enableIceRestart=false] - enables the ICE
* restart logic.
* @param {boolean} [options.config.p2p.enabled] when set to <tt>true</tt>
* the peer to peer mode will be enabled. It means that when there are only 2
* participants in the conference an attempt to make direct connection will be
* made. If the connection succeeds the conference will stop sending data
* through the JVB connection and will use the direct one instead.
* @param {number} [options.config.p2p.backToP2PDelay=5] a delay given in
* seconds, before the conference switches back to P2P, after the 3rd
* participant has left the room.
* @param {number} [options.config.channelLastN=-1] The requested amount of
* videos are going to be delivered after the value is in effect. Set to -1 for
* unlimited or all available videos.
* @param {number} [options.config.forceJVB121Ratio]
* "Math.random() < forceJVB121Ratio" will determine whether a 2 people
* conference should be moved to the JVB instead of P2P. The decision is made on
* the responder side, after ICE succeeds on the P2P connection.
* @param {*} [options.config.openBridgeChannel] Which kind of communication to
* open with the videobridge. Values can be "datachannel", "websocket", true
* (treat it as "datachannel"), undefined (treat it as "datachannel") and false
* (don't open any channel).
* @constructor
*
* FIXME Make all methods which are called from lib-internal classes
* to non-public (use _). To name a few:
* {@link JitsiConference.onLocalRoleChanged}
* {@link JitsiConference.onUserRoleChanged}
* {@link JitsiConference.onMemberLeft}
* and so on...
*/
constructor(options: any);
eventEmitter: EventEmitter;
options: any;
eventManager: JitsiConferenceEventManager;
participants: {[key:string]:JitsiParticipant};
componentsVersions: ComponentsVersions;
/**
* Jingle session instance for the JVB connection.
*/
jvbJingleSession: JingleSessionPC;
lastDominantSpeaker: any;
dtmfManager: any;
somebodySupportsDTMF: boolean;
authEnabled: boolean;
startAudioMuted: boolean;
startVideoMuted: boolean;
startMutedPolicy: {
audio: boolean;
video: boolean;
};
isMutedByFocus: boolean;
mutedByFocusActor: any;
wasStopped: boolean;
properties: {};
/**
* The object which monitors local and remote connection statistics (e.g.
* sending bitrate) and calculates a number which represents the connection
* quality.
*/
connectionQuality: ConnectionQuality;
/**
* Reports average RTP statistics to the analytics module.
* @type {AvgRTPStatsReporter}
*/
avgRtpStatsReporter: AvgRTPStatsReporter;
/**
* Indicates whether the connection is interrupted or not.
*/
isJvbConnectionInterrupted: boolean;
/**
* The object which tracks active speaker times
*/
speakerStatsCollector: SpeakerStatsCollector;
/**
* Stores reference to deferred start P2P task. It's created when 3rd
* participant leaves the room in order to avoid ping pong effect (it
* could be just a page reload).
* @type {number|null}
*/
deferredStartP2PTask: number | null;
/**
* A delay given in seconds, before the conference switches back to P2P
* after the 3rd participant has left.
* @type {number}
*/
backToP2PDelay: number;
/**
* If set to <tt>true</tt> it means the P2P ICE is no longer connected.
* When <tt>false</tt> it means that P2P ICE (media) connection is up
* and running.
* @type {boolean}
*/
isP2PConnectionInterrupted: boolean;
/**
* Flag set to <tt>true</tt> when P2P session has been established
* (ICE has been connected) and this conference is currently in the peer to
* peer mode (P2P connection is the active one).
* @type {boolean}
*/
p2p: boolean;
/**
* A JingleSession for the direct peer to peer connection.
*/
p2pJingleSession: JingleSessionPC;
videoSIPGWHandler: VideoSIPGW;
recordingManager: RecordingManager;
/**
* If the conference.joined event has been sent this will store the timestamp when it happened.
*
* @type {undefined|number}
* @private
*/
connection: JitsiConnection;
xmpp: XMPP;
room: ChatRoom;
e2eping: E2ePing;
rtc: RTC;
qualityController: QualityController;
participantConnectionStatus: ParticipantConnectionStatusHandler;
// statistics: Statistics;
/**
* Emits {@link JitsiConferenceEvents.JVB121_STATUS}.
* @type {Jvb121EventGenerator}
*/
jvb121Status: Jvb121EventGenerator;
p2pDominantSpeakerDetection: P2PDominantSpeakerDetection;
join(password: string): void;
authenticateAndUpgradeRole(options: any): any;
isJoined(): boolean;
isP2PEnabled(): boolean;
isP2PTestModeEnabled(): boolean;
leave(): Promise<any>;
getName(): any;
getConnection(): JitsiConnection;
isAuthEnabled(): boolean;
isLoggedIn(): boolean;
getAuthLogin(): any;
isExternalAuthEnabled(): boolean;
getExternalAuthUrl(urlForPopup?: boolean): Promise<any>;
getLocalTracks(mediaType?: typeof MediaType): JitsiLocalTrack[];
getLocalAudioTrack(): JitsiLocalTrack | null;
getLocalVideoTrack(): JitsiLocalTrack | null;
getPerformanceStats(): any | null;
on(eventId: string, handler: Function): void;
off(eventId: string, handler?: Function): void;
addEventListener(eventId: string, handler: Function): void;
removeEventListener(eventId: string, handler?: Function): void;
addCommandListener(command: string, handler: Function): void;
removeCommandListener(command: string, handler: Function): void;
sendTextMessage(message: any, elementName?: string): void;
sendPrivateTextMessage(id: any, message: any, elementName?: string): void;
sendCommand(name: string, values: any): void;
sendCommandOnce(name: string, values: any): void;
removeCommand(name: string): void;
setDisplayName(name: string): void;
setSubject(subject: string): void;
getTranscriber(): Transcriber;
transcriber: Transcriber;
getTranscriptionStatus(): string;
addTrack(track: JitsiLocalTrack): Promise<any>;
onLocalTrackRemoved(track: JitsiLocalTrack): void;
removeTrack(track: JitsiLocalTrack): Promise<any>;
replaceTrack(oldTrack: JitsiLocalTrack, newTrack: JitsiLocalTrack): Promise<any>;
getRole(): string;
isHidden(): boolean | null;
isModerator(): boolean | null;
lock(password: string): Promise<any>;
unlock(): Promise<any>;
selectParticipant(participantId: string): void;
selectParticipants(participantIds: string[]): void;
pinParticipant(participantId: string): void;
getLastN(): number;
setLastN(lastN: number): void;
isInLastN(participantId: string): boolean;
getParticipants(): JitsiParticipant[];
getParticipantCount(countHidden?: boolean): number;
getParticipantById(id: any): JitsiParticipant;
grantOwner(id: string): void;
kickParticipant(id: string): void;
muteParticipant(id: string): void;
onMemberJoined(jid: any, nick: any, role: any, isHidden: any, statsID: any, status: any, identity: any, botType: any): void;
onMemberLeft(jid: any): void;
onMemberKicked(isSelfPresence: boolean, actorId: string, kickedParticipantId: string | null): void;
onLocalRoleChanged(role: string): void;
onUserRoleChanged(jid: any, role: any): void;
onDisplayNameChanged(jid: any, displayName: any): void;
onRemoteTrackAdded(track: any): void;
onCallAccepted(session: any, answer: any): void;
onTransportInfo(session: any, transportInfo: any): void;
onRemoteTrackRemoved(removedTrack: any): void;
onIncomingCall(jingleSession: any, jingleOffer: any, now: any): void;
onCallEnded(jingleSession: any, reasonCondition: string, reasonText: string | null): void;
onSuspendDetected(jingleSession: any): void;
updateDTMFSupport(): void;
isDTMFSupported(): boolean;
myUserId(): string;
sendTones(tones: any, duration: any, pause: any): void;
startRecording(options: any): Promise<any>;
stopRecording(sessionID: string): Promise<any>;
isSIPCallingSupported(): any;
dial(number: any): any;
hangup(): any;
startTranscriber(): any;
/**
* Stops the transcription service.
*/
stopTranscriber: any;
getPhoneNumber(): any;
getPhonePin(): any;
getMeetingUniqueId(): string | undefined;
getActivePeerConnection(): any | null;
getConnectionState(): RTCIceConnectionState | null;
setStartMutedPolicy(policy: any): void;
getStartMutedPolicy(): any;
isStartAudioMuted(): boolean;
isStartVideoMuted(): boolean;
getConnectionTimes(): any;
setLocalParticipantProperty(name: any, value: any): void;
removeLocalParticipantProperty(name: any): void;
getLocalParticipantProperty(name: any): any;
sendFeedback(overallFeedback: any, detailedFeedback: any): Promise<any>;
isCallstatsEnabled(): boolean;
getSsrcByTrack(track: any): number | undefined;
sendApplicationLog(message: string): void;
sendEndpointMessage(to: string, payload: object): void;
broadcastEndpointMessage(payload: object): void;
sendMessage(message: string | object, to?: string, sendThroughVideobridge?: boolean): void;
isConnectionInterrupted(): boolean;
p2pEstablishmentDuration: number | undefined;
jvbEstablishmentDuration: number;
getProperty(key: string): any;
isP2PActive(): boolean;
getP2PConnectionState(): string | null;
startP2PSession(): void;
stopP2PSession(): void;
getSpeakerStats(): object;
setReceiverVideoConstraint(maxFrameHeight: number): void;
setSenderVideoConstraint(maxFrameHeight: number): Promise<any>;
createVideoSIPGWSession(sipAddress: string, displayName: string): any | Error;
isE2EESupported(): boolean;
toggleE2EE(enabled: boolean): void;
isLobbySupported(): boolean;
isMembersOnly(): boolean;
enableLobby(): Promise<any>;
disableLobby(): void;
joinLobby(displayName: string, email: string): Promise<never>;
lobbyDenyAccess(id: string): void;
lobbyApproveAccess(id: string): void;
}
declare namespace JitsiConference {
export function resourceCreator(jid: string, isAuthenticatedUser: boolean): string;
}
export default JitsiConference;
import JitsiConferenceEventManager from "./JitsiConferenceEventManager";
import ComponentsVersions from "./modules/version/ComponentsVersions";
import ConnectionQuality from "./modules/connectivity/ConnectionQuality";
import AvgRTPStatsReporter from "./modules/statistics/AvgRTPStatsReporter";
import AudioOutputProblemDetector from "./modules/statistics/AudioOutputProblemDetector";
import SpeakerStatsCollector from "./modules/statistics/SpeakerStatsCollector";
import VideoSIPGW from "./modules/videosipgw/VideoSIPGW";
import RecordingManager from "./modules/recording/RecordingManager";
import { E2EEncryption } from "./modules/e2ee/E2EEncryption";
import E2ePing from "./modules/e2eping/e2eping";
import RTC from "./modules/RTC/RTC";
import { QualityController } from "./modules/qualitycontrol/QualityController";
import ParticipantConnectionStatusHandler from "./modules/connectivity/ParticipantConnectionStatus";
import Statistics from "./modules/statistics/statistics";
import VADAudioAnalyser from "./modules/detection/VADAudioAnalyser";
import NoAudioSignalDetection from "./modules/detection/NoAudioSignalDetection";
import Jvb121EventGenerator from "./modules/event/Jvb121EventGenerator";
import P2PDominantSpeakerDetection from "./modules/detection/P2PDominantSpeakerDetection";
import * as MediaType from "./service/RTC/MediaType";
import Transcriber from "./modules/transcription/transcriber";
import JitsiParticipant from "./JitsiParticipant";
import IceFailedHandling from "./modules/connectivity/IceFailedHandling";
import { EventEmitter } from "events";
import JingleSessionPC from "./modules/xmpp/JingleSessionPC";
import JitsiConnection from "./JitsiConnection";
import XMPP from "./modules/xmpp/xmpp";
import ChatRoom from "./modules/xmpp/ChatRoom";
import JitsiLocalTrack from "./modules/RTC/JitsiLocalTrack";
import JitsiRemoteTrack from "./modules/RTC/JitsiRemoteTrack"; | the_stack |
import fs from 'fs';
import path from 'path';
import request from 'request';
import * as component from 'common/component';
import { EventEmitter } from 'events';
import { Deferred } from 'ts-deferred';
import { getExperimentId } from 'common/experimentStartupInfo';
import { getLogger, Logger } from 'common/log';
import { MethodNotImplementedError } from 'common/errors';
import {
HyperParameters, NNIManagerIpConfig, TrainingService,
TrialJobApplicationForm, TrialJobDetail, TrialJobMetric
} from 'common/trainingService';
import { delay } from 'common/utils';
import { OpenpaiConfig, toMegaBytes } from 'common/experimentConfig';
import { PAIJobInfoCollector } from './paiJobInfoCollector';
import { PAIJobRestServer } from './paiJobRestServer';
import { PAITrialJobDetail, PAI_TRIAL_COMMAND_FORMAT } from './paiConfig';
import { String } from 'typescript-string-operations';
import { generateParamFileName, getIPV4Address, uniqueString } from 'common/utils';
import { CONTAINER_INSTALL_NNI_SHELL_FORMAT } from '../common/containerJobData';
import { execMkdir, validateCodeDir, execCopydir } from '../common/util';
const yaml = require('js-yaml');
/**
* Training Service implementation for OpenPAI (Open Platform for AI)
* Refer https://github.com/Microsoft/pai for more info about OpenPAI
*/
@component.Singleton
class PAITrainingService implements TrainingService {
private readonly log!: Logger;
private readonly metricsEmitter: EventEmitter;
private readonly trialJobsMap: Map<string, PAITrialJobDetail>;
private readonly expRootDir: string;
private readonly jobQueue: string[];
private stopping: boolean = false;
private paiToken?: string;
private paiTokenUpdateTime?: number;
private readonly paiTokenUpdateInterval: number;
private readonly experimentId!: string;
private readonly paiJobCollector: PAIJobInfoCollector;
private paiRestServerPort?: number;
private nniManagerIpConfig?: NNIManagerIpConfig;
private versionCheck: boolean = true;
private logCollection: string = 'none';
private paiJobRestServer?: PAIJobRestServer;
private protocol: string;
private copyExpCodeDirPromise?: Promise<void>;
private paiJobConfig: any;
private nniVersion: string | undefined;
private config: OpenpaiConfig;
constructor(config: OpenpaiConfig) {
this.log = getLogger('PAITrainingService');
this.metricsEmitter = new EventEmitter();
this.trialJobsMap = new Map<string, PAITrialJobDetail>();
this.jobQueue = [];
this.expRootDir = path.join('/nni-experiments', getExperimentId());
this.experimentId = getExperimentId();
this.paiJobCollector = new PAIJobInfoCollector(this.trialJobsMap);
this.paiTokenUpdateInterval = 7200000; //2hours
this.log.info('Construct paiBase training service.');
this.config = config;
this.versionCheck = !this.config.debug;
this.paiJobRestServer = new PAIJobRestServer(this);
this.paiToken = this.config.token;
this.protocol = this.config.host.toLowerCase().startsWith('https://') ? 'https' : 'http';
this.copyExpCodeDirPromise = this.copyTrialCode();
}
private async copyTrialCode(): Promise<void> {
await validateCodeDir(this.config.trialCodeDirectory);
const nniManagerNFSExpCodeDir = path.join(this.config.localStorageMountPoint, this.experimentId, 'nni-code');
await execMkdir(nniManagerNFSExpCodeDir);
this.log.info(`Starting copy codeDir data from ${this.config.trialCodeDirectory} to ${nniManagerNFSExpCodeDir}`);
await execCopydir(this.config.trialCodeDirectory, nniManagerNFSExpCodeDir);
}
public async run(): Promise<void> {
this.log.info('Run PAI training service.');
if (this.paiJobRestServer === undefined) {
throw new Error('paiJobRestServer not initialized!');
}
await this.paiJobRestServer.start();
this.paiJobRestServer.setEnableVersionCheck = this.versionCheck;
this.log.info(`PAI Training service rest server listening on: ${this.paiJobRestServer.endPoint}`);
await Promise.all([
this.statusCheckingLoop(),
this.submitJobLoop()]);
this.log.info('PAI training service exit.');
}
protected async submitJobLoop(): Promise<void> {
while (!this.stopping) {
while (!this.stopping && this.jobQueue.length > 0) {
const trialJobId: string = this.jobQueue[0];
if (await this.submitTrialJobToPAI(trialJobId)) {
// Remove trial job with trialJobId from job queue
this.jobQueue.shift();
} else {
// Break the while loop since failed to submitJob
break;
}
}
await delay(3000);
}
}
public async listTrialJobs(): Promise<TrialJobDetail[]> {
const jobs: TrialJobDetail[] = [];
for (const key of this.trialJobsMap.keys()) {
jobs.push(await this.getTrialJob(key));
}
return jobs;
}
public async getTrialFile(_trialJobId: string, _fileName: string): Promise<string | Buffer> {
throw new MethodNotImplementedError();
}
public async getTrialJob(trialJobId: string): Promise<TrialJobDetail> {
const paiTrialJob: PAITrialJobDetail | undefined = this.trialJobsMap.get(trialJobId);
if (paiTrialJob === undefined) {
throw new Error(`trial job ${trialJobId} not found`);
}
return paiTrialJob;
}
public addTrialJobMetricListener(listener: (metric: TrialJobMetric) => void): void {
this.metricsEmitter.on('metric', listener);
}
public removeTrialJobMetricListener(listener: (metric: TrialJobMetric) => void): void {
this.metricsEmitter.off('metric', listener);
}
public cancelTrialJob(trialJobId: string, isEarlyStopped: boolean = false): Promise<void> {
const trialJobDetail: PAITrialJobDetail | undefined = this.trialJobsMap.get(trialJobId);
if (trialJobDetail === undefined) {
return Promise.reject(new Error(`cancelTrialJob: trial job id ${trialJobId} not found`));
}
if (trialJobDetail.status === 'UNKNOWN') {
trialJobDetail.status = 'USER_CANCELED';
return Promise.resolve();
}
const stopJobRequest: request.Options = {
uri: `${this.config.host}/rest-server/api/v2/jobs/${this.config.username}~${trialJobDetail.paiJobName}/executionType`,
method: 'PUT',
json: true,
body: { value: 'STOP' },
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${this.paiToken}`
}
};
// Set trialjobDetail's early stopped field, to mark the job's cancellation source
trialJobDetail.isEarlyStopped = isEarlyStopped;
const deferred: Deferred<void> = new Deferred<void>();
request(stopJobRequest, (error: Error, response: request.Response, _body: any) => {
// Status code 202 for success.
if ((error !== undefined && error !== null) || response.statusCode >= 400) {
this.log.error(`PAI Training service: stop trial ${trialJobId} to PAI Cluster failed!`);
deferred.reject((error !== undefined && error !== null) ? error.message :
`Stop trial failed, http code: ${response.statusCode}`);
} else {
deferred.resolve();
}
});
return deferred.promise;
}
public async cleanUp(): Promise<void> {
this.log.info('Stopping PAI training service...');
this.stopping = true;
if (this.paiJobRestServer === undefined) {
throw new Error('paiJobRestServer not initialized!');
}
try {
await this.paiJobRestServer.stop();
this.log.info('PAI Training service rest server stopped successfully.');
} catch (error) {
this.log.error(`PAI Training service rest server stopped failed, error: ${error.message}`);
}
}
public get MetricsEmitter(): EventEmitter {
return this.metricsEmitter;
}
protected formatPAIHost(host: string): string {
// If users' host start with 'http://' or 'https://', use the original host,
// or format to 'http//${host}'
if (host.startsWith('http://')) {
this.protocol = 'http';
return host.replace('http://', '');
} else if (host.startsWith('https://')) {
this.protocol = 'https';
return host.replace('https://', '');
} else {
return host;
}
}
protected async statusCheckingLoop(): Promise<void> {
while (!this.stopping) {
await this.paiJobCollector.retrieveTrialStatus(this.protocol, this.paiToken, this.config);
if (this.paiJobRestServer === undefined) {
throw new Error('paiBaseJobRestServer not implemented!');
}
if (this.paiJobRestServer.getErrorMessage !== undefined) {
throw new Error(this.paiJobRestServer.getErrorMessage);
}
await delay(3000);
}
}
public async setClusterMetadata(_key: string, _value: string): Promise<void> { return; }
public async getClusterMetadata(_key: string): Promise<string> { return ''; }
// update trial parameters for multi-phase
public async updateTrialJob(trialJobId: string, form: TrialJobApplicationForm): Promise<TrialJobDetail> {
const trialJobDetail: PAITrialJobDetail | undefined = this.trialJobsMap.get(trialJobId);
if (trialJobDetail === undefined) {
throw new Error(`updateTrialJob failed: ${trialJobId} not found`);
}
// Write file content ( parameter.cfg ) to working folders
await this.writeParameterFile(trialJobDetail.logPath, form.hyperParameters);
return trialJobDetail;
}
public async submitTrialJob(form: TrialJobApplicationForm): Promise<TrialJobDetail> {
this.log.info('submitTrialJob: form:', form);
const trialJobId: string = uniqueString(5);
//TODO: use HDFS working folder instead
const trialWorkingFolder: string = path.join(this.expRootDir, 'trials', trialJobId);
const paiJobName: string = `nni_exp_${this.experimentId}_trial_${trialJobId}`;
const logPath: string = path.join(this.config.localStorageMountPoint, this.experimentId, trialJobId);
const paiJobDetailUrl: string = `${this.config.host}/job-detail.html?username=${this.config.username}&jobName=${paiJobName}`;
const trialJobDetail: PAITrialJobDetail = new PAITrialJobDetail(
trialJobId,
'WAITING',
paiJobName,
Date.now(),
trialWorkingFolder,
form,
logPath,
paiJobDetailUrl);
this.trialJobsMap.set(trialJobId, trialJobDetail);
this.jobQueue.push(trialJobId);
return trialJobDetail;
}
private async generateNNITrialCommand(trialJobDetail: PAITrialJobDetail, command: string): Promise<string> {
const containerNFSExpCodeDir = `${this.config.containerStorageMountPoint}/${this.experimentId}/nni-code`;
const containerWorkingDir: string = `${this.config.containerStorageMountPoint}/${this.experimentId}/${trialJobDetail.id}`;
const nniPaiTrialCommand: string = String.Format(
PAI_TRIAL_COMMAND_FORMAT,
`${containerWorkingDir}`,
`${containerWorkingDir}/nnioutput`,
trialJobDetail.id,
this.experimentId,
trialJobDetail.form.sequenceId,
false, // multi-phase
containerNFSExpCodeDir,
command,
this.config.nniManagerIp || await getIPV4Address(),
this.paiRestServerPort,
this.nniVersion,
this.logCollection
)
.replace(/\r\n|\n|\r/gm, '');
return nniPaiTrialCommand;
}
private async generateJobConfigInYamlFormat(trialJobDetail: PAITrialJobDetail): Promise<any> {
const jobName = `nni_exp_${this.experimentId}_trial_${trialJobDetail.id}`
let nniJobConfig: any = undefined;
if (this.config.openpaiConfig !== undefined) {
nniJobConfig = JSON.parse(JSON.stringify(this.config.openpaiConfig)); //Trick for deep clone in Typescript
nniJobConfig.name = jobName;
// Each taskRole will generate new command in NNI's command format
// Each command will be formatted to NNI style
for (const taskRoleIndex in nniJobConfig.taskRoles) {
const commands = nniJobConfig.taskRoles[taskRoleIndex].commands
const nniTrialCommand = await this.generateNNITrialCommand(trialJobDetail, commands.join(" && ").replace(/(["'$`\\])/g, '\\$1'));
nniJobConfig.taskRoles[taskRoleIndex].commands = [nniTrialCommand]
}
} else {
nniJobConfig = {
protocolVersion: 2,
name: jobName,
type: 'job',
jobRetryCount: 0,
prerequisites: [
{
type: 'dockerimage',
uri: this.config.dockerImage,
name: 'docker_image_0'
}
],
taskRoles: {
taskrole: {
instances: 1,
completion: {
minFailedInstances: 1,
minSucceededInstances: -1
},
taskRetryCount: 0,
dockerImage: 'docker_image_0',
resourcePerInstance: {
gpu: this.config.trialGpuNumber,
cpu: this.config.trialCpuNumber,
memoryMB: toMegaBytes(this.config.trialMemorySize)
},
commands: [
await this.generateNNITrialCommand(trialJobDetail, this.config.trialCommand)
]
}
},
extras: {
'storages': [
{
name: this.config.storageConfigName
}
],
submitFrom: 'submit-job-v2'
}
}
if (this.config.virtualCluster) {
nniJobConfig.defaults = {
virtualCluster: this.config.virtualCluster
}
}
}
return yaml.safeDump(nniJobConfig);
}
protected async submitTrialJobToPAI(trialJobId: string): Promise<boolean> {
const deferred: Deferred<boolean> = new Deferred<boolean>();
const trialJobDetail: PAITrialJobDetail | undefined = this.trialJobsMap.get(trialJobId);
if (trialJobDetail === undefined) {
throw new Error(`Failed to find PAITrialJobDetail for job ${trialJobId}`);
}
if (this.paiJobRestServer === undefined) {
throw new Error('paiJobRestServer is not initialized');
}
// Make sure experiment code files is copied from local to NFS
if (this.copyExpCodeDirPromise !== undefined) {
await this.copyExpCodeDirPromise;
this.log.info(`Copy codeDir data finished.`);
// All trials share same destination NFS code folder, only copy codeDir once for an experiment.
// After copy data finished, set copyExpCodeDirPromise be undefined to avoid log content duplicated.
this.copyExpCodeDirPromise = undefined;
}
this.paiRestServerPort = this.paiJobRestServer.clusterRestServerPort;
// Step 1. Prepare PAI job configuration
//create trial local working folder locally.
await execMkdir(trialJobDetail.logPath);
// Write NNI installation file to local files
await fs.promises.writeFile(path.join(trialJobDetail.logPath, 'install_nni.sh'), CONTAINER_INSTALL_NNI_SHELL_FORMAT, { encoding: 'utf8' });
// Write file content ( parameter.cfg ) to local working folders
if (trialJobDetail.form !== undefined) {
await this.writeParameterFile(trialJobDetail.logPath, trialJobDetail.form.hyperParameters);
}
//Generate Job Configuration in yaml format
const paiJobConfig = await this.generateJobConfigInYamlFormat(trialJobDetail);
this.log.debug(paiJobConfig);
// Step 2. Submit PAI job via Rest call
// Refer https://github.com/Microsoft/pai/blob/master/docs/rest-server/API.md for more detail about PAI Rest API
const submitJobRequest: request.Options = {
uri: `${this.config.host}/rest-server/api/v2/jobs`,
method: 'POST',
body: paiJobConfig,
followAllRedirects: true,
headers: {
'Content-Type': 'text/yaml',
Authorization: `Bearer ${this.paiToken}`
}
};
request(submitJobRequest, (error: Error, response: request.Response, body: any) => {
// If submit success, will get status code 202. refer: https://github.com/microsoft/pai/blob/master/src/rest-server/docs/swagger.yaml
if ((error !== undefined && error !== null) || response.statusCode >= 400) {
const errorMessage: string = (error !== undefined && error !== null) ? error.message :
`Submit trial ${trialJobId} failed, http code:${response.statusCode}, http body: ${body}`;
this.log.error(errorMessage);
trialJobDetail.status = 'FAILED';
deferred.reject(errorMessage);
} else {
trialJobDetail.submitTime = Date.now();
}
deferred.resolve(true);
});
return deferred.promise;
}
private async writeParameterFile(directory: string, hyperParameters: HyperParameters): Promise<void> {
const filepath: string = path.join(directory, generateParamFileName(hyperParameters));
await fs.promises.writeFile(filepath, hyperParameters.value, { encoding: 'utf8' });
}
public getTrialOutputLocalPath(_trialJobId: string): Promise<string> {
throw new MethodNotImplementedError();
}
public fetchTrialOutput(_trialJobId: string, _subpath: string): Promise<void> {
throw new MethodNotImplementedError();
}
}
export { PAITrainingService }; | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.